Skip to content

armgit / codex

Public Imported from GitHub
0

Lightweight coding agent that runs in your terminal

Rust

feat(tui2): copy tui crate and normalize snapshots (#7833)

Josh McKinney90f262e9a46e
diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock
index 304343bf2c..95f4fecc48 100644
--- a/codex-rs/Cargo.lock
+++ b/codex-rs/Cargo.lock
@@ -1596,11 +1596,68 @@ name = "codex-tui2"
version = "0.0.0"
dependencies = [
"anyhow",
+ "arboard",
+ "assert_matches",
+ "async-stream",
+ "base64",
+ "chrono",
"clap",
+ "codex-ansi-escape",
+ "codex-app-server-protocol",
"codex-arg0",
+ "codex-backend-client",
"codex-common",
"codex-core",
+ "codex-feedback",
+ "codex-file-search",
+ "codex-login",
+ "codex-protocol",
"codex-tui",
+ "codex-windows-sandbox",
+ "color-eyre",
+ "crossterm",
+ "derive_more 2.1.0",
+ "diffy",
+ "dirs",
+ "dunce",
+ "image",
+ "insta",
+ "itertools 0.14.0",
+ "lazy_static",
+ "libc",
+ "mcp-types",
+ "opentelemetry-appender-tracing",
+ "pathdiff",
+ "pretty_assertions",
+ "pulldown-cmark",
+ "rand 0.9.2",
+ "ratatui",
+ "ratatui-macros",
+ "regex-lite",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "serial_test",
+ "shlex",
+ "strum 0.27.2",
+ "strum_macros 0.27.2",
+ "supports-color 3.0.2",
+ "tempfile",
+ "textwrap 0.16.2",
+ "tokio",
+ "tokio-stream",
+ "tokio-util",
+ "toml",
+ "tracing",
+ "tracing-appender",
+ "tracing-subscriber",
+ "tree-sitter-bash",
+ "tree-sitter-highlight",
+ "unicode-segmentation",
+ "unicode-width 0.2.1",
+ "url",
+ "uuid",
+ "vt100",
]
[[package]]
diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs
index c3788f83f4..113c6a7515 100644
--- a/codex-rs/cli/src/main.rs
+++ b/codex-rs/cli/src/main.rs
@@ -663,7 +663,8 @@ async fn run_interactive_tui(
codex_linux_sandbox_exe: Option<PathBuf>,
) -> std::io::Result<AppExitInfo> {
if is_tui2_enabled(&interactive).await? {
- tui2::run_main(interactive, codex_linux_sandbox_exe).await
+ let result = tui2::run_main(interactive.into(), codex_linux_sandbox_exe).await?;
+ Ok(result.into())
} else {
codex_tui::run_main(interactive, codex_linux_sandbox_exe).await
}
diff --git a/codex-rs/tui2/Cargo.toml b/codex-rs/tui2/Cargo.toml
index fececb1503..06308e996c 100644
--- a/codex-rs/tui2/Cargo.toml
+++ b/codex-rs/tui2/Cargo.toml
@@ -13,7 +13,7 @@ name = "codex-tui2"
path = "src/main.rs"
[features]
-# Keep feature surface aligned with codex-tui while tui2 delegates to it.
+# Keep feature surface aligned with codex-tui while tui2 evolves separately.
vt100-tests = []
debug-logs = []
@@ -22,8 +22,95 @@ workspace = true
[dependencies]
anyhow = { workspace = true }
+async-stream = { workspace = true }
+base64 = { workspace = true }
+chrono = { workspace = true, features = ["serde"] }
clap = { workspace = true, features = ["derive"] }
+codex-ansi-escape = { workspace = true }
+codex-app-server-protocol = { workspace = true }
codex-arg0 = { workspace = true }
-codex-common = { workspace = true }
+codex-backend-client = { workspace = true }
+codex-common = { workspace = true, features = [
+ "cli",
+ "elapsed",
+ "sandbox_summary",
+] }
codex-core = { workspace = true }
+codex-feedback = { workspace = true }
+codex-file-search = { workspace = true }
+codex-login = { workspace = true }
+codex-protocol = { workspace = true }
codex-tui = { workspace = true }
+color-eyre = { workspace = true }
+crossterm = { workspace = true, features = ["bracketed-paste", "event-stream"] }
+derive_more = { workspace = true, features = ["is_variant"] }
+diffy = { workspace = true }
+dirs = { workspace = true }
+dunce = { workspace = true }
+image = { workspace = true, features = ["jpeg", "png"] }
+itertools = { workspace = true }
+lazy_static = { workspace = true }
+mcp-types = { workspace = true }
+opentelemetry-appender-tracing = { workspace = true }
+pathdiff = { workspace = true }
+pulldown-cmark = { workspace = true }
+rand = { workspace = true }
+ratatui = { workspace = true, features = [
+ "scrolling-regions",
+ "unstable-backend-writer",
+ "unstable-rendered-line-info",
+ "unstable-widget-ref",
+] }
+ratatui-macros = { workspace = true }
+regex-lite = { workspace = true }
+reqwest = { version = "0.12", features = ["json"] }
+serde = { workspace = true, features = ["derive"] }
+serde_json = { workspace = true, features = ["preserve_order"] }
+shlex = { workspace = true }
+strum = { workspace = true }
+strum_macros = { workspace = true }
+supports-color = { workspace = true }
+tempfile = { workspace = true }
+textwrap = { workspace = true }
+tokio = { workspace = true, features = [
+ "io-std",
+ "macros",
+ "process",
+ "rt-multi-thread",
+ "signal",
+ "test-util",
+ "time",
+] }
+tokio-stream = { workspace = true }
+toml = { workspace = true }
+tracing = { workspace = true, features = ["log"] }
+tracing-appender = { workspace = true }
+tracing-subscriber = { workspace = true, features = ["env-filter"] }
+tree-sitter-bash = { workspace = true }
+tree-sitter-highlight = { workspace = true }
+unicode-segmentation = { workspace = true }
+unicode-width = { workspace = true }
+url = { workspace = true }
+
+codex-windows-sandbox = { workspace = true }
+tokio-util = { workspace = true, features = ["time"] }
+
+[target.'cfg(unix)'.dependencies]
+libc = { workspace = true }
+
+# Clipboard support via `arboard` is not available on Android/Termux.
+# Only include it for non-Android targets so the crate builds on Android.
+[target.'cfg(not(target_os = "android"))'.dependencies]
+arboard = { workspace = true }
+
+
+[dev-dependencies]
+codex-core = { workspace = true, features = ["test-support"] }
+assert_matches = { workspace = true }
+chrono = { workspace = true, features = ["serde"] }
+insta = { workspace = true }
+pretty_assertions = { workspace = true }
+rand = { workspace = true }
+serial_test = { workspace = true }
+vt100 = { workspace = true }
+uuid = { workspace = true }
diff --git a/codex-rs/tui2/frames/blocks/frame_1.txt b/codex-rs/tui2/frames/blocks/frame_1.txt
new file mode 100644
index 0000000000..8c3263f518
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_1.txt
@@ -0,0 +1,17 @@
+
+ ▒▓▒▓▒██▒▒██▒
+ ▒▒█▓█▒█▓█▒▒░░▒▒ ▒ █▒
+ █░█░███ ▒░ ░ █░ ░▒░░░█
+ ▓█▒▒████▒ ▓█░▓░█
+ ▒▒▓▓█▒░▒░▒▒ ▓░▒▒█
+ ░█ █░ ░█▓▓░░█ █▓▒░░█
+ █▒ ▓█ █▒░█▓ ░▒ ░▓░
+ ░░▒░░ █▓▓░▓░█ ░░
+ ░▒░█░ ▓░░▒▒░ ▓░██████▒██ ▒ ░
+ ▒░▓█ ▒▓█░ ▓█ ░ ░▒▒▒▓▓███░▓█▓█░
+ ▒▒▒ ▒ ▒▒█▓▓░ ░▒████ ▒█ ▓█▓▒▓
+ █▒█ █ ░ ██▓█▒░
+ ▒▒█░▒█▒ ▒▒▒█░▒█
+ ▒██▒▒ ██▓▓▒▓▓▓▒██▒█░█
+ ░█ █░░░▒▒▒█▒▓██
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_10.txt b/codex-rs/tui2/frames/blocks/frame_10.txt
new file mode 100644
index 0000000000..a6fbbf1a4b
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_10.txt
@@ -0,0 +1,17 @@
+
+ ▒████▒██▒
+ ██░███▒░▓▒██
+ ▒▒█░░▓░░▓░█▒██
+ ░▒▒▓▒░▓▒▓▒███▒▒█
+ ▓ ▓░░ ░▒ ██▓▒▓░▓
+ ░░ █░█░▓▓▒ ░▒ ░
+ ▒ ░█ █░░░░█ ░▓█
+ ░░▒█▓█░░▓▒░▓▒░░
+ ░▒ ▒▒░▓░░█▒█▓░░
+ ░ █░▒█░▒▓▒█▒▒▒░█░
+ █ ░░░░░ ▒█ ▒░░
+ ▒░██▒██ ▒░ █▓▓
+ ░█ ░░░░██▓█▓░▓░
+ ▓░██▓░█▓▒ ▓▓█
+ ██ ▒█▒▒█▓█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_11.txt b/codex-rs/tui2/frames/blocks/frame_11.txt
new file mode 100644
index 0000000000..88e3dfa7c5
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_11.txt
@@ -0,0 +1,17 @@
+
+ ███████▒
+ ▓ ▓░░░▒▒█
+ ▓ ▒▒░░▓▒█▓▒█
+ ░▒▒░░▒▓█▒▒▓▓
+ ▒ ▓▓▒░█▒█▓▒░░█
+ ░█░░░█▒▓▓░▒▓░░
+ ██ █░░░░░░▒░▒▒
+ ░ ░░▓░░▒▓ ░ ░
+ ▓ █░▓░░█▓█░▒░
+ ██ ▒░▓▒█ ▓░▒░▒
+ █░▓ ░░░░▒▓░▒▒░
+ ▒▒▓▓░▒█▓██▓░░
+ ▒ █░▒▒▒▒░▓
+ ▒█ █░░█▒▓█░
+ ▒▒ ███▒█░
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_12.txt b/codex-rs/tui2/frames/blocks/frame_12.txt
new file mode 100644
index 0000000000..c6c0ef3e87
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_12.txt
@@ -0,0 +1,17 @@
+
+ █████▓
+ █▒░▒▓░█▒
+ ░▓▒██
+ ▓█░░░▒▒ ░
+ ░ █░░░░▓▓░
+ ░█▓▓█▒ ▒░
+ ░ ░▓▒░░▒
+ ░ ▓█▒░░
+ ██ ░▓░░█░░
+ ░ ▓░█▓█▒
+ ░▓ ░ ▒██▓
+ █ █░ ▒█░
+ ▓ ██░██▒░
+ █▒▓ █░▒░░
+ ▒ █░▒▓▓
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_13.txt b/codex-rs/tui2/frames/blocks/frame_13.txt
new file mode 100644
index 0000000000..7a090e51e3
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_13.txt
@@ -0,0 +1,17 @@
+
+ ▓████
+ ░▒▒░░
+ ░░▒░
+ ░██░▒
+ █ ░░
+ ▓▓░░
+ █ ░░
+ █ ░
+ ▓█ ▒░▓
+ ░ █▒░
+ █░▓▓ ░░
+ ░▒▒▒░
+ ░██░▒
+ █▒▒░▒
+ █ ▓ ▒
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_14.txt b/codex-rs/tui2/frames/blocks/frame_14.txt
new file mode 100644
index 0000000000..f5e74d12b7
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_14.txt
@@ -0,0 +1,17 @@
+
+ ████▓
+ █▓▒▒▓▒
+ ░▒░░▓ ░
+ ░░▓░ ▒░█
+ ░░░▒ ░
+ ░█░░ █░
+ ░░░░ ▓ █
+ ░░▒░░ ▒
+ ░░░░
+ ▒▓▓ ▓▓
+ ▒░ █▓█░
+ ░█░░▒▒▒░
+ ▓ ░▒▒▒░
+ ░▒▓█▒▒▓
+ ▒█ █▒▓
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_15.txt b/codex-rs/tui2/frames/blocks/frame_15.txt
new file mode 100644
index 0000000000..f04599ea27
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_15.txt
@@ -0,0 +1,17 @@
+
+ █████░▒
+ ░█▒░░▒▓██
+ ▓▓░█▒▒░ █░
+ ░▓░ ▓▓█▓▒▒░
+ ░░▒ ▒▒░░▓ ▒░
+ ▒░░▓░░▓▓░
+ ░░ ░░░░░░█░
+ ░░▓░░█░░░ █▓░
+ ░░████░░░▒▓▓░
+ ░▒░▓▓░▒░█▓ ▓░
+ ░▓░░░░▒░ ░ ▓
+ ░██▓▒░░▒▓ ▒
+ █░▒█ ▓▓▓░ ▓░
+ ░▒░░▒▒▓█▒▓
+ ▒▒█▒▒▒▒▓
+ ░░
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_16.txt b/codex-rs/tui2/frames/blocks/frame_16.txt
new file mode 100644
index 0000000000..1eb080286e
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_16.txt
@@ -0,0 +1,17 @@
+
+ ▒▒█ ███░▒
+ ▓▒░░█░░▒░▒▒
+ ░▓▓ ▒▓▒▒░░ █▒
+ ▓▓▓ ▓█▒▒░▒░░██░
+ ░░▓▒▓██▒░░█▓░░▒
+ ░░░█░█ ░▒▒ ░ ░▓░
+ ▒▒░ ▓░█░░░░▓█ █ ░
+ ░▓▓ ░░░░▓░░░ ▓ ░░
+ ▒▒░░░█░▓▒░░ ██ ▓
+ █ ▒▒█▒▒▒█░▓▒░ █▒░
+ ░░░█ ▓█▒░▓ ▓▓░░░
+ ░░█ ░░ ░▓▓█ ▓
+ ▒░█ ░ ▓█▓▒█░
+ ▒░░ ▒█░▓▓█▒░
+ █▓▓▒▒▓▒▒▓█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_17.txt b/codex-rs/tui2/frames/blocks/frame_17.txt
new file mode 100644
index 0000000000..dd5f5c8da5
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_17.txt
@@ -0,0 +1,17 @@
+
+ █▒███▓▓░█▒
+ ▒▓██░░░█▒█░█ ▒█
+ ██▒▓▒▒▒░██ ░░░▒ ▒
+ ▓░▓▒▓░ ▒░ █░▓▒░░░▒▒
+ ░▓▒ ░ ░ ▓▒▒▒▓▓ █
+ ░▒██▓░ █▓▓░ ▓█▒▓░▓▓
+ █ ▓▓░ █▓▓░▒ █ ░░▓▒░
+ ▓ ▒░ ▓▓░░▓░█░░▒▓█
+ █▓█▓▒▒▒█░▒▒░▒▒▓▒░░░ ░
+ ░ ▒▓▒▒░▓█▒▓░░▒ ▒███▒
+ ▒▒▒▓ ████▒▒░█▓▓▒ ▒█
+ ▒░░▒█ ░▓░░░ ▓
+ ▒▒▒ █▒▒ ███▓▒▒▓
+ █ ░██▒▒█░▒▓█▓░█
+ ░█▓▓▒██░█▒██
+ ░
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_18.txt b/codex-rs/tui2/frames/blocks/frame_18.txt
new file mode 100644
index 0000000000..a6c93e6c01
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_18.txt
@@ -0,0 +1,17 @@
+
+ ▒▒▒█▒▒█▓░█▒
+ ▒█ ▒▓███░▒▒█ █▓▓▒
+ ▒▓▓░█ █▒ █ ▓▒ █▓▓▒ █
+ █░░█▓█▒ █ █▒░▒▓▒░▒▓▒▒▒█
+ ▒▒▓▓ ▓░ ▒ █▒▒▓░▓░▒▒▓▒▒▒
+ ▓▒░ ██░▓▒▒▒▓███░█▓▓▒▓░▓░
+ ░░▒▓▓ █▓█▓░ ▒▓ █░▒░▒█
+ ▒▓░░ ▒▒ ░░▓▒ ░▓░
+ ▒ █▒▒▒▓▒▓█░░█░█▓▒█ ░█░░
+ ▒▒▒░█▒█ ░░▓▒▒▒▒░░░▒▓░░▒ █
+ ░▓░▒░ █████░ ▒▒▒▓░▓█▓░▓░
+ ▒▒ █▒█ ░░█ ▓█▒█
+ ▒▒██▒▒▓ ▒█▒▒▓▒█░
+ █░▓████▒▒▒▒██▒▓▒██
+ ░░▒▓▒▒█▓█ ▓█
+ ░
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_19.txt b/codex-rs/tui2/frames/blocks/frame_19.txt
new file mode 100644
index 0000000000..73341b5d58
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_19.txt
@@ -0,0 +1,17 @@
+
+ ▒▒▒▒█░█▒▒░▓▒
+ ▒█░░░▒▓▒▒▒▒█▒█░███
+ ██▓▓▓ ░██░ ░█▓█░█▓▒
+ ▓▓░██▒░ ▒▒▒██▒░██
+ ░░▓░▓░ █░▒ ▓ ░▒ ░▒█
+ ░▒▓██ ▒░█░▓ ▓▓ █▓█░
+ ▒▒░░█ ▓█▒▓░██░ ▓▓▓█░
+ ░░░░ ░▓ ▒░ █ ░ ░░░
+ ░█░▒█▒▓▓▒▒▒░░░░██▓█░▓ ▒ ░░
+ ▒▓▓█░▒█▓▒██▒█░█ ▒▒ ▓▒▒▒█▓▓░▒
+ █▒ ▓█░ ██ ▒▒▒▓░▓▓ ▓▓█
+ ▒▒▒█▒▒ ░▓▓▒▓▓█
+ █ ▒▒░░██ █▓▒▓▓░▓░
+ █ ▓░█▓░█▒▒▒▓▓█ ▓█░█
+ ░▓▒▓▓█▒█▓▒█▓▒
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_2.txt b/codex-rs/tui2/frames/blocks/frame_2.txt
new file mode 100644
index 0000000000..1c7578c970
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_2.txt
@@ -0,0 +1,17 @@
+
+ ▒▓▒▓▒█▒▒▒██▒
+ ▒██▓█▓█░░░▒░░▒▒█░██▒
+ █░█░▒██░█░░ ░ █▒█▓░░▓░█
+ ▒░▓▒▓████▒ ▓█▒░▓░█
+ █▒ ▓█▒░▒▒▒▒▒ ▒█░▒░█
+ █▓█ ░ ░█▒█▓▒█ ▒▒░█░
+ █░██░ ▒▓░▓░▒░█ ▓ ░ ░
+ ░ ▒░ █░█░░▓█ ░█▓▓░
+ █ ▒░ ▓░▒▒▒░ ▓░█████████░▒░░█
+ ▒▒█░ ▓░░█ ▓█ ░▒▒▒▒▒▒▓▓▒▒░█▓ ░
+ ▒▒▒ █ █▒▓▓░█ ░ ███████ ░██░░
+ █▒▒▓▓█ ░ ██▓▓██
+ ▓▒▒▒░██ █▒▒█ ▒░
+ ░░▒▓▒▒ ██▓▓▒▓▓▓▒█░▒░░█
+ ░████░░▒▒▒▒░▓▓█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_20.txt b/codex-rs/tui2/frames/blocks/frame_20.txt
new file mode 100644
index 0000000000..3e0c5f0d9c
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_20.txt
@@ -0,0 +1,17 @@
+
+ ▒▒█▒░░▒█▒█▒▒
+ █▓▒ ▓█▒█▒▒▒░░▒▒█▒██
+ ██ ▒██ ░█ ░ ▒ ▒██░█▒
+ ▒░ ▒█░█ ▒██░▒▓█▒▒
+ ▒░ █░█ ▒▓ ▒░░▒█▒░░▒
+ ▓░█░█ ███▓░ ▓ █▒░░▒
+ ▓░▓█░ ██ ▓██▒ █▒░▓
+ ░▒▒▓░ ▓▓░ █ ░░ ░
+ ░▓░░▓█▒▓▒▒▒▒▒▒▒██▓▒▒▒▒█ ▓ ░▒
+ █░▒░▒ ▓░░▒▒▒▒░▒ █▒▒ ░▒▒ █▓ ░░
+ ▒█▒▒█ █ ▒█▒░░█░ ▓▒
+ █ ▒█▓█ ▒▓█▓░▓
+ ▒▒▒██░▒ █▓█░▓██
+ ▒█▓▓ ░█▒▓▓█▓ ░ ░█▓██
+ ░██░▒ ▒▒▒▒▒░█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_21.txt b/codex-rs/tui2/frames/blocks/frame_21.txt
new file mode 100644
index 0000000000..971877651f
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_21.txt
@@ -0,0 +1,17 @@
+
+ ▒▒█▒█▒▒█▒██▒▒
+ ███░░▒▒█░▒░█▓▒░▓██▒
+ ▓█▒▒██▒ ░ ░▒░██▒░██
+ ██░▓ █ ▒█▓██▓██
+ ▓█▓█░ █░▓▒▒ ▒▒▒▒█
+ ▓ ▓░ ███▒▓▓ ▒▒▒█
+ ░█░░ ▒ ▓░█▓█ ▒▓▒
+ ░▒ ▒▓ ░█ ░ ░
+ ░ ░ ██▓▓▓▓▓███ ▒░█ ░█ ▓▓ ░
+ ░ ░▒ ░▒ ▒█░ ▒ ░█░█ ▓ ▓▓
+ ▓ ▓ ░░ █░ ██▒█▓ ▓░ █
+ ██ ▓▓▒ ▒█ ▓
+ █▒ ▒▓▒ ▒▓▓██ █░
+ █▒▒ █ ██▓░░▓▓▒█ ▓░
+ ███▓█▒▒▒▒█▒▓██░
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_22.txt b/codex-rs/tui2/frames/blocks/frame_22.txt
new file mode 100644
index 0000000000..2713fd669e
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_22.txt
@@ -0,0 +1,17 @@
+
+ ▒██▒█▒▒█▒██▒
+ ▒█▓█░▓▒▓░▓▒░░▓░█▓██▒
+ █▓█▓░▒██░ ░ █▒███▒▒██
+ ▓█░██ ██░░░▒█▒
+ ▒░░▓█ █▒▓░▒░▓▓▓█░
+ ▒░█▓░ █░▓░▓▒▓░ ▒░▒▒░
+ ░██▒▓ ░█░▒█▓█ ░░▓░
+ ░░▒░░ ░▒░░▒▒ ░▒░ ░
+ ░░█ █ █░▒▒▓▓▓▒██▒▒█░▒ ▒█ ▒░▓
+ ▒░▒ █▒▒▒█ ▓█ ░▓▓░ ▒█▓▒ ░██ ▓▒▒
+ ▒▒▒▒░ ██ ░ ░▓██▒▓▓▓ █░
+ ▒█▒▒▒█ ▒██ ░██
+ █ █▓ ██▒ ▒▓██ █▒▓
+ █▓███ █░▓▒█▓▓▓▒█ ███
+ ░ ░▒▓▒▒▒▓▒▒▓▒█░
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_23.txt b/codex-rs/tui2/frames/blocks/frame_23.txt
new file mode 100644
index 0000000000..39a6c55644
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_23.txt
@@ -0,0 +1,17 @@
+
+ ▒██▒▒████▒█▒▒
+ ▒▒░█░▒▒█▒▒▒█░▒░█░█▒
+ █ █░██▓█░ ░▓█░▒▓░░█
+ ▓▓░█▓▓░ ▒▓▓▒░░▓▒
+ ▓▓░░▓█ █▓████▓█▒░▒
+ █▒░ ▓░ ▒█████▓██░░▒░█
+ ░░░ ░ ▓▓▓▓ ▒░░ ░██
+ ░▓░ ░ ░ ░█▒▒█ ░ █▓░
+ ▒ ▒ ░█░▓▒▒▒▒▒▓▒░▒█░▒ ▒▒ ░ ░░░
+ ░▒▒▒░ ▒ ▓░▒ ▒░▒▒█░ ▒▒░
+ ▓█░ ░ ░ █░▓▓▒░▒▓▒▓░
+ █░░▒░▓ █▓░▒▒▓░
+ ▒ ░██▓▒▒ ▒▓ ▓█▓█▓
+ ▒▒▒█▓██▒░▒▒▒██ ▓▒██░
+ ░ █▒▒░▒▒█▒▒██░
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_24.txt b/codex-rs/tui2/frames/blocks/frame_24.txt
new file mode 100644
index 0000000000..90ccc262f0
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_24.txt
@@ -0,0 +1,17 @@
+
+ ▒░▒▓███▒▒█▒
+ █ ▒▓ ░▒▒░▒▒██▒██
+ █ █▓▒▓█ ░ ▓░▓█░███ ▒
+ ██▓▓█▓░▒█▒░░▓░ ▒█▒░▒▒█
+ █ ▓▓▒▓█ ░ ▓▒▒░░░▒░██
+ ░█▒█▒░ ███▓ ▓░▓ ▓ ▒
+ ░ ░░ █▓▒█▓ ▓▒▒░▒▒░▒
+ ░ ▒░░ ░█▒▓▒▒░░▒▓▓░░░
+ ░▓ ░▓▓▓▓██░░░██▒██▒░ ░ ░░
+ ▒ ▓ █░▓██▓▓██░▓▒▒██░ ░█░
+ ▒ █▒░▒█ ░ ▒█▓█▒░▒▓█░
+ ▒ ▒██▒ ░ ▓▓▓
+ ▒▓█▒░░▓ ▒▒ ▒▓▓▒█
+ ▓▓██▒▒ ░░▓▒▒▓░▒▒▓░
+ █▓▒██▓▒▒▒▒▒██
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_25.txt b/codex-rs/tui2/frames/blocks/frame_25.txt
new file mode 100644
index 0000000000..d8fd5b45a8
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_25.txt
@@ -0,0 +1,17 @@
+
+ ▒█▒█▓████▒
+ █ ███░▒▓▒░█░░█
+ ▓░▓▓██ ▓░█▒▒▒░░░▒
+ ░██░ ▓ ▒░ ▒░██▒▓
+ █▒▒▒█▓█▒▓▓▒░ ░▓▓▒▓█
+ ▒█░░░▒██▓▒░▓ ▓░█░▓▓░█
+ ░▓░█░ ░▒▒▓▒▒▓░▒▓▒ ░▒░
+ ░░░▓░▓ ░▒▒▒▓░▒▒░▒░░▒
+ ▒█▒░ ░▒▒▒▒▒▒█░░▒▒░██░▒
+ ▓▓ ░▓░█░▒░░▓█▒░▒█▒▓▒░
+ ▒░█▓▒░░ ██▓░▒░▓░░
+ ░▒ ░▓█▓▒▓██▓▒▓█▓▓░▓
+ ▒░▒░▒▒▒█▓▓█▒▓▒░░▓
+ ▒▓▓▒▒▒█▒░██ █░█
+ ░█ █▒██▒█░█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_26.txt b/codex-rs/tui2/frames/blocks/frame_26.txt
new file mode 100644
index 0000000000..a4734b4486
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_26.txt
@@ -0,0 +1,17 @@
+
+ ▒▓███ ██
+ ▓█░▓▓▒░█▓░█
+ ▓█ ░▓▒░▒ ▒█
+ ▓█ █░░░▒░░▒█▓▒
+ ░▒█▒░▓░ █▒▓▓░▒▓
+ ▒ ░▓▓▓ █▒▒ ▒▒▓
+ ░ ██▒░░▓░░▓▓ █
+ ▓▓ ▒░░░▒▒▒░░▓░░
+ ░ ▓▒█▓█░█▒▒▓▒░░
+ ▓▒░▓█░▒▒██▒▒█░
+ ░░ ▓░█ ▒█▓░█▒░░
+ ▒▒░░▓▒ ▓▓ ░░░
+ █ █░▒ ▒░▓░▓█
+ ░ █▒▒ █▒██▓
+ ▒▓▓▒█░▒▒█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_27.txt b/codex-rs/tui2/frames/blocks/frame_27.txt
new file mode 100644
index 0000000000..b99e90e6d4
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_27.txt
@@ -0,0 +1,17 @@
+
+ ▓█████
+ ░▓▓▓░▓▒
+ ▓█░ █░▓█░
+ ░░░▒░░▓░░
+ ░ ░░▒▓█▒
+ ░▒▓▒ ░░░░░
+ ▒ ░░▒█░░
+ ░ ░░░░▒ ░░
+ ░▓ ▓ ░█░░░░
+ █▒ ▓ ▒░▒█░░
+ ░▓ ▒▒███▓█
+ ░░██░░▒▓░
+ ░▒▒█▒█▓░▒
+ ▒▒▒░▒▒▓▓
+ █▒ ▒▒▓
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_28.txt b/codex-rs/tui2/frames/blocks/frame_28.txt
new file mode 100644
index 0000000000..de6db173b4
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_28.txt
@@ -0,0 +1,17 @@
+
+ ▓██▓
+ ░█▒░░
+ ▒ ▓░░
+ ░▓░█░
+ ░ ░░
+ ░ ▓ ░
+ ▒░░ ▒░
+ ░▓ ░
+ ▓▒ ▒░
+ ░░▓▓░░
+ ░ ▒░
+ ░▒█▒░
+ ░▒█░░
+ █▒▒▓░
+ ░ ▓█░
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_29.txt b/codex-rs/tui2/frames/blocks/frame_29.txt
new file mode 100644
index 0000000000..d7b871c9c3
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_29.txt
@@ -0,0 +1,17 @@
+
+ ██████
+ █░█▓ █▒
+ ▒█░░ █ ░
+ ░░░░▒▒█▓
+ ▒ ░ ░ ░
+ ░█░░░ ▒▒
+ ░▒▒░░░ ▒
+ ░░▒░░
+ ░░░█░ ░
+ ▒░▒░░ ░
+ █░░▓░▒ ▒
+ ░▓░░░ ▒░
+ ░░░░░░▒░
+ ░▒░█▓ ░█
+ ░░█ ▓█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_3.txt b/codex-rs/tui2/frames/blocks/frame_3.txt
new file mode 100644
index 0000000000..833b2b3db2
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_3.txt
@@ -0,0 +1,17 @@
+
+ ▒▓▒▓██▒▒▒▒█▒
+ ▒██▓▒░░█░ ▒▒░▓▒▒░██▒
+ █▓▓█▓░█ ░ ░ ░ ███▓▒░█
+ ▓█▓▒░▓██▒ ░▒█ ░░▒
+ █▓█░▓▒▓░░█▒▒ ▒▒▒░░▒
+ ▓░▒▒▓ ▓█░▒▓▒▒ ░ ▒▒░
+ ▒█ ░ ██▒░▒ ░█ ▓█▓░█
+ █▓░█░ █▓░ ▓▒░ ░▒░▒░
+ ▓ █░ ▓░██░░█▓░▒██▒▒▒██▒░▒ ▓░
+ █▒▓▒█ ▓▓█▓▓▓░ ░█░▒▒█ ▒▓█▓▒░░▒░░
+ █▒░ ░ ░░██ ███ ███▓▓▓█▓
+ ██░ ▒█ ░ ▓▒█▒▓▓
+ ▒▒▓▓█▒█ ██▓▓ █░█
+ ▒▒██▒██▒▒▓▒▓█▓▒█▓░▒█
+ ░███▒▓░▒▒▒▒░▓▓▒
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_30.txt b/codex-rs/tui2/frames/blocks/frame_30.txt
new file mode 100644
index 0000000000..9c27cf67d0
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_30.txt
@@ -0,0 +1,17 @@
+
+ ▒▓ ████
+ ▒▓▓░░▒██▒▒
+ █▒░█▒▒░██▒
+ ░░▒░▓░▒▒░▒ ▒█
+ ▒█░░░▒░█░█ ░
+ ░█░▒█ █░░░░▓░
+ ▒▓░░░▒▒ ▒▓▒░ ▒░
+ ░ ██▒░█░ ░▓ ░
+ ░▒ ▒░▒░▒▓░█ ░
+ ░░▒░▒▒░░ ██ ░
+ ▒░░▓▒▒█░░░█░░
+ ░█▓▓█▓█▒░░ ░
+ ▒░▒░░▓█░░█░▓
+ █▒██▒▒▓░█▓█
+ ▒▓▓░▒▒▒▓█
+ ░░░░
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_31.txt b/codex-rs/tui2/frames/blocks/frame_31.txt
new file mode 100644
index 0000000000..c787451d71
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_31.txt
@@ -0,0 +1,17 @@
+
+ ▒▓▓████▒█
+ ▒██▓██▒ █▒███
+ █░▒▓▓█▒▒░▓ ░▒█▒
+ █░▓█▒▒█▓▒█▒▒░▒░░▒
+ ▒░░░░█▓█▒▒█ ▒░▓▒▒
+ ▓░▒░░▒░█ ▒▓██▓▓░█ ░
+ ▓░░ ░▒█░▒▓▒▓▓█░█░▓░
+ ▒▒█ ░░ ░▒ ░▒ ░░▒▓░
+ ░▒█▒░█▒░░░▓█░░░▒ ░
+ ░░░▓▓░░▒▒▒▒▒░▒░░ █
+ ▒█▒▓█░█ ▓███░▓░█░▒
+ ░░░▒▒▒█ ▒▒█ ░
+ ▓░█▒▒ █ ▓ ░█░▓░
+ ▓░▒░▓▒░░█░ █░░
+ █ ▒░▒██▓▓▓█
+ ░░░░
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_32.txt b/codex-rs/tui2/frames/blocks/frame_32.txt
new file mode 100644
index 0000000000..e5e7adf64d
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_32.txt
@@ -0,0 +1,17 @@
+
+ █████▓▓░█▒
+ ▓█░██░▒░░██░░█
+ ▓▒█▒▒██▒▓▓░█░█▒███
+ █▓▓░▒█░▓▓ ▓ █▒▒░██ █
+ ▓▓░█░█▒██░▓ █░█░▒▓▒█▒█
+ ▒▓▒▒█▒█░░▓░░█▒ ░█▓ █
+ █░ ▓█░█▒░░██░█▒░▓▒▓▓░█▒
+ ░░░█▒ ▒░░ ▓█░▓▓▒ ▒░ ░
+ ▒░░▓▒ █▒░ ▒▒░███░░░▒░ ▒░
+ █ ▒░░█▒█▒▒▒▒▒▒░░█░▓░▓▒
+ █▒█░░▓ ░█ ███▒▓▓▓▓▓▓
+ ▒█░▒▒▒ █▒░▓█░
+ ███░░░█▒ ▒▓▒░▓ █
+ ▒▓▒ ░█░▓▒█░▒█ ▒▓
+ ░▓▒▒▒██▓█▒
+ ░░░
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_33.txt b/codex-rs/tui2/frames/blocks/frame_33.txt
new file mode 100644
index 0000000000..31a607b29c
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_33.txt
@@ -0,0 +1,17 @@
+
+ ▒██▒█▒█▒░▓▒
+ ▒██░░▒█▒░▓░▓░█░█▓
+ ▒▓▒░████▒ ░ █▓░░█ █
+ █▒▓░▓▒░█▒ █░░▒▒█
+ ▒▓░▓░░░▓▒▒▒ ░█▒▒▒
+ ▓▓█ ▒▒▒▒░▒█ ▓▒▓▒▒
+ ░░█ ▒██░▒░▒ ░█░░
+ █░██ ███▒▓▒█ ▒ ░█
+ ░░░ ░ █░ ▓████▓▒▒█░░█▓▒░▒░
+ ▒▓░█ ▓▓█▓░░░▒▒▒▒▒░░█▒▒▒░░▓
+ ▒▒▒█ ░▓░▓ ▓ ███ ░░█▓▒░
+ ▒█▒██ █ ▓▓▓▓▒▓
+ █▒ ███▓█ ▒█░█▓█▒█
+ ▒░ █▒█░█▓█▒ ▓█▒█░█
+ ▒▒██▒▒▒▒██▓▓
+ ░░░░
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_34.txt b/codex-rs/tui2/frames/blocks/frame_34.txt
new file mode 100644
index 0000000000..db99cb73d6
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_34.txt
@@ -0,0 +1,17 @@
+
+ ▒█▒████▒░█▒
+ ▒███▓▒▓░ ░██▒██▓█▒▒
+ ▒▓▓█░█ ▓░█░ ░▒▒▒█ ███
+ █▓▒░█▒▓█▒ █░██▒▒
+ ▓▓░▒▓▓░ ░ █ ▒▒█▒▒
+ █▓▒░░▓ ▒▒ ░▒█▒ ▒█▒░▒
+ ░█▒░▒ █▒▒█░▒▒ ░▓░▒
+ ▒░▒ ▓ ░█▒░▓ ░ ▓ ▒▒
+ ██▓▓ ▓▒▓▓ ▒▒▒██████░▒▒ ░▒░
+ ░░▒█▓██▒ ▓▓█░░░▒░▓▒▒▒█▓▒░░░░▒
+ ▓▒▒█ ░▒░█▒ ██░░░░▒ █▓█▒░█
+ ▓█▒▓▒▒▒ ▓▓▓░▓█
+ ▒█░░█▒▓█ ▒█▒ ▒▓█░
+ ▓▒▓░ ░██▓██▒█▒█░██▓█
+ ░▒▓▒▒▒▒▒▒▓▒█▒▒
+ ░░░
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_35.txt b/codex-rs/tui2/frames/blocks/frame_35.txt
new file mode 100644
index 0000000000..814188563d
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_35.txt
@@ -0,0 +1,17 @@
+
+ ▒██▓▒███▒██▒
+ ██▒█▓░███ ░█░▓ ░█▒▒
+ ▒▓▓░▓██░▒█ ░ ░ █▒█▓ ░██
+ █▓▓█▓█▓█▒ ██▒▒░▒
+ ▓▓░░▓▓▒ ▒██ ░▒█░█
+ ▓▓▓▓█░ █░▒ ▓▓█▒ ░▒▒░
+ ▒ ▓▓ ▒▒ ██▒▓ ░▒▒▒
+ ░░░▓ ▓▒▒▓▓█ ▓ ▓
+ ▓ █▒ █░░▓▓ ▓░▒▒▒▓▒▒█░░ ░░▒█
+ ░█▒▓█ ▓▓▓ ██▓░▓ ▒█▒▒▒▒▓ ░▓█ ░█
+ ▓░▒██▓▒▒░▓▒░ ░ ▒▒▒▒█▒▒█▓▓▒█░
+ ▓▒▒▓░ ▒▓█ █▒
+ ▒▓░▒▓█▓█ █▓▓▒███
+ ▒▒ ░█░▓▓░░█░▓▓█ ▒▓▓
+ ▒░▓▒▒▒▓▒▒███ ▒
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_36.txt b/codex-rs/tui2/frames/blocks/frame_36.txt
new file mode 100644
index 0000000000..cde83b56f4
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_36.txt
@@ -0,0 +1,17 @@
+
+ ▒▒█▒████▒██▒
+ ▒▒ ▒█▓▓▓█▒█▓██ ███▒
+ █▒█▒███▓█ ░░ ░ █░██░██░█
+ ▒░ ██▒▒▒▒ ██░▒ ░
+ █▓▒▓▒█░▒░▒█▓ ▒▒▓█
+ ▓ █▓░ █▒ ░▓█ ▒▒█
+ ░ ▓ ░ ▒ ▒▒ ░▒░█
+ ░░▒░ ▒▒ ▒▓▓ ▒░ ░
+ ░█ ░ ▓▓ ██ ████▒█████▒ ░▒░░
+ ▒█░▒ █░▒▒▓░▓ ░░▒▒▒▒▒▒▒░░ ▒▓█░
+ █ █░▒ █▒█▓▒ ██▒▒▒▒▒ ░█ ▓
+ ██ ▒▓▓ █▓░ ▓
+ ▒▓░░█░█ ███ ▓█░
+ ██▒ ██▒▒▓░▒█░▓ ▓ █▓██
+ ░██▓░▒██▒██████
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_4.txt b/codex-rs/tui2/frames/blocks/frame_4.txt
new file mode 100644
index 0000000000..7ad27d16e7
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_4.txt
@@ -0,0 +1,17 @@
+
+ ▒▓▒▓█▒▒█▒██▒
+ ▒▓ ██░▓ ░▒▒▓█▓░ ▓██▒
+ ██▒░░░██ ░ ░▒░▒▒█░▓▒▒▒
+ ▓▓░█░ ▓██ ░██▒█▒
+ ▓░▓▒░▒░▒▓▒░█ ▒ ▒░█▒
+ ▓░░▒░ █▒░░▓█▒ █ ▒▒░█
+ ▒░▓░ ███▒█ ░█ █ ▓░
+ ░▓▒ █░▓█▒░░ ░░░
+ ▒░ ░▒ ▓░▓ ▒▓▓█░███▒▒▒▒██ ░░█
+ ░▒▓ ░ █▓▓▓█▒░░▒▒░█▓▒█▓▓▒▓░▓▓ ░
+ ░░▓█▒█▒▒█▒▓ ████████▒▓░░░░
+ █░▒ ░▒░ █▒▓▓███
+ ▒▒█▓▒ █▒ ▒▓▒██▓░▓
+ ░░░▒▒██▒▓▓▒▓██▒██▒░█░
+ █▒▒░▓░▒▒▒▒▒▓▓█░
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_5.txt b/codex-rs/tui2/frames/blocks/frame_5.txt
new file mode 100644
index 0000000000..24f9843954
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_5.txt
@@ -0,0 +1,17 @@
+
+ ▒▓▒▓▓█▒▒▒██▒
+ ▒█ █▓█▓░░█░▒█▓▒░ ██
+ █▒▓▒█░█ ░ ▒▒░█▒ ███
+ █░▓░▓░▓▒█ ▓▒░░░░▒
+ █▒▓█▓▒▒█░▒▒█ ░ ▒░▒░▒
+ ░░░░▓ ▒▒░▒▓▓░▒ █▓░░
+ ░▓░ █ ░▒▒░▒ ░█ ██░█░█
+ ░▓░▒ █▒▒░▓▒░ █░▒░
+ ░█░▒█ ▓▒░ █░█▒▒░█░▒▒▒██▒ ░▓░
+ ▒▒░▒██▓██ ░ ▓▓▒▒▒█▒▓█▓░▓█░░
+ ▒█░░█░█▒▒▓█░ ██ █░▓░▒▓
+ ▒▒█▓▒▒ ░ ▓▒▓██▒
+ ▒▓█▒░▒█▒ ▒▒████▓█
+ ▒░█░███▒▓░▒▒██▒█▒░▓█
+ ▒▓█▒█ ▒▒▒▓▒███░
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_6.txt b/codex-rs/tui2/frames/blocks/frame_6.txt
new file mode 100644
index 0000000000..fe185a7573
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_6.txt
@@ -0,0 +1,17 @@
+
+ ▒▓▒▓▓█▒▒██▒▒
+ █▒▓▓█░▒██░██▓▒███▒
+ ███░░░█ ░ ░▓▒███▓▒▒
+ ▓█░█░█▒▒█ ▒█░░░░█
+ █▒░░░█▒▒██▒ ▓▒▒░▒█
+ ▓▓▓░▓░▒█▓░▒▒░█ ▓▒▒▓░
+ ▒ █░░ ▒▒░▓▒▒ ▒█░▒░
+ ░ ░░░ ▒░▒░▓░░ ░█▒░░
+ ▒▓░▓░ ▓█░░█▓▓█▒░█░▒▒██▒▓▒▓░
+ ░░▒█▓▒▒▒▓█ ░▓▒██░░█▓▒▒▒░█░▒
+ ▓ ░ ▓░░░▓▓ █ ██ ░▒▒▓░
+ █ ▓ ▓█░ █▓▒▓▓░░
+ ▓░▒▒███ ▒█▒▒▓███
+ ░ ░██ █ ▓░▒▒████ ▓▓█
+ ▒▓▓███▒▒▒░▒███
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_7.txt b/codex-rs/tui2/frames/blocks/frame_7.txt
new file mode 100644
index 0000000000..7441f97e96
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_7.txt
@@ -0,0 +1,17 @@
+
+ ▒▓░▓██▒▒██▒
+ ██░█▒░███▒▒▒▓ ░██
+ █ █░░░█░ ░▒░░ █▓▒██
+ ▒▒░░░░▓█ ▒░▒█░▓█
+ ░█░█░░▒░▓▒█ ▓ █░░▒
+ ░ ▓░░ ░█▒▓░▒ █▓░░░
+ ░▒ ░ ▒▒░▒░▒░ ██▒░░
+ ▒ ▓░░ ▒█▓░█░░ █ ░░░
+ ▓ ░█ █ ▒▓░▒▓░░▓▓▒░░▒▓█▒░░
+ ░██░░▒▓░░▓█░▓▒░░▒▒█▒█▓▒░▒░
+ ▒ ▒▒▓█░█▒▓ ██████ ▒▓░░
+ █▒ ▓▒▓▒░ █ ▓▓▓▓█
+ █▓██▒▒▒▒ █▒░██▓██
+ ▒▒█▒░█▒▓░▒▒▒██░██▓
+ ░█ ░▓░▒▒█▒▓██
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_8.txt b/codex-rs/tui2/frames/blocks/frame_8.txt
new file mode 100644
index 0000000000..ea88b09538
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_8.txt
@@ -0,0 +1,17 @@
+
+ ▒▒█▒▓██▒██▒
+ █ █▓░░░█▒▒ ░ █
+ ▒░▒█░▓▓█ █ ░▓░█▒█▒█
+ ▒█▒█▓░██░ █ ▒▒░░▒
+ █ ▓░▓█▒░▓▒ ▓█▒░░█
+ ░██░▒▒▒▒▒░▒█ ▒█░░░
+ ░█░░░ █▒▓▒░░░ ░▒░▓░█
+ ▒█░░▓ ░█▒▓░██▓ ▓░▓░░
+ ▒ ▒░░▒▒ ▓█▒░░▓█████▒░░░
+ ▒█▓▒▒░ █░█░░▓░▒▒▒░░▒█
+ ▓▓▒▒░▒░░░▓█▒█▒█ ▒█ ▓▒░
+ ██ ░▒░░░ ▓█▓▓▓█
+ █▒▒█▒▒▒▒ ▒▓▒▒░█▓█
+ ▓▓█░██ ▓▓██▓▓▒█░░
+ ░░▒██▒░▒██▓▒░
+ ░░
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/blocks/frame_9.txt b/codex-rs/tui2/frames/blocks/frame_9.txt
new file mode 100644
index 0000000000..9066ba1bed
--- /dev/null
+++ b/codex-rs/tui2/frames/blocks/frame_9.txt
@@ -0,0 +1,17 @@
+
+ ▓▒▒█▓██▒█
+ ▓█▒▓░░█ ▒ ▒▓▒▒
+ ▓ █░░▓█▒▒▒▓ ▒▒░█
+ ░░▓▓▒▒ ▒▒█░▒▒░██
+ ▓█ ▓▒█ ░██ █▓██▓█░░
+ ░ ░░░ ▒░▒▓▒▒ ░█░█░░░
+ ░ ░█▒░██░▒▒█ ▓█▓ ░░░
+ ░ ░▓▒█▒░░░▒▓▒▒▒░ ░░
+ █░ ▓░ ░░░░█░░█░░░
+ ░▒░░░▒█░▒░▒░░░░▒▒░░░
+ ░▒▓▒▒░▓ ████░░ ▓▒░
+ ▒░░░▒█░ █▓ ▒▓░░
+ ▒█▒░▒▒ ▓▓▒▓░▓█
+ ▒▓ ▒▒░█▓█▒▓▓█░░
+ █▓▒ █▒▒░▓█▓
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_1.txt b/codex-rs/tui2/frames/codex/frame_1.txt
new file mode 100644
index 0000000000..63249f4242
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_1.txt
@@ -0,0 +1,17 @@
+
+ eoeddccddcoe
+ edoocecocedxxde ecce
+ oxcxccccee eccecxdxxxc
+ dceeccooe ocxdxo
+ eedocexeeee coxeeo
+ xc ce xcodxxo coexxo
+ cecoc cexcocxe xox
+ xxexe oooxdxc cex
+ xdxce dxxeexcoxcccccceco dc x
+ exdc edce oc xcxeeeodoooxoooox
+ eeece eeoooe eecccc eccoodeo
+ ceo co e ococex
+ eeoeece edecxecc
+ ecoee ccdddddodcceoxc
+ ecccxxxeeeoedccc
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_10.txt b/codex-rs/tui2/frames/codex/frame_10.txt
new file mode 100644
index 0000000000..fe5e51b984
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_10.txt
@@ -0,0 +1,17 @@
+
+ eccccecce
+ ccecccexoeco
+ eeoxxoxxoxceoo
+ xeeoexdeoeocceeo
+ o dxxcxe cooeoxo
+ xe cxcxooe eecx
+ e xcccxxxxc xoo
+ c xxecocxxoeeoexx
+ c xe eexdxxcecdxx
+ x oxeoxeoeceeexce
+ o cxxxxxcc eocexe
+ eecoeocc exccooo
+ xc xxxxcodooxoe
+ deccoxcde ooc
+ co eceeodc
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_11.txt b/codex-rs/tui2/frames/codex/frame_11.txt
new file mode 100644
index 0000000000..48e507a84a
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_11.txt
@@ -0,0 +1,17 @@
+
+ occcccce
+ oc dxxxeeo
+ oceexxdecoeo
+ xeexxddoedoo
+ ecodexcecdexxo
+ xcexxceddxeoxx
+ cc oxxxxxxexde
+ x xxoxxeo xcx
+ o cxoxxcocxex
+ cc exodocoxexe
+ ceo xxxxdoxeex
+ eeooxecoccdxe
+ e cxeeeexdc
+ ec cxxoeoce
+ ee cccece
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_12.txt b/codex-rs/tui2/frames/codex/frame_12.txt
new file mode 100644
index 0000000000..29de69516a
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_12.txt
@@ -0,0 +1,17 @@
+
+ ccccco
+ odeeoxoe
+ c xoeco
+ ocxxxddcx
+ x cxxxxoox
+ xcoocecexc
+ x xoexxe
+ x ocexxc
+ co xoxxcxx
+ x oxcdce
+ xo xcdcco
+ o cx eox
+ o ccxocex
+ ceocoxexe
+ e cxeoo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_13.txt b/codex-rs/tui2/frames/codex/frame_13.txt
new file mode 100644
index 0000000000..67fe336a13
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_13.txt
@@ -0,0 +1,17 @@
+
+ occco
+ xeexx
+ xeexc
+ xccxe
+ c xx
+ cdoxx
+ o xx
+ c cx
+ oc exo
+ xc cdx
+ ceoo xe
+ xeeex
+ xcoxe
+ ceexd
+ o ocd
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_14.txt b/codex-rs/tui2/frames/codex/frame_14.txt
new file mode 100644
index 0000000000..f8d32cd6d1
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_14.txt
@@ -0,0 +1,17 @@
+
+ ccccd
+ ooeeoe
+ xexxo x
+ xxoxcexo
+ xxxe x
+ xcxx cx
+ xxxx o c
+ xxexe e
+ xxxx c
+ ceoo do
+ exccooox
+ xcxxeeex
+ o cxddde
+ xeoceeo
+ ec cdo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_15.txt b/codex-rs/tui2/frames/codex/frame_15.txt
new file mode 100644
index 0000000000..2e14341237
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_15.txt
@@ -0,0 +1,17 @@
+
+ cccccxe
+ eodxxedco
+ ooxcdexccx
+ xoe ooooeex
+ xxdcdexxocex
+ exxoxxoox c
+ xx xxxxxxox
+ xxoxxcxxx cox
+ xxcoocxxxeodx
+ xexdoxexco ox
+ xoxxxxex e d
+ xccoexxeo d
+ cxeo oooe de
+ xexxeeoceo
+ eeceeeeo
+ ee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_16.txt b/codex-rs/tui2/frames/codex/frame_16.txt
new file mode 100644
index 0000000000..c90ce92cb6
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_16.txt
@@ -0,0 +1,17 @@
+
+ edcccccxe
+ oexxcxxexde
+ xooceodexx ce
+ ooo dceexexxccx
+ xxdeoccdxxcoxee
+ xxxcxc xed x xox
+ eex oeoxxxxocco x
+ xod xexxoxxxcd ex
+ eexxxcxoexxccc o
+ cceeoddecxoex oex
+ xxxcccocexdcdoxxe
+ xxc xe eooo o
+ exc x oooeox
+ exxcecxoocex
+ cdoeddeedc
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_17.txt b/codex-rs/tui2/frames/codex/frame_17.txt
new file mode 100644
index 0000000000..e1f2bb6d96
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_17.txt
@@ -0,0 +1,17 @@
+
+ odcccddxoe
+ edccxxxcdcxoceo
+ oceoeddecocxxxece
+ oxoeoxcee cxdexxxde
+ xoe x xcoedeoo o
+ edcooe odox oodoxoo
+ c dox oooxe ccxxodx
+ ocdx ooxxoxoxxddc
+ oocoeddcxeexeedexxx x
+ xcedeexoceoxxe eccce
+ eeeoccccccceexcooe ec
+ exxec eoxxe d
+ eee cee ocooeeo
+ o xccdeceedcdxc
+ ecdoeocxcecc
+ e
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_18.txt b/codex-rs/tui2/frames/codex/frame_18.txt
new file mode 100644
index 0000000000..be64251770
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_18.txt
@@ -0,0 +1,17 @@
+
+ eddcddcdxoe
+ eccedoccxeeoccdde
+ eodxcccdcocoeccooe c
+ oxxcooecc ceeeodxedeeeo
+ eeoo ox ecceeoxoxeedeee
+ oex ooxoeeeoocoxcooeoeox
+ xxedo cocoxceoccxdxdo
+ ceoxx eecxxde xdxc
+ ecc oedddddcxxoxcoeo xcxe
+ eeexcec xxoeeeexxxedxee o
+ xoxeeccccccce eeeoxocoeoe
+ ee oeo eeccocec
+ eecceeo eceeoeoe
+ cxoccccdddecceoeoc
+ cxxeoeeooccdcc
+ e
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_19.txt b/codex-rs/tui2/frames/codex/frame_19.txt
new file mode 100644
index 0000000000..8904157121
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_19.txt
@@ -0,0 +1,17 @@
+
+ eeddcxcddxoe
+ ecxxxeodddeceoxcoo
+ ocddocxcce ecdoecde
+ odxcoee eddcoexco
+ xxoeoe oxecocxe xeo
+ xeocc excxo oo cocx
+ edxxc oceoxcoe odocx
+ xxxx xdcexco x xxx
+ xcxeoddddddxxxxccdcxd e cxx
+ edooxdcoecceoeo ee deeeoooxe
+ cecocxcccccccc eeeoxoo ooc
+ eeecee eooeooc
+ c eexxco oddooxde
+ ccoxcoxceeddocc dcxc
+ cxoedoceooecoe
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_2.txt b/codex-rs/tui2/frames/codex/frame_2.txt
new file mode 100644
index 0000000000..a3c0663db4
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_2.txt
@@ -0,0 +1,17 @@
+
+ eoeddcdddcoe
+ ecoocdcxxxdxxdecxcce
+ oxcxeccxcee eccdcoxxdxo
+ exoeoccooe ooexoxo
+ oecocexeeeee eoxexo
+ cocce xcecoec eexcx
+ oxccx eoxdxexo ocxcx
+ xc ee oxcxxdc xcoox
+ cccdx dxeeexcoxccccccccoxexxc
+ edcx oxxc oc xdeeeeeooeexco x
+ eee c ceooxc ecccccccccxocxx
+ ceeooo e ocdooc
+ oeeexco odec exc
+ exedeecccdddddodceexxc
+ eccccxxeeeexdocc
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_20.txt b/codex-rs/tui2/frames/codex/frame_20.txt
new file mode 100644
index 0000000000..cea5393f75
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_20.txt
@@ -0,0 +1,17 @@
+
+ eecdxxdcdoee
+ oddcdoeodddxxeececo
+ oocecccxcc ecececcxce
+ excecxc eocxeocee
+ ex oxc eo exxecexxe
+ oeoxc cccdxco cexxe
+ dxdcx oc occe oexo
+ xeeoe ccddxco xxcx
+ xoxxdoddddddddeocdeeeec o xe
+ cxexec oeeeeeexe ceecxde oo xx
+ eoeecccccccccc eodxxox oe
+ c ecoo eocoxo
+ eeecoxe odcedcc
+ eooocxceddodcxceoocc
+ eccxe deeeexccc
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_21.txt b/codex-rs/tui2/frames/codex/frame_21.txt
new file mode 100644
index 0000000000..efa6d610d9
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_21.txt
@@ -0,0 +1,17 @@
+
+ eeodcddcdcoee
+ occeeeecxdxcdeeocce
+ dceeccece eexcceeco
+ ocxdcc eodcodco
+ oooce oxoee eeeeo
+ ocox occeoo eeeo
+ xcxe e oeooc edec
+ ee ed cxo x x
+ x x ocdddddccc exocxo do x
+ x xe xe eox ececxo ocoo
+ d co eeccc ce cceod oe o
+ cc dde ecc o
+ ce eoe eodcc oe
+ cde ccccdxxdddccc oe
+ cccdceeeeoedcce
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_22.txt b/codex-rs/tui2/frames/codex/frame_22.txt
new file mode 100644
index 0000000000..91c9c2ecaa
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_22.txt
@@ -0,0 +1,17 @@
+
+ eocdcddcdcoe
+ ecocxoeoxoexxdxcocce
+ odcdxecce ecceccceeco
+ dcxccc ooxxxece
+ exxoc oeoxdxoodcx
+ excoe oxoxdeoe exedx
+ xcceo xcxecoc xxox
+ xxdxe xexxee xexcx
+ xxoco cxddddddcceecxe eo exdc
+ exd ceeeo oocxoox ecdecxoo oed
+ eeeex cccccccce edcceooocoe
+ eceeeo ecocxoc
+ cccd cce eococceo
+ cdccoccxddcddodccccoc
+ cxcxedeeeodeodce
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_23.txt b/codex-rs/tui2/frames/codex/frame_23.txt
new file mode 100644
index 0000000000..5b5f1be139
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_23.txt
@@ -0,0 +1,17 @@
+
+ eocedccccdcee
+ edxcxeeoeddoxexcxce
+ occxcodce cxdcxedxxo
+ odxcdoe eddexxde
+ ooxeoc ooooccocexe
+ oexcoe ecccccoccxxexo
+ exxcx odoo exe c xcc
+ xox x xcxoeeo x cox
+ ece xcxddddddddxecxecee x xxx
+ xeeexcdc oee exeeox eex
+ ocx x eccccccc ceoddxeoeoe
+ oxxexo ooxeeoe
+ e xocoee eocdcoco
+ edecdccexddecccoecce
+ cx cdexeeceecce
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_24.txt b/codex-rs/tui2/frames/codex/frame_24.txt
new file mode 100644
index 0000000000..c0269d8eda
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_24.txt
@@ -0,0 +1,17 @@
+
+ exedcccddoe
+ oceocxeexddcoecc
+ occdeoccx oedcxcco e
+ ocooooxdoeexoe ecexeec
+ o ooeoo eccoeexeeexoc
+ xoecee cooo oxd oce
+ x xx ooeoocoeexeexe
+ x exx xodoeexxeooexx
+ xo xddddccxxxccecoex x xx
+ e o cxoooddooxoeeccx xcx
+ e cexeccccccce eoocexdooe
+ e eoce x codo
+ eoceexo edceodec
+ oocoeecxxddddxeeoe
+ cdeccdeeeddcc
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_25.txt b/codex-rs/tui2/frames/codex/frame_25.txt
new file mode 100644
index 0000000000..5b040665d0
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_25.txt
@@ -0,0 +1,17 @@
+
+ ecdcdcccce
+ o coceedexcxxo
+ oxoooocoxcedexxxe
+ xccx o dx cexoceo
+ oeeeoocedoexc xooeoc
+ eoxxxeccoexd oxoxooxo
+ xoxcx xeeoeeoxeoecxdx
+ xxxoxoc xedeoxeexdxxe
+ ecexcxeeddddcxxeexccxe
+ oocxoxoxexxdcexecdoex
+ excoexecccccccoxexoxe
+ xecxdcdeoocdeooooxo
+ eeexeeecdooeoexxo
+ eodeeecdxcc cxc
+ xoccecoecxc
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_26.txt b/codex-rs/tui2/frames/codex/frame_26.txt
new file mode 100644
index 0000000000..1592c09e8c
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_26.txt
@@ -0,0 +1,17 @@
+
+ edccccco
+ ocxdoexcdxo
+ occcxdexecceo
+ dccoxxxexxecoe
+ xeoexoxcceodxed
+ e cxodocceeceeo
+ x ccdxxoxxddcc
+ oo exxxeedxxoxx
+ x oecdcxcddoexx
+ oexooxeeoceecx
+ xecoxcceooecexx
+ eexxoe oocxxe
+ c cxe eeoxoo
+ xcceecceccd
+ eodecxeec
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_27.txt b/codex-rs/tui2/frames/codex/frame_27.txt
new file mode 100644
index 0000000000..5279157c04
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_27.txt
@@ -0,0 +1,17 @@
+
+ dcccco
+ xddoxoe
+ dce cxocx
+ xxxexxdxx
+ x exeocd
+ xeoecexxxe
+ d cxxecxx
+ x exxxdcxx
+ xo o xcxxxx
+ cd ocexecxx
+ xo eecccoc
+ xxccxxeox
+ xddcdooxe
+ eeexedoo
+ cec eeo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_28.txt b/codex-rs/tui2/frames/codex/frame_28.txt
new file mode 100644
index 0000000000..ea695865f4
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_28.txt
@@ -0,0 +1,17 @@
+
+ occd
+ xcexe
+ d dxe
+ xoecx
+ x xx
+ x ocx
+ exx ex
+ xoccx
+ oe ex
+ xxodxx
+ x ex
+ xdcdx
+ xdcxx
+ ceeox
+ x ocx
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_29.txt b/codex-rs/tui2/frames/codex/frame_29.txt
new file mode 100644
index 0000000000..328d426a41
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_29.txt
@@ -0,0 +1,17 @@
+
+ ccccco
+ oxco ce
+ eoxx ccx
+ xxxxeeoo
+ e xcx x
+ xoxxx ee
+ xeexxx e
+ xxdxx
+ xxxcx e
+ exdxx e
+ cxxoxe d
+ xoxxx ex
+ xxxxexex
+ xdxcocxc
+ xxc oo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_3.txt b/codex-rs/tui2/frames/codex/frame_3.txt
new file mode 100644
index 0000000000..3e9206577a
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_3.txt
@@ -0,0 +1,17 @@
+
+ eoddccddddoe
+ ecooexxcxcddxdeexcce
+ odocdxccce ecx cccoexo
+ ocoexdoce edc xxe
+ cocxoeoxxcee eeexxe
+ oxeeo ooxedee x eex
+ dc x ccexecxo ocoxo
+ ooxox ooxcoex xexdx
+ occx dxccxxcoxdcceeeccexecdx
+ oedeo oocoddx xcxeeo doodeexexe
+ cex x cxxcoc cccccccccoooooo
+ ccx ec e oeceoo
+ deooceo ocdocoxc
+ decoecceddddoddcdeecc
+ ecccedxeeeexdoec
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_30.txt b/codex-rs/tui2/frames/codex/frame_30.txt
new file mode 100644
index 0000000000..b9da98c5c3
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_30.txt
@@ -0,0 +1,17 @@
+
+ edcccco
+ eodxxeccde
+ ccexoeexcoe
+ xxexoxeexe eo
+ dcxxeexoxo x
+ xcxec cxxxxox
+ eoxxxee eoex de
+ cx ccdxoxcxo e
+ cxecexdxeoxo e
+ cxxexeexx co e
+ exxdeecxxxcxx
+ xcoooocexxc x
+ exexxocxxoxo
+ oeocdeoxooc
+ eooxeeedc
+ eeee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_31.txt b/codex-rs/tui2/frames/codex/frame_31.txt
new file mode 100644
index 0000000000..baef07474c
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_31.txt
@@ -0,0 +1,17 @@
+
+ eodccccdo
+ eccdcoeccecco
+ oxeooodeeocxece
+ oxoceecdeoeexexxe
+ exxxxcoceeocexoee
+ dxeexexccedcoooxocx
+ oxx xecxeododcxcxox
+ eeo xxcxe xeccxxeox
+ xeoexcexxxocxxxe x
+ cxxxooxxeeeeexexx c
+ eceocxo occceoxcxe
+ xxxeeeo edc x
+ dxcde o o xceoe
+ dxexoexeoxcoxe
+ ccdxeccoodc
+ eeee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_32.txt b/codex-rs/tui2/frames/codex/frame_32.txt
new file mode 100644
index 0000000000..c0997d9a14
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_32.txt
@@ -0,0 +1,17 @@
+
+ occccddxoe
+ dcxccxexxccxxo
+ oecdeocedoecxcecco
+ cooxeoedo o oeexco o
+ ooxoxceccxd ceoxeoeceo
+ eoeeoecxedxxce xco c
+ cxcdoecexxooxodeoeooxce
+ xxxoe cexxcocxdoecexcce
+ exxoe cexceexcccxxxdxcde
+ ccceexceceeeeeexxcxdxoe
+ oecxxo xccccccedooooo
+ eoxeee oexocx
+ cccxxxce eoexo o
+ eoecxcxddceecceo
+ xddeeococecc
+ eee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_33.txt b/codex-rs/tui2/frames/codex/frame_33.txt
new file mode 100644
index 0000000000..cd8691c150
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_33.txt
@@ -0,0 +1,17 @@
+
+ eocdcdcdxoe
+ eccxxecdxdxoxcxco
+ eoexcccodce ccoxxcco
+ oeoxoexoe cxxeec
+ eoxoexxoeee xceee
+ ooo eeeeeeo oeoee
+ xxc eocxexe xcxx
+ cxoo occeodo ecxc
+ xxx x oe ocooodddcxxcoexex
+ eoxccodooexxeeeeexxceeexxo
+ edeo xoxo o ccccccc xxooee
+ ececoco oododo
+ ceccocdo ecxoocec
+ exccecxodcecdoecxc
+ cddcoeeeeccdoc
+ eeee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_34.txt b/codex-rs/tui2/frames/codex/frame_34.txt
new file mode 100644
index 0000000000..ef8eabf7dc
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_34.txt
@@ -0,0 +1,17 @@
+
+ eodccccdxoe
+ ecccoedxcxccdccdode
+ eoooxccdxce eeeeoccco
+ ooexceooe cxocee
+ ooxeoox xc o eecee
+ ooexeo eecxece eoexe
+ xcexe ceecxee xdxe
+ exdcd xcexocx o ee
+ ocooc oeooceddccccccxeec xee
+ xxeooooecoocxxxexoeeeooexxexe
+ oeeo xexce ccceeeee oooexc
+ ooeddee odoxoc
+ ecexcedo ecdceooe
+ oeoxcxcodocdcdceccdc
+ cxeddeeeeeddcde
+ eee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_35.txt b/codex-rs/tui2/frames/codex/frame_35.txt
new file mode 100644
index 0000000000..1c53d2373f
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_35.txt
@@ -0,0 +1,17 @@
+
+ eocddcccdcoe
+ ocdcoxccccxcxdcxcde
+ eooxdccxecce eccdcocxco
+ ooocoodoe cceexe
+ ooxxooe ceco xecxo
+ dodoce cxecooce xeex
+ e oo ee cceo xeee
+ xxxd oeedoc o co
+ o oe oxxodcoxddededcxx xxdc
+ xoedc oodcccoxd eoeeeeocxoc xc
+ oeeocoeexoee eceeeeceecooeox
+ coeeox eoc oe
+ edeedodo odoeccc
+ ceecxcxodxxcxdocceodc
+ cexddeeoeecccce
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_36.txt b/codex-rs/tui2/frames/codex/frame_36.txt
new file mode 100644
index 0000000000..4928a2a9d0
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_36.txt
@@ -0,0 +1,17 @@
+
+ eecdccccdcoe
+ edccecodocecdcccccce
+ oeceoccoccee eccxccxocxo
+ exccceeee ccxecx
+ ooedecxeeeoo eeoc
+ o ooe ce cxoo ceec
+ x d e e cee xexo
+ xxex ee eoo ex x
+ xccx oo occcocceccccce xexx
+ ecxe oxeeoxo exeeeeeeexx eoce
+ c cxe cecoe ccceeeeec xoco
+ cocedo ooxco
+ eoxxcxo occcooe
+ coecccdedxecxdcocodcc
+ eccoxeooeooccccc
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_4.txt b/codex-rs/tui2/frames/codex/frame_4.txt
new file mode 100644
index 0000000000..a5ae50eeae
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_4.txt
@@ -0,0 +1,17 @@
+
+ eoddcddcdcoe
+ eocccxo xedocdxcocoe
+ ocdxxxccce eexeecxoeee
+ ooxoxcoco cxccece
+ oxoexdxedexo ecexce
+ oxxex cexxoce c edxo
+ cexde ccceccxo o cdx
+ xoe oxocexx xxx
+ ex xe dxoceoocxccceeeeoo xxc
+ xeo x oooooexedexooeodoedxoocx
+ exdceoeeoeo ccccccccceoxxxe
+ oxecxee oedoccc
+ eeode oe eoeocdxo
+ xxxdecceddddocdccexce
+ ceexdxeeeeedoce
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_5.txt b/codex-rs/tui2/frames/codex/frame_5.txt
new file mode 100644
index 0000000000..47abf7a0af
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_5.txt
@@ -0,0 +1,17 @@
+
+ eodddcdddcoe
+ ecccocoxxcxdcdexcco
+ ceoecxcce cedxce oco
+ oxoxoxodo oexxxxe
+ oeocoeecxeeo e exexe
+ xxxxo eexedoxe coxx
+ xox c eeexecxo ccxcxo
+ xoxec oedxoex cxex
+ xoxec oexcoxcdexcxeeecoecxox
+ eexeoooccc xc ooedeodoooxocxe
+ eoxxoxoeeoce ccccccccoxdxeo
+ eecoee e oeocoe
+ eocexdce edcoccdc
+ excxoccedxdeocdcexdc
+ eocecceeeoeocce
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_6.txt b/codex-rs/tui2/frames/codex/frame_6.txt
new file mode 100644
index 0000000000..ba04c52772
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_6.txt
@@ -0,0 +1,17 @@
+
+ eodddcddccee
+ oedocxdccxccdeocce
+ oooxxxcc ecxodcccoee
+ ooxcxcedo ecxxxxo
+ cdxxxceecce oeexeo
+ dooxoeecdxeexo odeox
+ e cxx eexoee ecxex
+ x xxx exdxoxx xcexx
+ eoxox ocxxcdocexcxeecceoeox
+ xxeooeeedc xodcoxxodddexoxe
+ o x oxxxdoc cccccccceeeox
+ o d ooe odeooxe
+ oeeecco eceeococ
+ ecxcocc dxeeoccc ddc
+ eodccoeeeeeocc
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_7.txt b/codex-rs/tui2/frames/codex/frame_7.txt
new file mode 100644
index 0000000000..f7dd0de9b6
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_7.txt
@@ -0,0 +1,17 @@
+
+ eoxdccddcoe
+ ocecexcccdded eco
+ c oxxxce eexe coeco
+ eexxxxdc execxoo
+ ecxcxxexoeo o cxxe
+ x dxxc ecedxe ooxxx
+ eecx eexexex ccexx
+ ecoxx dcoxcxe c xxx
+ ocxc oceoxeoxxddexxddcexx
+ xocxxddxxocxoexxeeododexex
+ e deocxceo cccccccceoxx
+ ce oeoee ocoodoc
+ cdoceeee oexococc
+ eecexcedxeeeccxcco
+ cxccxdxeeoedcc
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_8.txt b/codex-rs/tui2/frames/codex/frame_8.txt
new file mode 100644
index 0000000000..e3f93702f7
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_8.txt
@@ -0,0 +1,17 @@
+
+ eecedccdcoe
+ occoxxxcdd x cc
+ exdoxooc ocxoxceceo
+ ececoxocx c dexxe
+ c oxooexoe ocexxo
+ xcoxeeeeexec ecxxx
+ xcxxx cedexex xexoxo
+ eoxxo xceoxoco oeoxx
+ e exxee ocdxxococooexxx
+ ecodexcoxoxxdxdeexxdc
+ ooeexexxxocececceccoex
+ cocxexee oooooc
+ ceeceeee eoeexcoc
+ odcxoc ddccdodoxe
+ xxeccexeocode
+ ee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/codex/frame_9.txt b/codex-rs/tui2/frames/codex/frame_9.txt
new file mode 100644
index 0000000000..210e417d43
--- /dev/null
+++ b/codex-rs/tui2/frames/codex/frame_9.txt
@@ -0,0 +1,17 @@
+
+ odecoccdo
+ oceoxxccd eoee
+ o oxxoceedo eexo
+ c xxodde eeoxeexco
+ occdeccxco coccdcxx
+ x xxxcexedee xcxcxxx
+ e xcexccxeeocooo exx
+ x xoeoexxxeodeex xx
+ coxc oxcxxxxcxxoxxe
+ xexxxeoxexexxxxeexxx
+ c eeoeexocccccxxcoex
+ exxxeoe oo eoxe
+ ecexee odedxoc
+ eoceexcocdddcxe
+ coe ceexdcoc
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_1.txt b/codex-rs/tui2/frames/default/frame_1.txt
new file mode 100644
index 0000000000..64a140d2b9
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_1.txt
@@ -0,0 +1,17 @@
+                                      
+             _._:=++==+,_             
+         _=,/*\+/+\=||=_ _"+_         
+       ,|*|+**"^`   `"*`"~=~||+       
+      ;*_\*',,_            /*|;|,     
+     \^;/'^|\`\\            ".|\\,    
+    ~* +`  |*/;||,           '.\||,   
+   +^"-*    '\|*/"|_          ! |/|   
+   ||_|`     ,//|;|*            "`|   
+   |=~'`    ;||^\|".~++++++_+, =" |   
+    _~;*  _;+` /* |"|___.:,,,|/,/,|   
+    \^_"^ ^\,./`   `^*''* ^*"/,;_/    
+     *^, ", `              ,'/*_|     
+       ^\,`\+_          _=_+|_+"      
+         ^*,\_!*+:;=;;.=*+_,|*        
+           `*"*|~~___,_;+*"           
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_10.txt b/codex-rs/tui2/frames/default/frame_10.txt
new file mode 100644
index 0000000000..9d45417346
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_10.txt
@@ -0,0 +1,17 @@
+                                      
+              _+***\++_               
+             *'`+*+\~/_*,             
+            ^_,||/~~-~+\,,            
+           |__/\|;_.\,''\\,           
+           / ;||"|^  /_/|/           
+          |` '|*~//\   `_"|           
+          \  ~*"*||~|*   |/,          
+          "  ||\+/+||-_ .\||          
+          "  ~\ \\|;~~+\+;||          
+          |  ,|\,|_/_*___|*`          
+           , "|||||""!\,"\|`          
+           \`',\,*"  "",//           
+            |' |||~*,:,/|/`           
+             ;`**/|+;_!//'            
+              *, _*\_,;*              
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_11.txt b/codex-rs/tui2/frames/default/frame_11.txt
new file mode 100644
index 0000000000..769e5ae76d
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_11.txt
@@ -0,0 +1,17 @@
+                                      
+               ,****++_               
+              /" ;|||\\,              
+             /"__||;\*/\,             
+             |__||=;,_=//             
+            _".;\|+\';_||,            
+            |+`||+_;;|_/||            
+            ** ,||||||_|=\            
+            |  ||/||\/ |"|            
+            /  '|/||*/+|_|            
+            ** _|/=,"/|_|^            
+            '`- ||||=/|\\|            
+             \_-/|_*/**;|`            
+             !_ *|\\^_|;"             
+              \+!*||,_/*`             
+               \_ '*+_+`              
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_12.txt b/codex-rs/tui2/frames/default/frame_12.txt
new file mode 100644
index 0000000000..50cfd73302
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_12.txt
@@ -0,0 +1,17 @@
+                                      
+                +***+.                
+               ,=`_/|,\               
+               "  |/\+,               
+               /+~||=="|              
+              | '~|||./|              
+              |'..*^"_|"              
+              |   ~/\||\              
+              |   /+\||"              
+              *, ~/||+|~              
+              |   /|*;*_              
+              |.  |"=**/              
+               ,  *|!_,|              
+               / **|,*\|              
+               '^/",|\|`              
+                \ '~\./               
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_13.txt b/codex-rs/tui2/frames/default/frame_13.txt
new file mode 100644
index 0000000000..04ed71335c
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_13.txt
@@ -0,0 +1,17 @@
+                                      
+                 /***,                
+                 |__||                
+                 |`_|"                
+                 |**|_                
+                 *  ||                
+                 ":-||                
+                 ,  ||                
+                 +  "|                
+                /+  _~.               
+                |"  +=|               
+                '`.. ~`               
+                 |___|                
+                 |+,|_                
+                 *__|=                
+                 , ."=                
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_14.txt b/codex-rs/tui2/frames/default/frame_14.txt
new file mode 100644
index 0000000000..66e91f7187
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_14.txt
@@ -0,0 +1,17 @@
+                                      
+                 +***;                
+                 ,/__.\               
+                |_||. |               
+                ||/|"^~,              
+                |||\   |              
+                ~*||  '|              
+                |||| . *              
+                ||\|`  \              
+                |||~   "              
+                "^//  ;/              
+                \|"",.,|              
+                |*~|___|              
+                /!"|===`              
+                |\/*__/               
+                 _* '=/               
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_15.txt b/codex-rs/tui2/frames/default/frame_15.txt
new file mode 100644
index 0000000000..9d8132e3c4
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_15.txt
@@ -0,0 +1,17 @@
+                                      
+                 ++***~_              
+                `,=||^:*,             
+               //|*=\|"*|             
+               |/` //,.__|            
+              ||="=\||/"^|            
+              \||-||//|  "            
+              ||   ||||~~,|           
+              ||/~|+||| '-|           
+              ||+,,*|||_.:|           
+              |_|;/|\~*. .|           
+              |/||||_| ` ;            
+              |**.^~|\-  =            
+              '|\, ///` ;`            
+               |^||\\.+\/             
+                \^*^___/              
+                   ``                 
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_16.txt b/codex-rs/tui2/frames/default/frame_16.txt
new file mode 100644
index 0000000000..7217fe58b8
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_16.txt
@@ -0,0 +1,17 @@
+                                      
+                _=+"**+~_             
+               /^||*||\|=\            
+              |//"\/=\|| '\           
+             /// ;' \|\||**|          
+             ||;_ =||*/|`\          
+            |||*|  /|= !| ~.|         
+            \\|  ,||||/*", |         
+            |/; |`||/|||"; `|         
+            \\|~|+~/^||"*+  /         
+            *"__,==\*|._| ,_|         
+            |||+""/*\|;";.~|`         
+             ||* |   `//,  /          
+             \|*  |  /,/_,|           
+              \|~"_*~//+_|            
+               ':._=:__;*             
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_17.txt b/codex-rs/tui2/frames/default/frame_17.txt
new file mode 100644
index 0000000000..0d873df751
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_17.txt
@@ -0,0 +1,17 @@
+                                      
+                ,=+++;;~,_            
+             _;**|~~*=*|,"^,          
+            ,*\/_==`+,"|||_"\         
+           /|/_/|"   |;\~||=\        
+           |/_ ~     "/\=\//  ,       
+          `=*,/`   ,:/| /,=/|./       
+          *!;/|   ,//|_ *"||/=|       
+          -"=|!   !//||/ ,||=;*       
+          ,/*/\==+~\_|\^:\||| |       
+           |"_;__|/*\/||\!\+'+\       
+          \\\/"""****\_|*//\ \'       
+           \||_*       `/||` ;        
+            _\\!*\_   ,',/^_/         
+             , ~*+=\+`_;*:|'          
+              `+;/_,+~*_+*            
+                   `                  
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_18.txt b/codex-rs/tui2/frames/default/frame_18.txt
new file mode 100644
index 0000000000..a474a4f3d0
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_18.txt
@@ -0,0 +1,17 @@
+                                      
+               _==+==+;~,_            
+            _+"_;,++~__,"+;;_         
+          _/:|*"*=" "._"+//\ *        
+         ,||*.,^" _/=~\;\\\,      
+        _\// /|   _\/~/|_\;\\_      
+        /\| ,, _/,*,|'-/^/`/~!     
+        ||\:/     +/*/|"_/"*|=|=,     
+        "\-~|     ^\"||;^   |;|"      
+       \"" ,\==;=;+~|,|*/\, |*|`      
+        _\\|*\* ~|/__\_~||_;~`\ ,     
+        |/|\`""*****` \__/|/*/`-`     
+         \\!,\,         ``*"/*_'      
+          \^*+^^.      _*^_/\,`       
+           '|.**++===^'*_/_,*         
+             "~|_/__,.+";+"           
+                    `                 
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_19.txt b/codex-rs/tui2/frames/default/frame_19.txt
new file mode 100644
index 0000000000..e83b78bd3b
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_19.txt
@@ -0,0 +1,17 @@
+                                      
+              __==+~+==~._            
+           _+|||\/===_*_,|*,,         
+         ,*;;/"|+*`    `*:,`*;\       
+        /;|*,^`         _==+,^|*,     
+       ||/`/`         ,|^"/"|\ |\,    
+      |\/*'         _|*~/!./ '.*|     
+      ^=|~'        /*^/|+,`   /:/+|   
+      ||||         |;"\|",    | |||   
+      |*|\,=;;===~~~|+*;*|;   \ "||   
+      ^;/,|=*/^*+\,`, ^_ :\_\,/.|_    
+      '\"/+|"""""**"   ^\_/|// //'    
+       \\^*_\             `//_//'     
+        '!_\~~*,        ,;=./|;`      
+          '".|*/~+__=;/*" ;*~'        
+             "~._:-'_,.^*-^           
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_2.txt b/codex-rs/tui2/frames/default/frame_2.txt
new file mode 100644
index 0000000000..ac205dd4a5
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_2.txt
@@ -0,0 +1,17 @@
+                                      
+             _._:=+===+,_             
+         _+,/*;+||~=~|=_'|*+_         
+       ,|*|\**~*``  `"*=*/||;|,       
+     _|/_/*',,_           -,\|/|,     
+     ,^"/*^|\_\\_           ^,|\|,    
+    '/+"`  |*\+/\+           \\|*|    
+   ,|'*|    ^/|;|_|,          /"|"|   
+   |" \`     ,|*||;*          |'/.|   
+   *""=|    ;|^^_|".~++++++++,|_|~*   
+    _='|  /||' /* |=\____..__|+/!|!   
+    \\\ * *\..|'   `"*******"|,*||    
+     '\_./, `              ,+;/,*     
+       .\__|+,          ,=_+!_|"      
+        `~^;__"*+:;=;;.=*`_||*        
+           `*+*+~~____~;/*"           
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_20.txt b/codex-rs/tui2/frames/default/frame_20.txt
new file mode 100644
index 0000000000..bff8cc065f
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_20.txt
@@ -0,0 +1,17 @@
+                                      
+              __+=~~=+=,__            
+          ,;=";,_,===||_^*\+,         
+        ,,"_+*"~*"    `"^"\+*|+_      
+      _|"_*|*           _,+|\/*\\     
+     _| ,|*           _/!_||^*\||\    
+     /`,|'           +*';|"/  '\~|\   
+    ;|;+|          ,* .+*^     ,\|/   
+    |_^/`          "";:|",     |~"|   
+    |/||;,=;======_,';^^\\*    / |\   
+    '|^|_" /``____|\  *\\"|=\ ,/ ||   
+     \,^\'"""""""*"     \,=||,| /\    
+      * ^*/,               _/*.|/     
+        \_^*,~_          ,;*`;*'      
+          ^,-."~+^;;,:"~"`,/*'        
+            `*+~_!=____|*""           
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_21.txt b/codex-rs/tui2/frames/default/frame_21.txt
new file mode 100644
index 0000000000..b23aadbc7c
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_21.txt
@@ -0,0 +1,17 @@
+                                      
+             __,=+==+=+,__            
+          ,+*``__+~=~+;_`-*+_         
+        ;*^_+*^"`     `^~*+_`*,       
+      ,*|;"'             _,;*,;*,     
+     /,/*`             ,|/_\ \\_^,    
+    /"/|             ,**_//    \\^,   
+    |'|`           _!/`,/'     \;\"   
+     `\            \; "|,       | |   
+    | |  ,+;;;;;+++  ^|,"|,    ;/ |   
+    | ~\ |_      _,|   ^"`*|,  /"./   
+     ; ". ``"""  '`     '*_,; /` ,    
+     '+ :;_                 _*" /     
+       *_  ^-_          _.;*' ,`      
+         *=_ *"*+:~~;:=*""  -`        
+            *++;+____,_;+*`           
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_22.txt b/codex-rs/tui2/frames/default/frame_22.txt
new file mode 100644
index 0000000000..ccc8480d8b
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_22.txt
@@ -0,0 +1,17 @@
+                                      
+             _,+=+==+=+,_             
+         _+/*|._/|/\||;|+/*+_         
+       ,;*;~\**`    `"*\**+__+,       
+      ;*~**"            ,,|||_*\      
+     \|~/'            ,_/|=|./;'|     
+    \|*/`           ,~/|;^/` \|\=|    
+   |+*\/           ~+|\*/'    ~|/|    
+   ||=|`           |\|~^\     |^|"|   
+   ||,", +~==;;;=++_\*|_!\,   _|;"!   
+   ^|= *_\\,!/,"~//|  \*;_"|,,!/\=    
+    \\\_| """""**"`    `:*+_///",`    
+     \*\_\,               _*,"|,'     
+      '"+; ++_         _.*,"*_/       
+        ':*+,"*~;=+;;/=*""',*         
+           "~"~_;___-=_.=*`           
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_23.txt b/codex-rs/tui2/frames/default/frame_23.txt
new file mode 100644
index 0000000000..406ced01b0
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_23.txt
@@ -0,0 +1,17 @@
+                                      
+            _,+_=+*++=+__             
+         _=|+|\_,_==,|_|*|+_          
+       ,"+|',;*`    "~:+|\;||,        
+      /;|*;/`          _;;\||;\       
+     //|`/'          ,/,,'*/*\|\      
+    ,\|"/`         _***''/*'|~\|,     
+    `||"|         /:/. _|`  "!|'*     
+    ~/| |         |"|,_\,   | */|     
+    ^"\ |+~;=====;=|_*|_"\_ | |~|     
+    |\\_|"="       /`\ \|_\,~ \_|     
+     /'| | `"""""""   '`/;=|_/^/`     
+      ,||_|.             ,/|\^/`      
+       \ |,'/__       _.";*/+/        
+         \=\+;*+\~==_++"-_+*`         
+           "~!*=\~__+__**`            
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_24.txt b/codex-rs/tui2/frames/default/frame_24.txt
new file mode 100644
index 0000000000..73f5639390
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_24.txt
@@ -0,0 +1,17 @@
+                                      
+             _~_;++*==,_              
+          ,"_/"|__~==+,_'+            
+        ,"';\/+"~ .`:*~**, \          
+       ,'//,/|=,\`~/`!_*\|\_'         
+      , //\/,    `""/\_|``\|,'        
+      ~,\+\`       *,,/!.|;!/"\       
+     |  |~!      ,/_,/"/^\|\^|^       
+     | \||       |,=/\_|~_/.`||       
+     |. |;;;:++~~~++_*,_| |  ||       
+      _ / !*|/,,;;,,|.^\+*| |*|       
+      \ '\|\*""""""` \,.*\|=/,`       
+       \ \,*\           |!"/;/        
+        \.*\`|.      _="_/:_*         
+          .-*,\^"~~:==;|^_/`          
+            *:_*+;\__==+*             
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_25.txt b/codex-rs/tui2/frames/default/frame_25.txt
new file mode 100644
index 0000000000..6fb0cbc16c
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_25.txt
@@ -0,0 +1,17 @@
+                                      
+             _+=*;++++_               
+           ,!*,*`_;\|*||,             
+          /|//,,".|+\=\|||_           
+         |+*| /! =| "\|,*\/           
+        ,__\,/'^;/_|" |//\/*          
+        \,~|~_*+.^|: /|,|//|,         
+        |/|*| |__/\_/|\/_"|=|         
+        |||/|."!~_=\/|\_~=||\         
+       ^+\|"|__====+~|\\|+*|\         
+        /-"|/|,|_||;*_|\*=/\|         
+        \~*/\|`"""""'+/|\|/|`         
+         |_"|;+;\-,*:_/,//|/          
+          ^`^|_\_*;/,^/_||/           
+           \.;\\_*=|**!*|*            
+             ~,"*\+,_+|*              
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_26.txt b/codex-rs/tui2/frames/default/frame_26.txt
new file mode 100644
index 0000000000..8bd6052839
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_26.txt
@@ -0,0 +1,17 @@
+                                      
+              _;***"+,                
+             /*|;/\|+;|,              
+            /*""|;\|\""\,             
+           ;*",||~_||_+/^             
+           |_,\|.~"*\/;|\;            
+           \ "|/:/"*_\"\\/            
+          |!  *'=||/||;;"+            
+          /-  \|||^^=||/||            
+          |  .\*;+~+==/\||            
+          ! ._|/,|__,*\\*|            
+           |`"/|*"\,/`+\||            
+           \_~|/\   //"||`            
+            *  *|\ ^`/|/,             
+             |"*\\"*_**;              
+              \/:^*~_\*               
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_27.txt b/codex-rs/tui2/frames/default/frame_27.txt
new file mode 100644
index 0000000000..e8630695b8
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_27.txt
@@ -0,0 +1,17 @@
+                                      
+                ;***+,                
+               |;:/|/\                
+              ;'` *|/'|               
+              |~~^||;|~               
+              |  `|_-'=               
+              ~_._"`|||`              
+              = "||_*||!              
+             |  `||~="||              
+             |. .!|+||||              
+             '= ."_|_*||              
+              |- _^**+/'              
+              ||++||_/|               
+              |==+=,/|^               
+               \__|\=//               
+               '\" ^\/                
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_28.txt b/codex-rs/tui2/frames/default/frame_28.txt
new file mode 100644
index 0000000000..3313d8b9bf
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_28.txt
@@ -0,0 +1,17 @@
+                                      
+                 /**;                 
+                 |+_|`                
+                 = ;|`                
+                 |-`*|                
+                 |  ~|                
+                 | -"|                
+                ^|~ _|                
+                 |-""|                
+                /\  _|                
+                ||.:~|                
+                 |  _|                
+                 |=+=|                
+                 |=*||                
+                 *__/|                
+                 ~ .+|                
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_29.txt b/codex-rs/tui2/frames/default/frame_29.txt
new file mode 100644
index 0000000000..2ae088f1b9
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_29.txt
@@ -0,0 +1,17 @@
+                                      
+                 +****,               
+                ,|*/!*\               
+                ^,|| '"|              
+                ||||^\,/              
+                \ ~"|  |              
+                |,~|| __              
+                |\\||| ^              
+                ||=~|                 
+                ||~*|   `             
+                _|=||   `             
+                *||/|^ =              
+                |/~~| _|              
+                ~|||`~_|              
+                |=|*/"|'              
+                 ~|* .,               
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_3.txt b/codex-rs/tui2/frames/default/frame_3.txt
new file mode 100644
index 0000000000..727e25a8e8
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_3.txt
@@ -0,0 +1,17 @@
+                                      
+             _.=;++====,_             
+         _+,/\||+|"==|;_^|*+_         
+       ,;/*;|*""`   `"~!**+/^|,       
+      /+/\|;,+_          `=*!||\      
+     '/*|/^/||*\_           \^\||_    
+    /|\\/  .,|\;\\           | \\|    
+    =* |    '*\|_"|,          .*/|,   
+   ,-|,|     ,-|"/\|          ~_|=|   
+    -"'|    ;|*+~|*-~=++___++_~^";|   
+    ,\:\, ./*/;;| |*|__,!=.,;\`|\|`   
+    '^| | "||+,"   "***"""**,///,/    
+     '*~ \+ `              /^+^//     
+       =^//*\,          ,+;/",|'      
+         =^+,_**^=;=;,:=*;`_+"        
+           `*+*_:~____~;/^"           
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_30.txt b/codex-rs/tui2/frames/default/frame_30.txt
new file mode 100644
index 0000000000..99eeebce33
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_30.txt
@@ -0,0 +1,17 @@
+                                      
+                 _;"**+,              
+               _/;||\*'=\             
+               "'^|,\\|+,\            
+              ||\|/|_\|\ \,           
+              =*||`\|,|,  |           
+             |*|^+  *||||.|           
+             \/|||\_ \/\| =`          
+             "| '+=~,|"|-  `          
+             "|_"\~=~\/|,  `          
+             "||\|__~|!+,  `          
+             !\||;\_*~||+~|           
+              |*//,/*\||" |           
+              \|\||/*~|,~/            
+               ,^,+=^/|,/'            
+                \-.|^__;'             
+                  ````                
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_31.txt b/codex-rs/tui2/frames/default/frame_31.txt
new file mode 100644
index 0000000000..8d9adf28b2
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_31.txt
@@ -0,0 +1,17 @@
+                                      
+                _.:*+*+=,             
+              _+*;+,_"+\'*,           
+             ,|\//,=_`."|_*\          
+            ,~/+__*;_,\\|\~|\         
+            ^||||+-*\_,"\|/__         
+           ;|^`~_|'"\;*,./|,"|        
+           /|| |^*|\.=/;*|*|/|        
+           \\, |~"|\ |^""|~\.|        
+           |\,_|'^~|~/+~~|_  |        
+           "||~//||___\_|\|| *        
+           ^*_/+|, /***`/|'~_!        
+            |||\\\,     _=* |         
+             ;|*=_!,  . |*`/`         
+              :|\|/_|`,|",|`          
+               '"=~_+*/.;*            
+                   ````               
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_32.txt b/codex-rs/tui2/frames/default/frame_32.txt
new file mode 100644
index 0000000000..4175a7a66e
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_32.txt
@@ -0,0 +1,17 @@
+                                      
+                ,++++;;~,_            
+              ;*~**~\||**|~,          
+            /^*=^,+^:-`*|*\'*,        
+           '//|_,`;- - ,_\|+,!,       
+          //|,|*\'*|; '`,~\/\*\,      
+          \/\\,\*|`:||+_   |+/ *      
+         *|";,`'\||,,|,=`/_//|'_      
+         |||,_  "_||"/'|;-_"\|""`     
+         \||-_ '_|"__|+++~~~=|"=`     
+         '""_`|*\'\_____||*|;~-_      
+           ,\*||/ |*""***^;///./      
+           \,|^\\        ,\|/'~       
+           '**||~+_    _/_|/ ,        
+             \-\"~+|;=*`_+"_/         
+               ~;=__,+/*_""           
+                   ```                
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_33.txt b/codex-rs/tui2/frames/default/frame_33.txt
new file mode 100644
index 0000000000..dbd9568018
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_33.txt
@@ -0,0 +1,17 @@
+                                      
+               _,+=+=+=~._            
+            _+*||\*=~:|-|*|*.         
+          _/\|+*+,="`  "*/||+",       
+         ,\/|/_|,_        *||\_*      
+        _.|/`||/\^\         |+\\^     
+        //,   \_\\`\,        /\/_\    
+        ||+ !  \,*|_|\       |*||     
+        *|,,   ,''\/=,       \"|*     
+        ||| | ,` /*,,,;==+~~+/_|\~    
+        ^/|'"/:,/`~|_____||*^^^~|.    
+        \=\, |/|/ / """"*** ||,/^`    
+         \+\*,",           //;/=/     
+          *\"*,*;,      _+|,/*\'      
+            \~"*\+|,;+_";,\*~*        
+              "==+,___^+*;-"          
+                   ````               
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_34.txt b/codex-rs/tui2/frames/default/frame_34.txt
new file mode 100644
index 0000000000..7fc67a92db
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_34.txt
@@ -0,0 +1,17 @@
+                                      
+               _,=++++=~,_            
+           _+*+/\;|"~+*=**;,=_        
+         _//,|*":~*`   `^\\,"**,      
+        ,/_|*_/,_          *|,*\\     
+       //|\-/|!|"!,          \\*\^    
+      ,/\|`/ \\"|\*\          \,\|\   
+      |*^~_   '\_*|_^          |;~_   
+      \|=":    |*_|/"|         / _\   
+      ,'/."   /\//"_==++++++~__" ~^`  
+      ||\,/,,^"//'~||_~.___,/_||`|\   
+       /_\, |\|*^!  "**````^ ,/,\|'   
+        /,\;=\_             /;.|/'    
+         \+`|+\;,        _+="_/,`     
+           -\/~"|+,;,+=*=*`+*:'       
+             "~\;=_____;=*=^          
+                   ```                
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_35.txt b/codex-rs/tui2/frames/default/frame_35.txt
new file mode 100644
index 0000000000..570f34f0de
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_35.txt
@@ -0,0 +1,17 @@
+                                      
+              _,+;=+++=+,_            
+           ,*=*.~**+"|*~:"~*=_        
+        _//|;+*|^*"`  `"*=*."|*,      
+       ,//+/,;,_            *+_\|_    
+      //~|//\ "\*,            |\*|,   
+     ;/;/+` '|_"..*_           |\\|   
+     \ !./    \\ '*_.           |^\\  
+     ~|~:      /\\;/'           / "/  
+     / ,_    ,||/;"/|==_;_=+~~  |~=*  
+     |,^;'  //;"*+/|; \,____/"~/' |'  
+      /`\,'/\_|/^`  `"^^^^*^^*//_,|   
+       ".^\/~               _/* ,^    
+        \;`^;,:,          ,;/_**'     
+          "^_"~*~-:~~+~;/*"_/;"       
+             "^~;=__/__++*"^          
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_36.txt b/codex-rs/tui2/frames/default/frame_36.txt
new file mode 100644
index 0000000000..74d83c8e70
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_36.txt
@@ -0,0 +1,17 @@
+                                      
+              __+=++++=+,_            
+          _=""\+/;/+\+;++"**+_        
+        ,\'\,+*-*"`` `"*~*+|,*|,      
+      _|"*+____            '*~\"|     
+     ,/_;\'|\`\,.             ^\.*    
+     / ,/`  *_ "|/,            "\^*   
+    | ;!`     !\ "\\            |^|,  
+    ||\~      _\ _//!           \| |  
+    |'"|     // ,*"',++_+++++_  |\~|  
+     _*|\  ,|__/~/ !`~_______|| \/'`  
+     ' *|\ +_+/^     "**^^^^^" |,"/   
+      ',"\;.                 ,/|"/    
+        \/||+~,           ,++"/,`     
+          *,_"**=^;~_+~;"-",;+'       
+            `*+/~_,,_,,++**"          
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_4.txt b/codex-rs/tui2/frames/default/frame_4.txt
new file mode 100644
index 0000000000..06dbce99c0
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_4.txt
@@ -0,0 +1,17 @@
+                                      
+             _.=;+==+=+,_             
+         _-"+*|/!|\=/*;|"/*,_         
+       ,*=|||+*"`   `^~\^*|/\\_       
+      //|,|".+,          "|**\*\      
+     /|/_|=|\;^|,          \"\|*\     
+    /||^|  '_||/*\          ' \=|,    
+    "\|;`   '**\+"|,         , ";|    
+     |.\     ,|/*^||           |||    
+    _|!|_   ;|/"^//+~+++____,, ||*    
+    |\/!| ,///,_|`=\|,._,:/^;|//"|    
+     `|;'\,\\,\/   "*******'^-|||`    
+      ,|\"|_`             ,^;/**'     
+       \\,:^!,_        _.^,*;|/       
+         ~||=_**\;;=;,+=*+\|*`        
+            *\\~:~_____;-*`           
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_5.txt b/codex-rs/tui2/frames/default/frame_5.txt
new file mode 100644
index 0000000000..6b1ce12447
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_5.txt
@@ -0,0 +1,17 @@
+                                      
+             _.=;;+===+,_             
+         _+"+/*/||+~=+;_|"+,          
+        *_/\+|*"`   "^=|*\!,*,        
+      ,|/|/|.=,          -^||||_      
+     ,\/*/^_+|_\,         ` \|\|_     
+     ~|||/ \_|\;/|_          +/||     
+    |/|!+   `\_|\"|,        ''~+|,    
+    |/|_"    ,_=|/_|          +|_|    
+    |,|^*   /_|",|*=_~+~___+,_"|.|    
+     _\|\,,/+*" |"!//\=^,=.,/|/*|`    
+     \,||,~,\\/+`  "**""""",~;|\/     
+      \\+/\\ `            /_/*,^      
+       ^/*\|=+_        _=+,*';*       
+         ^|*|,*+\;~=_,+=*^~;*         
+            ^-*_*"___-_,+*`           
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_6.txt b/codex-rs/tui2/frames/default/frame_6.txt
new file mode 100644
index 0000000000..7724f483dc
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_6.txt
@@ -0,0 +1,17 @@
+                                      
+             _.=;;+==++__             
+          ,^;/*|=*+|++;_,*+_          
+        ,,,|||*"   `"~.=*+*/\_        
+       /,|*|*_=,        \+||||,       
+      '=|||*\\+*\         .\\|\,      
+     ;-/|/`^+;|\_|,        .=\/|      
+     _ +~|   !^\|/^\        ^+|_|     
+     ~ |~|   _|=~/||        ~+\||     
+     _.|-|  /'||*;/+_~+~__++_.\/|     
+     ||\,/_^_;+ |/=*,||,;==\|,|\!     
+      / | /~||;/"  "*"""'*"`\\/|      
+       , ; /,`           ,:_//|`      
+        .`\_**,       _+^_/*,+        
+         `"~*,"+!;~__,+**!:;'         
+            ^-;*+,___`_,+*            
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_7.txt b/codex-rs/tui2/frames/default/frame_7.txt
new file mode 100644
index 0000000000..0d0f43072c
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_7.txt
@@ -0,0 +1,17 @@
+                                      
+             _.~;*+==+,_              
+          ,*`+\|+*+==\;!`*,           
+         * ,|||*`  `^~`!*/_*,         
+        \\|||~;+       ^~\*|/,        
+       `'|*||^|/\,       . *||\       
+      | ;||" `'\;|\       ,-|||       
+       `\"|  ^_|\|\|       **^||      
+      _"/~|   =+/|*|`      ' |||      
+       /"~* ,"_/|\/~~;;_~~=;*\||      
+      |,'||=:~|/'|.\||\\,=,;\|\|      
+       \ =^/*|*_/  ******""_/||       
+       '_ /_/_`         ,"-/;/'       
+        ';,+\\\_      ,^~,*/*'        
+          \_'\|*\;~___+*|*+/          
+            "~*"~:~__,_;**            
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_8.txt b/codex-rs/tui2/frames/default/frame_8.txt
new file mode 100644
index 0000000000..2e8019c061
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_8.txt
@@ -0,0 +1,17 @@
+                                      
+             __+_;++=+,_              
+           ,"*/|||*==!~ "+            
+         _|=,|//*!,"~/~*\+^,          
+        _*\*/|,+|     ' =^||\         
+        ' /|/,\|/\      .'\||,        
+       |',|\^^_\|_*      \+|||        
+       |*||| '_;\|`|      ^|/|,       
+       \,||/  |+\/|,*.    .`/||       
+       \ \||_^ !/*=|~/+,+,,\~||       
+       !  \*/=_|",|,||;|=__||='       
+        //\\|\|||/'^*^*"\*"/\|        
+        ',"|\|``        .,///'        
+         '\_*\\\_    _/\_|+/*         
+           .:'|,*!;;+*;/=,|`          
+             ~~_**\|_,+/=`            
+                  ``                  
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/default/frame_9.txt b/codex-rs/tui2/frames/default/frame_9.txt
new file mode 100644
index 0000000000..128e915007
--- /dev/null
+++ b/codex-rs/tui2/frames/default/frame_9.txt
@@ -0,0 +1,17 @@
+                                      
+              .=^*/++=,               
+            /*_/||*"=!_-\_            
+           / ,||/*^^=/!\_~,           
+          " ||/;=_ _^,|\^|+,          
+         /*";\*"|*,  +:+||          
+         | |||"^|\;*   '|*|||         
+         ` ~*\ **|\\," / `||         
+        |  ~/_ ~||_/= | !||         
+        !  ",|" /|"|~~|+|~,||`        
+         |_|||_,|^|_||||__|||         
+         " `^/\\|/"****||"/\|         
+          \~||\,`     ,/ ^/|`         
+           \+\|\\    /;_;|/*          
+            ^-"\_|*/+=;;*|`           
+             '-_ *\\|;+/"             
+                                      
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_1.txt b/codex-rs/tui2/frames/dots/frame_1.txt
new file mode 100644
index 0000000000..36964a4864
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_1.txt
@@ -0,0 +1,17 @@
+
+ ○◉○◉○●●○○●●○
+ ○○●◉●○●◉●○○··○○ ○ ●○
+ ●·●·●●● ○· · ●· ·○···●
+ ◉●○○●●●●○ ◉●·◉·●
+ ○○◉◉●○·○·○○ ◉·○○●
+ ·● ●· ·●◉◉··● ●◉○··●
+ ●○ ◉● ●○·●◉ ·○ ·◉·
+ ··○·· ●◉◉·◉·● ··
+ ·○·●· ◉··○○· ◉·●●●●●●○●● ○ ·
+ ○·◉● ○◉●· ◉● · ·○○○◉◉●●●·◉●◉●·
+ ○○○ ○ ○○●◉◉· ·○●●●● ○● ◉●◉○◉
+ ●○● ● · ●●◉●○·
+ ○○●·○●○ ○○○●·○●
+ ○●●○○ ●●◉◉○◉◉◉○●●○●·●
+ ·● ●···○○○●○◉●●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_10.txt b/codex-rs/tui2/frames/dots/frame_10.txt
new file mode 100644
index 0000000000..3c687d7f64
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_10.txt
@@ -0,0 +1,17 @@
+
+ ○●●●●○●●○
+ ●●·●●●○·◉○●●
+ ○○●··◉··◉·●○●●
+ ·○○◉○·◉○◉○●●●○○●
+ ◉ ◉·· ·○ ●●◉○◉·◉
+ ·· ●·●·◉◉○ ·○ ·
+ ○ ·● ●····● ·◉●
+ ··○●◉●··◉○·◉○··
+ ·○ ○○·◉··●○●◉··
+ · ●·○●·○◉○●○○○·●·
+ ● ····· ○● ○··
+ ○·●●○●● ○· ●◉◉
+ ·● ····●●◉●◉·◉·
+ ◉·●●◉·●◉○ ◉◉●
+ ●● ○●○○●◉●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_11.txt b/codex-rs/tui2/frames/dots/frame_11.txt
new file mode 100644
index 0000000000..c2548db4b3
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_11.txt
@@ -0,0 +1,17 @@
+
+ ●●●●●●●○
+ ◉ ◉···○○●
+ ◉ ○○··◉○●◉○●
+ ·○○··○◉●○○◉◉
+ ○ ◉◉○·●○●◉○··●
+ ·●···●○◉◉·○◉··
+ ●● ●······○·○○
+ · ··◉··○◉ · ·
+ ◉ ●·◉··●◉●·○·
+ ●● ○·◉○● ◉·○·○
+ ●·◉ ····○◉·○○·
+ ○○◉◉·○●◉●●◉··
+ ○ ●·○○○○·◉
+ ○● ●··●○◉●·
+ ○○ ●●●○●·
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_12.txt b/codex-rs/tui2/frames/dots/frame_12.txt
new file mode 100644
index 0000000000..30b03392bf
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_12.txt
@@ -0,0 +1,17 @@
+
+ ●●●●●◉
+ ●○·○◉·●○
+ ·◉○●●
+ ◉●···○○ ·
+ · ●····◉◉·
+ ·●◉◉●○ ○·
+ · ·◉○··○
+ · ◉●○··
+ ●● ·◉··●··
+ · ◉·●◉●○
+ ·◉ · ○●●◉
+ ● ●· ○●·
+ ◉ ●●·●●○·
+ ●○◉ ●·○··
+ ○ ●·○◉◉
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_13.txt b/codex-rs/tui2/frames/dots/frame_13.txt
new file mode 100644
index 0000000000..cb95f3763d
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_13.txt
@@ -0,0 +1,17 @@
+
+ ◉●●●●
+ ·○○··
+ ··○·
+ ·●●·○
+ ● ··
+ ◉◉··
+ ● ··
+ ● ·
+ ◉● ○·◉
+ · ●○·
+ ●·◉◉ ··
+ ·○○○·
+ ·●●·○
+ ●○○·○
+ ● ◉ ○
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_14.txt b/codex-rs/tui2/frames/dots/frame_14.txt
new file mode 100644
index 0000000000..3a8ed60b8f
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_14.txt
@@ -0,0 +1,17 @@
+
+ ●●●●◉
+ ●◉○○◉○
+ ·○··◉ ·
+ ··◉· ○·●
+ ···○ ·
+ ·●·· ●·
+ ···· ◉ ●
+ ··○·· ○
+ ····
+ ○◉◉ ◉◉
+ ○· ●◉●·
+ ·●··○○○·
+ ◉ ·○○○·
+ ·○◉●○○◉
+ ○● ●○◉
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_15.txt b/codex-rs/tui2/frames/dots/frame_15.txt
new file mode 100644
index 0000000000..c57b4af0ee
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_15.txt
@@ -0,0 +1,17 @@
+
+ ●●●●●·○
+ ·●○··○◉●●
+ ◉◉·●○○· ●·
+ ·◉· ◉◉●◉○○·
+ ··○ ○○··◉ ○·
+ ○··◉··◉◉·
+ ·· ······●·
+ ··◉··●··· ●◉·
+ ··●●●●···○◉◉·
+ ·○·◉◉·○·●◉ ◉·
+ ·◉····○· · ◉
+ ·●●◉○··○◉ ○
+ ●·○● ◉◉◉· ◉·
+ ·○··○○◉●○◉
+ ○○●○○○○◉
+ ··
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_16.txt b/codex-rs/tui2/frames/dots/frame_16.txt
new file mode 100644
index 0000000000..18ae0e09ee
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_16.txt
@@ -0,0 +1,17 @@
+
+ ○○● ●●●·○
+ ◉○··●··○·○○
+ ·◉◉ ○◉○○·· ●○
+ ◉◉◉ ◉●○○·○··●●·
+ ··◉○◉●●○··●◉··○
+ ···●·● ·○○ · ·◉·
+ ○○· ◉·●····◉● ● ·
+ ·◉◉ ····◉··· ◉ ··
+ ○○···●·◉○·· ●● ◉
+ ● ○○●○○○●·◉○· ●○·
+ ···● ◉●○·◉ ◉◉···
+ ··● ·· ·◉◉● ◉
+ ○·● · ◉●◉○●·
+ ○·· ○●·◉◉●○·
+ ●◉◉○○◉○○◉●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_17.txt b/codex-rs/tui2/frames/dots/frame_17.txt
new file mode 100644
index 0000000000..a470b4ba8d
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_17.txt
@@ -0,0 +1,17 @@
+
+ ●○●●●◉◉·●○
+ ○◉●●···●○●·● ○●
+ ●●○◉○○○·●● ···○ ○
+ ◉·◉○◉· ○· ●·◉○···○○
+ ·◉○ · · ◉○○○◉◉ ●
+ ·○●●◉· ●◉◉· ◉●○◉·◉◉
+ ● ◉◉· ●◉◉·○ ● ··◉○·
+ ◉ ○· ◉◉··◉·●··○◉●
+ ●◉●◉○○○●·○○·○○◉○··· ·
+ · ○◉○○·◉●○◉··○ ○●●●○
+ ○○○◉ ●●●●○○·●◉◉○ ○●
+ ○··○● ·◉··· ◉
+ ○○○ ●○○ ●●●◉○○◉
+ ● ·●●○○●·○◉●◉·●
+ ·●◉◉○●●·●○●●
+ ·
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_18.txt b/codex-rs/tui2/frames/dots/frame_18.txt
new file mode 100644
index 0000000000..c0354b3933
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_18.txt
@@ -0,0 +1,17 @@
+
+ ○○○●○○●◉·●○
+ ○● ○◉●●●·○○● ●◉◉○
+ ○◉◉·● ●○ ● ◉○ ●◉◉○ ●
+ ●··●◉●○ ● ●○·○◉○·○◉○○○●
+ ○○◉◉ ◉· ○ ●○○◉·◉·○○◉○○○
+ ◉○· ●●·◉○○○◉●●●·●◉◉○◉·◉·
+ ··○◉◉ ●◉●◉· ○◉ ●·○·○●
+ ○◉·· ○○ ··◉○ ·◉·
+ ○ ●○○○◉○◉●··●·●◉○● ·●··
+ ○○○·●○● ··◉○○○○···○◉··○ ●
+ ·◉·○· ●●●●●· ○○○◉·◉●◉·◉·
+ ○○ ●○● ··● ◉●○●
+ ○○●●○○◉ ○●○○◉○●·
+ ●·◉●●●●○○○○●●○◉○●●
+ ··○◉○○●◉● ◉●
+ ·
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_19.txt b/codex-rs/tui2/frames/dots/frame_19.txt
new file mode 100644
index 0000000000..c9ded56838
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_19.txt
@@ -0,0 +1,17 @@
+
+ ○○○○●·●○○·◉○
+ ○●···○◉○○○○●○●·●●●
+ ●●◉◉◉ ·●●· ·●◉●·●◉○
+ ◉◉·●●○· ○○○●●○·●●
+ ··◉·◉· ●·○ ◉ ·○ ·○●
+ ·○◉●● ○·●·◉ ◉◉ ●◉●·
+ ○○··● ◉●○◉·●●· ◉◉◉●·
+ ···· ·◉ ○· ● · ···
+ ·●·○●○◉◉○○○····●●◉●·◉ ○ ··
+ ○◉◉●·○●◉○●●○●·● ○○ ◉○○○●◉◉·○
+ ●○ ◉●· ●● ○○○◉·◉◉ ◉◉●
+ ○○○●○○ ·◉◉○◉◉●
+ ● ○○··●● ●◉○◉◉·◉·
+ ● ◉·●◉·●○○○◉◉● ◉●·●
+ ·◉○◉◉●○●◉○●◉○
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_2.txt b/codex-rs/tui2/frames/dots/frame_2.txt
new file mode 100644
index 0000000000..6e7a27fb29
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_2.txt
@@ -0,0 +1,17 @@
+
+ ○◉○◉○●○○○●●○
+ ○●●◉●◉●···○··○○●·●●○
+ ●·●·○●●·●·· · ●○●◉··◉·●
+ ○·◉○◉●●●●○ ◉●○·◉·●
+ ●○ ◉●○·○○○○○ ○●·○·●
+ ●◉● · ·●○●◉○● ○○·●·
+ ●·●●· ○◉·◉·○·● ◉ · ·
+ · ○· ●·●··◉● ·●◉◉·
+ ● ○· ◉·○○○· ◉·●●●●●●●●●·○··●
+ ○○●· ◉··● ◉● ·○○○○○○◉◉○○·●◉ ·
+ ○○○ ● ●○◉◉·● · ●●●●●●● ·●●··
+ ●○○◉◉● · ●●◉◉●●
+ ◉○○○·●● ●○○● ○·
+ ··○◉○○ ●●◉◉○◉◉◉○●·○··●
+ ·●●●●··○○○○·◉◉●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_20.txt b/codex-rs/tui2/frames/dots/frame_20.txt
new file mode 100644
index 0000000000..d9809e733c
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_20.txt
@@ -0,0 +1,17 @@
+
+ ○○●○··○●○●○○
+ ●◉○ ◉●○●○○○··○○●○●●
+ ●● ○●● ·● · ○ ○●●·●○
+ ○· ○●·● ○●●·○◉●○○
+ ○· ●·● ○◉ ○··○●○··○
+ ◉·●·● ●●●◉· ◉ ●○··○
+ ◉·◉●· ●● ◉●●○ ●○·◉
+ ·○○◉· ◉◉· ● ·· ·
+ ·◉··◉●○◉○○○○○○○●●◉○○○○● ◉ ·○
+ ●·○·○ ◉··○○○○·○ ●○○ ·○○ ●◉ ··
+ ○●○○● ● ○●○··●· ◉○
+ ● ○●◉● ○◉●◉·◉
+ ○○○●●·○ ●◉●·◉●●
+ ○●◉◉ ·●○◉◉●◉ · ·●◉●●
+ ·●●·○ ○○○○○·●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_21.txt b/codex-rs/tui2/frames/dots/frame_21.txt
new file mode 100644
index 0000000000..0821f12d75
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_21.txt
@@ -0,0 +1,17 @@
+
+ ○○●○●○○●○●●○○
+ ●●●··○○●·○·●◉○·◉●●○
+ ◉●○○●●○ · ·○·●●○·●●
+ ●●·◉ ● ○●◉●●◉●●
+ ◉●◉●· ●·◉○○ ○○○○●
+ ◉ ◉· ●●●○◉◉ ○○○●
+ ·●·· ○ ◉·●◉● ○◉○
+ ·○ ○◉ ·● · ·
+ · · ●●◉◉◉◉◉●●● ○·● ·● ◉◉ ·
+ · ·○ ·○ ○●· ○ ·●·● ◉ ◉◉
+ ◉ ◉ ·· ●· ●●○●◉ ◉· ●
+ ●● ◉◉○ ○● ◉
+ ●○ ○◉○ ○◉◉●● ●·
+ ●○○ ● ●●◉··◉◉○● ◉·
+ ●●●◉●○○○○●○◉●●·
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_22.txt b/codex-rs/tui2/frames/dots/frame_22.txt
new file mode 100644
index 0000000000..d673349801
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_22.txt
@@ -0,0 +1,17 @@
+
+ ○●●○●○○●○●●○
+ ○●◉●·◉○◉·◉○··◉·●◉●●○
+ ●◉●◉·○●●· · ●○●●●○○●●
+ ◉●·●● ●●···○●○
+ ○··◉● ●○◉·○·◉◉◉●·
+ ○·●◉· ●·◉·◉○◉· ○·○○·
+ ·●●○◉ ·●·○●◉● ··◉·
+ ··○·· ·○··○○ ·○· ·
+ ··● ● ●·○○◉◉◉○●●○○●·○ ○● ○·◉
+ ○·○ ●○○○● ◉● ·◉◉· ○●◉○ ·●● ◉○○
+ ○○○○· ●● · ·◉●●○◉◉◉ ●·
+ ○●○○○● ○●● ·●●
+ ● ●◉ ●●○ ○◉●● ●○◉
+ ●◉●●● ●·◉○●◉◉◉○● ●●●
+ · ·○◉○○○◉○○◉○●·
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_23.txt b/codex-rs/tui2/frames/dots/frame_23.txt
new file mode 100644
index 0000000000..180ab16784
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_23.txt
@@ -0,0 +1,17 @@
+
+ ○●●○○●●●●○●○○
+ ○○·●·○○●○○○●·○·●·●○
+ ● ●·●●◉●· ·◉●·○◉··●
+ ◉◉·●◉◉· ○◉◉○··◉○
+ ◉◉··◉● ●◉●●●●◉●○·○
+ ●○· ◉· ○●●●●●◉●●··○·●
+ ··· · ◉◉◉◉ ○·· ·●●
+ ·◉· · · ·●○○● · ●◉·
+ ○ ○ ·●·◉○○○○○◉○·○●·○ ○○ · ···
+ ·○○○· ○ ◉·○ ○·○○●· ○○·
+ ◉●· · · ●·◉◉○·○◉○◉·
+ ●··○·◉ ●◉·○○◉·
+ ○ ·●●◉○○ ○◉ ◉●◉●◉
+ ○○○●◉●●○·○○○●● ◉○●●·
+ · ●○○·○○●○○●●·
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_24.txt b/codex-rs/tui2/frames/dots/frame_24.txt
new file mode 100644
index 0000000000..3244b1c6f9
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_24.txt
@@ -0,0 +1,17 @@
+
+ ○·○◉●●●○○●○
+ ● ○◉ ·○○·○○●●○●●
+ ● ●◉○◉● · ◉·◉●·●●● ○
+ ●●◉◉●◉·○●○··◉· ○●○·○○●
+ ● ◉◉○◉● · ◉○○···○·●●
+ ·●○●○· ●●●◉ ◉·◉ ◉ ○
+ · ·· ●◉○●◉ ◉○○·○○·○
+ · ○·· ·●○◉○○··○◉◉···
+ ·◉ ·◉◉◉◉●●···●●○●●○· · ··
+ ○ ◉ ●·◉●●◉◉●●·◉○○●●· ·●·
+ ○ ●○·○● · ○●◉●○·○◉●·
+ ○ ○●●○ · ◉◉◉
+ ○◉●○··◉ ○○ ○◉◉○●
+ ◉◉●●○○ ··◉○○◉·○○◉·
+ ●◉○●●◉○○○○○●●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_25.txt b/codex-rs/tui2/frames/dots/frame_25.txt
new file mode 100644
index 0000000000..c04ef18b74
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_25.txt
@@ -0,0 +1,17 @@
+
+ ○●○●◉●●●●○
+ ● ●●●·○◉○·●··●
+ ◉·◉◉●● ◉·●○○○···○
+ ·●●· ◉ ○· ○·●●○◉
+ ●○○○●◉●○◉◉○· ·◉◉○◉●
+ ○●···○●●◉○·◉ ◉·●·◉◉·●
+ ·◉·●· ·○○◉○○◉·○◉○ ·○·
+ ···◉·◉ ·○○○◉·○○·○··○
+ ○●○· ·○○○○○○●··○○·●●·○
+ ◉◉ ·◉·●·○··◉●○·○●○◉○·
+ ○·●◉○·· ●●◉·○·◉··
+ ·○ ·◉●◉○◉●●◉○◉●◉◉·◉
+ ○·○·○○○●◉◉●○◉○··◉
+ ○◉◉○○○●○·●● ●·●
+ ·● ●○●●○●·●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_26.txt b/codex-rs/tui2/frames/dots/frame_26.txt
new file mode 100644
index 0000000000..1ecc43beef
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_26.txt
@@ -0,0 +1,17 @@
+
+ ○◉●●● ●●
+ ◉●·◉◉○·●◉·●
+ ◉● ·◉○·○ ○●
+ ◉● ●···○··○●◉○
+ ·○●○·◉· ●○◉◉·○◉
+ ○ ·◉◉◉ ●○○ ○○◉
+ · ●●○··◉··◉◉ ●
+ ◉◉ ○···○○○··◉··
+ · ◉○●◉●·●○○◉○··
+ ◉○·◉●·○○●●○○●·
+ ·· ◉·● ○●◉·●○··
+ ○○··◉○ ◉◉ ···
+ ● ●·○ ○·◉·◉●
+ · ●○○ ●○●●◉
+ ○◉◉○●·○○●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_27.txt b/codex-rs/tui2/frames/dots/frame_27.txt
new file mode 100644
index 0000000000..83e62da52e
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_27.txt
@@ -0,0 +1,17 @@
+
+ ◉●●●●●
+ ·◉◉◉·◉○
+ ◉●· ●·◉●·
+ ···○··◉··
+ · ··○◉●○
+ ·○◉○ ·····
+ ○ ··○●··
+ · ····○ ··
+ ·◉ ◉ ·●····
+ ●○ ◉ ○·○●··
+ ·◉ ○○●●●◉●
+ ··●●··○◉·
+ ·○○●○●◉·○
+ ○○○·○○◉◉
+ ●○ ○○◉
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_28.txt b/codex-rs/tui2/frames/dots/frame_28.txt
new file mode 100644
index 0000000000..6d460c936d
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_28.txt
@@ -0,0 +1,17 @@
+
+ ◉●●◉
+ ·●○··
+ ○ ◉··
+ ·◉·●·
+ · ··
+ · ◉ ·
+ ○·· ○·
+ ·◉ ·
+ ◉○ ○·
+ ··◉◉··
+ · ○·
+ ·○●○·
+ ·○●··
+ ●○○◉·
+ · ◉●·
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_29.txt b/codex-rs/tui2/frames/dots/frame_29.txt
new file mode 100644
index 0000000000..d0d6b3c286
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_29.txt
@@ -0,0 +1,17 @@
+
+ ●●●●●●
+ ●·●◉ ●○
+ ○●·· ● ·
+ ····○○●◉
+ ○ · · ·
+ ·●··· ○○
+ ·○○··· ○
+ ··○··
+ ···●· ·
+ ○·○·· ·
+ ●··◉·○ ○
+ ·◉··· ○·
+ ······○·
+ ·○·●◉ ·●
+ ··● ◉●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_3.txt b/codex-rs/tui2/frames/dots/frame_3.txt
new file mode 100644
index 0000000000..062da3ed89
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_3.txt
@@ -0,0 +1,17 @@
+
+ ○◉○◉●●○○○○●○
+ ○●●◉○··●· ○○·◉○○·●●○
+ ●◉◉●◉·● · · · ●●●◉○·●
+ ◉●◉○·◉●●○ ·○● ··○
+ ●◉●·◉○◉··●○○ ○○○··○
+ ◉·○○◉ ◉●·○◉○○ · ○○·
+ ○● · ●●○·○ ·● ◉●◉·●
+ ●◉·●· ●◉· ◉○· ·○·○·
+ ◉ ●· ◉·●●··●◉·○●●○○○●●○·○ ◉·
+ ●○◉○● ◉◉●◉◉◉· ·●·○○● ○◉●◉○··○··
+ ●○· · ··●● ●●● ●●●◉◉◉●◉
+ ●●· ○● · ◉○●○◉◉
+ ○○◉◉●○● ●●◉◉ ●·●
+ ○○●●○●●○○◉○◉●◉○●◉·○●
+ ·●●●○◉·○○○○·◉◉○
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_30.txt b/codex-rs/tui2/frames/dots/frame_30.txt
new file mode 100644
index 0000000000..4bf02ade3d
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_30.txt
@@ -0,0 +1,17 @@
+
+ ○◉ ●●●●
+ ○◉◉··○●●○○
+ ●○·●○○·●●○
+ ··○·◉·○○·○ ○●
+ ○●···○·●·● ·
+ ·●·○● ●····◉·
+ ○◉···○○ ○◉○· ○·
+ · ●●○·●· ·◉ ·
+ ·○ ○·○·○◉·● ·
+ ··○·○○·· ●● ·
+ ○··◉○○●···●··
+ ·●◉◉●◉●○·· ·
+ ○·○··◉●··●·◉
+ ●○●●○○◉·●◉●
+ ○◉◉·○○○◉●
+ ····
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_31.txt b/codex-rs/tui2/frames/dots/frame_31.txt
new file mode 100644
index 0000000000..99385ee51f
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_31.txt
@@ -0,0 +1,17 @@
+
+ ○◉◉●●●●○●
+ ○●●◉●●○ ●○●●●
+ ●·○◉◉●○○·◉ ·○●○
+ ●·◉●○○●◉○●○○·○··○
+ ○····●◉●○○● ○·◉○○
+ ◉·○··○·● ○◉●●◉◉·● ·
+ ◉·· ·○●·○◉○◉◉●·●·◉·
+ ○○● ·· ·○ ·○ ··○◉·
+ ·○●○·●○···◉●···○ ·
+ ···◉◉··○○○○○·○·· ●
+ ○●○◉●·● ◉●●●·◉·●·○
+ ···○○○● ○○● ·
+ ◉·●○○ ● ◉ ·●·◉·
+ ◉·○·◉○··●· ●··
+ ● ○·○●●◉◉◉●
+ ····
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_32.txt b/codex-rs/tui2/frames/dots/frame_32.txt
new file mode 100644
index 0000000000..771e9c9106
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_32.txt
@@ -0,0 +1,17 @@
+
+ ●●●●●◉◉·●○
+ ◉●·●●·○··●●··●
+ ◉○●○○●●○◉◉·●·●○●●●
+ ●◉◉·○●·◉◉ ◉ ●○○·●● ●
+ ◉◉·●·●○●●·◉ ●·●·○◉○●○●
+ ○◉○○●○●··◉··●○ ·●◉ ●
+ ●· ◉●·●○··●●·●○·◉○◉◉·●○
+ ···●○ ○·· ◉●·◉◉○ ○· ·
+ ○··◉○ ●○· ○○·●●●···○· ○·
+ ● ○··●○●○○○○○○··●·◉·◉○
+ ●○●··◉ ·● ●●●○◉◉◉◉◉◉
+ ○●·○○○ ●○·◉●·
+ ●●●···●○ ○◉○·◉ ●
+ ○◉○ ·●·◉○●·○● ○◉
+ ·◉○○○●●◉●○
+ ···
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_33.txt b/codex-rs/tui2/frames/dots/frame_33.txt
new file mode 100644
index 0000000000..4d36c1eb6f
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_33.txt
@@ -0,0 +1,17 @@
+
+ ○●●○●○●○·◉○
+ ○●●··○●○·◉·◉·●·●◉
+ ○◉○·●●●●○ · ●◉··● ●
+ ●○◉·◉○·●○ ●··○○●
+ ○◉·◉···◉○○○ ·●○○○
+ ◉◉● ○○○○·○● ◉○◉○○
+ ··● ○●●·○·○ ·●··
+ ●·●● ●●●○◉○● ○ ·●
+ ··· · ●· ◉●●●●◉○○●··●◉○·○·
+ ○◉·● ◉◉●◉···○○○○○··●○○○··◉
+ ○○○● ·◉·◉ ◉ ●●● ··●◉○·
+ ○●○●● ● ◉◉◉◉○◉
+ ●○ ●●●◉● ○●·●◉●○●
+ ○· ●○●·●◉●○ ◉●○●·●
+ ○○●●○○○○●●◉◉
+ ····
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_34.txt b/codex-rs/tui2/frames/dots/frame_34.txt
new file mode 100644
index 0000000000..4cbd99c143
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_34.txt
@@ -0,0 +1,17 @@
+
+ ○●○●●●●○·●○
+ ○●●●◉○◉· ·●●○●●◉●○○
+ ○◉◉●·● ◉·●· ·○○○● ●●●
+ ●◉○·●○◉●○ ●·●●○○
+ ◉◉·○◉◉· · ● ○○●○○
+ ●◉○··◉ ○○ ·○●○ ○●○·○
+ ·●○·○ ●○○●·○○ ·◉·○
+ ○·○ ◉ ·●○·◉ · ◉ ○○
+ ●●◉◉ ◉○◉◉ ○○○●●●●●●·○○ ·○·
+ ··○●◉●●○ ◉◉●···○·◉○○○●◉○····○
+ ◉○○● ·○·●○ ●●····○ ●◉●○·●
+ ◉●○◉○○○ ◉◉◉·◉●
+ ○●··●○◉● ○●○ ○◉●·
+ ◉○◉· ·●●◉●●○●○●·●●◉●
+ ·○◉○○○○○○◉○●○○
+ ···
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_35.txt b/codex-rs/tui2/frames/dots/frame_35.txt
new file mode 100644
index 0000000000..5ccdf711b5
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_35.txt
@@ -0,0 +1,17 @@
+
+ ○●●◉○●●●○●●○
+ ●●○●◉·●●● ·●·◉ ·●○○
+ ○◉◉·◉●●·○● · · ●○●◉ ·●●
+ ●◉◉●◉●◉●○ ●●○○·○
+ ◉◉··◉◉○ ○●● ·○●·●
+ ◉◉◉◉●· ●·○ ◉◉●○ ·○○·
+ ○ ◉◉ ○○ ●●○◉ ·○○○
+ ···◉ ◉○○◉◉● ◉ ◉
+ ◉ ●○ ●··◉◉ ◉·○○○◉○○●·· ··○●
+ ·●○◉● ◉◉◉ ●●◉·◉ ○●○○○○◉ ·◉● ·●
+ ◉·○●●◉○○·◉○· · ○○○○●○○●◉◉○●·
+ ◉○○◉· ○◉● ●○
+ ○◉·○◉●◉● ●◉◉○●●●
+ ○○ ·●·◉◉··●·◉◉● ○◉◉
+ ○·◉○○○◉○○●●● ○
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_36.txt b/codex-rs/tui2/frames/dots/frame_36.txt
new file mode 100644
index 0000000000..6a26abaea6
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_36.txt
@@ -0,0 +1,17 @@
+
+ ○○●○●●●●○●●○
+ ○○ ○●◉◉◉●○●◉●● ●●●○
+ ●○●○●●●◉● ·· · ●·●●·●●·●
+ ○· ●●○○○○ ●●·○ ·
+ ●◉○◉○●·○·○●◉ ○○◉●
+ ◉ ●◉· ●○ ·◉● ○○●
+ · ◉ · ○ ○○ ·○·●
+ ··○· ○○ ○◉◉ ○· ·
+ ·● · ◉◉ ●● ●●●●○●●●●●○ ·○··
+ ○●·○ ●·○○◉·◉ ··○○○○○○○·· ○◉●·
+ ● ●·○ ●○●◉○ ●●○○○○○ ·● ◉
+ ●● ○◉◉ ●◉· ◉
+ ○◉··●·● ●●● ◉●·
+ ●●○ ●●○○◉·○●·◉ ◉ ●◉●●
+ ·●●◉·○●●○●●●●●●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_4.txt b/codex-rs/tui2/frames/dots/frame_4.txt
new file mode 100644
index 0000000000..b4496013b5
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_4.txt
@@ -0,0 +1,17 @@
+
+ ○◉○◉●○○●○●●○
+ ○◉ ●●·◉ ·○○◉●◉· ◉●●○
+ ●●○···●● · ·○·○○●·◉○○○
+ ◉◉·●· ◉●● ·●●○●○
+ ◉·◉○·○·○◉○·● ○ ○·●○
+ ◉··○· ●○··◉●○ ● ○○·●
+ ○·◉· ●●●○● ·● ● ◉·
+ ·◉○ ●·◉●○·· ···
+ ○· ·○ ◉·◉ ○◉◉●·●●●○○○○●● ··●
+ ·○◉ · ●◉◉◉●○··○○·●◉○●◉◉○◉·◉◉ ·
+ ··◉●○●○○●○◉ ●●●●●●●●○◉····
+ ●·○ ·○· ●○◉◉●●●
+ ○○●◉○ ●○ ○◉○●●◉·◉
+ ···○○●●○◉◉○◉●●○●●○·●·
+ ●○○·◉·○○○○○◉◉●·
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_5.txt b/codex-rs/tui2/frames/dots/frame_5.txt
new file mode 100644
index 0000000000..0905c495b2
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_5.txt
@@ -0,0 +1,17 @@
+
+ ○◉○◉◉●○○○●●○
+ ○● ●◉●◉··●·○●◉○· ●●
+ ●○◉○●·● · ○○·●○ ●●●
+ ●·◉·◉·◉○● ◉○····○
+ ●○◉●◉○○●·○○● · ○·○·○
+ ····◉ ○○·○◉◉·○ ●◉··
+ ·◉· ● ·○○·○ ·● ●●·●·●
+ ·◉·○ ●○○·◉○· ●·○·
+ ·●·○● ◉○· ●·●○○·●·○○○●●○ ·◉·
+ ○○·○●●◉●● · ◉◉○○○●○◉●◉·◉●··
+ ○●··●·●○○◉●· ●● ●·◉·○◉
+ ○○●◉○○ · ◉○◉●●○
+ ○◉●○·○●○ ○○●●●●◉●
+ ○·●·●●●○◉·○○●●○●○·◉●
+ ○◉●○● ○○○◉○●●●·
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_6.txt b/codex-rs/tui2/frames/dots/frame_6.txt
new file mode 100644
index 0000000000..3f96b66761
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_6.txt
@@ -0,0 +1,17 @@
+
+ ○◉○◉◉●○○●●○○
+ ●○◉◉●·○●●·●●◉○●●●○
+ ●●●···● · ·◉○●●●◉○○
+ ◉●·●·●○○● ○●····●
+ ●○···●○○●●○ ◉○○·○●
+ ◉◉◉·◉·○●◉·○○·● ◉○○◉·
+ ○ ●·· ○○·◉○○ ○●·○·
+ · ··· ○·○·◉·· ·●○··
+ ○◉·◉· ◉●··●◉◉●○·●·○○●●○◉○◉·
+ ··○●◉○○○◉● ·◉○●●··●◉○○○·●·○
+ ◉ · ◉···◉◉ ● ●● ·○○◉·
+ ● ◉ ◉●· ●◉○◉◉··
+ ◉·○○●●● ○●○○◉●●●
+ · ·●● ● ◉·○○●●●● ◉◉●
+ ○◉◉●●●○○○·○●●●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_7.txt b/codex-rs/tui2/frames/dots/frame_7.txt
new file mode 100644
index 0000000000..aa52e1b869
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_7.txt
@@ -0,0 +1,17 @@
+
+ ○◉·◉●●○○●●○
+ ●●·●○·●●●○○○◉ ·●●
+ ● ●···●· ·○·· ●◉○●●
+ ○○····◉● ○·○●·◉●
+ ·●·●··○·◉○● ◉ ●··○
+ · ◉·· ·●○◉·○ ●◉···
+ ·○ · ○○·○·○· ●●○··
+ ○ ◉·· ○●◉·●·· ● ···
+ ◉ ·● ● ○◉·○◉··◉◉○··○◉●○··
+ ·●●··○◉··◉●·◉○··○○●○●◉○·○·
+ ○ ○○◉●·●○◉ ●●●●●● ○◉··
+ ●○ ◉○◉○· ● ◉◉◉◉●
+ ●◉●●○○○○ ●○·●●◉●●
+ ○○●○·●○◉·○○○●●·●●◉
+ ·● ·◉·○○●○◉●●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_8.txt b/codex-rs/tui2/frames/dots/frame_8.txt
new file mode 100644
index 0000000000..5791ce70e4
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_8.txt
@@ -0,0 +1,17 @@
+
+ ○○●○◉●●○●●○
+ ● ●◉···●○○ · ●
+ ○·○●·◉◉● ● ·◉·●○●○●
+ ○●○●◉·●●· ● ○○··○
+ ● ◉·◉●○·◉○ ◉●○··●
+ ·●●·○○○○○·○● ○●···
+ ·●··· ●○◉○··· ·○·◉·●
+ ○●··◉ ·●○◉·●●◉ ◉·◉··
+ ○ ○··○○ ◉●○··◉●●●●●○···
+ ○●◉○○· ●·●··◉·○○○··○●
+ ◉◉○○·○···◉●○●○● ○● ◉○·
+ ●● ·○··· ◉●◉◉◉●
+ ●○○●○○○○ ○◉○○·●◉●
+ ◉◉●·●● ◉◉●●◉◉○●··
+ ··○●●○·○●●◉○·
+ ··
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/dots/frame_9.txt b/codex-rs/tui2/frames/dots/frame_9.txt
new file mode 100644
index 0000000000..35588ee1ee
--- /dev/null
+++ b/codex-rs/tui2/frames/dots/frame_9.txt
@@ -0,0 +1,17 @@
+
+ ◉○○●◉●●○●
+ ◉●○◉··● ○ ○◉○○
+ ◉ ●··◉●○○○◉ ○○·●
+ ··◉◉○○ ○○●·○○·●●
+ ◉● ◉○● ·●● ●◉●●◉●··
+ · ··· ○·○◉○○ ·●·●···
+ · ·●○·●●·○○● ◉●◉ ···
+ · ·◉○●○···○◉○○○· ··
+ ●· ◉· ····●··●···
+ ·○···○●·○·○····○○···
+ ·○◉○○·◉ ●●●●·· ◉○·
+ ○···○●· ●◉ ○◉··
+ ○●○·○○ ◉◉○◉·◉●
+ ○◉ ○○·●◉●○◉◉●··
+ ●◉○ ●○○·◉●◉
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_1.txt b/codex-rs/tui2/frames/hash/frame_1.txt
new file mode 100644
index 0000000000..45adbbac24
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_1.txt
@@ -0,0 +1,17 @@
+
+ -.-A*##**##-
+ -*#A**#A#**..*- -█#-
+ #.*.#**█-- -█*-█.*...#
+ **-**█##- A*.*.#
+ *-*A█-.*-** █..**#
+ .* #- .*A*..# █.*..#
+ #-█-* █*.*A█.- .A.
+ ..-.- #AA.*.* █-.
+ .*.█- *..-*.█..######-## *█ .
+ -.** -*#- A* .█.---.A###.A#A#.
+ *--█- -*#.A- --*██* -*█A#*-A
+ *-# █# - #█A*-.
+ -*#-*#- -*-#.-#█
+ -*#*- *#A****.**#-#.*
+ -*█*...---#-*#*█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_10.txt b/codex-rs/tui2/frames/hash/frame_10.txt
new file mode 100644
index 0000000000..0e9a76d4d8
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_10.txt
@@ -0,0 +1,17 @@
+
+ -#****##-
+ *█-#*#*.A-*#
+ --#..A..-.#*##
+ .--A*.*-.*#██**#
+ A *..█.- █#A-A.A
+ .- █.*.AA* --█.
+ * .*█*....* .A#
+ █ ..*#A#..---.*..
+ █ .* **.*..#*#*..
+ . #.*#.-A-*---.*-
+ # █.....██ *#█*.-
+ *-█#*#*█ -.██#AA
+ .█ ....*#A#A.A-
+ *-**A.#*- AA█
+ *# -**-#**
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_11.txt b/codex-rs/tui2/frames/hash/frame_11.txt
new file mode 100644
index 0000000000..b7e743b218
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_11.txt
@@ -0,0 +1,17 @@
+
+ #****##-
+ A█ *...**#
+ A█--..***A*#
+ .--..**#-*AA
+ -█.**.#*█*-..#
+ .#-..#-**.-A..
+ ** #......-.**
+ . ..A..*A .█.
+ A █.A..*A#.-.
+ ** -.A*#█A.-.-
+ █-- ....*A.**.
+ *--A.-*A***.-
+ - *.**--.*█
+ *# *..#-A*-
+ *- █*#-#-
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_12.txt b/codex-rs/tui2/frames/hash/frame_12.txt
new file mode 100644
index 0000000000..0c6c85043f
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_12.txt
@@ -0,0 +1,17 @@
+
+ #***#.
+ #*--A.#*
+ █ .A*##
+ A#...**█.
+ . █.....A.
+ .█..*-█-.█
+ . .A*..*
+ . A#*..█
+ *# .A..#..
+ . A.***-
+ .. .█***A
+ # *. -#.
+ A **.#**.
+ █-A█#.*.-
+ * █.*.A
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_13.txt b/codex-rs/tui2/frames/hash/frame_13.txt
new file mode 100644
index 0000000000..097cd508d7
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_13.txt
@@ -0,0 +1,17 @@
+
+ A***#
+ .--..
+ .--.█
+ .**.-
+ * ..
+ █A-..
+ # ..
+ # █.
+ A# -..
+ .█ #*.
+ █-.. .-
+ .---.
+ .##.-
+ *--.*
+ # .█*
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_14.txt b/codex-rs/tui2/frames/hash/frame_14.txt
new file mode 100644
index 0000000000..8eca909504
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_14.txt
@@ -0,0 +1,17 @@
+
+ #****
+ #A--.*
+ .-... .
+ ..A.█-.#
+ ...* .
+ .*.. █.
+ .... . *
+ ..*.- *
+ .... █
+ █-AA *A
+ *.██#.#.
+ .*..---.
+ A █.***-
+ .*A*--A
+ -* █*A
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_15.txt b/codex-rs/tui2/frames/hash/frame_15.txt
new file mode 100644
index 0000000000..cbf646ab35
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_15.txt
@@ -0,0 +1,17 @@
+
+ ##***.-
+ -#*..-A*#
+ AA.***.█*.
+ .A- AA#.--.
+ ..*█**..A█-.
+ *..-..AA. █
+ .. ......#.
+ ..A..#... █-.
+ ..###*...-.A.
+ .-.*A.*.*. ..
+ .A....-. - *
+ .**.-..*- *
+ █.*# AAA- *-
+ .-..**.#*A
+ *-*----A
+ --
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_16.txt b/codex-rs/tui2/frames/hash/frame_16.txt
new file mode 100644
index 0000000000..82698755af
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_16.txt
@@ -0,0 +1,17 @@
+
+ -*#█**#.-
+ A-..*..*.**
+ .AA█*A**.. █*
+ AAA **-*.*..**.
+ ..*-A*█*..*A.-*
+ ...*.█ .** . ...
+ **. A-#....A*█# .
+ .A* .-..A...█* -.
+ **...#.A-..█*# A
+ *█--#****..-. #-.
+ ...#██A**.*█*...-
+ ..* .- -AA# A
+ *.* . A#A-#.
+ *..█-*.AA#-.
+ █A.-*A--**
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_17.txt b/codex-rs/tui2/frames/hash/frame_17.txt
new file mode 100644
index 0000000000..57d02179e7
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_17.txt
@@ -0,0 +1,17 @@
+
+ #*###**.#-
+ -***...***.#█-#
+ #**A-**-##█...-█*
+ A.A-A.█-- █.**...**
+ .A- . .█A***AA #
+ -**#A- #AA. A#*A..A
+ * *A. #AA.- *█..A*.
+ -█*. AA..A.#..***
+ #A*A***#.*-.*-A*... .
+ .█-*--.A**A..* *#█#*
+ ***A███*****-.*AA* *█
+ *..-* -A..- *
+ -** **- #█#A--A
+ # .*#**#--**A.█
+ -#*A-##.*-#*
+ -
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_18.txt b/codex-rs/tui2/frames/hash/frame_18.txt
new file mode 100644
index 0000000000..ef524a0ed9
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_18.txt
@@ -0,0 +1,17 @@
+
+ -**#**#*.#-
+ -#█-*###.--#█#**-
+ -AA.*█**█#█.-█#AA* *
+ #..*.#-█* █*--A*.*****#
+ -*AA A. -█#-*A.A.-****-
+ A*. ##..---A#*#.█-A-A-A.
+ ..*AA #A*A.█-A█*.*.*#
+ █*-.. -*█..*- .*.█
+ *██ #******#..#.*A*# .*.-
+ -**.*** ..A--*-...-*.-* #
+ .A.*-██*****- *--A.A*A---
+ ** #*# --*█A*-█
+ *-*#--. -*--A*#-
+ █..**##***-█*-A-#*
+ █..-A--#.#█*#█
+ -
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_19.txt b/codex-rs/tui2/frames/hash/frame_19.txt
new file mode 100644
index 0000000000..80a9abf012
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_19.txt
@@ -0,0 +1,17 @@
+
+ --**#.#**..-
+ -#...*A***-*-#.*##
+ #***A█.#*- -*A#-***
+ A*.*#-- -**##-.*#
+ ..A-A- #.-█A█.* .*#
+ .*A*█ -.*.A .A █.*.
+ -*..█ A*-A.##- AAA#.
+ .... .*█*.█# . ...
+ .*.*#******....#***.* * █..
+ -*A#.**A-*#*#-# -- A*-*#A..-
+ █*█A#.█████**█ -*-A.AA AA█
+ **-*-* -AA-AA█
+ █ -*..*# #**.A.*-
+ ██..*A.#--**A*█ **.█
+ █..-A-█-#.-*--
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_2.txt b/codex-rs/tui2/frames/hash/frame_2.txt
new file mode 100644
index 0000000000..843df90f28
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_2.txt
@@ -0,0 +1,17 @@
+
+ -.-A*#***##-
+ -##A**#...*..*-█.*#-
+ #.*.***.*-- -█***A..*.#
+ -.A-A*█##- -#*.A.#
+ #-█A*-.*-**- -#.*.#
+ █A#█- .**#A*# **.*.
+ #.█*. -A.*.-.# A█.█.
+ .█ *- #.*..** .█A..
+ *██*. *.---.█..#########.-..*
+ -*█. A..█ A* .**----..--.#A .
+ *** * **...█ -█*******█.#*..
+ █*-.A# - ##*A#*
+ .*--.## #*-# -.█
+ -.-*--█*#A****.**--..*
+ -*#*#..----.*A*█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_20.txt b/codex-rs/tui2/frames/hash/frame_20.txt
new file mode 100644
index 0000000000..b588df3894
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_20.txt
@@ -0,0 +1,17 @@
+
+ --#*..*#*#--
+ #**█*#-#***..--**##
+ ##█-#*█.*█ -█-█*#*.#-
+ -.█-*.* -##.*A***
+ -. #.* -A -..-**..*
+ A-#.█ #*█*.█A █*..*
+ *.*#. #* .#*- #*.A
+ .--A- ██*A.█# ..█.
+ .A..*#********-#█*--*** A .*
+ █.-.-█ A------.* ***█.** #A ..
+ *#-*████████*█ *#*..#. A*
+ * -*A# -A*..A
+ *--*#.- #**-**█
+ -#-.█.#-**#A█.█-#A*█
+ -*#.- *----.*██
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_21.txt b/codex-rs/tui2/frames/hash/frame_21.txt
new file mode 100644
index 0000000000..0d1fc7ec26
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_21.txt
@@ -0,0 +1,17 @@
+
+ --#*#**#*##--
+ ##*----#.*.#*---*#-
+ **--#*-█- --.*#--*#
+ #*.*██ -#**#**#
+ A#A*- #.A-* **--#
+ A█A. #**-AA **-#
+ .█.- - A-#A█ ***█
+ -* ** █.# . .
+ . . ##*****### -.#█.# *A .
+ . .* .- -#. -█-*.# A█.A
+ * █. --███ █- █*-#* A- #
+ █# A*- -*█ A
+ *- --- -.**█ #-
+ **- *█*#A..*A**██ --
+ *##*#----#-*#*-
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_22.txt b/codex-rs/tui2/frames/hash/frame_22.txt
new file mode 100644
index 0000000000..8fbfdb5713
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_22.txt
@@ -0,0 +1,17 @@
+
+ -##*#**#*##-
+ -#A*..-A.A*..*.#A*#-
+ #***.***- -█****#--##
+ **.**█ ##...-**
+ *..A█ #-A.*..A*█.
+ *.*A- #.A.*-A- *.**.
+ .#**A .#.**A█ ..A.
+ ..*.- .*..-* .-.█.
+ ..#█# #.******##-**.- *# -.*█
+ -.* *-**# A#█.AA. ***-█.## A**
+ ***-. █████**█- -A*#-AAA█#-
+ ***-*# -*#█.#█
+ ██#* ##- -.*#█*-A
+ █A*##█*.**#**A**███#*
+ █.█.-*----*-.**-
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_23.txt b/codex-rs/tui2/frames/hash/frame_23.txt
new file mode 100644
index 0000000000..ef2f8adb70
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_23.txt
@@ -0,0 +1,17 @@
+
+ -##-*#*##*#--
+ -*.#.*-#-**#.-.*.#-
+ #█#.█#**- █.A#.**..#
+ A*.**A- -***..**
+ AA.-A█ #A##█*A**.*
+ #*.█A- -***██A*█..*.#
+ -..█. AAA. -.- █ .█*
+ .A. . .█.#-*# . *A.
+ -█* .#.********.-*.-█*- . ...
+ .**-.█*█ A-* *.-*#. *-.
+ A█. . -███████ █-A**.-A-A-
+ #..-.. #A.*-A-
+ * .#█A-- -.█**A#A
+ ***#**#*.**-##█--#*-
+ █. ***.--#--**-
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_24.txt b/codex-rs/tui2/frames/hash/frame_24.txt
new file mode 100644
index 0000000000..09a7fd520c
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_24.txt
@@ -0,0 +1,17 @@
+
+ -.-*##***#-
+ #█-A█.--.**##-█#
+ #██**A#█. .-A*.**# *
+ #█AA#A.*#*-.A- -**.*-█
+ # AA*A# -██A*-.--*.#█
+ .#*#*- *##A ..* A█*
+ . .. #A-#A█A-*.*-.-
+ . *.. .#*A*-..-A.-..
+ .. .***A##...##-*#-. . ..
+ - A *.A##**##..-*#*. .*.
+ * █*.**██████- *#.**.*A#-
+ * *#** . █A*A
+ *.**-.. -*█-AA-*
+ .-*#*-█..A***.--A-
+ *A-*#**--**#*
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_25.txt b/codex-rs/tui2/frames/hash/frame_25.txt
new file mode 100644
index 0000000000..af8bb947f6
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_25.txt
@@ -0,0 +1,17 @@
+
+ -#***####-
+ # *#*--**.*..#
+ A.AA##█..#***...-
+ .#*. A *. █*.#**A
+ #--*#A█-*A-.█ .AA*A*
+ *#...-*#.-.A A.#.AA.#
+ .A.*. .--A*-A.*A-█.*.
+ ...A..█ .-**A.*-.*..*
+ -#*.█.--****#..**.#*.*
+ A-█.A.#.-..**-.***A*.
+ *.*A*.-██████#A.*.A.-
+ .-█.*#**-#*A-A#AA.A
+ ---.-*-**A#-A-..A
+ *.***-**.** *.*
+ .#█**##-#.*
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_26.txt b/codex-rs/tui2/frames/hash/frame_26.txt
new file mode 100644
index 0000000000..7ff85c300a
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_26.txt
@@ -0,0 +1,17 @@
+
+ -****█##
+ A*.*A*.#*.#
+ A*██.**.*██*#
+ **█#...-..-#A-
+ .-#*...█**A*.**
+ * █.AAA█*-*█**A
+ . *█*..A..**█#
+ A- *...--*..A..
+ . .***#.#**A*..
+ .-.A#.--#****.
+ .-█A.*█*#A-#*..
+ *-..A* AA█..-
+ * *.* --A.A#
+ .█***█*-***
+ *AA-*.-**
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_27.txt b/codex-rs/tui2/frames/hash/frame_27.txt
new file mode 100644
index 0000000000..06e988b076
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_27.txt
@@ -0,0 +1,17 @@
+
+ ****##
+ .*AA.A*
+ *█- *.A█.
+ ...-..*..
+ . -.--█*
+ .-.-█-...-
+ * █..-*..
+ . -...*█..
+ .. . .#....
+ █* .█-.-*..
+ .- --**#A█
+ ..##..-A.
+ .**#*#A.-
+ *--.**AA
+ █*█ -*A
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_28.txt b/codex-rs/tui2/frames/hash/frame_28.txt
new file mode 100644
index 0000000000..0e25818145
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_28.txt
@@ -0,0 +1,17 @@
+
+ A***
+ .#-.-
+ * *.-
+ .--*.
+ . ..
+ . -█.
+ -.. -.
+ .-██.
+ A* -.
+ ...A..
+ . -.
+ .*#*.
+ .**..
+ *--A.
+ . .#.
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_29.txt b/codex-rs/tui2/frames/hash/frame_29.txt
new file mode 100644
index 0000000000..7f2ddab00a
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_29.txt
@@ -0,0 +1,17 @@
+
+ #****#
+ #.*A **
+ -#.. ██.
+ ....-*#A
+ * .█. .
+ .#... --
+ .**... -
+ ..*..
+ ...*. -
+ -.*.. -
+ *..A.- *
+ .A... -.
+ ....-.-.
+ .*.*A█.█
+ ..* .#
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_3.txt b/codex-rs/tui2/frames/hash/frame_3.txt
new file mode 100644
index 0000000000..8cce426bb4
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_3.txt
@@ -0,0 +1,17 @@
+
+ -.**##****#-
+ -##A*..#.█**.*--.*#-
+ #*A**.*██- -█. **#A-.#
+ A#A*.*##- -** ..*
+ █A*.A-A..**- *-*..-
+ A.**A .#.**** . **.
+ ** . █**.-█.# .*A.#
+ #-.#. #-.█A*. .-.*.
+ -██. *.*#..*-.*##---##-.-█*.
+ #*A*# .A*A**. .*.--# *.#**-.*.-
+ █-. . █..##█ █***███**#AAA#A
+ █*. *# - A-#-AA
+ *-AA**# ##*A█#.█
+ *-##-**-****#A***--#█
+ -*#*-A.----.*A-█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_30.txt b/codex-rs/tui2/frames/hash/frame_30.txt
new file mode 100644
index 0000000000..24a2165e45
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_30.txt
@@ -0,0 +1,17 @@
+
+ -*█**##
+ -A*..**█**
+ ██-.#**.##*
+ ..*.A.-*.* *#
+ **..-*.#.# .
+ .*.-# *......
+ *A...*- *A*. *-
+ █. █#*.#.█.- -
+ █.-█*.*.*A.# -
+ █..*.--.. ## -
+ *..**-*...#..
+ .*AA#A**..█ .
+ *.*..A*..#.A
+ #-##*-A.#A█
+ *-..---*█
+ ----
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_31.txt b/codex-rs/tui2/frames/hash/frame_31.txt
new file mode 100644
index 0000000000..65f139ab96
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_31.txt
@@ -0,0 +1,17 @@
+
+ -.A*#*#*#
+ -#**##-█#*█*#
+ #.*AA#*--.█.-**
+ #.A#--**-#**.*..*
+ -....#-**-#█*.A--
+ *.--.-.██***#.A.#█.
+ A.. .-*.*.*A**.*.A.
+ **# ..█.* .-██..*..
+ .*#-.█-...A#...- .
+ █...AA..---*-.*.. *
+ -*-A#.# A***-A.█.-
+ ...***# -** .
+ *.**- # . .*-A-
+ A.*.A-.-#.█#.-
+ ██*.-#*A.**
+ ----
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_32.txt b/codex-rs/tui2/frames/hash/frame_32.txt
new file mode 100644
index 0000000000..6cbec21aec
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_32.txt
@@ -0,0 +1,17 @@
+
+ #####**.#-
+ **.**.*..**..#
+ A-**-##-A--*.**█*#
+ █AA.-#-*- - #-*.## #
+ AA.#.**█*.* █-#.*A***#
+ *A**#**.-A..#- .#A *
+ *.█*#-█*..##.#*-A-AA.█-
+ ...#- █-..█A█.*--█*.██-
+ *..-- █-.█--.###...*.█*-
+ ███--.**█*-----..*.*.--
+ #**..A .*██***-*AAA.A
+ *#.-** #*.A█.
+ █**...#- -A-.A #
+ *-*█.#.***--#█-A
+ .**--##A*-██
+ ---
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_33.txt b/codex-rs/tui2/frames/hash/frame_33.txt
new file mode 100644
index 0000000000..a661feb2af
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_33.txt
@@ -0,0 +1,17 @@
+
+ -##*#*#*..-
+ -#*..***.A.-.*.*.
+ -A*.#*##*█- █*A..#█#
+ #*A.A-.#- *..*-*
+ -..A-..A*-* .#**-
+ AA# *-**-*# A*A-*
+ ..# *#*.-.* .*..
+ *.## #██*A*# *█.*
+ ... . #- A*###***#..#A-.*.
+ -A.██AA#A-..-----..*---...
+ ***# .A.A A ████*** ..#A--
+ *#**#█# AA*A*A
+ **█*#**# -#.#A**█
+ *.█**#.#*#-█*#**.*
+ █**##----#**-█
+ ----
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_34.txt b/codex-rs/tui2/frames/hash/frame_34.txt
new file mode 100644
index 0000000000..3427025326
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_34.txt
@@ -0,0 +1,17 @@
+
+ -#*####*.#-
+ -#*#A**.█.#*****#*-
+ -AA#.*█A.*- --**#█**#
+ #A-.*-A#- *.#***
+ AA.*-A. .█ # ****-
+ #A*.-A **█.*** *#*.*
+ .*-.- █*-*.-- .*.-
+ *.*█A .*-.A█. A -*
+ #█A.█ A*AA█-**######.--█ .--
+ ..*#A##-█AA█...-..---#A-..-.*
+ A-*# .*.*- █**----- #A#*.█
+ A#****- A*..A█
+ *#-.#**# -#*█-A#-
+ -*A.█.##*##****-#*A█
+ █.***-----****-
+ ---
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_35.txt b/codex-rs/tui2/frames/hash/frame_35.txt
new file mode 100644
index 0000000000..e0919ec5d0
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_35.txt
@@ -0,0 +1,17 @@
+
+ -##**###*##-
+ #***..**#█.*.A█.**-
+ -AA.*#*.-*█- -█***.█.*#
+ #AA#A#*#- *#-*.-
+ AA..AA* █**# .**.#
+ *A*A#- █.-█..*- .**.
+ * .A ** █*-. .-**
+ ...A A***A█ A █A
+ A #- #..A*█A.**-*-*#.. ..**
+ .#-*█ AA*█*#A.* *#----A█.A█ .█
+ A-*#█A*-.A-- -█----*--*AA-#.
+ █.-*A. -A* #-
+ **--*#A# #*A-**█
+ █--█.*.-A..#.*A*█-A*█
+ █-.**--A--##*█-
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_36.txt b/codex-rs/tui2/frames/hash/frame_36.txt
new file mode 100644
index 0000000000..0355f68b47
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_36.txt
@@ -0,0 +1,17 @@
+
+ --#*####*##-
+ -*██*#A*A#*#*##█**#-
+ #*█*##*-*█-- -█*.*#.#*.#
+ -.█*#---- █*.*█.
+ #A-**█.*-*#. -*.*
+ A #A- *- █.A# █*-*
+ . * - * █** .-.#
+ ..*. -* -AA *. .
+ .██. AA #*██###-#####- .*..
+ -*.* #.--A.A -.-------.. *A█-
+ █ *.* #-#A- █**-----█ .#█A
+ █#█**. #A.█A
+ *A..#.# ###█A#-
+ *#-█***-*.-#.*█-█#*#█
+ -*#A.-##-####**█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_4.txt b/codex-rs/tui2/frames/hash/frame_4.txt
new file mode 100644
index 0000000000..2b4b7c670b
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_4.txt
@@ -0,0 +1,17 @@
+
+ -.**#**#*##-
+ --█#*.A .**A**.█A*#-
+ #**...#*█- --.*-*.A**-
+ AA.#.█.## █.*****
+ A.A-.*.**-.# *█*.**
+ A..-. █-..A** █ **.#
+ █*.*- █***#█.# # █*.
+ ..* #.A*-.. ...
+ -. .- *.A█-AA#.###----## ..*
+ .*A . #AAA#-.-**.#.-#AA-*.AA█.
+ -.*█*#**#*A █*******█--...-
+ #.*█.-- #-*A**█
+ **#A- #- -.-#**.A
+ ...*-*******##**#*.*-
+ ***.A.-----*-*-
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_5.txt b/codex-rs/tui2/frames/hash/frame_5.txt
new file mode 100644
index 0000000000..c71575690b
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_5.txt
@@ -0,0 +1,17 @@
+
+ -.***#***##-
+ -#█#A*A..#.*#*-.█##
+ *-A*#.*█- █-*.** #*#
+ #.A.A..*# --....-
+ #*A*A--#.-*# - *.*.-
+ ....A *-.**A.- #A..
+ .A. # -*-.*█.# ██.#.#
+ .A.-█ #-*.A-. #.-.
+ .#.-* A-.█#.**-.#.---##-█...
+ -*.*##A#*█ .█ AA**-#*.#A.A*.-
+ *#..#.#**A#- █**█████#.*.*A
+ **#A** - A-A*#-
+ -A**.*#- -*##*█**
+ -.*.#*#**.*-##**-.**
+ --*-*█-----##*-
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_6.txt b/codex-rs/tui2/frames/hash/frame_6.txt
new file mode 100644
index 0000000000..799e3a1cf5
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_6.txt
@@ -0,0 +1,17 @@
+
+ -.***#**##--
+ #-*A*.**#.##*-#*#-
+ ###...*█ -█..**#*A*-
+ A#.*.*-*# *#....#
+ █*...***#** .**.*#
+ *-A.A--#*.*-.# .**A.
+ - #.. -*.A-* -#.-.
+ . ... -.*.A.. .#*..
+ -..-. A█..**A#-.#.--##-.*A.
+ ..*#A---*# .A**#..#****.#.*
+ A . A...*A█ █*████*█-**A.
+ # * A#- #A-AA.-
+ .-*-**# -#--A*##
+ -█.*#█# *.--##** A*█
+ --**##-----##*
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_7.txt b/codex-rs/tui2/frames/hash/frame_7.txt
new file mode 100644
index 0000000000..4a3f9f202f
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_7.txt
@@ -0,0 +1,17 @@
+
+ -..**#**##-
+ #*-#*.#*#**** -*#
+ * #...*- --.- *A-*#
+ **....*# -.**.A#
+ -█.*..-.A*# . *..*
+ . *..█ -█**.* #-...
+ -*█. --.*.*. **-..
+ -█A.. *#A.*.- █ ...
+ A█.* #█-A.*A..**-..****..
+ .#█..*A..A█..*..**#*#**.*.
+ * *-A*.*-A ******██-A..
+ █- A-A-- #█-A*A█
+ █*##***- #-.#*A*█
+ *-█*.***.---#*.*#A
+ █.*█.A.--#-***
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_8.txt b/codex-rs/tui2/frames/hash/frame_8.txt
new file mode 100644
index 0000000000..4bc5a6f118
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_8.txt
@@ -0,0 +1,17 @@
+
+ --#-*##*##-
+ #█*A...*** . █#
+ -.*#.AA* #█.A.**#-#
+ -***A.##. █ *-..*
+ █ A.A#*.A* .█*..#
+ .█#.*---*.-* *#...
+ .*... █-**.-. .-.A.#
+ *#..A .#*A.#*. .-A..
+ * *..-- A**..A#####*...
+ **A*-.█#.#..*.*--..*█
+ AA**.*...A█-*-*█**█A*.
+ █#█.*.-- .#AAA█
+ █*-****- -A*-.#A*
+ .A█.#* **#**A*#.-
+ ..-***.-##A*-
+ --
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hash/frame_9.txt b/codex-rs/tui2/frames/hash/frame_9.txt
new file mode 100644
index 0000000000..db3507db59
--- /dev/null
+++ b/codex-rs/tui2/frames/hash/frame_9.txt
@@ -0,0 +1,17 @@
+
+ .*-*A##*#
+ A*-A..*█* --*-
+ A #..A*--*A *-.#
+ █ ..A**- --#.*-.##
+ A*█***█.*# *.█#A#..
+ . ...█-.**-- .█.*...
+ - .**.**.**#█.#A -..
+ . .A-#*...-A**-. ..
+ █#.█ A.█....#..#..-
+ .-...-#.-.-....--...
+ █ --A**.A█****..█A*.
+ *...*#- #A -A.-
+ *#*.** A*-*.A*
+ --█*-.*A#****.-
+ █-- ***.*#A█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_1.txt b/codex-rs/tui2/frames/hbars/frame_1.txt
new file mode 100644
index 0000000000..ab8be3eb1e
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_1.txt
@@ -0,0 +1,17 @@
+
+ ▂▅▂▅▄▇▇▄▄▇▆▂
+ ▂▄▆▅▇▃▇▅▇▃▄▁▁▄▂ ▂█▇▂
+ ▆▁▇▁▇▇▇█▃▂ ▂█▇▂█▁▄▁▁▁▇
+ ▄▇▂▃▇█▆▆▂ ▅▇▁▄▁▆
+ ▃▃▄▅█▃▁▃▂▃▃ █▅▁▃▃▆
+ ▁▇ ▇▂ ▁▇▅▄▁▁▆ █▅▃▁▁▆
+ ▇▃█▆▇ █▃▁▇▅█▁▂ ▁▅▁
+ ▁▁▂▁▂ ▆▅▅▁▄▁▇ █▂▁
+ ▁▄▁█▂ ▄▁▁▃▃▁█▅▁▇▇▇▇▇▇▂▇▆ ▄█ ▁
+ ▂▁▄▇ ▂▄▇▂ ▅▇ ▁█▁▂▂▂▅▅▆▆▆▁▅▆▅▆▁
+ ▃▃▂█▃ ▃▃▆▅▅▂ ▂▃▇██▇ ▃▇█▅▆▄▂▅
+ ▇▃▆ █▆ ▂ ▆█▅▇▂▁
+ ▃▃▆▂▃▇▂ ▂▄▂▇▁▂▇█
+ ▃▇▆▃▂ ▇▇▅▄▄▄▄▅▄▇▇▂▆▁▇
+ ▂▇█▇▁▁▁▂▂▂▆▂▄▇▇█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_10.txt b/codex-rs/tui2/frames/hbars/frame_10.txt
new file mode 100644
index 0000000000..5e565ce40b
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_10.txt
@@ -0,0 +1,17 @@
+
+ ▂▇▇▇▇▃▇▇▂
+ ▇█▂▇▇▇▃▁▅▂▇▆
+ ▃▂▆▁▁▅▁▁▆▁▇▃▆▆
+ ▁▂▂▅▃▁▄▂▅▃▆██▃▃▆
+ ▅ ▄▁▁█▁▃ █▆▅▂▅▁▅
+ ▁▂ █▁▇▁▅▅▃ ▂▂█▁
+ ▃ ▁▇█▇▁▁▁▁▇ ▁▅▆
+ █ ▁▁▃▇▅▇▁▁▆▂▂▅▃▁▁
+ █ ▁▃ ▃▃▁▄▁▁▇▃▇▄▁▁
+ ▁ ▆▁▃▆▁▂▅▂▇▂▂▂▁▇▂
+ ▆ █▁▁▁▁▁██ ▃▆█▃▁▂
+ ▃▂█▆▃▆▇█ ▂▁██▆▅▅
+ ▁█ ▁▁▁▁▇▆▅▆▅▁▅▂
+ ▄▂▇▇▅▁▇▄▂ ▅▅█
+ ▇▆ ▂▇▃▂▆▄▇
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_11.txt b/codex-rs/tui2/frames/hbars/frame_11.txt
new file mode 100644
index 0000000000..5305252a8d
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_11.txt
@@ -0,0 +1,17 @@
+
+ ▆▇▇▇▇▇▇▂
+ ▅█ ▄▁▁▁▃▃▆
+ ▅█▂▂▁▁▄▃▇▅▃▆
+ ▁▂▂▁▁▄▄▆▂▄▅▅
+ ▂█▅▄▃▁▇▃█▄▂▁▁▆
+ ▁▇▂▁▁▇▂▄▄▁▂▅▁▁
+ ▇▇ ▆▁▁▁▁▁▁▂▁▄▃
+ ▁ ▁▁▅▁▁▃▅ ▁█▁
+ ▅ █▁▅▁▁▇▅▇▁▂▁
+ ▇▇ ▂▁▅▄▆█▅▁▂▁▃
+ █▂▆ ▁▁▁▁▄▅▁▃▃▁
+ ▃▂▆▅▁▂▇▅▇▇▄▁▂
+ ▂ ▇▁▃▃▃▂▁▄█
+ ▃▇ ▇▁▁▆▂▅▇▂
+ ▃▂ █▇▇▂▇▂
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_12.txt b/codex-rs/tui2/frames/hbars/frame_12.txt
new file mode 100644
index 0000000000..cebfe226e1
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_12.txt
@@ -0,0 +1,17 @@
+
+ ▇▇▇▇▇▅
+ ▆▄▂▂▅▁▆▃
+ █ ▁▅▃▇▆
+ ▅▇▁▁▁▄▄█▁
+ ▁ █▁▁▁▁▅▅▁
+ ▁█▅▅▇▃█▂▁█
+ ▁ ▁▅▃▁▁▃
+ ▁ ▅▇▃▁▁█
+ ▇▆ ▁▅▁▁▇▁▁
+ ▁ ▅▁▇▄▇▂
+ ▁▅ ▁█▄▇▇▅
+ ▆ ▇▁ ▂▆▁
+ ▅ ▇▇▁▆▇▃▁
+ █▃▅█▆▁▃▁▂
+ ▃ █▁▃▅▅
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_13.txt b/codex-rs/tui2/frames/hbars/frame_13.txt
new file mode 100644
index 0000000000..566cc4ffa3
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_13.txt
@@ -0,0 +1,17 @@
+
+ ▅▇▇▇▆
+ ▁▂▂▁▁
+ ▁▂▂▁█
+ ▁▇▇▁▂
+ ▇ ▁▁
+ █▅▆▁▁
+ ▆ ▁▁
+ ▇ █▁
+ ▅▇ ▂▁▅
+ ▁█ ▇▄▁
+ █▂▅▅ ▁▂
+ ▁▂▂▂▁
+ ▁▇▆▁▂
+ ▇▂▂▁▄
+ ▆ ▅█▄
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_14.txt b/codex-rs/tui2/frames/hbars/frame_14.txt
new file mode 100644
index 0000000000..380790e11c
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_14.txt
@@ -0,0 +1,17 @@
+
+ ▇▇▇▇▄
+ ▆▅▂▂▅▃
+ ▁▂▁▁▅ ▁
+ ▁▁▅▁█▃▁▆
+ ▁▁▁▃ ▁
+ ▁▇▁▁ █▁
+ ▁▁▁▁ ▅ ▇
+ ▁▁▃▁▂ ▃
+ ▁▁▁▁ █
+ █▃▅▅ ▄▅
+ ▃▁██▆▅▆▁
+ ▁▇▁▁▂▂▂▁
+ ▅ █▁▄▄▄▂
+ ▁▃▅▇▂▂▅
+ ▂▇ █▄▅
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_15.txt b/codex-rs/tui2/frames/hbars/frame_15.txt
new file mode 100644
index 0000000000..47d169e98b
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_15.txt
@@ -0,0 +1,17 @@
+
+ ▇▇▇▇▇▁▂
+ ▂▆▄▁▁▃▅▇▆
+ ▅▅▁▇▄▃▁█▇▁
+ ▁▅▂ ▅▅▆▅▂▂▁
+ ▁▁▄█▄▃▁▁▅█▃▁
+ ▃▁▁▆▁▁▅▅▁ █
+ ▁▁ ▁▁▁▁▁▁▆▁
+ ▁▁▅▁▁▇▁▁▁ █▆▁
+ ▁▁▇▆▆▇▁▁▁▂▅▅▁
+ ▁▂▁▄▅▁▃▁▇▅ ▅▁
+ ▁▅▁▁▁▁▂▁ ▂ ▄
+ ▁▇▇▅▃▁▁▃▆ ▄
+ █▁▃▆ ▅▅▅▂ ▄▂
+ ▁▃▁▁▃▃▅▇▃▅
+ ▃▃▇▃▂▂▂▅
+ ▂▂
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_16.txt b/codex-rs/tui2/frames/hbars/frame_16.txt
new file mode 100644
index 0000000000..3b1fb1fc5d
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_16.txt
@@ -0,0 +1,17 @@
+
+ ▂▄▇█▇▇▇▁▂
+ ▅▃▁▁▇▁▁▃▁▄▃
+ ▁▅▅█▃▅▄▃▁▁ █▃
+ ▅▅▅ ▄▇▂▃▁▃▁▁▇▇▁
+ ▁▁▄▂▅▇█▄▁▁▇▅▁▂▃
+ ▁▁▁▇▁█ ▁▃▄ ▁ ▁▅▁
+ ▃▃▁ ▅▂▆▁▁▁▁▅▇█▆ ▁
+ ▁▅▄ ▁▂▁▁▅▁▁▁█▄ ▂▁
+ ▃▃▁▁▁▇▁▅▃▁▁█▇▇ ▅
+ ▇█▂▂▆▄▄▃▇▁▅▂▁ ▆▂▁
+ ▁▁▁▇██▅▇▃▁▄█▄▅▁▁▂
+ ▁▁▇ ▁▂ ▂▅▅▆ ▅
+ ▃▁▇ ▁ ▅▆▅▂▆▁
+ ▃▁▁█▂▇▁▅▅▇▂▁
+ █▅▅▂▄▅▂▂▄▇
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_17.txt b/codex-rs/tui2/frames/hbars/frame_17.txt
new file mode 100644
index 0000000000..93817e2ead
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_17.txt
@@ -0,0 +1,17 @@
+
+ ▆▄▇▇▇▄▄▁▆▂
+ ▂▄▇▇▁▁▁▇▄▇▁▆█▃▆
+ ▆▇▃▅▂▄▄▂▇▆█▁▁▁▂█▃
+ ▅▁▅▂▅▁█▂▂ █▁▄▃▁▁▁▄▃
+ ▁▅▂ ▁ ▁█▅▃▄▃▅▅ ▆
+ ▂▄▇▆▅▂ ▆▅▅▁ ▅▆▄▅▁▅▅
+ ▇ ▄▅▁ ▆▅▅▁▂ ▇█▁▁▅▄▁
+ ▆█▄▁ ▅▅▁▁▅▁▆▁▁▄▄▇
+ ▆▅▇▅▃▄▄▇▁▃▂▁▃▃▅▃▁▁▁ ▁
+ ▁█▂▄▂▂▁▅▇▃▅▁▁▃ ▃▇█▇▃
+ ▃▃▃▅███▇▇▇▇▃▂▁▇▅▅▃ ▃█
+ ▃▁▁▂▇ ▂▅▁▁▂ ▄
+ ▂▃▃ ▇▃▂ ▆█▆▅▃▂▅
+ ▆ ▁▇▇▄▃▇▂▂▄▇▅▁█
+ ▂▇▄▅▂▆▇▁▇▂▇▇
+ ▂
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_18.txt b/codex-rs/tui2/frames/hbars/frame_18.txt
new file mode 100644
index 0000000000..03d2c5e94b
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_18.txt
@@ -0,0 +1,17 @@
+
+ ▂▄▄▇▄▄▇▄▁▆▂
+ ▂▇█▂▄▆▇▇▁▂▂▆█▇▄▄▂
+ ▂▅▅▁▇█▇▄█▆█▅▂█▇▅▅▃ ▇
+ ▆▁▁▇▅▆▃█▇ █▃▂▂▅▄▁▃▄▃▃▃▆
+ ▂▃▅▅ ▅▁ ▂█▇▂▃▅▁▅▁▂▃▄▃▃▂
+ ▅▃▁ ▆▆▁▅▂▂▂▅▆▇▆▁█▆▅▃▅▂▅▁
+ ▁▁▃▅▅ ▇▅▇▅▁█▂▅█▇▁▄▁▄▆
+ █▃▆▁▁ ▃▃█▁▁▄▃ ▁▄▁█
+ ▃██ ▆▃▄▄▄▄▄▇▁▁▆▁▇▅▃▆ ▁▇▁▂
+ ▂▃▃▁▇▃▇ ▁▁▅▂▂▃▂▁▁▁▂▄▁▂▃ ▆
+ ▁▅▁▃▂██▇▇▇▇▇▂ ▃▂▂▅▁▅▇▅▂▆▂
+ ▃▃ ▆▃▆ ▂▂▇█▅▇▂█
+ ▃▃▇▇▃▃▅ ▂▇▃▂▅▃▆▂
+ █▁▅▇▇▇▇▄▄▄▃█▇▂▅▂▆▇
+ █▁▁▂▅▂▂▆▅▇█▄▇█
+ ▂
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_19.txt b/codex-rs/tui2/frames/hbars/frame_19.txt
new file mode 100644
index 0000000000..f826776170
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_19.txt
@@ -0,0 +1,17 @@
+
+ ▂▂▄▄▇▁▇▄▄▁▅▂
+ ▂▇▁▁▁▃▅▄▄▄▂▇▂▆▁▇▆▆
+ ▆▇▄▄▅█▁▇▇▂ ▂▇▅▆▂▇▄▃
+ ▅▄▁▇▆▃▂ ▂▄▄▇▆▃▁▇▆
+ ▁▁▅▂▅▂ ▆▁▃█▅█▁▃ ▁▃▆
+ ▁▃▅▇█ ▂▁▇▁▅ ▅▅ █▅▇▁
+ ▃▄▁▁█ ▅▇▃▅▁▇▆▂ ▅▅▅▇▁
+ ▁▁▁▁ ▁▄█▃▁█▆ ▁ ▁▁▁
+ ▁▇▁▃▆▄▄▄▄▄▄▁▁▁▁▇▇▄▇▁▄ ▃ █▁▁
+ ▃▄▅▆▁▄▇▅▃▇▇▃▆▂▆ ▃▂ ▅▃▂▃▆▅▅▁▂
+ █▃█▅▇▁█████▇▇█ ▃▃▂▅▁▅▅ ▅▅█
+ ▃▃▃▇▂▃ ▂▅▅▂▅▅█
+ █ ▂▃▁▁▇▆ ▆▄▄▅▅▁▄▂
+ ██▅▁▇▅▁▇▂▂▄▄▅▇█ ▄▇▁█
+ █▁▅▂▅▆█▂▆▅▃▇▆▃
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_2.txt b/codex-rs/tui2/frames/hbars/frame_2.txt
new file mode 100644
index 0000000000..d4efa4def0
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_2.txt
@@ -0,0 +1,17 @@
+
+ ▂▅▂▅▄▇▄▄▄▇▆▂
+ ▂▇▆▅▇▄▇▁▁▁▄▁▁▄▂█▁▇▇▂
+ ▆▁▇▁▃▇▇▁▇▂▂ ▂█▇▄▇▅▁▁▄▁▆
+ ▂▁▅▂▅▇█▆▆▂ ▆▆▃▁▅▁▆
+ ▆▃█▅▇▃▁▃▂▃▃▂ ▃▆▁▃▁▆
+ █▅▇█▂ ▁▇▃▇▅▃▇ ▃▃▁▇▁
+ ▆▁█▇▁ ▃▅▁▄▁▂▁▆ ▅█▁█▁
+ ▁█ ▃▂ ▆▁▇▁▁▄▇ ▁█▅▅▁
+ ▇██▄▁ ▄▁▃▃▂▁█▅▁▇▇▇▇▇▇▇▇▆▁▂▁▁▇
+ ▂▄█▁ ▅▁▁█ ▅▇ ▁▄▃▂▂▂▂▅▅▂▂▁▇▅ ▁
+ ▃▃▃ ▇ ▇▃▅▅▁█ ▂█▇▇▇▇▇▇▇█▁▆▇▁▁
+ █▃▂▅▅▆ ▂ ▆▇▄▅▆▇
+ ▅▃▂▂▁▇▆ ▆▄▂▇ ▂▁█
+ ▂▁▃▄▂▂█▇▇▅▄▄▄▄▅▄▇▂▂▁▁▇
+ ▂▇▇▇▇▁▁▂▂▂▂▁▄▅▇█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_20.txt b/codex-rs/tui2/frames/hbars/frame_20.txt
new file mode 100644
index 0000000000..30c29f51c9
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_20.txt
@@ -0,0 +1,17 @@
+
+ ▂▂▇▄▁▁▄▇▄▆▂▂
+ ▆▄▄█▄▆▂▆▄▄▄▁▁▂▃▇▃▇▆
+ ▆▆█▂▇▇█▁▇█ ▂█▃█▃▇▇▁▇▂
+ ▂▁█▂▇▁▇ ▂▆▇▁▃▅▇▃▃
+ ▂▁ ▆▁▇ ▂▅ ▂▁▁▃▇▃▁▁▃
+ ▅▂▆▁█ ▇▇█▄▁█▅ █▃▁▁▃
+ ▄▁▄▇▁ ▆▇ ▅▇▇▃ ▆▃▁▅
+ ▁▂▃▅▂ ██▄▅▁█▆ ▁▁█▁
+ ▁▅▁▁▄▆▄▄▄▄▄▄▄▄▂▆█▄▃▃▃▃▇ ▅ ▁▃
+ █▁▃▁▂█ ▅▂▂▂▂▂▂▁▃ ▇▃▃█▁▄▃ ▆▅ ▁▁
+ ▃▆▃▃████████▇█ ▃▆▄▁▁▆▁ ▅▃
+ ▇ ▃▇▅▆ ▂▅▇▅▁▅
+ ▃▂▃▇▆▁▂ ▆▄▇▂▄▇█
+ ▃▆▆▅█▁▇▃▄▄▆▅█▁█▂▆▅▇█
+ ▂▇▇▁▂ ▄▂▂▂▂▁▇██
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_21.txt b/codex-rs/tui2/frames/hbars/frame_21.txt
new file mode 100644
index 0000000000..b6a6c2c109
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_21.txt
@@ -0,0 +1,17 @@
+
+ ▂▂▆▄▇▄▄▇▄▇▆▂▂
+ ▆▇▇▂▂▂▂▇▁▄▁▇▄▂▂▆▇▇▂
+ ▄▇▃▂▇▇▃█▂ ▂▃▁▇▇▂▂▇▆
+ ▆▇▁▄██ ▂▆▄▇▆▄▇▆
+ ▅▆▅▇▂ ▆▁▅▂▃ ▃▃▂▃▆
+ ▅█▅▁ ▆▇▇▂▅▅ ▃▃▃▆
+ ▁█▁▂ ▂ ▅▂▆▅█ ▃▄▃█
+ ▂▃ ▃▄ █▁▆ ▁ ▁
+ ▁ ▁ ▆▇▄▄▄▄▄▇▇▇ ▃▁▆█▁▆ ▄▅ ▁
+ ▁ ▁▃ ▁▂ ▂▆▁ ▃█▂▇▁▆ ▅█▅▅
+ ▄ █▅ ▂▂███ █▂ █▇▂▆▄ ▅▂ ▆
+ █▇ ▅▄▂ ▂▇█ ▅
+ ▇▂ ▃▆▂ ▂▅▄▇█ ▆▂
+ ▇▄▂ ▇█▇▇▅▁▁▄▅▄▇██ ▆▂
+ ▇▇▇▄▇▂▂▂▂▆▂▄▇▇▂
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_22.txt b/codex-rs/tui2/frames/hbars/frame_22.txt
new file mode 100644
index 0000000000..38195cd38b
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_22.txt
@@ -0,0 +1,17 @@
+
+ ▂▆▇▄▇▄▄▇▄▇▆▂
+ ▂▇▅▇▁▅▂▅▁▅▃▁▁▄▁▇▅▇▇▂
+ ▆▄▇▄▁▃▇▇▂ ▂█▇▃▇▇▇▂▂▇▆
+ ▄▇▁▇▇█ ▆▆▁▁▁▂▇▃
+ ▃▁▁▅█ ▆▂▅▁▄▁▅▅▄█▁
+ ▃▁▇▅▂ ▆▁▅▁▄▃▅▂ ▃▁▃▄▁
+ ▁▇▇▃▅ ▁▇▁▃▇▅█ ▁▁▅▁
+ ▁▁▄▁▂ ▁▃▁▁▃▃ ▁▃▁█▁
+ ▁▁▆█▆ ▇▁▄▄▄▄▄▄▇▇▂▃▇▁▂ ▃▆ ▂▁▄█
+ ▃▁▄ ▇▂▃▃▆ ▅▆█▁▅▅▁ ▃▇▄▂█▁▆▆ ▅▃▄
+ ▃▃▃▂▁ █████▇▇█▂ ▂▅▇▇▂▅▅▅█▆▂
+ ▃▇▃▂▃▆ ▂▇▆█▁▆█
+ ██▇▄ ▇▇▂ ▂▅▇▆█▇▂▅
+ █▅▇▇▆█▇▁▄▄▇▄▄▅▄▇███▆▇
+ █▁█▁▂▄▂▂▂▆▄▂▅▄▇▂
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_23.txt b/codex-rs/tui2/frames/hbars/frame_23.txt
new file mode 100644
index 0000000000..a81cac3ef2
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_23.txt
@@ -0,0 +1,17 @@
+
+ ▂▆▇▂▄▇▇▇▇▄▇▂▂
+ ▂▄▁▇▁▃▂▆▂▄▄▆▁▂▁▇▁▇▂
+ ▆█▇▁█▆▄▇▂ █▁▅▇▁▃▄▁▁▆
+ ▅▄▁▇▄▅▂ ▂▄▄▃▁▁▄▃
+ ▅▅▁▂▅█ ▆▅▆▆█▇▅▇▃▁▃
+ ▆▃▁█▅▂ ▂▇▇▇██▅▇█▁▁▃▁▆
+ ▂▁▁█▁ ▅▅▅▅ ▂▁▂ █ ▁█▇
+ ▁▅▁ ▁ ▁█▁▆▂▃▆ ▁ ▇▅▁
+ ▃█▃ ▁▇▁▄▄▄▄▄▄▄▄▁▂▇▁▂█▃▂ ▁ ▁▁▁
+ ▁▃▃▂▁█▄█ ▅▂▃ ▃▁▂▃▆▁ ▃▂▁
+ ▅█▁ ▁ ▂███████ █▂▅▄▄▁▂▅▃▅▂
+ ▆▁▁▂▁▅ ▆▅▁▃▃▅▂
+ ▃ ▁▆█▅▂▂ ▂▅█▄▇▅▇▅
+ ▃▄▃▇▄▇▇▃▁▄▄▂▇▇█▆▂▇▇▂
+ █▁ ▇▄▃▁▂▂▇▂▂▇▇▂
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_24.txt b/codex-rs/tui2/frames/hbars/frame_24.txt
new file mode 100644
index 0000000000..791f93b591
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_24.txt
@@ -0,0 +1,17 @@
+
+ ▂▁▂▄▇▇▇▄▄▆▂
+ ▆█▂▅█▁▂▂▁▄▄▇▆▂█▇
+ ▆██▄▃▅▇█▁ ▅▂▅▇▁▇▇▆ ▃
+ ▆█▅▅▆▅▁▄▆▃▂▁▅▂ ▂▇▃▁▃▂█
+ ▆ ▅▅▃▅▆ ▂██▅▃▂▁▂▂▃▁▆█
+ ▁▆▃▇▃▂ ▇▆▆▅ ▅▁▄ ▅█▃
+ ▁ ▁▁ ▆▅▂▆▅█▅▃▃▁▃▃▁▃
+ ▁ ▃▁▁ ▁▆▄▅▃▂▁▁▂▅▅▂▁▁
+ ▁▅ ▁▄▄▄▅▇▇▁▁▁▇▇▂▇▆▂▁ ▁ ▁▁
+ ▂ ▅ ▇▁▅▆▆▄▄▆▆▁▅▃▃▇▇▁ ▁▇▁
+ ▃ █▃▁▃▇██████▂ ▃▆▅▇▃▁▄▅▆▂
+ ▃ ▃▆▇▃ ▁ █▅▄▅
+ ▃▅▇▃▂▁▅ ▂▄█▂▅▅▂▇
+ ▅▆▇▆▃▃█▁▁▅▄▄▄▁▃▂▅▂
+ ▇▅▂▇▇▄▃▂▂▄▄▇▇
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_25.txt b/codex-rs/tui2/frames/hbars/frame_25.txt
new file mode 100644
index 0000000000..565fdb82ea
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_25.txt
@@ -0,0 +1,17 @@
+
+ ▂▇▄▇▄▇▇▇▇▂
+ ▆ ▇▆▇▂▂▄▃▁▇▁▁▆
+ ▅▁▅▅▆▆█▅▁▇▃▄▃▁▁▁▂
+ ▁▇▇▁ ▅ ▄▁ █▃▁▆▇▃▅
+ ▆▂▂▃▆▅█▃▄▅▂▁█ ▁▅▅▃▅▇
+ ▃▆▁▁▁▂▇▇▅▃▁▅ ▅▁▆▁▅▅▁▆
+ ▁▅▁▇▁ ▁▂▂▅▃▂▅▁▃▅▂█▁▄▁
+ ▁▁▁▅▁▅█ ▁▂▄▃▅▁▃▂▁▄▁▁▃
+ ▃▇▃▁█▁▂▂▄▄▄▄▇▁▁▃▃▁▇▇▁▃
+ ▅▆█▁▅▁▆▁▂▁▁▄▇▂▁▃▇▄▅▃▁
+ ▃▁▇▅▃▁▂██████▇▅▁▃▁▅▁▂
+ ▁▂█▁▄▇▄▃▆▆▇▅▂▅▆▅▅▁▅
+ ▃▂▃▁▂▃▂▇▄▅▆▃▅▂▁▁▅
+ ▃▅▄▃▃▂▇▄▁▇▇ ▇▁▇
+ ▁▆█▇▃▇▆▂▇▁▇
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_26.txt b/codex-rs/tui2/frames/hbars/frame_26.txt
new file mode 100644
index 0000000000..e37d671dc4
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_26.txt
@@ -0,0 +1,17 @@
+
+ ▂▄▇▇▇█▇▆
+ ▅▇▁▄▅▃▁▇▄▁▆
+ ▅▇██▁▄▃▁▃██▃▆
+ ▄▇█▆▁▁▁▂▁▁▂▇▅▃
+ ▁▂▆▃▁▅▁█▇▃▅▄▁▃▄
+ ▃ █▁▅▅▅█▇▂▃█▃▃▅
+ ▁ ▇█▄▁▁▅▁▁▄▄█▇
+ ▅▆ ▃▁▁▁▃▃▄▁▁▅▁▁
+ ▁ ▅▃▇▄▇▁▇▄▄▅▃▁▁
+ ▅▂▁▅▆▁▂▂▆▇▃▃▇▁
+ ▁▂█▅▁▇█▃▆▅▂▇▃▁▁
+ ▃▂▁▁▅▃ ▅▅█▁▁▂
+ ▇ ▇▁▃ ▃▂▅▁▅▆
+ ▁█▇▃▃█▇▂▇▇▄
+ ▃▅▅▃▇▁▂▃▇
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_27.txt b/codex-rs/tui2/frames/hbars/frame_27.txt
new file mode 100644
index 0000000000..d3dbefa975
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_27.txt
@@ -0,0 +1,17 @@
+
+ ▄▇▇▇▇▆
+ ▁▄▅▅▁▅▃
+ ▄█▂ ▇▁▅█▁
+ ▁▁▁▃▁▁▄▁▁
+ ▁ ▂▁▂▆█▄
+ ▁▂▅▂█▂▁▁▁▂
+ ▄ █▁▁▂▇▁▁
+ ▁ ▂▁▁▁▄█▁▁
+ ▁▅ ▅ ▁▇▁▁▁▁
+ █▄ ▅█▂▁▂▇▁▁
+ ▁▆ ▂▃▇▇▇▅█
+ ▁▁▇▇▁▁▂▅▁
+ ▁▄▄▇▄▆▅▁▃
+ ▃▂▂▁▃▄▅▅
+ █▃█ ▃▃▅
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_28.txt b/codex-rs/tui2/frames/hbars/frame_28.txt
new file mode 100644
index 0000000000..0ae0f54e0b
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_28.txt
@@ -0,0 +1,17 @@
+
+ ▅▇▇▄
+ ▁▇▂▁▂
+ ▄ ▄▁▂
+ ▁▆▂▇▁
+ ▁ ▁▁
+ ▁ ▆█▁
+ ▃▁▁ ▂▁
+ ▁▆██▁
+ ▅▃ ▂▁
+ ▁▁▅▅▁▁
+ ▁ ▂▁
+ ▁▄▇▄▁
+ ▁▄▇▁▁
+ ▇▂▂▅▁
+ ▁ ▅▇▁
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_29.txt b/codex-rs/tui2/frames/hbars/frame_29.txt
new file mode 100644
index 0000000000..d333f278dc
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_29.txt
@@ -0,0 +1,17 @@
+
+ ▇▇▇▇▇▆
+ ▆▁▇▅ ▇▃
+ ▃▆▁▁ ██▁
+ ▁▁▁▁▃▃▆▅
+ ▃ ▁█▁ ▁
+ ▁▆▁▁▁ ▂▂
+ ▁▃▃▁▁▁ ▃
+ ▁▁▄▁▁
+ ▁▁▁▇▁ ▂
+ ▂▁▄▁▁ ▂
+ ▇▁▁▅▁▃ ▄
+ ▁▅▁▁▁ ▂▁
+ ▁▁▁▁▂▁▂▁
+ ▁▄▁▇▅█▁█
+ ▁▁▇ ▅▆
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_3.txt b/codex-rs/tui2/frames/hbars/frame_3.txt
new file mode 100644
index 0000000000..5d0b07202a
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_3.txt
@@ -0,0 +1,17 @@
+
+ ▂▅▄▄▇▇▄▄▄▄▆▂
+ ▂▇▆▅▃▁▁▇▁█▄▄▁▄▂▃▁▇▇▂
+ ▆▄▅▇▄▁▇██▂ ▂█▁ ▇▇▇▅▃▁▆
+ ▅▇▅▃▁▄▆▇▂ ▂▄▇ ▁▁▃
+ █▅▇▁▅▃▅▁▁▇▃▂ ▃▃▃▁▁▂
+ ▅▁▃▃▅ ▅▆▁▃▄▃▃ ▁ ▃▃▁
+ ▄▇ ▁ █▇▃▁▂█▁▆ ▅▇▅▁▆
+ ▆▆▁▆▁ ▆▆▁█▅▃▁ ▁▂▁▄▁
+ ▆██▁ ▄▁▇▇▁▁▇▆▁▄▇▇▂▂▂▇▇▂▁▃█▄▁
+ ▆▃▅▃▆ ▅▅▇▅▄▄▁ ▁▇▁▂▂▆ ▄▅▆▄▃▂▁▃▁▂
+ █▃▁ ▁ █▁▁▇▆█ █▇▇▇███▇▇▆▅▅▅▆▅
+ █▇▁ ▃▇ ▂ ▅▃▇▃▅▅
+ ▄▃▅▅▇▃▆ ▆▇▄▅█▆▁█
+ ▄▃▇▆▂▇▇▃▄▄▄▄▆▅▄▇▄▂▂▇█
+ ▂▇▇▇▂▅▁▂▂▂▂▁▄▅▃█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_30.txt b/codex-rs/tui2/frames/hbars/frame_30.txt
new file mode 100644
index 0000000000..7ceb36d37a
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_30.txt
@@ -0,0 +1,17 @@
+
+ ▂▄█▇▇▇▆
+ ▂▅▄▁▁▃▇█▄▃
+ ██▃▁▆▃▃▁▇▆▃
+ ▁▁▃▁▅▁▂▃▁▃ ▃▆
+ ▄▇▁▁▂▃▁▆▁▆ ▁
+ ▁▇▁▃▇ ▇▁▁▁▁▅▁
+ ▃▅▁▁▁▃▂ ▃▅▃▁ ▄▂
+ █▁ █▇▄▁▆▁█▁▆ ▂
+ █▁▂█▃▁▄▁▃▅▁▆ ▂
+ █▁▁▃▁▂▂▁▁ ▇▆ ▂
+ ▃▁▁▄▃▂▇▁▁▁▇▁▁
+ ▁▇▅▅▆▅▇▃▁▁█ ▁
+ ▃▁▃▁▁▅▇▁▁▆▁▅
+ ▆▃▆▇▄▃▅▁▆▅█
+ ▃▆▅▁▃▂▂▄█
+ ▂▂▂▂
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_31.txt b/codex-rs/tui2/frames/hbars/frame_31.txt
new file mode 100644
index 0000000000..419be30ed9
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_31.txt
@@ -0,0 +1,17 @@
+
+ ▂▅▅▇▇▇▇▄▆
+ ▂▇▇▄▇▆▂█▇▃█▇▆
+ ▆▁▃▅▅▆▄▂▂▅█▁▂▇▃
+ ▆▁▅▇▂▂▇▄▂▆▃▃▁▃▁▁▃
+ ▃▁▁▁▁▇▆▇▃▂▆█▃▁▅▂▂
+ ▄▁▃▂▁▂▁██▃▄▇▆▅▅▁▆█▁
+ ▅▁▁ ▁▃▇▁▃▅▄▅▄▇▁▇▁▅▁
+ ▃▃▆ ▁▁█▁▃ ▁▃██▁▁▃▅▁
+ ▁▃▆▂▁█▃▁▁▁▅▇▁▁▁▂ ▁
+ █▁▁▁▅▅▁▁▂▂▂▃▂▁▃▁▁ ▇
+ ▃▇▂▅▇▁▆ ▅▇▇▇▂▅▁█▁▂
+ ▁▁▁▃▃▃▆ ▂▄▇ ▁
+ ▄▁▇▄▂ ▆ ▅ ▁▇▂▅▂
+ ▅▁▃▁▅▂▁▂▆▁█▆▁▂
+ ██▄▁▂▇▇▅▅▄▇
+ ▂▂▂▂
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_32.txt b/codex-rs/tui2/frames/hbars/frame_32.txt
new file mode 100644
index 0000000000..1234a419b0
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_32.txt
@@ -0,0 +1,17 @@
+
+ ▆▇▇▇▇▄▄▁▆▂
+ ▄▇▁▇▇▁▃▁▁▇▇▁▁▆
+ ▅▃▇▄▃▆▇▃▅▆▂▇▁▇▃█▇▆
+ █▅▅▁▂▆▂▄▆ ▆ ▆▂▃▁▇▆ ▆
+ ▅▅▁▆▁▇▃█▇▁▄ █▂▆▁▃▅▃▇▃▆
+ ▃▅▃▃▆▃▇▁▂▅▁▁▇▂ ▁▇▅ ▇
+ ▇▁█▄▆▂█▃▁▁▆▆▁▆▄▂▅▂▅▅▁█▂
+ ▁▁▁▆▂ █▂▁▁█▅█▁▄▆▂█▃▁██▂
+ ▃▁▁▆▂ █▂▁█▂▂▁▇▇▇▁▁▁▄▁█▄▂
+ ███▂▂▁▇▃█▃▂▂▂▂▂▁▁▇▁▄▁▆▂
+ ▆▃▇▁▁▅ ▁▇██▇▇▇▃▄▅▅▅▅▅
+ ▃▆▁▃▃▃ ▆▃▁▅█▁
+ █▇▇▁▁▁▇▂ ▂▅▂▁▅ ▆
+ ▃▆▃█▁▇▁▄▄▇▂▂▇█▂▅
+ ▁▄▄▂▂▆▇▅▇▂██
+ ▂▂▂
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_33.txt b/codex-rs/tui2/frames/hbars/frame_33.txt
new file mode 100644
index 0000000000..780eb104ef
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_33.txt
@@ -0,0 +1,17 @@
+
+ ▂▆▇▄▇▄▇▄▁▅▂
+ ▂▇▇▁▁▃▇▄▁▅▁▆▁▇▁▇▅
+ ▂▅▃▁▇▇▇▆▄█▂ █▇▅▁▁▇█▆
+ ▆▃▅▁▅▂▁▆▂ ▇▁▁▃▂▇
+ ▂▅▁▅▂▁▁▅▃▃▃ ▁▇▃▃▃
+ ▅▅▆ ▃▂▃▃▂▃▆ ▅▃▅▂▃
+ ▁▁▇ ▃▆▇▁▂▁▃ ▁▇▁▁
+ ▇▁▆▆ ▆██▃▅▄▆ ▃█▁▇
+ ▁▁▁ ▁ ▆▂ ▅▇▆▆▆▄▄▄▇▁▁▇▅▂▁▃▁
+ ▃▅▁██▅▅▆▅▂▁▁▂▂▂▂▂▁▁▇▃▃▃▁▁▅
+ ▃▄▃▆ ▁▅▁▅ ▅ ████▇▇▇ ▁▁▆▅▃▂
+ ▃▇▃▇▆█▆ ▅▅▄▅▄▅
+ ▇▃█▇▆▇▄▆ ▂▇▁▆▅▇▃█
+ ▃▁█▇▃▇▁▆▄▇▂█▄▆▃▇▁▇
+ █▄▄▇▆▂▂▂▃▇▇▄▆█
+ ▂▂▂▂
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_34.txt b/codex-rs/tui2/frames/hbars/frame_34.txt
new file mode 100644
index 0000000000..4bf69e69eb
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_34.txt
@@ -0,0 +1,17 @@
+
+ ▂▆▄▇▇▇▇▄▁▆▂
+ ▂▇▇▇▅▃▄▁█▁▇▇▄▇▇▄▆▄▂
+ ▂▅▅▆▁▇█▅▁▇▂ ▂▃▃▃▆█▇▇▆
+ ▆▅▂▁▇▂▅▆▂ ▇▁▆▇▃▃
+ ▅▅▁▃▆▅▁ ▁█ ▆ ▃▃▇▃▃
+ ▆▅▃▁▂▅ ▃▃█▁▃▇▃ ▃▆▃▁▃
+ ▁▇▃▁▂ █▃▂▇▁▂▃ ▁▄▁▂
+ ▃▁▄█▅ ▁▇▂▁▅█▁ ▅ ▂▃
+ ▆█▅▅█ ▅▃▅▅█▂▄▄▇▇▇▇▇▇▁▂▂█ ▁▃▂
+ ▁▁▃▆▅▆▆▃█▅▅█▁▁▁▂▁▅▂▂▂▆▅▂▁▁▂▁▃
+ ▅▂▃▆ ▁▃▁▇▃ █▇▇▂▂▂▂▃ ▆▅▆▃▁█
+ ▅▆▃▄▄▃▂ ▅▄▅▁▅█
+ ▃▇▂▁▇▃▄▆ ▂▇▄█▂▅▆▂
+ ▆▃▅▁█▁▇▆▄▆▇▄▇▄▇▂▇▇▅█
+ █▁▃▄▄▂▂▂▂▂▄▄▇▄▃
+ ▂▂▂
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_35.txt b/codex-rs/tui2/frames/hbars/frame_35.txt
new file mode 100644
index 0000000000..86dde2ad34
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_35.txt
@@ -0,0 +1,17 @@
+
+ ▂▆▇▄▄▇▇▇▄▇▆▂
+ ▆▇▄▇▅▁▇▇▇█▁▇▁▅█▁▇▄▂
+ ▂▅▅▁▄▇▇▁▃▇█▂ ▂█▇▄▇▅█▁▇▆
+ ▆▅▅▇▅▆▄▆▂ ▇▇▂▃▁▂
+ ▅▅▁▁▅▅▃ █▃▇▆ ▁▃▇▁▆
+ ▄▅▄▅▇▂ █▁▂█▅▅▇▂ ▁▃▃▁
+ ▃ ▅▅ ▃▃ █▇▂▅ ▁▃▃▃
+ ▁▁▁▅ ▅▃▃▄▅█ ▅ █▅
+ ▅ ▆▂ ▆▁▁▅▄█▅▁▄▄▂▄▂▄▇▁▁ ▁▁▄▇
+ ▁▆▃▄█ ▅▅▄█▇▇▅▁▄ ▃▆▂▂▂▂▅█▁▅█ ▁█
+ ▅▂▃▆█▅▃▂▁▅▃▂ ▂█▃▃▃▃▇▃▃▇▅▅▂▆▁
+ █▅▃▃▅▁ ▂▅▇ ▆▃
+ ▃▄▂▃▄▆▅▆ ▆▄▅▂▇▇█
+ █▃▂█▁▇▁▆▅▁▁▇▁▄▅▇█▂▅▄█
+ █▃▁▄▄▂▂▅▂▂▇▇▇█▃
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_36.txt b/codex-rs/tui2/frames/hbars/frame_36.txt
new file mode 100644
index 0000000000..bccadcf7b7
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_36.txt
@@ -0,0 +1,17 @@
+
+ ▂▂▇▄▇▇▇▇▄▇▆▂
+ ▂▄██▃▇▅▄▅▇▃▇▄▇▇█▇▇▇▂
+ ▆▃█▃▆▇▇▆▇█▂▂ ▂█▇▁▇▇▁▆▇▁▆
+ ▂▁█▇▇▂▂▂▂ █▇▁▃█▁
+ ▆▅▂▄▃█▁▃▂▃▆▅ ▃▃▅▇
+ ▅ ▆▅▂ ▇▂ █▁▅▆ █▃▃▇
+ ▁ ▄ ▂ ▃ █▃▃ ▁▃▁▆
+ ▁▁▃▁ ▂▃ ▂▅▅ ▃▁ ▁
+ ▁██▁ ▅▅ ▆▇██▆▇▇▂▇▇▇▇▇▂ ▁▃▁▁
+ ▂▇▁▃ ▆▁▂▂▅▁▅ ▂▁▂▂▂▂▂▂▂▁▁ ▃▅█▂
+ █ ▇▁▃ ▇▂▇▅▃ █▇▇▃▃▃▃▃█ ▁▆█▅
+ █▆█▃▄▅ ▆▅▁█▅
+ ▃▅▁▁▇▁▆ ▆▇▇█▅▆▂
+ ▇▆▂█▇▇▄▃▄▁▂▇▁▄█▆█▆▄▇█
+ ▂▇▇▅▁▂▆▆▂▆▆▇▇▇▇█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_4.txt b/codex-rs/tui2/frames/hbars/frame_4.txt
new file mode 100644
index 0000000000..5867215a96
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_4.txt
@@ -0,0 +1,17 @@
+
+ ▂▅▄▄▇▄▄▇▄▇▆▂
+ ▂▆█▇▇▁▅ ▁▃▄▅▇▄▁█▅▇▆▂
+ ▆▇▄▁▁▁▇▇█▂ ▂▃▁▃▃▇▁▅▃▃▂
+ ▅▅▁▆▁█▅▇▆ █▁▇▇▃▇▃
+ ▅▁▅▂▁▄▁▃▄▃▁▆ ▃█▃▁▇▃
+ ▅▁▁▃▁ █▂▁▁▅▇▃ █ ▃▄▁▆
+ █▃▁▄▂ █▇▇▃▇█▁▆ ▆ █▄▁
+ ▁▅▃ ▆▁▅▇▃▁▁ ▁▁▁
+ ▂▁ ▁▂ ▄▁▅█▃▅▅▇▁▇▇▇▂▂▂▂▆▆ ▁▁▇
+ ▁▃▅ ▁ ▆▅▅▅▆▂▁▂▄▃▁▆▅▂▆▅▅▃▄▁▅▅█▁
+ ▂▁▄█▃▆▃▃▆▃▅ █▇▇▇▇▇▇▇█▃▆▁▁▁▂
+ ▆▁▃█▁▂▂ ▆▃▄▅▇▇█
+ ▃▃▆▅▃ ▆▂ ▂▅▃▆▇▄▁▅
+ ▁▁▁▄▂▇▇▃▄▄▄▄▆▇▄▇▇▃▁▇▂
+ ▇▃▃▁▅▁▂▂▂▂▂▄▆▇▂
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_5.txt b/codex-rs/tui2/frames/hbars/frame_5.txt
new file mode 100644
index 0000000000..d0cd750b8a
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_5.txt
@@ -0,0 +1,17 @@
+
+ ▂▅▄▄▄▇▄▄▄▇▆▂
+ ▂▇█▇▅▇▅▁▁▇▁▄▇▄▂▁█▇▆
+ ▇▂▅▃▇▁▇█▂ █▃▄▁▇▃ ▆▇▆
+ ▆▁▅▁▅▁▅▄▆ ▆▃▁▁▁▁▂
+ ▆▃▅▇▅▃▂▇▁▂▃▆ ▂ ▃▁▃▁▂
+ ▁▁▁▁▅ ▃▂▁▃▄▅▁▂ ▇▅▁▁
+ ▁▅▁ ▇ ▂▃▂▁▃█▁▆ ██▁▇▁▆
+ ▁▅▁▂█ ▆▂▄▁▅▂▁ ▇▁▂▁
+ ▁▆▁▃▇ ▅▂▁█▆▁▇▄▂▁▇▁▂▂▂▇▆▂█▁▅▁
+ ▂▃▁▃▆▆▅▇▇█ ▁█ ▅▅▃▄▃▆▄▅▆▅▁▅▇▁▂
+ ▃▆▁▁▆▁▆▃▃▅▇▂ █▇▇█████▆▁▄▁▃▅
+ ▃▃▇▅▃▃ ▂ ▅▂▅▇▆▃
+ ▃▅▇▃▁▄▇▂ ▂▄▇▆▇█▄▇
+ ▃▁▇▁▆▇▇▃▄▁▄▂▆▇▄▇▃▁▄▇
+ ▃▆▇▂▇█▂▂▂▆▂▆▇▇▂
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_6.txt b/codex-rs/tui2/frames/hbars/frame_6.txt
new file mode 100644
index 0000000000..2fde73afab
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_6.txt
@@ -0,0 +1,17 @@
+
+ ▂▅▄▄▄▇▄▄▇▇▂▂
+ ▆▃▄▅▇▁▄▇▇▁▇▇▄▂▆▇▇▂
+ ▆▆▆▁▁▁▇█ ▂█▁▅▄▇▇▇▅▃▂
+ ▅▆▁▇▁▇▂▄▆ ▃▇▁▁▁▁▆
+ █▄▁▁▁▇▃▃▇▇▃ ▅▃▃▁▃▆
+ ▄▆▅▁▅▂▃▇▄▁▃▂▁▆ ▅▄▃▅▁
+ ▂ ▇▁▁ ▃▃▁▅▃▃ ▃▇▁▂▁
+ ▁ ▁▁▁ ▂▁▄▁▅▁▁ ▁▇▃▁▁
+ ▂▅▁▆▁ ▅█▁▁▇▄▅▇▂▁▇▁▂▂▇▇▂▅▃▅▁
+ ▁▁▃▆▅▂▃▂▄▇ ▁▅▄▇▆▁▁▆▄▄▄▃▁▆▁▃
+ ▅ ▁ ▅▁▁▁▄▅█ █▇████▇█▂▃▃▅▁
+ ▆ ▄ ▅▆▂ ▆▅▂▅▅▁▂
+ ▅▂▃▂▇▇▆ ▂▇▃▂▅▇▆▇
+ ▂█▁▇▆█▇ ▄▁▂▂▆▇▇▇ ▅▄█
+ ▃▆▄▇▇▆▂▂▂▂▂▆▇▇
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_7.txt b/codex-rs/tui2/frames/hbars/frame_7.txt
new file mode 100644
index 0000000000..f9b4ed9219
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_7.txt
@@ -0,0 +1,17 @@
+
+ ▂▅▁▄▇▇▄▄▇▆▂
+ ▆▇▂▇▃▁▇▇▇▄▄▃▄ ▂▇▆
+ ▇ ▆▁▁▁▇▂ ▂▃▁▂ ▇▅▂▇▆
+ ▃▃▁▁▁▁▄▇ ▃▁▃▇▁▅▆
+ ▂█▁▇▁▁▃▁▅▃▆ ▅ ▇▁▁▃
+ ▁ ▄▁▁█ ▂█▃▄▁▃ ▆▆▁▁▁
+ ▂▃█▁ ▃▂▁▃▁▃▁ ▇▇▃▁▁
+ ▂█▅▁▁ ▄▇▅▁▇▁▂ █ ▁▁▁
+ ▅█▁▇ ▆█▂▅▁▃▅▁▁▄▄▂▁▁▄▄▇▃▁▁
+ ▁▆█▁▁▄▅▁▁▅█▁▅▃▁▁▃▃▆▄▆▄▃▁▃▁
+ ▃ ▄▃▅▇▁▇▂▅ ▇▇▇▇▇▇██▂▅▁▁
+ █▂ ▅▂▅▂▂ ▆█▆▅▄▅█
+ █▄▆▇▃▃▃▂ ▆▃▁▆▇▅▇█
+ ▃▂█▃▁▇▃▄▁▂▂▂▇▇▁▇▇▅
+ █▁▇█▁▅▁▂▂▆▂▄▇▇
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_8.txt b/codex-rs/tui2/frames/hbars/frame_8.txt
new file mode 100644
index 0000000000..44c448de8a
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_8.txt
@@ -0,0 +1,17 @@
+
+ ▂▂▇▂▄▇▇▄▇▆▂
+ ▆█▇▅▁▁▁▇▄▄ ▁ █▇
+ ▂▁▄▆▁▅▅▇ ▆█▁▅▁▇▃▇▃▆
+ ▂▇▃▇▅▁▆▇▁ █ ▄▃▁▁▃
+ █ ▅▁▅▆▃▁▅▃ ▅█▃▁▁▆
+ ▁█▆▁▃▃▃▂▃▁▂▇ ▃▇▁▁▁
+ ▁▇▁▁▁ █▂▄▃▁▂▁ ▁▃▁▅▁▆
+ ▃▆▁▁▅ ▁▇▃▅▁▆▇▅ ▅▂▅▁▁
+ ▃ ▃▁▁▂▃ ▅▇▄▁▁▅▇▆▇▆▆▃▁▁▁
+ ▃▇▅▄▂▁█▆▁▆▁▁▄▁▄▂▂▁▁▄█
+ ▅▅▃▃▁▃▁▁▁▅█▃▇▃▇█▃▇█▅▃▁
+ █▆█▁▃▁▂▂ ▅▆▅▅▅█
+ █▃▂▇▃▃▃▂ ▂▅▃▂▁▇▅▇
+ ▅▅█▁▆▇ ▄▄▇▇▄▅▄▆▁▂
+ ▁▁▂▇▇▃▁▂▆▇▅▄▂
+ ▂▂
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/hbars/frame_9.txt b/codex-rs/tui2/frames/hbars/frame_9.txt
new file mode 100644
index 0000000000..a18a8a231c
--- /dev/null
+++ b/codex-rs/tui2/frames/hbars/frame_9.txt
@@ -0,0 +1,17 @@
+
+ ▅▄▃▇▅▇▇▄▆
+ ▅▇▂▅▁▁▇█▄ ▂▆▃▂
+ ▅ ▆▁▁▅▇▃▃▄▅ ▃▂▁▆
+ █ ▁▁▅▄▄▂ ▂▃▆▁▃▃▁▇▆
+ ▅▇█▄▃▇█▁▇▆ ▇▅█▇▅▇▁▁
+ ▁ ▁▁▁█▃▁▃▄▂▂ ▁█▁▇▁▁▁
+ ▂ ▁▇▃▁▇▇▁▃▃▆█▅▆▅ ▂▁▁
+ ▁ ▁▅▂▆▃▁▁▁▂▅▄▃▂▁ ▁▁
+ █▆▁█ ▅▁█▁▁▁▁▇▁▁▆▁▁▂
+ ▁▂▁▁▁▂▆▁▃▁▂▁▁▁▁▂▂▁▁▁
+ █ ▂▃▅▃▃▁▅█▇▇▇▇▁▁█▅▃▁
+ ▃▁▁▁▃▆▂ ▆▅ ▃▅▁▂
+ ▃▇▃▁▃▃ ▅▄▂▄▁▅▇
+ ▃▆█▃▂▁▇▅▇▄▄▄▇▁▂
+ █▆▂ ▇▃▃▁▄▇▅█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_1.txt b/codex-rs/tui2/frames/openai/frame_1.txt
new file mode 100644
index 0000000000..1019a11c95
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_1.txt
@@ -0,0 +1,17 @@
+
+ aeaenppnnppa
+ anpeonpepnniina aopa
+ pioipoooaa aooaoiniiip
+ noanooppa eoinip
+ naneoainann oeinnp
+ io pa ioeniip oeniip
+ paopo onioeoia iei
+ iiaia peeinio oai
+ inioa niianioeippppppapp no i
+ aino anpa eo ioiaaaeepppiepepi
+ naaoa anpeea aaoooo aooepnae
+ oap op a poeoai
+ anpanpa anapiapo
+ aopna opennnnenopapio
+ aoooiiiaaapanpoo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_10.txt b/codex-rs/tui2/frames/openai/frame_10.txt
new file mode 100644
index 0000000000..942f59e944
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_10.txt
@@ -0,0 +1,17 @@
+
+ apooonppa
+ ooapopnieaop
+ aapiieiipipnpp
+ iaaeninaenpoonnp
+ e niioia opeaeie
+ ia oioieen aaoi
+ n ioooiiiio iep
+ o iinpepiipaaenii
+ o in nniniipnpnii
+ i pinpiaeaoaaaioa
+ p oiiiiioo nponia
+ naopnpoo aioopee
+ io iiiiopepeiea
+ naooeipna eeo
+ op aonapno
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_11.txt b/codex-rs/tui2/frames/openai/frame_11.txt
new file mode 100644
index 0000000000..ef0aff76e0
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_11.txt
@@ -0,0 +1,17 @@
+
+ pooooppa
+ eo niiinnp
+ eoaaiinnoenp
+ iaaiinnpanee
+ aoennipnonaiip
+ ipaiipanniaeii
+ oo piiiiiiainn
+ i iieiine ioi
+ e oieiioepiai
+ oo aienpoeiaia
+ oap iiiineinni
+ napeiaoeoonia
+ a oinnaaino
+ np oiipaeoa
+ na oopapa
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_12.txt b/codex-rs/tui2/frames/openai/frame_12.txt
new file mode 100644
index 0000000000..8940e05bd6
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_12.txt
@@ -0,0 +1,17 @@
+
+ pooope
+ pnaaeipn
+ o ienpp
+ epiiinnoi
+ i oiiiieei
+ ioeeoaoaio
+ i ieniin
+ i epniio
+ op ieiipii
+ i eionoa
+ ie ionooe
+ p oi api
+ e ooiponi
+ oaeopinia
+ n oinee
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_13.txt b/codex-rs/tui2/frames/openai/frame_13.txt
new file mode 100644
index 0000000000..c73afab740
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_13.txt
@@ -0,0 +1,17 @@
+
+ eooop
+ iaaii
+ iaaio
+ iooia
+ o ii
+ oepii
+ p ii
+ p oi
+ ep aie
+ io pni
+ oaee ia
+ iaaai
+ ippia
+ oaain
+ p eon
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_14.txt b/codex-rs/tui2/frames/openai/frame_14.txt
new file mode 100644
index 0000000000..8a273a1666
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_14.txt
@@ -0,0 +1,17 @@
+
+ pooon
+ peaaen
+ iaiie i
+ iieioaip
+ iiin i
+ ioii oi
+ iiii e o
+ iinia n
+ iiii o
+ oaee ne
+ nioopepi
+ ioiiaaai
+ e oinnna
+ ineoaae
+ ao one
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_15.txt b/codex-rs/tui2/frames/openai/frame_15.txt
new file mode 100644
index 0000000000..5a0e8f1b54
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_15.txt
@@ -0,0 +1,17 @@
+
+ ppoooia
+ apniiaeop
+ eeionniooi
+ iea eepeaai
+ iinonniieoai
+ niipiieei o
+ ii iiiiiipi
+ iieiipiii opi
+ iipppoiiiaeei
+ iaineinioe ei
+ ieiiiiai a n
+ iooeaiinp n
+ oinp eeea na
+ iaiinnepne
+ naoaaaae
+ aa
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_16.txt b/codex-rs/tui2/frames/openai/frame_16.txt
new file mode 100644
index 0000000000..06c519f602
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_16.txt
@@ -0,0 +1,17 @@
+
+ anpooopia
+ eaiioiininn
+ ieeonennii on
+ eee noaniniiooi
+ iinaeooniioeian
+ iiioio inn i iei
+ nni eapiiiieoop i
+ ien iaiieiiion ai
+ nniiipieaiioop e
+ ooaapnnnoieai pai
+ iiipooeoninoneiia
+ iio ia aeep e
+ nio i epeapi
+ niioaoieepai
+ oeeaneaano
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_17.txt b/codex-rs/tui2/frames/openai/frame_17.txt
new file mode 100644
index 0000000000..0bd4ef6dfc
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_17.txt
@@ -0,0 +1,17 @@
+
+ pnpppnnipa
+ anooiiionoipoap
+ poneannappoiiiaon
+ eieaeioaa oinniiinn
+ iea i ioennnee p
+ anopea peei epneiee
+ o nei peeia ooiieni
+ poni eeiieipiinno
+ peoennnpinainaeniii i
+ ioanaaieoneiin npopn
+ nnneooooooonaioeen no
+ niiao aeiia n
+ ann ona popeaae
+ p iopnnpaanoeio
+ apneappioapo
+ a
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_18.txt b/codex-rs/tui2/frames/openai/frame_18.txt
new file mode 100644
index 0000000000..de59f344ef
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_18.txt
@@ -0,0 +1,17 @@
+
+ annpnnpnipa
+ apoanpppiaapopnna
+ aeeiooonopoeaopeen o
+ piioepaoo onaaeninnnnnp
+ anee ei aopaneieiannnna
+ eni ppieaaaepopiopeaeaei
+ iinee peoeioaeooininp
+ onpii anoiina inio
+ noo pnnnnnnpiipioenp ioia
+ anniono iieaanaiiianian p
+ ieinaoooooooa naaeieoeapa
+ nn pnp aaooeoao
+ naopaae aoaaenpa
+ oieooppnnnaooaeapo
+ oiiaeaapeponpo
+ a
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_19.txt b/codex-rs/tui2/frames/openai/frame_19.txt
new file mode 100644
index 0000000000..ade5662359
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_19.txt
@@ -0,0 +1,17 @@
+
+ aannpipnniea
+ apiiinennnaoapiopp
+ ponneoipoa aoepaonn
+ eniopaa annppaiop
+ iieaea piaoeoin inp
+ ineoo aioie ee oeoi
+ aniio eoaeippa eeepi
+ iiii inoniop i iii
+ ioinpnnnnnniiiiponoin n oii
+ anepinoeaopnpap aa enanpeeia
+ onoepioooooooo anaeiee eeo
+ nnaoan aeeaeeo
+ o aniiop pnneeina
+ ooeioeipaanneoo noio
+ oieaepoapeaopa
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_2.txt b/codex-rs/tui2/frames/openai/frame_2.txt
new file mode 100644
index 0000000000..be49360bbf
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_2.txt
@@ -0,0 +1,17 @@
+
+ aeaenpnnnppa
+ appeonpiiiniinaoiopa
+ pioinooioaa aoonoeiinip
+ aieaeooppa ppnieip
+ paoeoainanna apinip
+ oepoa ionpenp nnioi
+ piooi aeiniaip eoioi
+ io na pioiino ioeei
+ oooni niaaaioeipppppppppiaiio
+ anoi eiio eo innaaaaeeaaipe i
+ nnn o oneeio aoooooooooipoii
+ onaeep a ppnepo
+ enaaipp pnap aio
+ aianaaoopennnnenoaaiio
+ aopopiiaaaaineoo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_20.txt b/codex-rs/tui2/frames/openai/frame_20.txt
new file mode 100644
index 0000000000..6eaf358e88
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_20.txt
@@ -0,0 +1,17 @@
+
+ aapniinpnpaa
+ pnnonpapnnniiaaonpp
+ ppoapooioo aoaonpoipa
+ aioaoio appineonn
+ ai pio ae aiiaoniin
+ eapio poonioe oniin
+ ninpi po epoa pnie
+ iaaea ooneiop iioi
+ ieiinpnnnnnnnnaponaanno e in
+ oiaiao eaaaaaain onnoinn pe ii
+ npanoooooooooo npniipi en
+ o aoep aeoeie
+ naaopia pnoanoo
+ appeoipannpeoioapeoo
+ aopia naaaaiooo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_21.txt b/codex-rs/tui2/frames/openai/frame_21.txt
new file mode 100644
index 0000000000..5f317f375c
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_21.txt
@@ -0,0 +1,17 @@
+
+ aapnpnnpnppaa
+ ppoaaaapinipnaapopa
+ noaapoaoa aaiopaaop
+ poinoo apnopnop
+ epeoa piean nnaap
+ eoei pooaee nnap
+ ioia a eapeo nnno
+ an nn oip i i
+ i i ppnnnnnppp aipoip ne i
+ i in ia api aoaoip eoee
+ n oe aaooo oa ooapn ea p
+ op ena aoo e
+ oa apa aenoo pa
+ ona ooopeiinenooo pa
+ oppnpaaaapanpoa
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_22.txt b/codex-rs/tui2/frames/openai/frame_22.txt
new file mode 100644
index 0000000000..74b75b9113
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_22.txt
@@ -0,0 +1,17 @@
+
+ appnpnnpnppa
+ apeoieaeieniinipeopa
+ pnoninooa aoonoopaapp
+ noiooo ppiiiaon
+ niieo paeinieenoi
+ nioea pieinaea ninni
+ ipone ipinoeo iiei
+ iinia iniian iaioi
+ iipop pinnnnnnppanoia np aino
+ ain oannp epoieei nonaoipp enn
+ nnnai ooooooooa aeopaeeeopa
+ nonanp aopoipo
+ oopn ppa aeopooae
+ oeoppooinnpnnenoooopo
+ oioianaaapnaenoa
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_23.txt b/codex-rs/tui2/frames/openai/frame_23.txt
new file mode 100644
index 0000000000..35e7fe2210
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_23.txt
@@ -0,0 +1,17 @@
+
+ appanpoppnpaa
+ anipinapannpiaioipa
+ popiopnoa oiepinniip
+ enionea annniinn
+ eeiaeo peppooeonin
+ pnioea aoooooeooiinip
+ aiioi eeee aia o ioo
+ iei i ioipanp i oei
+ aon ipinnnnnnnniaoiaona i iii
+ innaiono ean nianpi nai
+ eoi i aooooooo oaenniaeaea
+ piiaie peinaea
+ n ipoeaa aeonoepe
+ nnnpnopninnappopapoa
+ oi onniaapaaooa
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_24.txt b/codex-rs/tui2/frames/openai/frame_24.txt
new file mode 100644
index 0000000000..a74ea1f0bb
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_24.txt
@@ -0,0 +1,17 @@
+
+ aianpponnpa
+ poaeoiaainnppaop
+ poonnepoi eaeoioop n
+ poeepeinpnaiea aoninao
+ p eenep aooenaiaanipo
+ ipnpna oppe ein eon
+ i ii peapeoeaninaia
+ i nii ipnenaiiaeeaii
+ ie innneppiiippaopai i ii
+ a e oieppnnppieanpoi ioi
+ n oninoooooooa npeoninepa
+ n npon i oene
+ neonaie anoaeeao
+ epopnaoiiennniaaea
+ oeaopnnaannpo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_25.txt b/codex-rs/tui2/frames/openai/frame_25.txt
new file mode 100644
index 0000000000..c2c5b30b29
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_25.txt
@@ -0,0 +1,17 @@
+
+ apnonppppa
+ p opoaannioiip
+ eieeppoeipnnniiia
+ ipoi e ni onipone
+ paanpeoaneaio ieeneo
+ npiiiaopeaie eipieeip
+ ieioi iaaenaeineaoini
+ iiieieo ianneinainiin
+ apnioiaannnnpiinnipoin
+ epoieipiaiinoainoneni
+ nioeniaoooooopeinieia
+ iaoinpnnppoeaepeeie
+ aaaianaonepaeaiie
+ nennnaonioo oio
+ ipoonppapio
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_26.txt b/codex-rs/tui2/frames/openai/frame_26.txt
new file mode 100644
index 0000000000..09a947d35d
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_26.txt
@@ -0,0 +1,17 @@
+
+ anoooopp
+ eoinenipnip
+ eoooinninoonp
+ noopiiiaiiapea
+ iapnieiooneninn
+ n oieeeooanonne
+ i ooniieiinnop
+ ep niiiaaniieii
+ i enonpipnnenii
+ eaiepiaaponnoi
+ iaoeioonpeapnii
+ naiien eeoiia
+ o oin aaeiep
+ ioonnooaoon
+ neeaoiano
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_27.txt b/codex-rs/tui2/frames/openai/frame_27.txt
new file mode 100644
index 0000000000..b3fef11ac8
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_27.txt
@@ -0,0 +1,17 @@
+
+ nooopp
+ ineeien
+ noa oieoi
+ iiiaiinii
+ i aiapon
+ iaeaoaiiia
+ n oiiaoii
+ i aiiinoii
+ ie e ipiiii
+ on eoaiaoii
+ ip aaoopeo
+ iippiiaei
+ innpnpeia
+ naainnee
+ ono ane
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_28.txt b/codex-rs/tui2/frames/openai/frame_28.txt
new file mode 100644
index 0000000000..11fdcec520
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_28.txt
@@ -0,0 +1,17 @@
+
+ eoon
+ ipaia
+ n nia
+ ipaoi
+ i ii
+ i poi
+ aii ai
+ ipooi
+ en ai
+ iieeii
+ i ai
+ inpni
+ inoii
+ oaaei
+ i epi
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_29.txt b/codex-rs/tui2/frames/openai/frame_29.txt
new file mode 100644
index 0000000000..2dc6c66753
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_29.txt
@@ -0,0 +1,17 @@
+
+ poooop
+ pioe on
+ apii ooi
+ iiiianpe
+ n ioi i
+ ipiii aa
+ inniii a
+ iinii
+ iiioi a
+ ainii a
+ oiieia n
+ ieiii ai
+ iiiiaiai
+ inioeoio
+ iio ep
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_3.txt b/codex-rs/tui2/frames/openai/frame_3.txt
new file mode 100644
index 0000000000..9026d59a43
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_3.txt
@@ -0,0 +1,17 @@
+
+ aennppnnnnpa
+ appeniipionninaaiopa
+ pneonioooa aoi oopeaip
+ epeninppa ano iin
+ oeoieaeiiona naniia
+ einne epinnnn i nni
+ no i ooniaoip eoeip
+ ppipi ppioeni iaini
+ pooi niopiiopinppaaappaiaoni
+ pnenp eeoenni ioiaap nepnnainia
+ oai i oiippo ooooooooopeeepe
+ ooi np a eapaee
+ naeeonp ppneopio
+ nappaooannnnpenonaapo
+ aopoaeiaaaaineao
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_30.txt b/codex-rs/tui2/frames/openai/frame_30.txt
new file mode 100644
index 0000000000..73b4906d0e
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_30.txt
@@ -0,0 +1,17 @@
+
+ anooopp
+ aeniinoonn
+ ooaipnnippn
+ iinieianin np
+ noiianipip i
+ ioiap oiiiiei
+ neiiina neni na
+ oi opnipioip a
+ oiaoninineip a
+ oiiniaaii pp a
+ niinnaoiiipii
+ ioeepeoniio i
+ niniieoiipie
+ pappnaeipeo
+ npeiaaano
+ aaaa
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_31.txt b/codex-rs/tui2/frames/openai/frame_31.txt
new file mode 100644
index 0000000000..cc71fce920
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_31.txt
@@ -0,0 +1,17 @@
+
+ aeeopopnp
+ aponppaopnoop
+ pineepnaaeoiaon
+ piepaaonapnniniin
+ aiiiipponaponieaa
+ niaaiaioonnopeeipoi
+ eii iaoinenenoioiei
+ nnp iioin iaooiinei
+ inpaioaiiiepiiia i
+ oiiieeiiaaanainii o
+ aoaepip eoooaeioia
+ iiinnnp ano i
+ niona p e ioaea
+ einieaiapiopia
+ ooniapoeeno
+ aaaa
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_32.txt b/codex-rs/tui2/frames/openai/frame_32.txt
new file mode 100644
index 0000000000..c0d6573da7
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_32.txt
@@ -0,0 +1,17 @@
+
+ pppppnnipa
+ noiooiniiooiip
+ eaonappaepaoionoop
+ oeeiapanp p panipp p
+ eeipionooin oapinenonp
+ nennpnoiaeiipa ipe o
+ oionpaoniippipnaeaeeioa
+ iiipa oaiioeoinpaoniooa
+ niipa oaioaaipppiiiniona
+ oooaaiononaaaaaiioinipa
+ pnoiie iooooooaneeeee
+ npiann pnieoi
+ oooiiipa aeaie p
+ npnoipinnoaapoae
+ innaappeoaoo
+ aaa
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_33.txt b/codex-rs/tui2/frames/openai/frame_33.txt
new file mode 100644
index 0000000000..56ef96d36a
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_33.txt
@@ -0,0 +1,17 @@
+
+ appnpnpniea
+ apoiinonieipioioe
+ aenipoppnoa ooeiipop
+ pneieaipa oiinao
+ aeieaiienan ipnna
+ eep nannanp enean
+ iip npoiain ioii
+ oipp poonenp noio
+ iii i pa eopppnnnpiipeaini
+ aeiooeepeaiiaaaaaiioaaaiie
+ nnnp ieie e ooooooo iipeaa
+ npnopop eenene
+ onooponp apipeono
+ nioonpipnpaonpnoio
+ onnppaaaaponpo
+ aaaa
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_34.txt b/codex-rs/tui2/frames/openai/frame_34.txt
new file mode 100644
index 0000000000..b6e87c62f1
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_34.txt
@@ -0,0 +1,17 @@
+
+ apnppppnipa
+ apopennioiponoonpna
+ aeepiooeioa aannpooop
+ peaioaepa oiponn
+ eeinpei io p nnona
+ peniae nnoinon npnin
+ ioaia onaoiaa inia
+ ninoe ioaieoi e an
+ poeeo eneeoannppppppiaao iaa
+ iinpeppaoeeoiiiaieaaapeaiiain
+ eanp inioa oooaaaaa pepnio
+ epnnnna eneieo
+ npaipnnp apnoaepa
+ pneioippnppnonoapoeo
+ oinnnaaaaannona
+ aaa
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_35.txt b/codex-rs/tui2/frames/openai/frame_35.txt
new file mode 100644
index 0000000000..899d6766b7
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_35.txt
@@ -0,0 +1,17 @@
+
+ appnnpppnppa
+ ponoeioopoioieoiona
+ aeeinpoiaooa aoonoeoiop
+ peepepnpa opania
+ eeiieen onop inoip
+ nenepa oiaoeeoa inni
+ n ee nn ooae iann
+ iiie ennneo e oe
+ e pa piienoeinnananpii iino
+ ipano eenoopein npaaaaeoieo io
+ eanpoenaieaa aoaaaaoaaoeeapi
+ oeanei aeo pa
+ nnaanpep pneaooo
+ oaaoioipeiipineooaeno
+ oainnaaeaappooa
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_36.txt b/codex-rs/tui2/frames/openai/frame_36.txt
new file mode 100644
index 0000000000..9a23d2ddd6
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_36.txt
@@ -0,0 +1,17 @@
+
+ aapnppppnppa
+ anoonpenepnpnppooopa
+ pnonppopooaa aooiopipoip
+ aioopaaaa ooinoi
+ peannoinanpe aneo
+ e pea oa oiep onao
+ i n a n onn iaip
+ iini an aee ni i
+ iooi ee pooopppapppppa inii
+ aoin piaaeie aiaaaaaaaii neoa
+ o oin papea oooaaaaao ipoe
+ oponne peioe
+ neiipip pppoepa
+ opaooonaniapinopopnpo
+ aopeiappappppooo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_4.txt b/codex-rs/tui2/frames/openai/frame_4.txt
new file mode 100644
index 0000000000..0c76cc5ce8
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_4.txt
@@ -0,0 +1,17 @@
+
+ aennpnnpnppa
+ apopoie inneonioeopa
+ poniiipooa aainaoienna
+ eeipioepp oioonon
+ eieaininnaip nonion
+ eiiai oaiieon o nnip
+ onina ooonpoip p oni
+ ien pieoaii iii
+ ai ia nieoaeepipppaaaapp iio
+ ine i peeepaiannipeapeeanieeoi
+ ainonpnnpne oooooooooapiiia
+ pinoiaa paneooo
+ nnpea pa aeaponie
+ iiinaoonnnnnppnopnioa
+ onnieiaaaaanpoa
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_5.txt b/codex-rs/tui2/frames/openai/frame_5.txt
new file mode 100644
index 0000000000..2b06cade09
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_5.txt
@@ -0,0 +1,17 @@
+
+ aennnpnnnppa
+ apopeoeiipinpnaiopp
+ oaenpiooa oanion pop
+ pieieienp paiiiia
+ pneoeaapianp a ninia
+ iiiie nainneia peii
+ iei p anainoip ooipip
+ ieiao panieai piai
+ ipiao eaiopionaipiaaappaoiei
+ aninppepoo io eennapnepeieoia
+ npiipipnnepa oooooooopinine
+ nnpenn a eaeopa
+ aeoninpa anppoono
+ aioipopnninappnoaino
+ apoaooaaapappoa
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_6.txt b/codex-rs/tui2/frames/openai/frame_6.txt
new file mode 100644
index 0000000000..2ca8bb0bc7
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_6.txt
@@ -0,0 +1,17 @@
+
+ aennnpnnppaa
+ paneoinopippnapopa
+ pppiiioo aoienopoena
+ epioioanp npiiiip
+ oniiionnpon enninp
+ npeieaapninaip ennei
+ a pii aniean apiai
+ i iii ainieii ipnii
+ aeipi eoiionepaipiaappaenei
+ iinpeaaanp ienopiipnnnnipin
+ e i eiiineo ooooooooannei
+ p n epa peaeeia
+ eanaoop apaaeopp
+ aoiopop niaappoo eno
+ apnoppaaaaappo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_7.txt b/codex-rs/tui2/frames/openai/frame_7.txt
new file mode 100644
index 0000000000..f66ddaf5a6
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_7.txt
@@ -0,0 +1,17 @@
+
+ aeinopnnppa
+ poapnipopnnnn aop
+ o piiioa aaia oeaop
+ nniiiinp ainoiep
+ aoioiiaienp e oiin
+ i niio aonnin ppiii
+ anoi aainini ooaii
+ aoeii npeioia o iii
+ eoio poaeineiinnaiinnonii
+ ipoiineiieoieniinnpnpnnini
+ n naeoioae ooooooooaeii
+ oa eaeaa popeneo
+ onppnnna paipoeoo
+ naonionniaaapoiope
+ oiooieiaapanoo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_8.txt b/codex-rs/tui2/frames/openai/frame_8.txt
new file mode 100644
index 0000000000..e54163d2c8
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_8.txt
@@ -0,0 +1,17 @@
+
+ aapanppnppa
+ pooeiiionn i op
+ ainpieeo poieionpap
+ aonoeippi o naiin
+ o eiepnien eoniip
+ iopinaaaniao npiii
+ ioiii oanniai iaieip
+ npiie ipneipoe eaeii
+ n niiaa eoniiepppppniii
+ noenaiopipiininaaiino
+ eenniniiieoaoaoonooeni
+ opoiniaa epeeeo
+ onaonnna aenaipeo
+ eeoipo nnponenpia
+ iiaooniappena
+ aa
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/openai/frame_9.txt b/codex-rs/tui2/frames/openai/frame_9.txt
new file mode 100644
index 0000000000..a339de1118
--- /dev/null
+++ b/codex-rs/tui2/frames/openai/frame_9.txt
@@ -0,0 +1,17 @@
+
+ enaoeppnp
+ eoaeiioon apna
+ e piieoaane naip
+ o iienna aapinaipp
+ eoonnooiop oeopepii
+ i iiioainnaa ioioiii
+ a ioniooinnpoepe aii
+ i ieapniiiaennai ii
+ opio eioiiiipiipiia
+ iaiiiapiaiaiiiiaaiii
+ o aaennieoooooiioeni
+ niiinpa pe aeia
+ npninn enanieo
+ aponaioepnnnoia
+ opa onninpeo
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_1.txt b/codex-rs/tui2/frames/shapes/frame_1.txt
new file mode 100644
index 0000000000..244e2470b4
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_1.txt
@@ -0,0 +1,17 @@
+
+ ◆△◆△●□□●●□▲◆
+ ◆●▲△□○□△□○●◇◇●◆ ◆■□◆
+ ▲◇□◇□□□■○◆ ◆■□◆■◇●◇◇◇□
+ ●□◆○□■▲▲◆ △□◇●◇▲
+ ○○●△■○◇○◆○○ ■△◇○○▲
+ ◇□ □◆ ◇□△●◇◇▲ ■△○◇◇▲
+ □○■▲□ ■○◇□△■◇◆ ◇△◇
+ ◇◇◆◇◆ ▲△△◇●◇□ ■◆◇
+ ◇●◇■◆ ●◇◇○○◇■△◇□□□□□□◆□▲ ●■ ◇
+ ◆◇●□ ◆●□◆ △□ ◇■◇◆◆◆△△▲▲▲◇△▲△▲◇
+ ○○◆■○ ○○▲△△◆ ◆○□■■□ ○□■△▲●◆△
+ □○▲ ■▲ ◆ ▲■△□◆◇
+ ○○▲◆○□◆ ◆●◆□◇◆□■
+ ○□▲○◆ □□△●●●●△●□□◆▲◇□
+ ◆□■□◇◇◇◆◆◆▲◆●□□■
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_10.txt b/codex-rs/tui2/frames/shapes/frame_10.txt
new file mode 100644
index 0000000000..f306dffc08
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_10.txt
@@ -0,0 +1,17 @@
+
+ ◆□□□□○□□◆
+ □■◆□□□○◇△◆□▲
+ ○◆▲◇◇△◇◇▲◇□○▲▲
+ ◇◆◆△○◇●◆△○▲■■○○▲
+ △ ●◇◇■◇○ ■▲△◆△◇△
+ ◇◆ ■◇□◇△△○ ◆◆■◇
+ ○ ◇□■□◇◇◇◇□ ◇△▲
+ ■ ◇◇○□△□◇◇▲◆◆△○◇◇
+ ■ ◇○ ○○◇●◇◇□○□●◇◇
+ ◇ ▲◇○▲◇◆△◆□◆◆◆◇□◆
+ ▲ ■◇◇◇◇◇■■ ○▲■○◇◆
+ ○◆■▲○▲□■ ◆◇■■▲△△
+ ◇■ ◇◇◇◇□▲△▲△◇△◆
+ ●◆□□△◇□●◆ △△■
+ □▲ ◆□○◆▲●□
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_11.txt b/codex-rs/tui2/frames/shapes/frame_11.txt
new file mode 100644
index 0000000000..dcf944902b
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_11.txt
@@ -0,0 +1,17 @@
+
+ ▲□□□□□□◆
+ △■ ●◇◇◇○○▲
+ △■◆◆◇◇●○□△○▲
+ ◇◆◆◇◇●●▲◆●△△
+ ◆■△●○◇□○■●◆◇◇▲
+ ◇□◆◇◇□◆●●◇◆△◇◇
+ □□ ▲◇◇◇◇◇◇◆◇●○
+ ◇ ◇◇△◇◇○△ ◇■◇
+ △ ■◇△◇◇□△□◇◆◇
+ □□ ◆◇△●▲■△◇◆◇○
+ ■◆▲ ◇◇◇◇●△◇○○◇
+ ○◆▲△◇◆□△□□●◇◆
+ ◆ □◇○○○◆◇●■
+ ○□ □◇◇▲◆△□◆
+ ○◆ ■□□◆□◆
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_12.txt b/codex-rs/tui2/frames/shapes/frame_12.txt
new file mode 100644
index 0000000000..d8d1fbf334
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_12.txt
@@ -0,0 +1,17 @@
+
+ □□□□□△
+ ▲●◆◆△◇▲○
+ ■ ◇△○□▲
+ △□◇◇◇●●■◇
+ ◇ ■◇◇◇◇△△◇
+ ◇■△△□○■◆◇■
+ ◇ ◇△○◇◇○
+ ◇ △□○◇◇■
+ □▲ ◇△◇◇□◇◇
+ ◇ △◇□●□◆
+ ◇△ ◇■●□□△
+ ▲ □◇ ◆▲◇
+ △ □□◇▲□○◇
+ ■○△■▲◇○◇◆
+ ○ ■◇○△△
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_13.txt b/codex-rs/tui2/frames/shapes/frame_13.txt
new file mode 100644
index 0000000000..1387fc9b91
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_13.txt
@@ -0,0 +1,17 @@
+
+ △□□□▲
+ ◇◆◆◇◇
+ ◇◆◆◇■
+ ◇□□◇◆
+ □ ◇◇
+ ■△▲◇◇
+ ▲ ◇◇
+ □ ■◇
+ △□ ◆◇△
+ ◇■ □●◇
+ ■◆△△ ◇◆
+ ◇◆◆◆◇
+ ◇□▲◇◆
+ □◆◆◇●
+ ▲ △■●
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_14.txt b/codex-rs/tui2/frames/shapes/frame_14.txt
new file mode 100644
index 0000000000..70a5070ba9
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_14.txt
@@ -0,0 +1,17 @@
+
+ □□□□●
+ ▲△◆◆△○
+ ◇◆◇◇△ ◇
+ ◇◇△◇■○◇▲
+ ◇◇◇○ ◇
+ ◇□◇◇ ■◇
+ ◇◇◇◇ △ □
+ ◇◇○◇◆ ○
+ ◇◇◇◇ ■
+ ■○△△ ●△
+ ○◇■■▲△▲◇
+ ◇□◇◇◆◆◆◇
+ △ ■◇●●●◆
+ ◇○△□◆◆△
+ ◆□ ■●△
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_15.txt b/codex-rs/tui2/frames/shapes/frame_15.txt
new file mode 100644
index 0000000000..584e0e043a
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_15.txt
@@ -0,0 +1,17 @@
+
+ □□□□□◇◆
+ ◆▲●◇◇○△□▲
+ △△◇□●○◇■□◇
+ ◇△◆ △△▲△◆◆◇
+ ◇◇●■●○◇◇△■○◇
+ ○◇◇▲◇◇△△◇ ■
+ ◇◇ ◇◇◇◇◇◇▲◇
+ ◇◇△◇◇□◇◇◇ ■▲◇
+ ◇◇□▲▲□◇◇◇◆△△◇
+ ◇◆◇●△◇○◇□△ △◇
+ ◇△◇◇◇◇◆◇ ◆ ●
+ ◇□□△○◇◇○▲ ●
+ ■◇○▲ △△△◆ ●◆
+ ◇○◇◇○○△□○△
+ ○○□○◆◆◆△
+ ◆◆
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_16.txt b/codex-rs/tui2/frames/shapes/frame_16.txt
new file mode 100644
index 0000000000..af6c836855
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_16.txt
@@ -0,0 +1,17 @@
+
+ ◆●□■□□□◇◆
+ △○◇◇□◇◇○◇●○
+ ◇△△■○△●○◇◇ ■○
+ △△△ ●□◆○◇○◇◇□□◇
+ ◇◇●◆△□■●◇◇□△◇◆○
+ ◇◇◇□◇■ ◇○● ◇ ◇△◇
+ ○○◇ △◆▲◇◇◇◇△□■▲ ◇
+ ◇△● ◇◆◇◇△◇◇◇■● ◆◇
+ ○○◇◇◇□◇△○◇◇■□□ △
+ □■◆◆▲●●○□◇△◆◇ ▲◆◇
+ ◇◇◇□■■△□○◇●■●△◇◇◆
+ ◇◇□ ◇◆ ◆△△▲ △
+ ○◇□ ◇ △▲△◆▲◇
+ ○◇◇■◆□◇△△□◆◇
+ ■△△◆●△◆◆●□
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_17.txt b/codex-rs/tui2/frames/shapes/frame_17.txt
new file mode 100644
index 0000000000..4a158cf609
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_17.txt
@@ -0,0 +1,17 @@
+
+ ▲●□□□●●◇▲◆
+ ◆●□□◇◇◇□●□◇▲■○▲
+ ▲□○△◆●●◆□▲■◇◇◇◆■○
+ △◇△◆△◇■◆◆ ■◇●○◇◇◇●○
+ ◇△◆ ◇ ◇■△○●○△△ ▲
+ ◆●□▲△◆ ▲△△◇ △▲●△◇△△
+ □ ●△◇ ▲△△◇◆ □■◇◇△●◇
+ ▲■●◇ △△◇◇△◇▲◇◇●●□
+ ▲△□△○●●□◇○◆◇○○△○◇◇◇ ◇
+ ◇■◆●◆◆◇△□○△◇◇○ ○□■□○
+ ○○○△■■■□□□□○◆◇□△△○ ○■
+ ○◇◇◆□ ◆△◇◇◆ ●
+ ◆○○ □○◆ ▲■▲△○◆△
+ ▲ ◇□□●○□◆◆●□△◇■
+ ◆□●△◆▲□◇□◆□□
+ ◆
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_18.txt b/codex-rs/tui2/frames/shapes/frame_18.txt
new file mode 100644
index 0000000000..16bf8c1b58
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_18.txt
@@ -0,0 +1,17 @@
+
+ ◆●●□●●□●◇▲◆
+ ◆□■◆●▲□□◇◆◆▲■□●●◆
+ ◆△△◇□■□●■▲■△◆■□△△○ □
+ ▲◇◇□△▲○■□ ■○◆◆△●◇○●○○○▲
+ ◆○△△ △◇ ◆■□◆○△◇△◇◆○●○○◆
+ △○◇ ▲▲◇△◆◆◆△▲□▲◇■▲△○△◆△◇
+ ◇◇○△△ □△□△◇■◆△■□◇●◇●▲
+ ■○▲◇◇ ○○■◇◇●○ ◇●◇■
+ ○■■ ▲○●●●●●□◇◇▲◇□△○▲ ◇□◇◆
+ ◆○○◇□○□ ◇◇△◆◆○◆◇◇◇◆●◇◆○ ▲
+ ◇△◇○◆■■□□□□□◆ ○◆◆△◇△□△◆▲◆
+ ○○ ▲○▲ ◆◆□■△□◆■
+ ○○□□○○△ ◆□○◆△○▲◆
+ ■◇△□□□□●●●○■□◆△◆▲□
+ ■◇◇◆△◆◆▲△□■●□■
+ ◆
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_19.txt b/codex-rs/tui2/frames/shapes/frame_19.txt
new file mode 100644
index 0000000000..e1bc51ae1b
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_19.txt
@@ -0,0 +1,17 @@
+
+ ◆◆●●□◇□●●◇△◆
+ ◆□◇◇◇○△●●●◆□◆▲◇□▲▲
+ ▲□●●△■◇□□◆ ◆□△▲◆□●○
+ △●◇□▲○◆ ◆●●□▲○◇□▲
+ ◇◇△◆△◆ ▲◇○■△■◇○ ◇○▲
+ ◇○△□■ ◆◇□◇△ △△ ■△□◇
+ ○●◇◇■ △□○△◇□▲◆ △△△□◇
+ ◇◇◇◇ ◇●■○◇■▲ ◇ ◇◇◇
+ ◇□◇○▲●●●●●●◇◇◇◇□□●□◇● ○ ■◇◇
+ ○●△▲◇●□△○□□○▲◆▲ ○◆ △○◆○▲△△◇◆
+ ■○■△□◇■■■■■□□■ ○○◆△◇△△ △△■
+ ○○○□◆○ ◆△△◆△△■
+ ■ ◆○◇◇□▲ ▲●●△△◇●◆
+ ■■△◇□△◇□◆◆●●△□■ ●□◇■
+ ■◇△◆△▲■◆▲△○□▲○
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_2.txt b/codex-rs/tui2/frames/shapes/frame_2.txt
new file mode 100644
index 0000000000..af71459f5e
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_2.txt
@@ -0,0 +1,17 @@
+
+ ◆△◆△●□●●●□▲◆
+ ◆□▲△□●□◇◇◇●◇◇●◆■◇□□◆
+ ▲◇□◇○□□◇□◆◆ ◆■□●□△◇◇●◇▲
+ ◆◇△◆△□■▲▲◆ ▲▲○◇△◇▲
+ ▲○■△□○◇○◆○○◆ ○▲◇○◇▲
+ ■△□■◆ ◇□○□△○□ ○○◇□◇
+ ▲◇■□◇ ○△◇●◇◆◇▲ △■◇■◇
+ ◇■ ○◆ ▲◇□◇◇●□ ◇■△△◇
+ □■■●◇ ●◇○○◆◇■△◇□□□□□□□□▲◇◆◇◇□
+ ◆●■◇ △◇◇■ △□ ◇●○◆◆◆◆△△◆◆◇□△ ◇
+ ○○○ □ □○△△◇■ ◆■□□□□□□□■◇▲□◇◇
+ ■○◆△△▲ ◆ ▲□●△▲□
+ △○◆◆◇□▲ ▲●◆□ ◆◇■
+ ◆◇○●◆◆■□□△●●●●△●□◆◆◇◇□
+ ◆□□□□◇◇◆◆◆◆◇●△□■
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_20.txt b/codex-rs/tui2/frames/shapes/frame_20.txt
new file mode 100644
index 0000000000..c5eb01382d
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_20.txt
@@ -0,0 +1,17 @@
+
+ ◆◆□●◇◇●□●▲◆◆
+ ▲●●■●▲◆▲●●●◇◇◆○□○□▲
+ ▲▲■◆□□■◇□■ ◆■○■○□□◇□◆
+ ◆◇■◆□◇□ ◆▲□◇○△□○○
+ ◆◇ ▲◇□ ◆△ ◆◇◇○□○◇◇○
+ △◆▲◇■ □□■●◇■△ ■○◇◇○
+ ●◇●□◇ ▲□ △□□○ ▲○◇△
+ ◇◆○△◆ ■■●△◇■▲ ◇◇■◇
+ ◇△◇◇●▲●●●●●●●●◆▲■●○○○○□ △ ◇○
+ ■◇○◇◆■ △◆◆◆◆◆◆◇○ □○○■◇●○ ▲△ ◇◇
+ ○▲○○■■■■■■■■□■ ○▲●◇◇▲◇ △○
+ □ ○□△▲ ◆△□△◇△
+ ○◆○□▲◇◆ ▲●□◆●□■
+ ○▲▲△■◇□○●●▲△■◇■◆▲△□■
+ ◆□□◇◆ ●◆◆◆◆◇□■■
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_21.txt b/codex-rs/tui2/frames/shapes/frame_21.txt
new file mode 100644
index 0000000000..944b99f058
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_21.txt
@@ -0,0 +1,17 @@
+
+ ◆◆▲●□●●□●□▲◆◆
+ ▲□□◆◆◆◆□◇●◇□●◆◆▲□□◆
+ ●□○◆□□○■◆ ◆○◇□□◆◆□▲
+ ▲□◇●■■ ◆▲●□▲●□▲
+ △▲△□◆ ▲◇△◆○ ○○◆○▲
+ △■△◇ ▲□□◆△△ ○○○▲
+ ◇■◇◆ ◆ △◆▲△■ ○●○■
+ ◆○ ○● ■◇▲ ◇ ◇
+ ◇ ◇ ▲□●●●●●□□□ ○◇▲■◇▲ ●△ ◇
+ ◇ ◇○ ◇◆ ◆▲◇ ○■◆□◇▲ △■△△
+ ● ■△ ◆◆■■■ ■◆ ■□◆▲● △◆ ▲
+ ■□ △●◆ ◆□■ △
+ □◆ ○▲◆ ◆△●□■ ▲◆
+ □●◆ □■□□△◇◇●△●□■■ ▲◆
+ □□□●□◆◆◆◆▲◆●□□◆
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_22.txt b/codex-rs/tui2/frames/shapes/frame_22.txt
new file mode 100644
index 0000000000..60ea930d46
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_22.txt
@@ -0,0 +1,17 @@
+
+ ◆▲□●□●●□●□▲◆
+ ◆□△□◇△◆△◇△○◇◇●◇□△□□◆
+ ▲●□●◇○□□◆ ◆■□○□□□◆◆□▲
+ ●□◇□□■ ▲▲◇◇◇◆□○
+ ○◇◇△■ ▲◆△◇●◇△△●■◇
+ ○◇□△◆ ▲◇△◇●○△◆ ○◇○●◇
+ ◇□□○△ ◇□◇○□△■ ◇◇△◇
+ ◇◇●◇◆ ◇○◇◇○○ ◇○◇■◇
+ ◇◇▲■▲ □◇●●●●●●□□◆○□◇◆ ○▲ ◆◇●■
+ ○◇● □◆○○▲ △▲■◇△△◇ ○□●◆■◇▲▲ △○●
+ ○○○◆◇ ■■■■■□□■◆ ◆△□□◆△△△■▲◆
+ ○□○◆○▲ ◆□▲■◇▲■
+ ■■□● □□◆ ◆△□▲■□◆△
+ ■△□□▲■□◇●●□●●△●□■■■▲□
+ ■◇■◇◆●◆◆◆▲●◆△●□◆
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_23.txt b/codex-rs/tui2/frames/shapes/frame_23.txt
new file mode 100644
index 0000000000..5d340640bf
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_23.txt
@@ -0,0 +1,17 @@
+
+ ◆▲□◆●□□□□●□◆◆
+ ◆●◇□◇○◆▲◆●●▲◇◆◇□◇□◆
+ ▲■□◇■▲●□◆ ■◇△□◇○●◇◇▲
+ △●◇□●△◆ ◆●●○◇◇●○
+ △△◇◆△■ ▲△▲▲■□△□○◇○
+ ▲○◇■△◆ ◆□□□■■△□■◇◇○◇▲
+ ◆◇◇■◇ △△△△ ◆◇◆ ■ ◇■□
+ ◇△◇ ◇ ◇■◇▲◆○▲ ◇ □△◇
+ ○■○ ◇□◇●●●●●●●●◇◆□◇◆■○◆ ◇ ◇◇◇
+ ◇○○◆◇■●■ △◆○ ○◇◆○▲◇ ○◆◇
+ △■◇ ◇ ◆■■■■■■■ ■◆△●●◇◆△○△◆
+ ▲◇◇◆◇△ ▲△◇○○△◆
+ ○ ◇▲■△◆◆ ◆△■●□△□△
+ ○●○□●□□○◇●●◆□□■▲◆□□◆
+ ■◇ □●○◇◆◆□◆◆□□◆
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_24.txt b/codex-rs/tui2/frames/shapes/frame_24.txt
new file mode 100644
index 0000000000..558224147d
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_24.txt
@@ -0,0 +1,17 @@
+
+ ◆◇◆●□□□●●▲◆
+ ▲■◆△■◇◆◆◇●●□▲◆■□
+ ▲■■●○△□■◇ △◆△□◇□□▲ ○
+ ▲■△△▲△◇●▲○◆◇△◆ ◆□○◇○◆■
+ ▲ △△○△▲ ◆■■△○◆◇◆◆○◇▲■
+ ◇▲○□○◆ □▲▲△ △◇● △■○
+ ◇ ◇◇ ▲△◆▲△■△○○◇○○◇○
+ ◇ ○◇◇ ◇▲●△○◆◇◇◆△△◆◇◇
+ ◇△ ◇●●●△□□◇◇◇□□◆□▲◆◇ ◇ ◇◇
+ ◆ △ □◇△▲▲●●▲▲◇△○○□□◇ ◇□◇
+ ○ ■○◇○□■■■■■■◆ ○▲△□○◇●△▲◆
+ ○ ○▲□○ ◇ ■△●△
+ ○△□○◆◇△ ◆●■◆△△◆□
+ △▲□▲○○■◇◇△●●●◇○◆△◆
+ □△◆□□●○◆◆●●□□
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_25.txt b/codex-rs/tui2/frames/shapes/frame_25.txt
new file mode 100644
index 0000000000..38d3250764
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_25.txt
@@ -0,0 +1,17 @@
+
+ ◆□●□●□□□□◆
+ ▲ □▲□◆◆●○◇□◇◇▲
+ △◇△△▲▲■△◇□○●○◇◇◇◆
+ ◇□□◇ △ ●◇ ■○◇▲□○△
+ ▲◆◆○▲△■○●△◆◇■ ◇△△○△□
+ ○▲◇◇◇◆□□△○◇△ △◇▲◇△△◇▲
+ ◇△◇□◇ ◇◆◆△○◆△◇○△◆■◇●◇
+ ◇◇◇△◇△■ ◇◆●○△◇○◆◇●◇◇○
+ ○□○◇■◇◆◆●●●●□◇◇○○◇□□◇○
+ △▲■◇△◇▲◇◆◇◇●□◆◇○□●△○◇
+ ○◇□△○◇◆■■■■■■□△◇○◇△◇◆
+ ◇◆■◇●□●○▲▲□△◆△▲△△◇△
+ ○◆○◇◆○◆□●△▲○△◆◇◇△
+ ○△●○○◆□●◇□□ □◇□
+ ◇▲■□○□▲◆□◇□
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_26.txt b/codex-rs/tui2/frames/shapes/frame_26.txt
new file mode 100644
index 0000000000..4aac44389a
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_26.txt
@@ -0,0 +1,17 @@
+
+ ◆●□□□■□▲
+ △□◇●△○◇□●◇▲
+ △□■■◇●○◇○■■○▲
+ ●□■▲◇◇◇◆◇◇◆□△○
+ ◇◆▲○◇△◇■□○△●◇○●
+ ○ ■◇△△△■□◆○■○○△
+ ◇ □■●◇◇△◇◇●●■□
+ △▲ ○◇◇◇○○●◇◇△◇◇
+ ◇ △○□●□◇□●●△○◇◇
+ △◆◇△▲◇◆◆▲□○○□◇
+ ◇◆■△◇□■○▲△◆□○◇◇
+ ○◆◇◇△○ △△■◇◇◆
+ □ □◇○ ○◆△◇△▲
+ ◇■□○○■□◆□□●
+ ○△△○□◇◆○□
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_27.txt b/codex-rs/tui2/frames/shapes/frame_27.txt
new file mode 100644
index 0000000000..9896590f79
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_27.txt
@@ -0,0 +1,17 @@
+
+ ●□□□□▲
+ ◇●△△◇△○
+ ●■◆ □◇△■◇
+ ◇◇◇○◇◇●◇◇
+ ◇ ◆◇◆▲■●
+ ◇◆△◆■◆◇◇◇◆
+ ● ■◇◇◆□◇◇
+ ◇ ◆◇◇◇●■◇◇
+ ◇△ △ ◇□◇◇◇◇
+ ■● △■◆◇◆□◇◇
+ ◇▲ ◆○□□□△■
+ ◇◇□□◇◇◆△◇
+ ◇●●□●▲△◇○
+ ○◆◆◇○●△△
+ ■○■ ○○△
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_28.txt b/codex-rs/tui2/frames/shapes/frame_28.txt
new file mode 100644
index 0000000000..16b349dc3d
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_28.txt
@@ -0,0 +1,17 @@
+
+ △□□●
+ ◇□◆◇◆
+ ● ●◇◆
+ ◇▲◆□◇
+ ◇ ◇◇
+ ◇ ▲■◇
+ ○◇◇ ◆◇
+ ◇▲■■◇
+ △○ ◆◇
+ ◇◇△△◇◇
+ ◇ ◆◇
+ ◇●□●◇
+ ◇●□◇◇
+ □◆◆△◇
+ ◇ △□◇
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_29.txt b/codex-rs/tui2/frames/shapes/frame_29.txt
new file mode 100644
index 0000000000..24be1563b2
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_29.txt
@@ -0,0 +1,17 @@
+
+ □□□□□▲
+ ▲◇□△ □○
+ ○▲◇◇ ■■◇
+ ◇◇◇◇○○▲△
+ ○ ◇■◇ ◇
+ ◇▲◇◇◇ ◆◆
+ ◇○○◇◇◇ ○
+ ◇◇●◇◇
+ ◇◇◇□◇ ◆
+ ◆◇●◇◇ ◆
+ □◇◇△◇○ ●
+ ◇△◇◇◇ ◆◇
+ ◇◇◇◇◆◇◆◇
+ ◇●◇□△■◇■
+ ◇◇□ △▲
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_3.txt b/codex-rs/tui2/frames/shapes/frame_3.txt
new file mode 100644
index 0000000000..3f55b79ac5
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_3.txt
@@ -0,0 +1,17 @@
+
+ ◆△●●□□●●●●▲◆
+ ◆□▲△○◇◇□◇■●●◇●◆○◇□□◆
+ ▲●△□●◇□■■◆ ◆■◇ □□□△○◇▲
+ △□△○◇●▲□◆ ◆●□ ◇◇○
+ ■△□◇△○△◇◇□○◆ ○○○◇◇◆
+ △◇○○△ △▲◇○●○○ ◇ ○○◇
+ ●□ ◇ ■□○◇◆■◇▲ △□△◇▲
+ ▲▲◇▲◇ ▲▲◇■△○◇ ◇◆◇●◇
+ ▲■■◇ ●◇□□◇◇□▲◇●□□◆◆◆□□◆◇○■●◇
+ ▲○△○▲ △△□△●●◇ ◇□◇◆◆▲ ●△▲●○◆◇○◇◆
+ ■○◇ ◇ ■◇◇□▲■ ■□□□■■■□□▲△△△▲△
+ ■□◇ ○□ ◆ △○□○△△
+ ●○△△□○▲ ▲□●△■▲◇■
+ ●○□▲◆□□○●●●●▲△●□●◆◆□■
+ ◆□□□◆△◇◆◆◆◆◇●△○■
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_30.txt b/codex-rs/tui2/frames/shapes/frame_30.txt
new file mode 100644
index 0000000000..54886a319d
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_30.txt
@@ -0,0 +1,17 @@
+
+ ◆●■□□□▲
+ ◆△●◇◇○□■●○
+ ■■○◇▲○○◇□▲○
+ ◇◇○◇△◇◆○◇○ ○▲
+ ●□◇◇◆○◇▲◇▲ ◇
+ ◇□◇○□ □◇◇◇◇△◇
+ ○△◇◇◇○◆ ○△○◇ ●◆
+ ■◇ ■□●◇▲◇■◇▲ ◆
+ ■◇◆■○◇●◇○△◇▲ ◆
+ ■◇◇○◇◆◆◇◇ □▲ ◆
+ ○◇◇●○◆□◇◇◇□◇◇
+ ◇□△△▲△□○◇◇■ ◇
+ ○◇○◇◇△□◇◇▲◇△
+ ▲○▲□●○△◇▲△■
+ ○▲△◇○◆◆●■
+ ◆◆◆◆
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_31.txt b/codex-rs/tui2/frames/shapes/frame_31.txt
new file mode 100644
index 0000000000..b3989b89df
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_31.txt
@@ -0,0 +1,17 @@
+
+ ◆△△□□□□●▲
+ ◆□□●□▲◆■□○■□▲
+ ▲◇○△△▲●◆◆△■◇◆□○
+ ▲◇△□◆◆□●◆▲○○◇○◇◇○
+ ○◇◇◇◇□▲□○◆▲■○◇△◆◆
+ ●◇○◆◇◆◇■■○●□▲△△◇▲■◇
+ △◇◇ ◇○□◇○△●△●□◇□◇△◇
+ ○○▲ ◇◇■◇○ ◇○■■◇◇○△◇
+ ◇○▲◆◇■○◇◇◇△□◇◇◇◆ ◇
+ ■◇◇◇△△◇◇◆◆◆○◆◇○◇◇ □
+ ○□◆△□◇▲ △□□□◆△◇■◇◆
+ ◇◇◇○○○▲ ◆●□ ◇
+ ●◇□●◆ ▲ △ ◇□◆△◆
+ △◇○◇△◆◇◆▲◇■▲◇◆
+ ■■●◇◆□□△△●□
+ ◆◆◆◆
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_32.txt b/codex-rs/tui2/frames/shapes/frame_32.txt
new file mode 100644
index 0000000000..919eee3b0f
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_32.txt
@@ -0,0 +1,17 @@
+
+ ▲□□□□●●◇▲◆
+ ●□◇□□◇○◇◇□□◇◇▲
+ △○□●○▲□○△▲◆□◇□○■□▲
+ ■△△◇◆▲◆●▲ ▲ ▲◆○◇□▲ ▲
+ △△◇▲◇□○■□◇● ■◆▲◇○△○□○▲
+ ○△○○▲○□◇◆△◇◇□◆ ◇□△ □
+ □◇■●▲◆■○◇◇▲▲◇▲●◆△◆△△◇■◆
+ ◇◇◇▲◆ ■◆◇◇■△■◇●▲◆■○◇■■◆
+ ○◇◇▲◆ ■◆◇■◆◆◇□□□◇◇◇●◇■●◆
+ ■■■◆◆◇□○■○◆◆◆◆◆◇◇□◇●◇▲◆
+ ▲○□◇◇△ ◇□■■□□□○●△△△△△
+ ○▲◇○○○ ▲○◇△■◇
+ ■□□◇◇◇□◆ ◆△◆◇△ ▲
+ ○▲○■◇□◇●●□◆◆□■◆△
+ ◇●●◆◆▲□△□◆■■
+ ◆◆◆
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_33.txt b/codex-rs/tui2/frames/shapes/frame_33.txt
new file mode 100644
index 0000000000..c5598aa7a7
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_33.txt
@@ -0,0 +1,17 @@
+
+ ◆▲□●□●□●◇△◆
+ ◆□□◇◇○□●◇△◇▲◇□◇□△
+ ◆△○◇□□□▲●■◆ ■□△◇◇□■▲
+ ▲○△◇△◆◇▲◆ □◇◇○◆□
+ ◆△◇△◆◇◇△○○○ ◇□○○○
+ △△▲ ○◆○○◆○▲ △○△◆○
+ ◇◇□ ○▲□◇◆◇○ ◇□◇◇
+ □◇▲▲ ▲■■○△●▲ ○■◇□
+ ◇◇◇ ◇ ▲◆ △□▲▲▲●●●□◇◇□△◆◇○◇
+ ○△◇■■△△▲△◆◇◇◆◆◆◆◆◇◇□○○○◇◇△
+ ○●○▲ ◇△◇△ △ ■■■■□□□ ◇◇▲△○◆
+ ○□○□▲■▲ △△●△●△
+ □○■□▲□●▲ ◆□◇▲△□○■
+ ○◇■□○□◇▲●□◆■●▲○□◇□
+ ■●●□▲◆◆◆○□□●▲■
+ ◆◆◆◆
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_34.txt b/codex-rs/tui2/frames/shapes/frame_34.txt
new file mode 100644
index 0000000000..5a44de8256
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_34.txt
@@ -0,0 +1,17 @@
+
+ ◆▲●□□□□●◇▲◆
+ ◆□□□△○●◇■◇□□●□□●▲●◆
+ ◆△△▲◇□■△◇□◆ ◆○○○▲■□□▲
+ ▲△◆◇□◆△▲◆ □◇▲□○○
+ △△◇○▲△◇ ◇■ ▲ ○○□○○
+ ▲△○◇◆△ ○○■◇○□○ ○▲○◇○
+ ◇□○◇◆ ■○◆□◇◆○ ◇●◇◆
+ ○◇●■△ ◇□◆◇△■◇ △ ◆○
+ ▲■△△■ △○△△■◆●●□□□□□□◇◆◆■ ◇○◆
+ ◇◇○▲△▲▲○■△△■◇◇◇◆◇△◆◆◆▲△◆◇◇◆◇○
+ △◆○▲ ◇○◇□○ ■□□◆◆◆◆○ ▲△▲○◇■
+ △▲○●●○◆ △●△◇△■
+ ○□◆◇□○●▲ ◆□●■◆△▲◆
+ ▲○△◇■◇□▲●▲□●□●□◆□□△■
+ ■◇○●●◆◆◆◆◆●●□●○
+ ◆◆◆
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_35.txt b/codex-rs/tui2/frames/shapes/frame_35.txt
new file mode 100644
index 0000000000..1c1728676b
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_35.txt
@@ -0,0 +1,17 @@
+
+ ◆▲□●●□□□●□▲◆
+ ▲□●□△◇□□□■◇□◇△■◇□●◆
+ ◆△△◇●□□◇○□■◆ ◆■□●□△■◇□▲
+ ▲△△□△▲●▲◆ □□◆○◇◆
+ △△◇◇△△○ ■○□▲ ◇○□◇▲
+ ●△●△□◆ ■◇◆■△△□◆ ◇○○◇
+ ○ △△ ○○ ■□◆△ ◇○○○
+ ◇◇◇△ △○○●△■ △ ■△
+ △ ▲◆ ▲◇◇△●■△◇●●◆●◆●□◇◇ ◇◇●□
+ ◇▲○●■ △△●■□□△◇● ○▲◆◆◆◆△■◇△■ ◇■
+ △◆○▲■△○◆◇△○◆ ◆■○○○○□○○□△△◆▲◇
+ ■△○○△◇ ◆△□ ▲○
+ ○●◆○●▲△▲ ▲●△◆□□■
+ ■○◆■◇□◇▲△◇◇□◇●△□■◆△●■
+ ■○◇●●◆◆△◆◆□□□■○
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_36.txt b/codex-rs/tui2/frames/shapes/frame_36.txt
new file mode 100644
index 0000000000..0cac995ed7
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_36.txt
@@ -0,0 +1,17 @@
+
+ ◆◆□●□□□□●□▲◆
+ ◆●■■○□△●△□○□●□□■□□□◆
+ ▲○■○▲□□▲□■◆◆ ◆■□◇□□◇▲□◇▲
+ ◆◇■□□◆◆◆◆ ■□◇○■◇
+ ▲△◆●○■◇○◆○▲△ ○○△□
+ △ ▲△◆ □◆ ■◇△▲ ■○○□
+ ◇ ● ◆ ○ ■○○ ◇○◇▲
+ ◇◇○◇ ◆○ ◆△△ ○◇ ◇
+ ◇■■◇ △△ ▲□■■▲□□◆□□□□□◆ ◇○◇◇
+ ◆□◇○ ▲◇◆◆△◇△ ◆◇◆◆◆◆◆◆◆◇◇ ○△■◆
+ ■ □◇○ □◆□△○ ■□□○○○○○■ ◇▲■△
+ ■▲■○●△ ▲△◇■△
+ ○△◇◇□◇▲ ▲□□■△▲◆
+ □▲◆■□□●○●◇◆□◇●■▲■▲●□■
+ ◆□□△◇◆▲▲◆▲▲□□□□■
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_4.txt b/codex-rs/tui2/frames/shapes/frame_4.txt
new file mode 100644
index 0000000000..31e55f9cb8
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_4.txt
@@ -0,0 +1,17 @@
+
+ ◆△●●□●●□●□▲◆
+ ◆▲■□□◇△ ◇○●△□●◇■△□▲◆
+ ▲□●◇◇◇□□■◆ ◆○◇○○□◇△○○◆
+ △△◇▲◇■△□▲ ■◇□□○□○
+ △◇△◆◇●◇○●○◇▲ ○■○◇□○
+ △◇◇○◇ ■◆◇◇△□○ ■ ○●◇▲
+ ■○◇●◆ ■□□○□■◇▲ ▲ ■●◇
+ ◇△○ ▲◇△□○◇◇ ◇◇◇
+ ◆◇ ◇◆ ●◇△■○△△□◇□□□◆◆◆◆▲▲ ◇◇□
+ ◇○△ ◇ ▲△△△▲◆◇◆●○◇▲△◆▲△△○●◇△△■◇
+ ◆◇●■○▲○○▲○△ ■□□□□□□□■○▲◇◇◇◆
+ ▲◇○■◇◆◆ ▲○●△□□■
+ ○○▲△○ ▲◆ ◆△○▲□●◇△
+ ◇◇◇●◆□□○●●●●▲□●□□○◇□◆
+ □○○◇△◇◆◆◆◆◆●▲□◆
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_5.txt b/codex-rs/tui2/frames/shapes/frame_5.txt
new file mode 100644
index 0000000000..a8ae0ab819
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_5.txt
@@ -0,0 +1,17 @@
+
+ ◆△●●●□●●●□▲◆
+ ◆□■□△□△◇◇□◇●□●◆◇■□▲
+ □◆△○□◇□■◆ ■○●◇□○ ▲□▲
+ ▲◇△◇△◇△●▲ ▲○◇◇◇◇◆
+ ▲○△□△○◆□◇◆○▲ ◆ ○◇○◇◆
+ ◇◇◇◇△ ○◆◇○●△◇◆ □△◇◇
+ ◇△◇ □ ◆○◆◇○■◇▲ ■■◇□◇▲
+ ◇△◇◆■ ▲◆●◇△◆◇ □◇◆◇
+ ◇▲◇○□ △◆◇■▲◇□●◆◇□◇◆◆◆□▲◆■◇△◇
+ ◆○◇○▲▲△□□■ ◇■ △△○●○▲●△▲△◇△□◇◆
+ ○▲◇◇▲◇▲○○△□◆ ■□□■■■■■▲◇●◇○△
+ ○○□△○○ ◆ △◆△□▲○
+ ○△□○◇●□◆ ◆●□▲□■●□
+ ○◇□◇▲□□○●◇●◆▲□●□○◇●□
+ ○▲□◆□■◆◆◆▲◆▲□□◆
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_6.txt b/codex-rs/tui2/frames/shapes/frame_6.txt
new file mode 100644
index 0000000000..e0b1f85454
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_6.txt
@@ -0,0 +1,17 @@
+
+ ◆△●●●□●●□□◆◆
+ ▲○●△□◇●□□◇□□●◆▲□□◆
+ ▲▲▲◇◇◇□■ ◆■◇△●□□□△○◆
+ △▲◇□◇□◆●▲ ○□◇◇◇◇▲
+ ■●◇◇◇□○○□□○ △○○◇○▲
+ ●▲△◇△◆○□●◇○◆◇▲ △●○△◇
+ ◆ □◇◇ ○○◇△○○ ○□◇◆◇
+ ◇ ◇◇◇ ◆◇●◇△◇◇ ◇□○◇◇
+ ◆△◇▲◇ △■◇◇□●△□◆◇□◇◆◆□□◆△○△◇
+ ◇◇○▲△◆○◆●□ ◇△●□▲◇◇▲●●●○◇▲◇○
+ △ ◇ △◇◇◇●△■ ■□■■■■□■◆○○△◇
+ ▲ ● △▲◆ ▲△◆△△◇◆
+ △◆○◆□□▲ ◆□○◆△□▲□
+ ◆■◇□▲■□ ●◇◆◆▲□□□ △●■
+ ○▲●□□▲◆◆◆◆◆▲□□
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_7.txt b/codex-rs/tui2/frames/shapes/frame_7.txt
new file mode 100644
index 0000000000..7e69d68d57
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_7.txt
@@ -0,0 +1,17 @@
+
+ ◆△◇●□□●●□▲◆
+ ▲□◆□○◇□□□●●○● ◆□▲
+ □ ▲◇◇◇□◆ ◆○◇◆ □△◆□▲
+ ○○◇◇◇◇●□ ○◇○□◇△▲
+ ◆■◇□◇◇○◇△○▲ △ □◇◇○
+ ◇ ●◇◇■ ◆■○●◇○ ▲▲◇◇◇
+ ◆○■◇ ○◆◇○◇○◇ □□○◇◇
+ ◆■△◇◇ ●□△◇□◇◆ ■ ◇◇◇
+ △■◇□ ▲■◆△◇○△◇◇●●◆◇◇●●□○◇◇
+ ◇▲■◇◇●△◇◇△■◇△○◇◇○○▲●▲●○◇○◇
+ ○ ●○△□◇□◆△ □□□□□□■■◆△◇◇
+ ■◆ △◆△◆◆ ▲■▲△●△■
+ ■●▲□○○○◆ ▲○◇▲□△□■
+ ○◆■○◇□○●◇◆◆◆□□◇□□△
+ ■◇□■◇△◇◆◆▲◆●□□
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_8.txt b/codex-rs/tui2/frames/shapes/frame_8.txt
new file mode 100644
index 0000000000..b7bddd4156
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_8.txt
@@ -0,0 +1,17 @@
+
+ ◆◆□◆●□□●□▲◆
+ ▲■□△◇◇◇□●● ◇ ■□
+ ◆◇●▲◇△△□ ▲■◇△◇□○□○▲
+ ◆□○□△◇▲□◇ ■ ●○◇◇○
+ ■ △◇△▲○◇△○ △■○◇◇▲
+ ◇■▲◇○○○◆○◇◆□ ○□◇◇◇
+ ◇□◇◇◇ ■◆●○◇◆◇ ◇○◇△◇▲
+ ○▲◇◇△ ◇□○△◇▲□△ △◆△◇◇
+ ○ ○◇◇◆○ △□●◇◇△□▲□▲▲○◇◇◇
+ ○□△●◆◇■▲◇▲◇◇●◇●◆◆◇◇●■
+ △△○○◇○◇◇◇△■○□○□■○□■△○◇
+ ■▲■◇○◇◆◆ △▲△△△■
+ ■○◆□○○○◆ ◆△○◆◇□△□
+ △△■◇▲□ ●●□□●△●▲◇◆
+ ◇◇◆□□○◇◆▲□△●◆
+ ◆◆
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/shapes/frame_9.txt b/codex-rs/tui2/frames/shapes/frame_9.txt
new file mode 100644
index 0000000000..4342d3c81e
--- /dev/null
+++ b/codex-rs/tui2/frames/shapes/frame_9.txt
@@ -0,0 +1,17 @@
+
+ △●○□△□□●▲
+ △□◆△◇◇□■● ◆▲○◆
+ △ ▲◇◇△□○○●△ ○◆◇▲
+ ■ ◇◇△●●◆ ◆○▲◇○○◇□▲
+ △□■●○□■◇□▲ □△■□△□◇◇
+ ◇ ◇◇◇■○◇○●◆◆ ◇■◇□◇◇◇
+ ◆ ◇□○◇□□◇○○▲■△▲△ ◆◇◇
+ ◇ ◇△◆▲○◇◇◇◆△●○◆◇ ◇◇
+ ■▲◇■ △◇■◇◇◇◇□◇◇▲◇◇◆
+ ◇◆◇◇◇◆▲◇○◇◆◇◇◇◇◆◆◇◇◇
+ ■ ◆○△○○◇△■□□□□◇◇■△○◇
+ ○◇◇◇○▲◆ ▲△ ○△◇◆
+ ○□○◇○○ △●◆●◇△□
+ ○▲■○◆◇□△□●●●□◇◆
+ ■▲◆ □○○◇●□△■
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_1.txt b/codex-rs/tui2/frames/slug/frame_1.txt
new file mode 100644
index 0000000000..514dc8ac49
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_1.txt
@@ -0,0 +1,17 @@
+
+ d-dcottoottd
+ dot5pot5tooeeod dgtd
+ tepetppgde egpegxoxeet
+ cpdoppttd 5pecet
+ odc5pdeoeoo g-eoot
+ xp te ep5ceet p-oeet
+ tdg-p poep5ged g e5e
+ eedee t55ecep gee
+ eoxpe ceedoeg-xttttttdtt og e
+ dxcp dcte 5p egeddd-cttte5t5te
+ oddgd dot-5e edpppp dpg5tcd5
+ pdt gt e tp5pde
+ doteotd dodtedtg
+ dptodgptccocc-optdtep
+ epgpexxdddtdctpg
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_10.txt b/codex-rs/tui2/frames/slug/frame_10.txt
new file mode 100644
index 0000000000..bd3b8fafff
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_10.txt
@@ -0,0 +1,17 @@
+
+ dtpppottd
+ ppetptox5dpt
+ ddtee5xx-xtott
+ edd5oecd-otppoot
+ 5 ceeged pt5d5e5
+ ee pepx55o gedge
+ o xpgpeexep e5t
+ g eeot5tee-de-oee
+ g xo ooecxxtotcee
+ e teoted5dpdddepe
+ t geeeeegggotgoee
+ oeptotpg dxggt55
+ ep eeexptct5e5e
+ cepp5etcdg55p
+ pt dpodtcp
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_11.txt b/codex-rs/tui2/frames/slug/frame_11.txt
new file mode 100644
index 0000000000..9eaf147a6a
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_11.txt
@@ -0,0 +1,17 @@
+
+ tppppttd
+ 5g ceeeoot
+ 5gddeecop5ot
+ eddeeoctdo55
+ dg-coetopcdeet
+ eteeetdcced5ee
+ pp teeeeeedeoo
+ e ee5eeo5 ege
+ 5 pe5eep5tede
+ pp de5otg5eded
+ pe- eeeeo5eooe
+ od-5edp5ppcee
+ gd peooddecg
+ otgpeetd5pe
+ od pptdte
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_12.txt b/codex-rs/tui2/frames/slug/frame_12.txt
new file mode 100644
index 0000000000..11163a99b9
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_12.txt
@@ -0,0 +1,17 @@
+
+ tpppt-
+ toed5eto
+ g e5ott
+ 5txeeooge
+ e pxeee-5e
+ ep--pdgdeg
+ e x5oeeo
+ e 5toeeg
+ pt x5eetex
+ e 5epcpd
+ e- egopp5
+ t pegdte
+ 5 ppetpoe
+ pd5gteoee
+ o pxo-5
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_13.txt b/codex-rs/tui2/frames/slug/frame_13.txt
new file mode 100644
index 0000000000..eb072e40ad
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_13.txt
@@ -0,0 +1,17 @@
+
+ 5pppt
+ eddee
+ eedeg
+ epped
+ p ee
+ gc-ee
+ t ee
+ t ge
+ 5t dx-
+ eg toe
+ pe-- xe
+ eddde
+ etted
+ pddeo
+ t -go
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_14.txt b/codex-rs/tui2/frames/slug/frame_14.txt
new file mode 100644
index 0000000000..100f309302
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_14.txt
@@ -0,0 +1,17 @@
+
+ tpppc
+ t5dd-o
+ edee- e
+ ee5egdxt
+ eeeo e
+ xpee pe
+ eeee - p
+ eeoee o
+ eeex g
+ gd55 c5
+ oeggt-te
+ epxeddde
+ 5ggeoooe
+ eo5pdd5
+ dp po5
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_15.txt b/codex-rs/tui2/frames/slug/frame_15.txt
new file mode 100644
index 0000000000..5761f309d4
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_15.txt
@@ -0,0 +1,17 @@
+
+ ttpppxd
+ etoeedcpt
+ 55epooegpe
+ e5e 55t-dde
+ eeogooee5gde
+ oee-ee55e g
+ ee eeeexxte
+ ee5xeteee p-e
+ eetttpeeed-ce
+ edec5eoxp- -e
+ e5eeeede e c
+ epp-dxeo- o
+ peot 555e ce
+ edeeoo-to5
+ odpdddd5
+ ee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_16.txt b/codex-rs/tui2/frames/slug/frame_16.txt
new file mode 100644
index 0000000000..f9001140ed
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_16.txt
@@ -0,0 +1,17 @@
+
+ dotgpptxd
+ 5deepeeoeoo
+ e55go5ooee po
+ 555 cpdoeoeeppe
+ eecd5ppoeep5eeo
+ eeepep eoo ge x-e
+ ooe 5eteeee5pgt e
+ e5c eeee5eeegc ee
+ ooexetx5deegpt 5
+ pgddtooope-de tde
+ eeetgg5poecgc-xee
+ eep ee e55t 5
+ oep e 5t5dte
+ oexgdpx55tde
+ pc-docddcp
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_17.txt b/codex-rs/tui2/frames/slug/frame_17.txt
new file mode 100644
index 0000000000..696d932d40
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_17.txt
@@ -0,0 +1,17 @@
+
+ totttccxtd
+ dcppexxpopetgdt
+ tpo5dooettgeeedgo
+ 5e5d5egde pecoxeeoo
+ e5d x eg5ooo55 t
+ eopt5e tc5e 5to5e-5
+ pgc5e t55ed pgee5oe
+ -goeg g55ee5eteeocp
+ t5p5oootxodeodcoeee e
+ egdcdde5po5eeogotpto
+ ooo5gggppppodep55o op
+ oeedp e5eee c
+ doogpod tpt5dd5
+ t xptootedcpcep
+ etc5dttxpdtp
+ e
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_18.txt b/codex-rs/tui2/frames/slug/frame_18.txt
new file mode 100644
index 0000000000..abb0da53d2
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_18.txt
@@ -0,0 +1,17 @@
+
+ dootootcxtd
+ dtgdctttxddtgtccd
+ d5cepgpogtg-dgt55o p
+ teep-tdgp poed5oxocooot
+ do55 5e dgtdo5x5edocood
+ 5oe ttx-ddd5tptep-5d5e5xg
+ eeoc5 t5p5egd5gpeoeot
+ go-xe dogeecd eceg
+ ogg tooococtxetep5ot epee
+ dooepop xe5ddodxeedcxeo t
+ e5eoeggpppppe odd5e5p5e-e
+ oogtot eepg5pdp
+ odptdd- dpdd5ote
+ pe-ppttooodppd5dtp
+ gxed5ddt-tgctg
+ e
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_19.txt b/codex-rs/tui2/frames/slug/frame_19.txt
new file mode 100644
index 0000000000..ffc4d2b475
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_19.txt
@@ -0,0 +1,17 @@
+
+ ddootxtoox-d
+ dteeeo5ooodpdteptt
+ tpcc5getpe epctepco
+ 5ceptde doottdept
+ ee5e5e tedg5geo eot
+ eo5pp depx5g-5 p-pe
+ doexp 5pd5ette 5c5te
+ eeee ecgoegt e eee
+ epeotoccoooxxxetpcpec o gee
+ dc5teop5dptotet dd codot5-ed
+ pog5tegggggppg dod5e55 55p
+ oodpdo e55d55p
+ pgdoxxpt tco-5ece
+ pg-ep5xtddoc5pg cpxp
+ gx-dc-pdt-dp-d
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_2.txt b/codex-rs/tui2/frames/slug/frame_2.txt
new file mode 100644
index 0000000000..f4419e3d69
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_2.txt
@@ -0,0 +1,17 @@
+
+ d-dcotooottd
+ dtt5pcteexoxeodpeptd
+ tepeoppxpee egpop5eecet
+ de5d5ppttd -toe5et
+ tdg5pdeodood dteoet
+ p5tge epot5ot ooepe
+ teppe d5ecedet 5gege
+ eg oe tepeecp ep5-e
+ pggoe cedddeg-xtttttttttedexp
+ dope 5eep 5p eoodddd--ddet5geg
+ ooo p po--ep egpppppppgetpee
+ pod-5t e ttc5tp
+ -oddett todtgdeg
+ exdcddgptccocc-opedeep
+ eptptxxddddxc5pg
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_20.txt b/codex-rs/tui2/frames/slug/frame_20.txt
new file mode 100644
index 0000000000..0039bd880b
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_20.txt
@@ -0,0 +1,17 @@
+
+ ddtoxxototdd
+ tcogctdtoooeeddpott
+ ttgdtpgxpg egdgotpetd
+ degdpep dtteo5poo
+ de tep d5gdeedpoeeo
+ 5etep tppceg5 poxeo
+ cecte tp -tpd toe5
+ edd5e ggccegt exge
+ e5eectocoooooodtpcddoop 5 eo
+ pededg 5eeddddeo poogeoo t5 ee
+ otdopgggggggpg otoeete 5o
+ p dp5t d5p-e5
+ oddptxd tcpecpp
+ dt--gxtdcctcgxget5pp
+ eptxdgoddddepgg
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_21.txt b/codex-rs/tui2/frames/slug/frame_21.txt
new file mode 100644
index 0000000000..87e3597d5d
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_21.txt
@@ -0,0 +1,17 @@
+
+ ddtotootottdd
+ ttpeeddtxoxtcde-ptd
+ cpddtpdge edxptdept
+ tpecgp dtcptcpt
+ 5t5pe te5do ooddt
+ 5g5e tppd55 oodt
+ epee dg5et5p ocog
+ eo oc get e e
+ e e ttcccccttt detget c5 e
+ e xo ed dte dgepet 5g-5
+ c g- eeggg pe ppdtc 5e t
+ pt ccd dpg 5
+ pd d-d d-cpp te
+ pod pgptcxxccopgg -e
+ pttctddddtdctpe
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_22.txt b/codex-rs/tui2/frames/slug/frame_22.txt
new file mode 100644
index 0000000000..8dfe7daaab
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_22.txt
@@ -0,0 +1,17 @@
+
+ dttotootottd
+ dt5pe-d5e5oeecet5ptd
+ tcpcxoppe egpopptddtt
+ cpxppg tteeedpo
+ oex5p td5eoe-5cpe
+ oep5e tx5ecd5e oeooe
+ etpo5 xteop5p xe5e
+ eeoee eoexdo edege
+ eetgt txoocccottdopedgot decgg
+ deo pdootg5tgx55e opcdgettg5oo
+ ooode gggggppge ecptd555gte
+ opodot dptgetp
+ pgtc ttd d-ptgpd5
+ pcpttgpxcotcc5opggptp
+ gxgxdcddd-od-ope
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_23.txt b/codex-rs/tui2/frames/slug/frame_23.txt
new file mode 100644
index 0000000000..f573acb714
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_23.txt
@@ -0,0 +1,17 @@
+
+ dttdotpttotdd
+ doeteodtdootedepetd
+ tgteptcpe gxcteoceet
+ 5cepc5e dccoeeco
+ 55ee5p t5ttpp5poeo
+ toeg5e dppppp5ppexoet
+ eeege 5c5- dee ggepp
+ x5e e egetdot e p5e
+ dgo etxcooooocoedpedgod e exe
+ eoodegog 5eo oedotx ode
+ 5pe e eggggggg pe5coed5d5e
+ teede- t5eod5e
+ o etp5dd d-gcp5t5
+ oootcptoxoodttg-dtpe
+ gxgpooxddtddppe
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_24.txt b/codex-rs/tui2/frames/slug/frame_24.txt
new file mode 100644
index 0000000000..92833e8c58
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_24.txt
@@ -0,0 +1,17 @@
+
+ dxdcttpootd
+ tgd5geddxoottdpt
+ tgpco5tgx -ecpxppt o
+ tp55t5eotoex5egdpoeodp
+ t 55o5t egg5odeeeoetp
+ xtotoe ptt5g-ecg5go
+ e exg t5dt5g5doeoded
+ e oee eto5odexd5-eee
+ e- eccccttxxxttdptde e ee
+ d 5 gpe5ttcctte-dotpe epe
+ o poeopgggggge ot-poeo5te
+ o otpo egg5c5
+ o-poee- dogd5cdp
+ --ptodgxxcoocedd5e
+ pcdptcoddootp
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_25.txt b/codex-rs/tui2/frames/slug/frame_25.txt
new file mode 100644
index 0000000000..d8b8655dac
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_25.txt
@@ -0,0 +1,17 @@
+
+ dtopcttttd
+ tgptpedcoepeet
+ 5e55ttg-etoooeeed
+ etpe 5g oe goetpo5
+ tddot5pdc5deg e55o5p
+ otxexdpt-dec 5ete55et
+ e5epe edd5od5eo5dgeoe
+ eee5e-ggxdoo5eodxoeeo
+ dtoegeddooootxeooetpeo
+ 5-ge5etedeecpdeopo5oe
+ oxp5oeegggggpt5eoe5ee
+ edgectco-tpcd5t55e5
+ dededodpc5td5dee5
+ o-coodpoeppgpep
+ xtgpottdtep
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_26.txt b/codex-rs/tui2/frames/slug/frame_26.txt
new file mode 100644
index 0000000000..4be73d44de
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_26.txt
@@ -0,0 +1,17 @@
+
+ dcpppgtt
+ 5pec5oetcet
+ 5pggecoeoggot
+ cpgteexdeedt5d
+ edtoe-xgpo5ceoc
+ o ge5c5gpdogoo5
+ eg ppoee5eeccgt
+ 5- oeeeddoee5ee
+ e -opctxtoo5oee
+ g -de5teddtpoope
+ eeg5epgot5etoee
+ odxe5o 55geee
+ p peo de5e5t
+ egpoogpdppc
+ o5cdpxdop
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_27.txt b/codex-rs/tui2/frames/slug/frame_27.txt
new file mode 100644
index 0000000000..f333909d2b
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_27.txt
@@ -0,0 +1,17 @@
+
+ cppptt
+ ecc5e5o
+ cpe pe5pe
+ exxdeecex
+ e eed-po
+ xd-dgeeeee
+ o geedpeeg
+ e eeexogee
+ e- -geteeee
+ po -gdedpee
+ e- ddppt5p
+ eetteed5e
+ eootot5ed
+ oddeoo55
+ pog do5
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_28.txt b/codex-rs/tui2/frames/slug/frame_28.txt
new file mode 100644
index 0000000000..3c0deb542c
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_28.txt
@@ -0,0 +1,17 @@
+
+ 5ppc
+ etdee
+ o cee
+ e-epe
+ e xe
+ e -ge
+ dex de
+ e-gge
+ 5o de
+ ee-cxe
+ e de
+ eotoe
+ eopee
+ pdd5e
+ x -te
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_29.txt b/codex-rs/tui2/frames/slug/frame_29.txt
new file mode 100644
index 0000000000..0c6277f4d5
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_29.txt
@@ -0,0 +1,17 @@
+
+ tppppt
+ tep5gpo
+ dtee pge
+ eeeedot5
+ o xge e
+ etxee dd
+ eooeee d
+ eeoxe
+ eexpe e
+ deoee e
+ pee5ed o
+ e5xxe de
+ xeeeexde
+ eoep5gep
+ xep -t
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_3.txt b/codex-rs/tui2/frames/slug/frame_3.txt
new file mode 100644
index 0000000000..b1e9173608
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_3.txt
@@ -0,0 +1,17 @@
+
+ d-octtooootd
+ dtt5oeetegooecddeptd
+ tc5pcepgge egxgppt5det
+ 5t5oecttd eopgeeo
+ p5pe5d5eepod odoeed
+ 5eoo5 -teocoo e ooe
+ op e ppoedget -p5et
+ t-ete t-eg5oe xdeoe
+ -gpe ceptxep-xottdddttdxdgce
+ tocot -5p5cce epeddtgo-tcoeeoee
+ pde e geettg gpppgggppt555t5
+ ppx ot e 5dtd55
+ od55pot ttc5gtep
+ odttdppdococtcopcedtg
+ eptpdcxddddxc5dg
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_30.txt b/codex-rs/tui2/frames/slug/frame_30.txt
new file mode 100644
index 0000000000..9dfd28bc20
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_30.txt
@@ -0,0 +1,17 @@
+
+ dcgpptt
+ d5ceeoppoo
+ gpdetooetto
+ eeoe5edoeo ot
+ opeeeoetet e
+ epedt peeee-e
+ o5eeeod o5oe oe
+ ge ptoxtege- e
+ gedgoxoxo5et e
+ geeoeddxegtt e
+ goeecodpxeetxe
+ ep55t5poeeg e
+ oeoee5pxetx5
+ tdttod5et5p
+ o--edddcp
+ eeee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_31.txt b/codex-rs/tui2/frames/slug/frame_31.txt
new file mode 100644
index 0000000000..1dba8edd8f
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_31.txt
@@ -0,0 +1,17 @@
+
+ d-cptptot
+ dtpcttdgtoppt
+ teo55tode-gedpo
+ tx5tddpcdtooeoxeo
+ deeeet-podtgoe5dd
+ cedexdepgocpt-5etge
+ 5ee edpeo-o5cpepe5e
+ oot exgeo edggexo-e
+ eotdepdxex5txxed e
+ geex55eedddodeoee p
+ dpd5tet 5pppe5epxdg
+ eeeooot dop e
+ cepodgt - epe5e
+ ceoe5deetegtee
+ pgoxdtp5-cp
+ eeee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_32.txt b/codex-rs/tui2/frames/slug/frame_32.txt
new file mode 100644
index 0000000000..33160e7163
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_32.txt
@@ -0,0 +1,17 @@
+
+ tttttccxtd
+ cpxppxoeeppext
+ 5dpodttdc-epepoppt
+ p55edtec- - tdoettgt
+ 55etepoppec petxo5opot
+ o5ootopeeceetd et5 p
+ pegctepoeettetoe5d55epd
+ eeetd gdeeg5pec-dgoegge
+ oee-d pdegddetttxxxoegoe
+ pggdeepopodddddeepecx-d
+ topee5 epggpppdc555-5
+ otedoo toe5px
+ pppeextd d5de5 t
+ o-ogxtecopedtgd5
+ xcoddtt5pdgg
+ eee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_33.txt b/codex-rs/tui2/frames/slug/frame_33.txt
new file mode 100644
index 0000000000..ff8827f3d2
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_33.txt
@@ -0,0 +1,17 @@
+
+ dttototox-d
+ dtpeeopoxce-epep-
+ d5oetpttoge gp5eetgt
+ to5e5detd peeodp
+ d-e5eee5odo etood
+ 55t odooeot 5o5do
+ eet g otpedeo epee
+ pett tppo5ot ogep
+ eee e te 5ptttcootxxt5deox
+ d5epg5ct5exedddddeepdddxe-
+ ooot e5e5 5 ggggppp eet5de
+ otoptgt 55c5o5
+ pogptpct dtet5pop
+ oxgpotetctdgctopxp
+ goottddddtpc-g
+ eeee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_34.txt b/codex-rs/tui2/frames/slug/frame_34.txt
new file mode 100644
index 0000000000..4b1eb6a5a2
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_34.txt
@@ -0,0 +1,17 @@
+
+ dtottttoxtd
+ dtpt5ocegxtpoppctod
+ d55tepgcxpe edootgppt
+ t5depd5td petpoo
+ 55eo-5egeggt oopod
+ t5oee5 oogeopo otoeo
+ epdxd podpedd ecxd
+ oeogc epde5ge 5 do
+ tp5-g 5o55gdoottttttxddg xde
+ eeot5ttdg55pxeedx-dddt5deeeeo
+ 5dot eoepdg gppeeeed t5toep
+ 5tocood 5c-e5p
+ oteetoct dtogd5te
+ -o5xgettcttopopetpcp
+ gxocodddddcopod
+ eee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_35.txt b/codex-rs/tui2/frames/slug/frame_35.txt
new file mode 100644
index 0000000000..f2432dc0ad
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_35.txt
@@ -0,0 +1,17 @@
+
+ dttcotttottd
+ tpop-xpptgepxcgxpod
+ d55ectpedpge egpop-gept
+ t55t5tctd ptdoed
+ 55xe55o gopt eopet
+ c5c5te pedg--pd eooe
+ o g-5 oo ppd- edoo
+ xexc 5ooc5p 5 g5
+ 5 td tee5cg5eoodcdotxx exop
+ etdcp 55cgpt5ec otdddd5gx5p ep
+ 5eotp5ode5de egddddpddp55dte
+ g-do5x d5p td
+ ocedctct tc5dppp
+ gddgxpx-cxxtxc5pgd5cg
+ gdxcodd5ddttpgd
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_36.txt b/codex-rs/tui2/frames/slug/frame_36.txt
new file mode 100644
index 0000000000..c84a104e4a
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_36.txt
@@ -0,0 +1,17 @@
+
+ ddtottttottd
+ doggot5c5totcttgpptd
+ topottp-pgee egpxptetpet
+ degptdddd ppxoge
+ t5dcopeoeot- do-p
+ 5 t5e pd ge5t godp
+ e cge go goo edet
+ eeox do d55g oe e
+ epge 55 tpgptttdtttttd eoxe
+ dpeo tedd5x5 gexdddddddee o5pe
+ p peo tdt5d gppdddddg etg5
+ ptgoc- t5eg5
+ o5eetxt tttg5te
+ ptdgppodcxdtxcg-gtctp
+ ept5xdttdttttppg
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_4.txt b/codex-rs/tui2/frames/slug/frame_4.txt
new file mode 100644
index 0000000000..2eed2c8465
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_4.txt
@@ -0,0 +1,17 @@
+
+ d-octootottd
+ d-gtpe5geoo5pceg5ptd
+ tpoeeetpge edxodpe5ood
+ 55eteg-tt geppopo
+ 5e5deoeocdet ogoepo
+ 5eede pdee5po p ooet
+ goece pppotget t gce
+ e-o te5pdee eee
+ deged ce5gd55txtttddddtt eep
+ eo5ge t555tdeeooet-dtc5dce55ge
+ eecpotooto5 gppppppppd-eeee
+ teogede tdc5ppp
+ ootcdgtd d-dtpce5
+ xeeodppoccocttoptoepe
+ pooxcxdddddc-pe
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_5.txt b/codex-rs/tui2/frames/slug/frame_5.txt
new file mode 100644
index 0000000000..e0c7693a9e
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_5.txt
@@ -0,0 +1,17 @@
+
+ d-occtooottd
+ dtgt5p5eetxotcdegtt
+ pd5otepge gdoepogtpt
+ te5e5e-ot -deeeed
+ to5p5ddtedot e oeoed
+ xeee5 odeoc5ed t5ee
+ e5egt eodeoget ppxtet
+ e5edg tdoe5de tede
+ etedp 5degtepodxtxdddttdge-e
+ doeott5tpg egg55oodto-t5e5pee
+ oteetxtoo5te gppgggggtxceo5
+ oot5oo e 5d5ptd
+ d5poeotd dottppcp
+ depetptocxodttopdxcp
+ d-pdpgddd-dttpe
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_6.txt b/codex-rs/tui2/frames/slug/frame_6.txt
new file mode 100644
index 0000000000..d5ac091f39
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_6.txt
@@ -0,0 +1,17 @@
+
+ d-occtoottdd
+ tdc5peoptettcdtptd
+ ttteeepg egx-optp5od
+ 5tepepdot oteeeet
+ poeeepootpo -ooeot
+ c-5e5edtceodet -oo5e
+ d txe gdoe5do dtede
+ x exe deox5ee xtoee
+ d-e-e 5peepc5tdxtxddttd-o5e
+ eeot5dddct e5opteetcoooeteog
+ 5 e 5xeec5g gpgggppgeoo5e
+ t c 5te tcd55ee
+ -eodppt dtdd5ptt
+ egxptgtgcxddttppgccp
+ d-cpttdddedttp
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_7.txt b/codex-rs/tui2/frames/slug/frame_7.txt
new file mode 100644
index 0000000000..02d1f1ae52
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_7.txt
@@ -0,0 +1,17 @@
+
+ d-xcptoottd
+ tpetoetptooocgept
+ p teeepe edxegp5dpt
+ ooeeexct dxope5t
+ epepeede5ot - peeo
+ e ceeg epoceo t-eee
+ eoge ddeoeoe ppdee
+ dg5xe ot5epee p eee
+ 5gxp tgd5eo5xxccdxxocpoee
+ etpeeocxe5pe-oeeoototcoeoe
+ o od5pepd5 ppppppggd5ee
+ pd 5d5de tg-5c5p
+ pcttoood tdxtp5pp
+ odpoepocxdddtpept5
+ gxpgxcxddtdcpp
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_8.txt b/codex-rs/tui2/frames/slug/frame_8.txt
new file mode 100644
index 0000000000..d028ab360e
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_8.txt
@@ -0,0 +1,17 @@
+
+ ddtdcttottd
+ tgp5eeepoogx gt
+ deote55pgtgx5xpotdt
+ dpop5ette p odeeo
+ p 5e5toe5o -poeet
+ epteodddoedp oteee
+ epeee pdcoeee ede5et
+ otee5 eto5etp- -e5ee
+ o oeedd g5poex5tttttoxee
+ g op5odegteteeceoddeeop
+ 55ooeoeee5pdpdpgopg5oe
+ ptgeoeee -t555p
+ podpoood d5odet5p
+ -cpetpgcctpc5otee
+ xxdppoedtt5oe
+ ee
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/slug/frame_9.txt b/codex-rs/tui2/frames/slug/frame_9.txt
new file mode 100644
index 0000000000..2481e07a35
--- /dev/null
+++ b/codex-rs/tui2/frames/slug/frame_9.txt
@@ -0,0 +1,17 @@
+
+ -odp5ttot
+ 5pd5eepgogd-od
+ 5 tee5pddo5godxt
+ g ee5cod ddteodett
+ 5pgcopgept p-ptctee
+ e eeegdeocdd epepeee
+ e xpoeppeootg-t5 eee
+ e x5dtoxeed5oode gee
+ g gteg 5egexxetexteee
+ edeeedtededeeeeddeee
+ g ed5ooe5gppppeeg5oe
+ oxeeote t5 d5ee
+ otoeoo 5cdce5p
+ d-godep5toccpee
+ p-d pooect5g
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_1.txt b/codex-rs/tui2/frames/vbars/frame_1.txt
new file mode 100644
index 0000000000..0ca3a5d334
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_1.txt
@@ -0,0 +1,17 @@
+
+ ▎▋▎▋▌▉▉▌▌▉▊▎
+ ▎▌▊▋▉▍▉▋▉▍▌▏▏▌▎ ▎█▉▎
+ ▊▏▉▏▉▉▉█▍▎ ▎█▉▎█▏▌▏▏▏▉
+ ▌▉▎▍▉█▊▊▎ ▋▉▏▌▏▊
+ ▍▍▌▋█▍▏▍▎▍▍ █▋▏▍▍▊
+ ▏▉ ▉▎ ▏▉▋▌▏▏▊ █▋▍▏▏▊
+ ▉▍█▊▉ █▍▏▉▋█▏▎ ▏▋▏
+ ▏▏▎▏▎ ▊▋▋▏▌▏▉ █▎▏
+ ▏▌▏█▎ ▌▏▏▍▍▏█▋▏▉▉▉▉▉▉▎▉▊ ▌█ ▏
+ ▎▏▌▉ ▎▌▉▎ ▋▉ ▏█▏▎▎▎▋▋▊▊▊▏▋▊▋▊▏
+ ▍▍▎█▍ ▍▍▊▋▋▎ ▎▍▉██▉ ▍▉█▋▊▌▎▋
+ ▉▍▊ █▊ ▎ ▊█▋▉▎▏
+ ▍▍▊▎▍▉▎ ▎▌▎▉▏▎▉█
+ ▍▉▊▍▎ ▉▉▋▌▌▌▌▋▌▉▉▎▊▏▉
+ ▎▉█▉▏▏▏▎▎▎▊▎▌▉▉█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_10.txt b/codex-rs/tui2/frames/vbars/frame_10.txt
new file mode 100644
index 0000000000..b422fb1274
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_10.txt
@@ -0,0 +1,17 @@
+
+ ▎▉▉▉▉▍▉▉▎
+ ▉█▎▉▉▉▍▏▋▎▉▊
+ ▍▎▊▏▏▋▏▏▊▏▉▍▊▊
+ ▏▎▎▋▍▏▌▎▋▍▊██▍▍▊
+ ▋ ▌▏▏█▏▍ █▊▋▎▋▏▋
+ ▏▎ █▏▉▏▋▋▍ ▎▎█▏
+ ▍ ▏▉█▉▏▏▏▏▉ ▏▋▊
+ █ ▏▏▍▉▋▉▏▏▊▎▎▋▍▏▏
+ █ ▏▍ ▍▍▏▌▏▏▉▍▉▌▏▏
+ ▏ ▊▏▍▊▏▎▋▎▉▎▎▎▏▉▎
+ ▊ █▏▏▏▏▏██ ▍▊█▍▏▎
+ ▍▎█▊▍▊▉█ ▎▏██▊▋▋
+ ▏█ ▏▏▏▏▉▊▋▊▋▏▋▎
+ ▌▎▉▉▋▏▉▌▎ ▋▋█
+ ▉▊ ▎▉▍▎▊▌▉
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_11.txt b/codex-rs/tui2/frames/vbars/frame_11.txt
new file mode 100644
index 0000000000..5d4524e293
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_11.txt
@@ -0,0 +1,17 @@
+
+ ▊▉▉▉▉▉▉▎
+ ▋█ ▌▏▏▏▍▍▊
+ ▋█▎▎▏▏▌▍▉▋▍▊
+ ▏▎▎▏▏▌▌▊▎▌▋▋
+ ▎█▋▌▍▏▉▍█▌▎▏▏▊
+ ▏▉▎▏▏▉▎▌▌▏▎▋▏▏
+ ▉▉ ▊▏▏▏▏▏▏▎▏▌▍
+ ▏ ▏▏▋▏▏▍▋ ▏█▏
+ ▋ █▏▋▏▏▉▋▉▏▎▏
+ ▉▉ ▎▏▋▌▊█▋▏▎▏▍
+ █▎▊ ▏▏▏▏▌▋▏▍▍▏
+ ▍▎▊▋▏▎▉▋▉▉▌▏▎
+ ▎ ▉▏▍▍▍▎▏▌█
+ ▍▉ ▉▏▏▊▎▋▉▎
+ ▍▎ █▉▉▎▉▎
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_12.txt b/codex-rs/tui2/frames/vbars/frame_12.txt
new file mode 100644
index 0000000000..f81900edb1
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_12.txt
@@ -0,0 +1,17 @@
+
+ ▉▉▉▉▉▋
+ ▊▌▎▎▋▏▊▍
+ █ ▏▋▍▉▊
+ ▋▉▏▏▏▌▌█▏
+ ▏ █▏▏▏▏▋▋▏
+ ▏█▋▋▉▍█▎▏█
+ ▏ ▏▋▍▏▏▍
+ ▏ ▋▉▍▏▏█
+ ▉▊ ▏▋▏▏▉▏▏
+ ▏ ▋▏▉▌▉▎
+ ▏▋ ▏█▌▉▉▋
+ ▊ ▉▏ ▎▊▏
+ ▋ ▉▉▏▊▉▍▏
+ █▍▋█▊▏▍▏▎
+ ▍ █▏▍▋▋
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_13.txt b/codex-rs/tui2/frames/vbars/frame_13.txt
new file mode 100644
index 0000000000..4231032a45
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_13.txt
@@ -0,0 +1,17 @@
+
+ ▋▉▉▉▊
+ ▏▎▎▏▏
+ ▏▎▎▏█
+ ▏▉▉▏▎
+ ▉ ▏▏
+ █▋▊▏▏
+ ▊ ▏▏
+ ▉ █▏
+ ▋▉ ▎▏▋
+ ▏█ ▉▌▏
+ █▎▋▋ ▏▎
+ ▏▎▎▎▏
+ ▏▉▊▏▎
+ ▉▎▎▏▌
+ ▊ ▋█▌
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_14.txt b/codex-rs/tui2/frames/vbars/frame_14.txt
new file mode 100644
index 0000000000..6eab794e0a
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_14.txt
@@ -0,0 +1,17 @@
+
+ ▉▉▉▉▌
+ ▊▋▎▎▋▍
+ ▏▎▏▏▋ ▏
+ ▏▏▋▏█▍▏▊
+ ▏▏▏▍ ▏
+ ▏▉▏▏ █▏
+ ▏▏▏▏ ▋ ▉
+ ▏▏▍▏▎ ▍
+ ▏▏▏▏ █
+ █▍▋▋ ▌▋
+ ▍▏██▊▋▊▏
+ ▏▉▏▏▎▎▎▏
+ ▋ █▏▌▌▌▎
+ ▏▍▋▉▎▎▋
+ ▎▉ █▌▋
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_15.txt b/codex-rs/tui2/frames/vbars/frame_15.txt
new file mode 100644
index 0000000000..fa9a859bd0
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_15.txt
@@ -0,0 +1,17 @@
+
+ ▉▉▉▉▉▏▎
+ ▎▊▌▏▏▍▋▉▊
+ ▋▋▏▉▌▍▏█▉▏
+ ▏▋▎ ▋▋▊▋▎▎▏
+ ▏▏▌█▌▍▏▏▋█▍▏
+ ▍▏▏▊▏▏▋▋▏ █
+ ▏▏ ▏▏▏▏▏▏▊▏
+ ▏▏▋▏▏▉▏▏▏ █▊▏
+ ▏▏▉▊▊▉▏▏▏▎▋▋▏
+ ▏▎▏▌▋▏▍▏▉▋ ▋▏
+ ▏▋▏▏▏▏▎▏ ▎ ▌
+ ▏▉▉▋▍▏▏▍▊ ▌
+ █▏▍▊ ▋▋▋▎ ▌▎
+ ▏▍▏▏▍▍▋▉▍▋
+ ▍▍▉▍▎▎▎▋
+ ▎▎
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_16.txt b/codex-rs/tui2/frames/vbars/frame_16.txt
new file mode 100644
index 0000000000..1fcc2090a2
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_16.txt
@@ -0,0 +1,17 @@
+
+ ▎▌▉█▉▉▉▏▎
+ ▋▍▏▏▉▏▏▍▏▌▍
+ ▏▋▋█▍▋▌▍▏▏ █▍
+ ▋▋▋ ▌▉▎▍▏▍▏▏▉▉▏
+ ▏▏▌▎▋▉█▌▏▏▉▋▏▎▍
+ ▏▏▏▉▏█ ▏▍▌ ▏ ▏▋▏
+ ▍▍▏ ▋▎▊▏▏▏▏▋▉█▊ ▏
+ ▏▋▌ ▏▎▏▏▋▏▏▏█▌ ▎▏
+ ▍▍▏▏▏▉▏▋▍▏▏█▉▉ ▋
+ ▉█▎▎▊▌▌▍▉▏▋▎▏ ▊▎▏
+ ▏▏▏▉██▋▉▍▏▌█▌▋▏▏▎
+ ▏▏▉ ▏▎ ▎▋▋▊ ▋
+ ▍▏▉ ▏ ▋▊▋▎▊▏
+ ▍▏▏█▎▉▏▋▋▉▎▏
+ █▋▋▎▌▋▎▎▌▉
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_17.txt b/codex-rs/tui2/frames/vbars/frame_17.txt
new file mode 100644
index 0000000000..1adf01af90
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_17.txt
@@ -0,0 +1,17 @@
+
+ ▊▌▉▉▉▌▌▏▊▎
+ ▎▌▉▉▏▏▏▉▌▉▏▊█▍▊
+ ▊▉▍▋▎▌▌▎▉▊█▏▏▏▎█▍
+ ▋▏▋▎▋▏█▎▎ █▏▌▍▏▏▏▌▍
+ ▏▋▎ ▏ ▏█▋▍▌▍▋▋ ▊
+ ▎▌▉▊▋▎ ▊▋▋▏ ▋▊▌▋▏▋▋
+ ▉ ▌▋▏ ▊▋▋▏▎ ▉█▏▏▋▌▏
+ ▊█▌▏ ▋▋▏▏▋▏▊▏▏▌▌▉
+ ▊▋▉▋▍▌▌▉▏▍▎▏▍▍▋▍▏▏▏ ▏
+ ▏█▎▌▎▎▏▋▉▍▋▏▏▍ ▍▉█▉▍
+ ▍▍▍▋███▉▉▉▉▍▎▏▉▋▋▍ ▍█
+ ▍▏▏▎▉ ▎▋▏▏▎ ▌
+ ▎▍▍ ▉▍▎ ▊█▊▋▍▎▋
+ ▊ ▏▉▉▌▍▉▎▎▌▉▋▏█
+ ▎▉▌▋▎▊▉▏▉▎▉▉
+ ▎
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_18.txt b/codex-rs/tui2/frames/vbars/frame_18.txt
new file mode 100644
index 0000000000..9c46c64821
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_18.txt
@@ -0,0 +1,17 @@
+
+ ▎▌▌▉▌▌▉▌▏▊▎
+ ▎▉█▎▌▊▉▉▏▎▎▊█▉▌▌▎
+ ▎▋▋▏▉█▉▌█▊█▋▎█▉▋▋▍ ▉
+ ▊▏▏▉▋▊▍█▉ █▍▎▎▋▌▏▍▌▍▍▍▊
+ ▎▍▋▋ ▋▏ ▎█▉▎▍▋▏▋▏▎▍▌▍▍▎
+ ▋▍▏ ▊▊▏▋▎▎▎▋▊▉▊▏█▊▋▍▋▎▋▏
+ ▏▏▍▋▋ ▉▋▉▋▏█▎▋█▉▏▌▏▌▊
+ █▍▊▏▏ ▍▍█▏▏▌▍ ▏▌▏█
+ ▍██ ▊▍▌▌▌▌▌▉▏▏▊▏▉▋▍▊ ▏▉▏▎
+ ▎▍▍▏▉▍▉ ▏▏▋▎▎▍▎▏▏▏▎▌▏▎▍ ▊
+ ▏▋▏▍▎██▉▉▉▉▉▎ ▍▎▎▋▏▋▉▋▎▊▎
+ ▍▍ ▊▍▊ ▎▎▉█▋▉▎█
+ ▍▍▉▉▍▍▋ ▎▉▍▎▋▍▊▎
+ █▏▋▉▉▉▉▌▌▌▍█▉▎▋▎▊▉
+ █▏▏▎▋▎▎▊▋▉█▌▉█
+ ▎
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_19.txt b/codex-rs/tui2/frames/vbars/frame_19.txt
new file mode 100644
index 0000000000..572f5ffc32
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_19.txt
@@ -0,0 +1,17 @@
+
+ ▎▎▌▌▉▏▉▌▌▏▋▎
+ ▎▉▏▏▏▍▋▌▌▌▎▉▎▊▏▉▊▊
+ ▊▉▌▌▋█▏▉▉▎ ▎▉▋▊▎▉▌▍
+ ▋▌▏▉▊▍▎ ▎▌▌▉▊▍▏▉▊
+ ▏▏▋▎▋▎ ▊▏▍█▋█▏▍ ▏▍▊
+ ▏▍▋▉█ ▎▏▉▏▋ ▋▋ █▋▉▏
+ ▍▌▏▏█ ▋▉▍▋▏▉▊▎ ▋▋▋▉▏
+ ▏▏▏▏ ▏▌█▍▏█▊ ▏ ▏▏▏
+ ▏▉▏▍▊▌▌▌▌▌▌▏▏▏▏▉▉▌▉▏▌ ▍ █▏▏
+ ▍▌▋▊▏▌▉▋▍▉▉▍▊▎▊ ▍▎ ▋▍▎▍▊▋▋▏▎
+ █▍█▋▉▏█████▉▉█ ▍▍▎▋▏▋▋ ▋▋█
+ ▍▍▍▉▎▍ ▎▋▋▎▋▋█
+ █ ▎▍▏▏▉▊ ▊▌▌▋▋▏▌▎
+ ██▋▏▉▋▏▉▎▎▌▌▋▉█ ▌▉▏█
+ █▏▋▎▋▊█▎▊▋▍▉▊▍
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_2.txt b/codex-rs/tui2/frames/vbars/frame_2.txt
new file mode 100644
index 0000000000..0e0c021f43
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_2.txt
@@ -0,0 +1,17 @@
+
+ ▎▋▎▋▌▉▌▌▌▉▊▎
+ ▎▉▊▋▉▌▉▏▏▏▌▏▏▌▎█▏▉▉▎
+ ▊▏▉▏▍▉▉▏▉▎▎ ▎█▉▌▉▋▏▏▌▏▊
+ ▎▏▋▎▋▉█▊▊▎ ▊▊▍▏▋▏▊
+ ▊▍█▋▉▍▏▍▎▍▍▎ ▍▊▏▍▏▊
+ █▋▉█▎ ▏▉▍▉▋▍▉ ▍▍▏▉▏
+ ▊▏█▉▏ ▍▋▏▌▏▎▏▊ ▋█▏█▏
+ ▏█ ▍▎ ▊▏▉▏▏▌▉ ▏█▋▋▏
+ ▉██▌▏ ▌▏▍▍▎▏█▋▏▉▉▉▉▉▉▉▉▊▏▎▏▏▉
+ ▎▌█▏ ▋▏▏█ ▋▉ ▏▌▍▎▎▎▎▋▋▎▎▏▉▋ ▏
+ ▍▍▍ ▉ ▉▍▋▋▏█ ▎█▉▉▉▉▉▉▉█▏▊▉▏▏
+ █▍▎▋▋▊ ▎ ▊▉▌▋▊▉
+ ▋▍▎▎▏▉▊ ▊▌▎▉ ▎▏█
+ ▎▏▍▌▎▎█▉▉▋▌▌▌▌▋▌▉▎▎▏▏▉
+ ▎▉▉▉▉▏▏▎▎▎▎▏▌▋▉█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_20.txt b/codex-rs/tui2/frames/vbars/frame_20.txt
new file mode 100644
index 0000000000..42c288df92
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_20.txt
@@ -0,0 +1,17 @@
+
+ ▎▎▉▌▏▏▌▉▌▊▎▎
+ ▊▌▌█▌▊▎▊▌▌▌▏▏▎▍▉▍▉▊
+ ▊▊█▎▉▉█▏▉█ ▎█▍█▍▉▉▏▉▎
+ ▎▏█▎▉▏▉ ▎▊▉▏▍▋▉▍▍
+ ▎▏ ▊▏▉ ▎▋ ▎▏▏▍▉▍▏▏▍
+ ▋▎▊▏█ ▉▉█▌▏█▋ █▍▏▏▍
+ ▌▏▌▉▏ ▊▉ ▋▉▉▍ ▊▍▏▋
+ ▏▎▍▋▎ ██▌▋▏█▊ ▏▏█▏
+ ▏▋▏▏▌▊▌▌▌▌▌▌▌▌▎▊█▌▍▍▍▍▉ ▋ ▏▍
+ █▏▍▏▎█ ▋▎▎▎▎▎▎▏▍ ▉▍▍█▏▌▍ ▊▋ ▏▏
+ ▍▊▍▍████████▉█ ▍▊▌▏▏▊▏ ▋▍
+ ▉ ▍▉▋▊ ▎▋▉▋▏▋
+ ▍▎▍▉▊▏▎ ▊▌▉▎▌▉█
+ ▍▊▊▋█▏▉▍▌▌▊▋█▏█▎▊▋▉█
+ ▎▉▉▏▎ ▌▎▎▎▎▏▉██
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_21.txt b/codex-rs/tui2/frames/vbars/frame_21.txt
new file mode 100644
index 0000000000..aa5d4f7274
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_21.txt
@@ -0,0 +1,17 @@
+
+ ▎▎▊▌▉▌▌▉▌▉▊▎▎
+ ▊▉▉▎▎▎▎▉▏▌▏▉▌▎▎▊▉▉▎
+ ▌▉▍▎▉▉▍█▎ ▎▍▏▉▉▎▎▉▊
+ ▊▉▏▌██ ▎▊▌▉▊▌▉▊
+ ▋▊▋▉▎ ▊▏▋▎▍ ▍▍▎▍▊
+ ▋█▋▏ ▊▉▉▎▋▋ ▍▍▍▊
+ ▏█▏▎ ▎ ▋▎▊▋█ ▍▌▍█
+ ▎▍ ▍▌ █▏▊ ▏ ▏
+ ▏ ▏ ▊▉▌▌▌▌▌▉▉▉ ▍▏▊█▏▊ ▌▋ ▏
+ ▏ ▏▍ ▏▎ ▎▊▏ ▍█▎▉▏▊ ▋█▋▋
+ ▌ █▋ ▎▎███ █▎ █▉▎▊▌ ▋▎ ▊
+ █▉ ▋▌▎ ▎▉█ ▋
+ ▉▎ ▍▊▎ ▎▋▌▉█ ▊▎
+ ▉▌▎ ▉█▉▉▋▏▏▌▋▌▉██ ▊▎
+ ▉▉▉▌▉▎▎▎▎▊▎▌▉▉▎
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_22.txt b/codex-rs/tui2/frames/vbars/frame_22.txt
new file mode 100644
index 0000000000..3b1ce4ecde
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_22.txt
@@ -0,0 +1,17 @@
+
+ ▎▊▉▌▉▌▌▉▌▉▊▎
+ ▎▉▋▉▏▋▎▋▏▋▍▏▏▌▏▉▋▉▉▎
+ ▊▌▉▌▏▍▉▉▎ ▎█▉▍▉▉▉▎▎▉▊
+ ▌▉▏▉▉█ ▊▊▏▏▏▎▉▍
+ ▍▏▏▋█ ▊▎▋▏▌▏▋▋▌█▏
+ ▍▏▉▋▎ ▊▏▋▏▌▍▋▎ ▍▏▍▌▏
+ ▏▉▉▍▋ ▏▉▏▍▉▋█ ▏▏▋▏
+ ▏▏▌▏▎ ▏▍▏▏▍▍ ▏▍▏█▏
+ ▏▏▊█▊ ▉▏▌▌▌▌▌▌▉▉▎▍▉▏▎ ▍▊ ▎▏▌█
+ ▍▏▌ ▉▎▍▍▊ ▋▊█▏▋▋▏ ▍▉▌▎█▏▊▊ ▋▍▌
+ ▍▍▍▎▏ █████▉▉█▎ ▎▋▉▉▎▋▋▋█▊▎
+ ▍▉▍▎▍▊ ▎▉▊█▏▊█
+ ██▉▌ ▉▉▎ ▎▋▉▊█▉▎▋
+ █▋▉▉▊█▉▏▌▌▉▌▌▋▌▉███▊▉
+ █▏█▏▎▌▎▎▎▊▌▎▋▌▉▎
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_23.txt b/codex-rs/tui2/frames/vbars/frame_23.txt
new file mode 100644
index 0000000000..0b99396129
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_23.txt
@@ -0,0 +1,17 @@
+
+ ▎▊▉▎▌▉▉▉▉▌▉▎▎
+ ▎▌▏▉▏▍▎▊▎▌▌▊▏▎▏▉▏▉▎
+ ▊█▉▏█▊▌▉▎ █▏▋▉▏▍▌▏▏▊
+ ▋▌▏▉▌▋▎ ▎▌▌▍▏▏▌▍
+ ▋▋▏▎▋█ ▊▋▊▊█▉▋▉▍▏▍
+ ▊▍▏█▋▎ ▎▉▉▉██▋▉█▏▏▍▏▊
+ ▎▏▏█▏ ▋▋▋▋ ▎▏▎ █ ▏█▉
+ ▏▋▏ ▏ ▏█▏▊▎▍▊ ▏ ▉▋▏
+ ▍█▍ ▏▉▏▌▌▌▌▌▌▌▌▏▎▉▏▎█▍▎ ▏ ▏▏▏
+ ▏▍▍▎▏█▌█ ▋▎▍ ▍▏▎▍▊▏ ▍▎▏
+ ▋█▏ ▏ ▎███████ █▎▋▌▌▏▎▋▍▋▎
+ ▊▏▏▎▏▋ ▊▋▏▍▍▋▎
+ ▍ ▏▊█▋▎▎ ▎▋█▌▉▋▉▋
+ ▍▌▍▉▌▉▉▍▏▌▌▎▉▉█▊▎▉▉▎
+ █▏ ▉▌▍▏▎▎▉▎▎▉▉▎
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_24.txt b/codex-rs/tui2/frames/vbars/frame_24.txt
new file mode 100644
index 0000000000..5e26d7a27b
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_24.txt
@@ -0,0 +1,17 @@
+
+ ▎▏▎▌▉▉▉▌▌▊▎
+ ▊█▎▋█▏▎▎▏▌▌▉▊▎█▉
+ ▊██▌▍▋▉█▏ ▋▎▋▉▏▉▉▊ ▍
+ ▊█▋▋▊▋▏▌▊▍▎▏▋▎ ▎▉▍▏▍▎█
+ ▊ ▋▋▍▋▊ ▎██▋▍▎▏▎▎▍▏▊█
+ ▏▊▍▉▍▎ ▉▊▊▋ ▋▏▌ ▋█▍
+ ▏ ▏▏ ▊▋▎▊▋█▋▍▍▏▍▍▏▍
+ ▏ ▍▏▏ ▏▊▌▋▍▎▏▏▎▋▋▎▏▏
+ ▏▋ ▏▌▌▌▋▉▉▏▏▏▉▉▎▉▊▎▏ ▏ ▏▏
+ ▎ ▋ ▉▏▋▊▊▌▌▊▊▏▋▍▍▉▉▏ ▏▉▏
+ ▍ █▍▏▍▉██████▎ ▍▊▋▉▍▏▌▋▊▎
+ ▍ ▍▊▉▍ ▏ █▋▌▋
+ ▍▋▉▍▎▏▋ ▎▌█▎▋▋▎▉
+ ▋▊▉▊▍▍█▏▏▋▌▌▌▏▍▎▋▎
+ ▉▋▎▉▉▌▍▎▎▌▌▉▉
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_25.txt b/codex-rs/tui2/frames/vbars/frame_25.txt
new file mode 100644
index 0000000000..5009b8b66d
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_25.txt
@@ -0,0 +1,17 @@
+
+ ▎▉▌▉▌▉▉▉▉▎
+ ▊ ▉▊▉▎▎▌▍▏▉▏▏▊
+ ▋▏▋▋▊▊█▋▏▉▍▌▍▏▏▏▎
+ ▏▉▉▏ ▋ ▌▏ █▍▏▊▉▍▋
+ ▊▎▎▍▊▋█▍▌▋▎▏█ ▏▋▋▍▋▉
+ ▍▊▏▏▏▎▉▉▋▍▏▋ ▋▏▊▏▋▋▏▊
+ ▏▋▏▉▏ ▏▎▎▋▍▎▋▏▍▋▎█▏▌▏
+ ▏▏▏▋▏▋█ ▏▎▌▍▋▏▍▎▏▌▏▏▍
+ ▍▉▍▏█▏▎▎▌▌▌▌▉▏▏▍▍▏▉▉▏▍
+ ▋▊█▏▋▏▊▏▎▏▏▌▉▎▏▍▉▌▋▍▏
+ ▍▏▉▋▍▏▎██████▉▋▏▍▏▋▏▎
+ ▏▎█▏▌▉▌▍▊▊▉▋▎▋▊▋▋▏▋
+ ▍▎▍▏▎▍▎▉▌▋▊▍▋▎▏▏▋
+ ▍▋▌▍▍▎▉▌▏▉▉ ▉▏▉
+ ▏▊█▉▍▉▊▎▉▏▉
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_26.txt b/codex-rs/tui2/frames/vbars/frame_26.txt
new file mode 100644
index 0000000000..900a51c3b5
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_26.txt
@@ -0,0 +1,17 @@
+
+ ▎▌▉▉▉█▉▊
+ ▋▉▏▌▋▍▏▉▌▏▊
+ ▋▉██▏▌▍▏▍██▍▊
+ ▌▉█▊▏▏▏▎▏▏▎▉▋▍
+ ▏▎▊▍▏▋▏█▉▍▋▌▏▍▌
+ ▍ █▏▋▋▋█▉▎▍█▍▍▋
+ ▏ ▉█▌▏▏▋▏▏▌▌█▉
+ ▋▊ ▍▏▏▏▍▍▌▏▏▋▏▏
+ ▏ ▋▍▉▌▉▏▉▌▌▋▍▏▏
+ ▋▎▏▋▊▏▎▎▊▉▍▍▉▏
+ ▏▎█▋▏▉█▍▊▋▎▉▍▏▏
+ ▍▎▏▏▋▍ ▋▋█▏▏▎
+ ▉ ▉▏▍ ▍▎▋▏▋▊
+ ▏█▉▍▍█▉▎▉▉▌
+ ▍▋▋▍▉▏▎▍▉
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_27.txt b/codex-rs/tui2/frames/vbars/frame_27.txt
new file mode 100644
index 0000000000..0b2e8c7306
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_27.txt
@@ -0,0 +1,17 @@
+
+ ▌▉▉▉▉▊
+ ▏▌▋▋▏▋▍
+ ▌█▎ ▉▏▋█▏
+ ▏▏▏▍▏▏▌▏▏
+ ▏ ▎▏▎▊█▌
+ ▏▎▋▎█▎▏▏▏▎
+ ▌ █▏▏▎▉▏▏
+ ▏ ▎▏▏▏▌█▏▏
+ ▏▋ ▋ ▏▉▏▏▏▏
+ █▌ ▋█▎▏▎▉▏▏
+ ▏▊ ▎▍▉▉▉▋█
+ ▏▏▉▉▏▏▎▋▏
+ ▏▌▌▉▌▊▋▏▍
+ ▍▎▎▏▍▌▋▋
+ █▍█ ▍▍▋
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_28.txt b/codex-rs/tui2/frames/vbars/frame_28.txt
new file mode 100644
index 0000000000..01ce82b6d3
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_28.txt
@@ -0,0 +1,17 @@
+
+ ▋▉▉▌
+ ▏▉▎▏▎
+ ▌ ▌▏▎
+ ▏▊▎▉▏
+ ▏ ▏▏
+ ▏ ▊█▏
+ ▍▏▏ ▎▏
+ ▏▊██▏
+ ▋▍ ▎▏
+ ▏▏▋▋▏▏
+ ▏ ▎▏
+ ▏▌▉▌▏
+ ▏▌▉▏▏
+ ▉▎▎▋▏
+ ▏ ▋▉▏
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_29.txt b/codex-rs/tui2/frames/vbars/frame_29.txt
new file mode 100644
index 0000000000..c682a6082c
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_29.txt
@@ -0,0 +1,17 @@
+
+ ▉▉▉▉▉▊
+ ▊▏▉▋ ▉▍
+ ▍▊▏▏ ██▏
+ ▏▏▏▏▍▍▊▋
+ ▍ ▏█▏ ▏
+ ▏▊▏▏▏ ▎▎
+ ▏▍▍▏▏▏ ▍
+ ▏▏▌▏▏
+ ▏▏▏▉▏ ▎
+ ▎▏▌▏▏ ▎
+ ▉▏▏▋▏▍ ▌
+ ▏▋▏▏▏ ▎▏
+ ▏▏▏▏▎▏▎▏
+ ▏▌▏▉▋█▏█
+ ▏▏▉ ▋▊
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_3.txt b/codex-rs/tui2/frames/vbars/frame_3.txt
new file mode 100644
index 0000000000..6c202bc0c3
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_3.txt
@@ -0,0 +1,17 @@
+
+ ▎▋▌▌▉▉▌▌▌▌▊▎
+ ▎▉▊▋▍▏▏▉▏█▌▌▏▌▎▍▏▉▉▎
+ ▊▌▋▉▌▏▉██▎ ▎█▏ ▉▉▉▋▍▏▊
+ ▋▉▋▍▏▌▊▉▎ ▎▌▉ ▏▏▍
+ █▋▉▏▋▍▋▏▏▉▍▎ ▍▍▍▏▏▎
+ ▋▏▍▍▋ ▋▊▏▍▌▍▍ ▏ ▍▍▏
+ ▌▉ ▏ █▉▍▏▎█▏▊ ▋▉▋▏▊
+ ▊▊▏▊▏ ▊▊▏█▋▍▏ ▏▎▏▌▏
+ ▊██▏ ▌▏▉▉▏▏▉▊▏▌▉▉▎▎▎▉▉▎▏▍█▌▏
+ ▊▍▋▍▊ ▋▋▉▋▌▌▏ ▏▉▏▎▎▊ ▌▋▊▌▍▎▏▍▏▎
+ █▍▏ ▏ █▏▏▉▊█ █▉▉▉███▉▉▊▋▋▋▊▋
+ █▉▏ ▍▉ ▎ ▋▍▉▍▋▋
+ ▌▍▋▋▉▍▊ ▊▉▌▋█▊▏█
+ ▌▍▉▊▎▉▉▍▌▌▌▌▊▋▌▉▌▎▎▉█
+ ▎▉▉▉▎▋▏▎▎▎▎▏▌▋▍█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_30.txt b/codex-rs/tui2/frames/vbars/frame_30.txt
new file mode 100644
index 0000000000..a44dbb6ed0
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_30.txt
@@ -0,0 +1,17 @@
+
+ ▎▌█▉▉▉▊
+ ▎▋▌▏▏▍▉█▌▍
+ ██▍▏▊▍▍▏▉▊▍
+ ▏▏▍▏▋▏▎▍▏▍ ▍▊
+ ▌▉▏▏▎▍▏▊▏▊ ▏
+ ▏▉▏▍▉ ▉▏▏▏▏▋▏
+ ▍▋▏▏▏▍▎ ▍▋▍▏ ▌▎
+ █▏ █▉▌▏▊▏█▏▊ ▎
+ █▏▎█▍▏▌▏▍▋▏▊ ▎
+ █▏▏▍▏▎▎▏▏ ▉▊ ▎
+ ▍▏▏▌▍▎▉▏▏▏▉▏▏
+ ▏▉▋▋▊▋▉▍▏▏█ ▏
+ ▍▏▍▏▏▋▉▏▏▊▏▋
+ ▊▍▊▉▌▍▋▏▊▋█
+ ▍▊▋▏▍▎▎▌█
+ ▎▎▎▎
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_31.txt b/codex-rs/tui2/frames/vbars/frame_31.txt
new file mode 100644
index 0000000000..70da8799e2
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_31.txt
@@ -0,0 +1,17 @@
+
+ ▎▋▋▉▉▉▉▌▊
+ ▎▉▉▌▉▊▎█▉▍█▉▊
+ ▊▏▍▋▋▊▌▎▎▋█▏▎▉▍
+ ▊▏▋▉▎▎▉▌▎▊▍▍▏▍▏▏▍
+ ▍▏▏▏▏▉▊▉▍▎▊█▍▏▋▎▎
+ ▌▏▍▎▏▎▏██▍▌▉▊▋▋▏▊█▏
+ ▋▏▏ ▏▍▉▏▍▋▌▋▌▉▏▉▏▋▏
+ ▍▍▊ ▏▏█▏▍ ▏▍██▏▏▍▋▏
+ ▏▍▊▎▏█▍▏▏▏▋▉▏▏▏▎ ▏
+ █▏▏▏▋▋▏▏▎▎▎▍▎▏▍▏▏ ▉
+ ▍▉▎▋▉▏▊ ▋▉▉▉▎▋▏█▏▎
+ ▏▏▏▍▍▍▊ ▎▌▉ ▏
+ ▌▏▉▌▎ ▊ ▋ ▏▉▎▋▎
+ ▋▏▍▏▋▎▏▎▊▏█▊▏▎
+ ██▌▏▎▉▉▋▋▌▉
+ ▎▎▎▎
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_32.txt b/codex-rs/tui2/frames/vbars/frame_32.txt
new file mode 100644
index 0000000000..ddfb4be3fe
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_32.txt
@@ -0,0 +1,17 @@
+
+ ▊▉▉▉▉▌▌▏▊▎
+ ▌▉▏▉▉▏▍▏▏▉▉▏▏▊
+ ▋▍▉▌▍▊▉▍▋▊▎▉▏▉▍█▉▊
+ █▋▋▏▎▊▎▌▊ ▊ ▊▎▍▏▉▊ ▊
+ ▋▋▏▊▏▉▍█▉▏▌ █▎▊▏▍▋▍▉▍▊
+ ▍▋▍▍▊▍▉▏▎▋▏▏▉▎ ▏▉▋ ▉
+ ▉▏█▌▊▎█▍▏▏▊▊▏▊▌▎▋▎▋▋▏█▎
+ ▏▏▏▊▎ █▎▏▏█▋█▏▌▊▎█▍▏██▎
+ ▍▏▏▊▎ █▎▏█▎▎▏▉▉▉▏▏▏▌▏█▌▎
+ ███▎▎▏▉▍█▍▎▎▎▎▎▏▏▉▏▌▏▊▎
+ ▊▍▉▏▏▋ ▏▉██▉▉▉▍▌▋▋▋▋▋
+ ▍▊▏▍▍▍ ▊▍▏▋█▏
+ █▉▉▏▏▏▉▎ ▎▋▎▏▋ ▊
+ ▍▊▍█▏▉▏▌▌▉▎▎▉█▎▋
+ ▏▌▌▎▎▊▉▋▉▎██
+ ▎▎▎
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_33.txt b/codex-rs/tui2/frames/vbars/frame_33.txt
new file mode 100644
index 0000000000..7fa5ac29bc
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_33.txt
@@ -0,0 +1,17 @@
+
+ ▎▊▉▌▉▌▉▌▏▋▎
+ ▎▉▉▏▏▍▉▌▏▋▏▊▏▉▏▉▋
+ ▎▋▍▏▉▉▉▊▌█▎ █▉▋▏▏▉█▊
+ ▊▍▋▏▋▎▏▊▎ ▉▏▏▍▎▉
+ ▎▋▏▋▎▏▏▋▍▍▍ ▏▉▍▍▍
+ ▋▋▊ ▍▎▍▍▎▍▊ ▋▍▋▎▍
+ ▏▏▉ ▍▊▉▏▎▏▍ ▏▉▏▏
+ ▉▏▊▊ ▊██▍▋▌▊ ▍█▏▉
+ ▏▏▏ ▏ ▊▎ ▋▉▊▊▊▌▌▌▉▏▏▉▋▎▏▍▏
+ ▍▋▏██▋▋▊▋▎▏▏▎▎▎▎▎▏▏▉▍▍▍▏▏▋
+ ▍▌▍▊ ▏▋▏▋ ▋ ████▉▉▉ ▏▏▊▋▍▎
+ ▍▉▍▉▊█▊ ▋▋▌▋▌▋
+ ▉▍█▉▊▉▌▊ ▎▉▏▊▋▉▍█
+ ▍▏█▉▍▉▏▊▌▉▎█▌▊▍▉▏▉
+ █▌▌▉▊▎▎▎▍▉▉▌▊█
+ ▎▎▎▎
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_34.txt b/codex-rs/tui2/frames/vbars/frame_34.txt
new file mode 100644
index 0000000000..a8c447ff18
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_34.txt
@@ -0,0 +1,17 @@
+
+ ▎▊▌▉▉▉▉▌▏▊▎
+ ▎▉▉▉▋▍▌▏█▏▉▉▌▉▉▌▊▌▎
+ ▎▋▋▊▏▉█▋▏▉▎ ▎▍▍▍▊█▉▉▊
+ ▊▋▎▏▉▎▋▊▎ ▉▏▊▉▍▍
+ ▋▋▏▍▊▋▏ ▏█ ▊ ▍▍▉▍▍
+ ▊▋▍▏▎▋ ▍▍█▏▍▉▍ ▍▊▍▏▍
+ ▏▉▍▏▎ █▍▎▉▏▎▍ ▏▌▏▎
+ ▍▏▌█▋ ▏▉▎▏▋█▏ ▋ ▎▍
+ ▊█▋▋█ ▋▍▋▋█▎▌▌▉▉▉▉▉▉▏▎▎█ ▏▍▎
+ ▏▏▍▊▋▊▊▍█▋▋█▏▏▏▎▏▋▎▎▎▊▋▎▏▏▎▏▍
+ ▋▎▍▊ ▏▍▏▉▍ █▉▉▎▎▎▎▍ ▊▋▊▍▏█
+ ▋▊▍▌▌▍▎ ▋▌▋▏▋█
+ ▍▉▎▏▉▍▌▊ ▎▉▌█▎▋▊▎
+ ▊▍▋▏█▏▉▊▌▊▉▌▉▌▉▎▉▉▋█
+ █▏▍▌▌▎▎▎▎▎▌▌▉▌▍
+ ▎▎▎
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_35.txt b/codex-rs/tui2/frames/vbars/frame_35.txt
new file mode 100644
index 0000000000..ba905231e1
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_35.txt
@@ -0,0 +1,17 @@
+
+ ▎▊▉▌▌▉▉▉▌▉▊▎
+ ▊▉▌▉▋▏▉▉▉█▏▉▏▋█▏▉▌▎
+ ▎▋▋▏▌▉▉▏▍▉█▎ ▎█▉▌▉▋█▏▉▊
+ ▊▋▋▉▋▊▌▊▎ ▉▉▎▍▏▎
+ ▋▋▏▏▋▋▍ █▍▉▊ ▏▍▉▏▊
+ ▌▋▌▋▉▎ █▏▎█▋▋▉▎ ▏▍▍▏
+ ▍ ▋▋ ▍▍ █▉▎▋ ▏▍▍▍
+ ▏▏▏▋ ▋▍▍▌▋█ ▋ █▋
+ ▋ ▊▎ ▊▏▏▋▌█▋▏▌▌▎▌▎▌▉▏▏ ▏▏▌▉
+ ▏▊▍▌█ ▋▋▌█▉▉▋▏▌ ▍▊▎▎▎▎▋█▏▋█ ▏█
+ ▋▎▍▊█▋▍▎▏▋▍▎ ▎█▍▍▍▍▉▍▍▉▋▋▎▊▏
+ █▋▍▍▋▏ ▎▋▉ ▊▍
+ ▍▌▎▍▌▊▋▊ ▊▌▋▎▉▉█
+ █▍▎█▏▉▏▊▋▏▏▉▏▌▋▉█▎▋▌█
+ █▍▏▌▌▎▎▋▎▎▉▉▉█▍
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_36.txt b/codex-rs/tui2/frames/vbars/frame_36.txt
new file mode 100644
index 0000000000..246ed3d692
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_36.txt
@@ -0,0 +1,17 @@
+
+ ▎▎▉▌▉▉▉▉▌▉▊▎
+ ▎▌██▍▉▋▌▋▉▍▉▌▉▉█▉▉▉▎
+ ▊▍█▍▊▉▉▊▉█▎▎ ▎█▉▏▉▉▏▊▉▏▊
+ ▎▏█▉▉▎▎▎▎ █▉▏▍█▏
+ ▊▋▎▌▍█▏▍▎▍▊▋ ▍▍▋▉
+ ▋ ▊▋▎ ▉▎ █▏▋▊ █▍▍▉
+ ▏ ▌ ▎ ▍ █▍▍ ▏▍▏▊
+ ▏▏▍▏ ▎▍ ▎▋▋ ▍▏ ▏
+ ▏██▏ ▋▋ ▊▉██▊▉▉▎▉▉▉▉▉▎ ▏▍▏▏
+ ▎▉▏▍ ▊▏▎▎▋▏▋ ▎▏▎▎▎▎▎▎▎▏▏ ▍▋█▎
+ █ ▉▏▍ ▉▎▉▋▍ █▉▉▍▍▍▍▍█ ▏▊█▋
+ █▊█▍▌▋ ▊▋▏█▋
+ ▍▋▏▏▉▏▊ ▊▉▉█▋▊▎
+ ▉▊▎█▉▉▌▍▌▏▎▉▏▌█▊█▊▌▉█
+ ▎▉▉▋▏▎▊▊▎▊▊▉▉▉▉█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_4.txt b/codex-rs/tui2/frames/vbars/frame_4.txt
new file mode 100644
index 0000000000..5dcae750bc
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_4.txt
@@ -0,0 +1,17 @@
+
+ ▎▋▌▌▉▌▌▉▌▉▊▎
+ ▎▊█▉▉▏▋ ▏▍▌▋▉▌▏█▋▉▊▎
+ ▊▉▌▏▏▏▉▉█▎ ▎▍▏▍▍▉▏▋▍▍▎
+ ▋▋▏▊▏█▋▉▊ █▏▉▉▍▉▍
+ ▋▏▋▎▏▌▏▍▌▍▏▊ ▍█▍▏▉▍
+ ▋▏▏▍▏ █▎▏▏▋▉▍ █ ▍▌▏▊
+ █▍▏▌▎ █▉▉▍▉█▏▊ ▊ █▌▏
+ ▏▋▍ ▊▏▋▉▍▏▏ ▏▏▏
+ ▎▏ ▏▎ ▌▏▋█▍▋▋▉▏▉▉▉▎▎▎▎▊▊ ▏▏▉
+ ▏▍▋ ▏ ▊▋▋▋▊▎▏▎▌▍▏▊▋▎▊▋▋▍▌▏▋▋█▏
+ ▎▏▌█▍▊▍▍▊▍▋ █▉▉▉▉▉▉▉█▍▊▏▏▏▎
+ ▊▏▍█▏▎▎ ▊▍▌▋▉▉█
+ ▍▍▊▋▍ ▊▎ ▎▋▍▊▉▌▏▋
+ ▏▏▏▌▎▉▉▍▌▌▌▌▊▉▌▉▉▍▏▉▎
+ ▉▍▍▏▋▏▎▎▎▎▎▌▊▉▎
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_5.txt b/codex-rs/tui2/frames/vbars/frame_5.txt
new file mode 100644
index 0000000000..cab16091cb
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_5.txt
@@ -0,0 +1,17 @@
+
+ ▎▋▌▌▌▉▌▌▌▉▊▎
+ ▎▉█▉▋▉▋▏▏▉▏▌▉▌▎▏█▉▊
+ ▉▎▋▍▉▏▉█▎ █▍▌▏▉▍ ▊▉▊
+ ▊▏▋▏▋▏▋▌▊ ▊▍▏▏▏▏▎
+ ▊▍▋▉▋▍▎▉▏▎▍▊ ▎ ▍▏▍▏▎
+ ▏▏▏▏▋ ▍▎▏▍▌▋▏▎ ▉▋▏▏
+ ▏▋▏ ▉ ▎▍▎▏▍█▏▊ ██▏▉▏▊
+ ▏▋▏▎█ ▊▎▌▏▋▎▏ ▉▏▎▏
+ ▏▊▏▍▉ ▋▎▏█▊▏▉▌▎▏▉▏▎▎▎▉▊▎█▏▋▏
+ ▎▍▏▍▊▊▋▉▉█ ▏█ ▋▋▍▌▍▊▌▋▊▋▏▋▉▏▎
+ ▍▊▏▏▊▏▊▍▍▋▉▎ █▉▉█████▊▏▌▏▍▋
+ ▍▍▉▋▍▍ ▎ ▋▎▋▉▊▍
+ ▍▋▉▍▏▌▉▎ ▎▌▉▊▉█▌▉
+ ▍▏▉▏▊▉▉▍▌▏▌▎▊▉▌▉▍▏▌▉
+ ▍▊▉▎▉█▎▎▎▊▎▊▉▉▎
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_6.txt b/codex-rs/tui2/frames/vbars/frame_6.txt
new file mode 100644
index 0000000000..e41e013ab0
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_6.txt
@@ -0,0 +1,17 @@
+
+ ▎▋▌▌▌▉▌▌▉▉▎▎
+ ▊▍▌▋▉▏▌▉▉▏▉▉▌▎▊▉▉▎
+ ▊▊▊▏▏▏▉█ ▎█▏▋▌▉▉▉▋▍▎
+ ▋▊▏▉▏▉▎▌▊ ▍▉▏▏▏▏▊
+ █▌▏▏▏▉▍▍▉▉▍ ▋▍▍▏▍▊
+ ▌▊▋▏▋▎▍▉▌▏▍▎▏▊ ▋▌▍▋▏
+ ▎ ▉▏▏ ▍▍▏▋▍▍ ▍▉▏▎▏
+ ▏ ▏▏▏ ▎▏▌▏▋▏▏ ▏▉▍▏▏
+ ▎▋▏▊▏ ▋█▏▏▉▌▋▉▎▏▉▏▎▎▉▉▎▋▍▋▏
+ ▏▏▍▊▋▎▍▎▌▉ ▏▋▌▉▊▏▏▊▌▌▌▍▏▊▏▍
+ ▋ ▏ ▋▏▏▏▌▋█ █▉████▉█▎▍▍▋▏
+ ▊ ▌ ▋▊▎ ▊▋▎▋▋▏▎
+ ▋▎▍▎▉▉▊ ▎▉▍▎▋▉▊▉
+ ▎█▏▉▊█▉ ▌▏▎▎▊▉▉▉ ▋▌█
+ ▍▊▌▉▉▊▎▎▎▎▎▊▉▉
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_7.txt b/codex-rs/tui2/frames/vbars/frame_7.txt
new file mode 100644
index 0000000000..7a88d5ef14
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_7.txt
@@ -0,0 +1,17 @@
+
+ ▎▋▏▌▉▉▌▌▉▊▎
+ ▊▉▎▉▍▏▉▉▉▌▌▍▌ ▎▉▊
+ ▉ ▊▏▏▏▉▎ ▎▍▏▎ ▉▋▎▉▊
+ ▍▍▏▏▏▏▌▉ ▍▏▍▉▏▋▊
+ ▎█▏▉▏▏▍▏▋▍▊ ▋ ▉▏▏▍
+ ▏ ▌▏▏█ ▎█▍▌▏▍ ▊▊▏▏▏
+ ▎▍█▏ ▍▎▏▍▏▍▏ ▉▉▍▏▏
+ ▎█▋▏▏ ▌▉▋▏▉▏▎ █ ▏▏▏
+ ▋█▏▉ ▊█▎▋▏▍▋▏▏▌▌▎▏▏▌▌▉▍▏▏
+ ▏▊█▏▏▌▋▏▏▋█▏▋▍▏▏▍▍▊▌▊▌▍▏▍▏
+ ▍ ▌▍▋▉▏▉▎▋ ▉▉▉▉▉▉██▎▋▏▏
+ █▎ ▋▎▋▎▎ ▊█▊▋▌▋█
+ █▌▊▉▍▍▍▎ ▊▍▏▊▉▋▉█
+ ▍▎█▍▏▉▍▌▏▎▎▎▉▉▏▉▉▋
+ █▏▉█▏▋▏▎▎▊▎▌▉▉
+
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_8.txt b/codex-rs/tui2/frames/vbars/frame_8.txt
new file mode 100644
index 0000000000..bbf2016fab
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_8.txt
@@ -0,0 +1,17 @@
+
+ ▎▎▉▎▌▉▉▌▉▊▎
+ ▊█▉▋▏▏▏▉▌▌ ▏ █▉
+ ▎▏▌▊▏▋▋▉ ▊█▏▋▏▉▍▉▍▊
+ ▎▉▍▉▋▏▊▉▏ █ ▌▍▏▏▍
+ █ ▋▏▋▊▍▏▋▍ ▋█▍▏▏▊
+ ▏█▊▏▍▍▍▎▍▏▎▉ ▍▉▏▏▏
+ ▏▉▏▏▏ █▎▌▍▏▎▏ ▏▍▏▋▏▊
+ ▍▊▏▏▋ ▏▉▍▋▏▊▉▋ ▋▎▋▏▏
+ ▍ ▍▏▏▎▍ ▋▉▌▏▏▋▉▊▉▊▊▍▏▏▏
+ ▍▉▋▌▎▏█▊▏▊▏▏▌▏▌▎▎▏▏▌█
+ ▋▋▍▍▏▍▏▏▏▋█▍▉▍▉█▍▉█▋▍▏
+ █▊█▏▍▏▎▎ ▋▊▋▋▋█
+ █▍▎▉▍▍▍▎ ▎▋▍▎▏▉▋▉
+ ▋▋█▏▊▉ ▌▌▉▉▌▋▌▊▏▎
+ ▏▏▎▉▉▍▏▎▊▉▋▌▎
+ ▎▎
\ No newline at end of file
diff --git a/codex-rs/tui2/frames/vbars/frame_9.txt b/codex-rs/tui2/frames/vbars/frame_9.txt
new file mode 100644
index 0000000000..4e36e6e126
--- /dev/null
+++ b/codex-rs/tui2/frames/vbars/frame_9.txt
@@ -0,0 +1,17 @@
+
+ ▋▌▍▉▋▉▉▌▊
+ ▋▉▎▋▏▏▉█▌ ▎▊▍▎
+ ▋ ▊▏▏▋▉▍▍▌▋ ▍▎▏▊
+ █ ▏▏▋▌▌▎ ▎▍▊▏▍▍▏▉▊
+ ▋▉█▌▍▉█▏▉▊ ▉▋█▉▋▉▏▏
+ ▏ ▏▏▏█▍▏▍▌▎▎ ▏█▏▉▏▏▏
+ ▎ ▏▉▍▏▉▉▏▍▍▊█▋▊▋ ▎▏▏
+ ▏ ▏▋▎▊▍▏▏▏▎▋▌▍▎▏ ▏▏
+ █▊▏█ ▋▏█▏▏▏▏▉▏▏▊▏▏▎
+ ▏▎▏▏▏▎▊▏▍▏▎▏▏▏▏▎▎▏▏▏
+ █ ▎▍▋▍▍▏▋█▉▉▉▉▏▏█▋▍▏
+ ▍▏▏▏▍▊▎ ▊▋ ▍▋▏▎
+ ▍▉▍▏▍▍ ▋▌▎▌▏▋▉
+ ▍▊█▍▎▏▉▋▉▌▌▌▉▏▎
+ █▊▎ ▉▍▍▏▌▉▋█
+
\ No newline at end of file
diff --git a/codex-rs/tui2/prompt_for_init_command.md b/codex-rs/tui2/prompt_for_init_command.md
new file mode 100644
index 0000000000..b8fd3886b3
--- /dev/null
+++ b/codex-rs/tui2/prompt_for_init_command.md
@@ -0,0 +1,40 @@
+Generate a file named AGENTS.md that serves as a contributor guide for this repository.
+Your goal is to produce a clear, concise, and well-structured document with descriptive headings and actionable explanations for each section.
+Follow the outline below, but adapt as needed — add sections if relevant, and omit those that do not apply to this project.
+
+Document Requirements
+
+- Title the document "Repository Guidelines".
+- Use Markdown headings (#, ##, etc.) for structure.
+- Keep the document concise. 200-400 words is optimal.
+- Keep explanations short, direct, and specific to this repository.
+- Provide examples where helpful (commands, directory paths, naming patterns).
+- Maintain a professional, instructional tone.
+
+Recommended Sections
+
+Project Structure & Module Organization
+
+- Outline the project structure, including where the source code, tests, and assets are located.
+
+Build, Test, and Development Commands
+
+- List key commands for building, testing, and running locally (e.g., npm test, make build).
+- Briefly explain what each command does.
+
+Coding Style & Naming Conventions
+
+- Specify indentation rules, language-specific style preferences, and naming patterns.
+- Include any formatting or linting tools used.
+
+Testing Guidelines
+
+- Identify testing frameworks and coverage requirements.
+- State test naming conventions and how to run tests.
+
+Commit & Pull Request Guidelines
+
+- Summarize commit message conventions found in the project’s Git history.
+- Outline pull request requirements (descriptions, linked issues, screenshots, etc.).
+
+(Optional) Add other sections if relevant, such as Security & Configuration Tips, Architecture Overview, or Agent-Specific Instructions.
diff --git a/codex-rs/tui2/src/additional_dirs.rs b/codex-rs/tui2/src/additional_dirs.rs
new file mode 100644
index 0000000000..cc43f3294b
--- /dev/null
+++ b/codex-rs/tui2/src/additional_dirs.rs
@@ -0,0 +1,71 @@
+use codex_core::protocol::SandboxPolicy;
+use std::path::PathBuf;
+
+/// Returns a warning describing why `--add-dir` entries will be ignored for the
+/// resolved sandbox policy. The caller is responsible for presenting the
+/// warning to the user (for example, printing to stderr).
+pub fn add_dir_warning_message(
+ additional_dirs: &[PathBuf],
+ sandbox_policy: &SandboxPolicy,
+) -> Option<String> {
+ if additional_dirs.is_empty() {
+ return None;
+ }
+
+ match sandbox_policy {
+ SandboxPolicy::WorkspaceWrite { .. } | SandboxPolicy::DangerFullAccess => None,
+ SandboxPolicy::ReadOnly => Some(format_warning(additional_dirs)),
+ }
+}
+
+fn format_warning(additional_dirs: &[PathBuf]) -> String {
+ let joined_paths = additional_dirs
+ .iter()
+ .map(|path| path.to_string_lossy())
+ .collect::<Vec<_>>()
+ .join(", ");
+ format!(
+ "Ignoring --add-dir ({joined_paths}) because the effective sandbox mode is read-only. Switch to workspace-write or danger-full-access to allow additional writable roots."
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::add_dir_warning_message;
+ use codex_core::protocol::SandboxPolicy;
+ use pretty_assertions::assert_eq;
+ use std::path::PathBuf;
+
+ #[test]
+ fn returns_none_for_workspace_write() {
+ let sandbox = SandboxPolicy::new_workspace_write_policy();
+ let dirs = vec![PathBuf::from("/tmp/example")];
+ assert_eq!(add_dir_warning_message(&dirs, &sandbox), None);
+ }
+
+ #[test]
+ fn returns_none_for_danger_full_access() {
+ let sandbox = SandboxPolicy::DangerFullAccess;
+ let dirs = vec![PathBuf::from("/tmp/example")];
+ assert_eq!(add_dir_warning_message(&dirs, &sandbox), None);
+ }
+
+ #[test]
+ fn warns_for_read_only() {
+ let sandbox = SandboxPolicy::ReadOnly;
+ let dirs = vec![PathBuf::from("relative"), PathBuf::from("/abs")];
+ let message = add_dir_warning_message(&dirs, &sandbox)
+ .expect("expected warning for read-only sandbox");
+ assert_eq!(
+ message,
+ "Ignoring --add-dir (relative, /abs) because the effective sandbox mode is read-only. Switch to workspace-write or danger-full-access to allow additional writable roots."
+ );
+ }
+
+ #[test]
+ fn returns_none_when_no_additional_dirs() {
+ let sandbox = SandboxPolicy::ReadOnly;
+ let dirs: Vec<PathBuf> = Vec::new();
+ assert_eq!(add_dir_warning_message(&dirs, &sandbox), None);
+ }
+}
diff --git a/codex-rs/tui2/src/app.rs b/codex-rs/tui2/src/app.rs
new file mode 100644
index 0000000000..4d4970b572
--- /dev/null
+++ b/codex-rs/tui2/src/app.rs
@@ -0,0 +1,1510 @@
+use crate::app_backtrack::BacktrackState;
+use crate::app_event::AppEvent;
+use crate::app_event_sender::AppEventSender;
+use crate::bottom_pane::ApprovalRequest;
+use crate::chatwidget::ChatWidget;
+use crate::diff_render::DiffSummary;
+use crate::exec_command::strip_bash_lc_and_escape;
+use crate::file_search::FileSearchManager;
+use crate::history_cell::HistoryCell;
+use crate::model_migration::ModelMigrationOutcome;
+use crate::model_migration::migration_copy_for_config;
+use crate::model_migration::run_model_migration_prompt;
+use crate::pager_overlay::Overlay;
+use crate::render::highlight::highlight_bash_to_lines;
+use crate::render::renderable::Renderable;
+use crate::resume_picker::ResumeSelection;
+use crate::skill_error_prompt::SkillErrorPromptOutcome;
+use crate::skill_error_prompt::run_skill_error_prompt;
+use crate::tui;
+use crate::tui::TuiEvent;
+use crate::update_action::UpdateAction;
+use codex_ansi_escape::ansi_escape_line;
+use codex_app_server_protocol::AuthMode;
+use codex_core::AuthManager;
+use codex_core::ConversationManager;
+use codex_core::config::Config;
+use codex_core::config::edit::ConfigEditsBuilder;
+use codex_core::features::Feature;
+use codex_core::openai_models::model_presets::HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG;
+use codex_core::openai_models::model_presets::HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG;
+use codex_core::openai_models::models_manager::ModelsManager;
+use codex_core::protocol::EventMsg;
+use codex_core::protocol::FinalOutput;
+use codex_core::protocol::Op;
+use codex_core::protocol::SessionSource;
+use codex_core::protocol::TokenUsage;
+use codex_core::skills::load_skills;
+use codex_core::skills::model::SkillMetadata;
+use codex_protocol::ConversationId;
+use codex_protocol::openai_models::ModelPreset;
+use codex_protocol::openai_models::ModelUpgrade;
+use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
+use color_eyre::eyre::Result;
+use color_eyre::eyre::WrapErr;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::Wrap;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::sync::atomic::AtomicBool;
+use std::sync::atomic::Ordering;
+use std::thread;
+use std::time::Duration;
+use tokio::select;
+use tokio::sync::mpsc::unbounded_channel;
+
+#[cfg(not(debug_assertions))]
+use crate::history_cell::UpdateAvailableHistoryCell;
+
+const GPT_5_1_MIGRATION_AUTH_MODES: [AuthMode; 2] = [AuthMode::ChatGPT, AuthMode::ApiKey];
+const GPT_5_1_CODEX_MIGRATION_AUTH_MODES: [AuthMode; 2] = [AuthMode::ChatGPT, AuthMode::ApiKey];
+
+#[derive(Debug, Clone)]
+pub struct AppExitInfo {
+ pub token_usage: TokenUsage,
+ pub conversation_id: Option<ConversationId>,
+ pub update_action: Option<UpdateAction>,
+}
+
+impl From<AppExitInfo> for codex_tui::AppExitInfo {
+ fn from(info: AppExitInfo) -> Self {
+ codex_tui::AppExitInfo {
+ token_usage: info.token_usage,
+ conversation_id: info.conversation_id,
+ update_action: info.update_action.map(Into::into),
+ }
+ }
+}
+
+fn session_summary(
+ token_usage: TokenUsage,
+ conversation_id: Option<ConversationId>,
+) -> Option<SessionSummary> {
+ if token_usage.is_zero() {
+ return None;
+ }
+
+ let usage_line = FinalOutput::from(token_usage).to_string();
+ let resume_command =
+ conversation_id.map(|conversation_id| format!("codex resume {conversation_id}"));
+ Some(SessionSummary {
+ usage_line,
+ resume_command,
+ })
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct SessionSummary {
+ usage_line: String,
+ resume_command: Option<String>,
+}
+
+fn should_show_model_migration_prompt(
+ current_model: &str,
+ target_model: &str,
+ hide_prompt_flag: Option<bool>,
+ available_models: Vec<ModelPreset>,
+) -> bool {
+ if target_model == current_model || hide_prompt_flag.unwrap_or(false) {
+ return false;
+ }
+
+ available_models
+ .iter()
+ .filter(|preset| preset.upgrade.is_some())
+ .any(|preset| preset.model == current_model)
+}
+
+fn migration_prompt_hidden(config: &Config, migration_config_key: &str) -> Option<bool> {
+ match migration_config_key {
+ HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG => {
+ config.notices.hide_gpt_5_1_codex_max_migration_prompt
+ }
+ HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG => config.notices.hide_gpt5_1_migration_prompt,
+ _ => None,
+ }
+}
+
+async fn handle_model_migration_prompt_if_needed(
+ tui: &mut tui::Tui,
+ config: &mut Config,
+ model: &str,
+ app_event_tx: &AppEventSender,
+ auth_mode: Option<AuthMode>,
+ models_manager: Arc<ModelsManager>,
+) -> Option<AppExitInfo> {
+ let available_models = models_manager.list_models(config).await;
+ let upgrade = available_models
+ .iter()
+ .find(|preset| preset.model == model)
+ .and_then(|preset| preset.upgrade.as_ref());
+
+ if let Some(ModelUpgrade {
+ id: target_model,
+ reasoning_effort_mapping,
+ migration_config_key,
+ }) = upgrade
+ {
+ if !migration_prompt_allows_auth_mode(auth_mode, migration_config_key.as_str()) {
+ return None;
+ }
+
+ let target_model = target_model.to_string();
+ let hide_prompt_flag = migration_prompt_hidden(config, migration_config_key.as_str());
+ if !should_show_model_migration_prompt(
+ model,
+ &target_model,
+ hide_prompt_flag,
+ available_models.clone(),
+ ) {
+ return None;
+ }
+
+ let prompt_copy = migration_copy_for_config(migration_config_key.as_str());
+ match run_model_migration_prompt(tui, prompt_copy).await {
+ ModelMigrationOutcome::Accepted => {
+ app_event_tx.send(AppEvent::PersistModelMigrationPromptAcknowledged {
+ migration_config: migration_config_key.to_string(),
+ });
+ config.model = Some(target_model.clone());
+
+ let mapped_effort = if let Some(reasoning_effort_mapping) = reasoning_effort_mapping
+ && let Some(reasoning_effort) = config.model_reasoning_effort
+ {
+ reasoning_effort_mapping
+ .get(&reasoning_effort)
+ .cloned()
+ .or(config.model_reasoning_effort)
+ } else {
+ config.model_reasoning_effort
+ };
+
+ config.model_reasoning_effort = mapped_effort;
+
+ app_event_tx.send(AppEvent::UpdateModel(target_model.clone()));
+ app_event_tx.send(AppEvent::UpdateReasoningEffort(mapped_effort));
+ app_event_tx.send(AppEvent::PersistModelSelection {
+ model: target_model.clone(),
+ effort: mapped_effort,
+ });
+ }
+ ModelMigrationOutcome::Rejected => {
+ app_event_tx.send(AppEvent::PersistModelMigrationPromptAcknowledged {
+ migration_config: migration_config_key.to_string(),
+ });
+ }
+ ModelMigrationOutcome::Exit => {
+ return Some(AppExitInfo {
+ token_usage: TokenUsage::default(),
+ conversation_id: None,
+ update_action: None,
+ });
+ }
+ }
+ }
+
+ None
+}
+
+pub(crate) struct App {
+ pub(crate) server: Arc<ConversationManager>,
+ pub(crate) app_event_tx: AppEventSender,
+ pub(crate) chat_widget: ChatWidget,
+ pub(crate) auth_manager: Arc<AuthManager>,
+ /// Config is stored here so we can recreate ChatWidgets as needed.
+ pub(crate) config: Config,
+ pub(crate) current_model: String,
+ pub(crate) active_profile: Option<String>,
+
+ pub(crate) file_search: FileSearchManager,
+
+ pub(crate) transcript_cells: Vec<Arc<dyn HistoryCell>>,
+
+ // Pager overlay state (Transcript or Static like Diff)
+ pub(crate) overlay: Option<Overlay>,
+ pub(crate) deferred_history_lines: Vec<Line<'static>>,
+ has_emitted_history_lines: bool,
+
+ pub(crate) enhanced_keys_supported: bool,
+
+ /// Controls the animation thread that sends CommitTick events.
+ pub(crate) commit_anim_running: Arc<AtomicBool>,
+
+ // Esc-backtracking state grouped
+ pub(crate) backtrack: crate::app_backtrack::BacktrackState,
+ pub(crate) feedback: codex_feedback::CodexFeedback,
+ /// Set when the user confirms an update; propagated on exit.
+ pub(crate) pending_update_action: Option<UpdateAction>,
+
+ /// Ignore the next ShutdownComplete event when we're intentionally
+ /// stopping a conversation (e.g., before starting a new one).
+ suppress_shutdown_complete: bool,
+
+ // One-shot suppression of the next world-writable scan after user confirmation.
+ skip_world_writable_scan_once: bool,
+
+ pub(crate) skills: Option<Vec<SkillMetadata>>,
+}
+
+impl App {
+ async fn shutdown_current_conversation(&mut self) {
+ if let Some(conversation_id) = self.chat_widget.conversation_id() {
+ self.suppress_shutdown_complete = true;
+ self.chat_widget.submit_op(Op::Shutdown);
+ self.server.remove_conversation(&conversation_id).await;
+ }
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ pub async fn run(
+ tui: &mut tui::Tui,
+ auth_manager: Arc<AuthManager>,
+ mut config: Config,
+ active_profile: Option<String>,
+ initial_prompt: Option<String>,
+ initial_images: Vec<PathBuf>,
+ resume_selection: ResumeSelection,
+ feedback: codex_feedback::CodexFeedback,
+ is_first_run: bool,
+ ) -> Result<AppExitInfo> {
+ use tokio_stream::StreamExt;
+ let (app_event_tx, mut app_event_rx) = unbounded_channel();
+ let app_event_tx = AppEventSender::new(app_event_tx);
+
+ let auth_mode = auth_manager.auth().map(|auth| auth.mode);
+ let conversation_manager = Arc::new(ConversationManager::new(
+ auth_manager.clone(),
+ SessionSource::Cli,
+ ));
+ let mut model = conversation_manager
+ .get_models_manager()
+ .get_model(&config.model, &config)
+ .await;
+ let exit_info = handle_model_migration_prompt_if_needed(
+ tui,
+ &mut config,
+ model.as_str(),
+ &app_event_tx,
+ auth_mode,
+ conversation_manager.get_models_manager(),
+ )
+ .await;
+ if let Some(exit_info) = exit_info {
+ return Ok(exit_info);
+ }
+ if let Some(updated_model) = config.model.clone() {
+ model = updated_model;
+ }
+
+ let skills_outcome = load_skills(&config);
+ if !skills_outcome.errors.is_empty() {
+ match run_skill_error_prompt(tui, &skills_outcome.errors).await {
+ SkillErrorPromptOutcome::Exit => {
+ return Ok(AppExitInfo {
+ token_usage: TokenUsage::default(),
+ conversation_id: None,
+ update_action: None,
+ });
+ }
+ SkillErrorPromptOutcome::Continue => {}
+ }
+ }
+
+ let skills = if config.features.enabled(Feature::Skills) {
+ Some(skills_outcome.skills.clone())
+ } else {
+ None
+ };
+
+ let enhanced_keys_supported = tui.enhanced_keys_supported();
+ let model_family = conversation_manager
+ .get_models_manager()
+ .construct_model_family(model.as_str(), &config)
+ .await;
+ let mut chat_widget = match resume_selection {
+ ResumeSelection::StartFresh | ResumeSelection::Exit => {
+ let init = crate::chatwidget::ChatWidgetInit {
+ config: config.clone(),
+ frame_requester: tui.frame_requester(),
+ app_event_tx: app_event_tx.clone(),
+ initial_prompt: initial_prompt.clone(),
+ initial_images: initial_images.clone(),
+ enhanced_keys_supported,
+ auth_manager: auth_manager.clone(),
+ models_manager: conversation_manager.get_models_manager(),
+ feedback: feedback.clone(),
+ skills: skills.clone(),
+ is_first_run,
+ model_family: model_family.clone(),
+ };
+ ChatWidget::new(init, conversation_manager.clone())
+ }
+ ResumeSelection::Resume(path) => {
+ let resumed = conversation_manager
+ .resume_conversation_from_rollout(
+ config.clone(),
+ path.clone(),
+ auth_manager.clone(),
+ )
+ .await
+ .wrap_err_with(|| {
+ format!("Failed to resume session from {}", path.display())
+ })?;
+ let init = crate::chatwidget::ChatWidgetInit {
+ config: config.clone(),
+ frame_requester: tui.frame_requester(),
+ app_event_tx: app_event_tx.clone(),
+ initial_prompt: initial_prompt.clone(),
+ initial_images: initial_images.clone(),
+ enhanced_keys_supported,
+ auth_manager: auth_manager.clone(),
+ models_manager: conversation_manager.get_models_manager(),
+ feedback: feedback.clone(),
+ skills: skills.clone(),
+ is_first_run,
+ model_family: model_family.clone(),
+ };
+ ChatWidget::new_from_existing(
+ init,
+ resumed.conversation,
+ resumed.session_configured,
+ )
+ }
+ };
+
+ chat_widget.maybe_prompt_windows_sandbox_enable();
+
+ let file_search = FileSearchManager::new(config.cwd.clone(), app_event_tx.clone());
+ #[cfg(not(debug_assertions))]
+ let upgrade_version = crate::updates::get_upgrade_version(&config);
+
+ let mut app = Self {
+ server: conversation_manager.clone(),
+ app_event_tx,
+ chat_widget,
+ auth_manager: auth_manager.clone(),
+ config,
+ current_model: model.clone(),
+ active_profile,
+ file_search,
+ enhanced_keys_supported,
+ transcript_cells: Vec::new(),
+ overlay: None,
+ deferred_history_lines: Vec::new(),
+ has_emitted_history_lines: false,
+ commit_anim_running: Arc::new(AtomicBool::new(false)),
+ backtrack: BacktrackState::default(),
+ feedback: feedback.clone(),
+ pending_update_action: None,
+ suppress_shutdown_complete: false,
+ skip_world_writable_scan_once: false,
+ skills,
+ };
+
+ // On startup, if Agent mode (workspace-write) or ReadOnly is active, warn about world-writable dirs on Windows.
+ #[cfg(target_os = "windows")]
+ {
+ let should_check = codex_core::get_platform_sandbox().is_some()
+ && matches!(
+ app.config.sandbox_policy,
+ codex_core::protocol::SandboxPolicy::WorkspaceWrite { .. }
+ | codex_core::protocol::SandboxPolicy::ReadOnly
+ )
+ && !app
+ .config
+ .notices
+ .hide_world_writable_warning
+ .unwrap_or(false);
+ if should_check {
+ let cwd = app.config.cwd.clone();
+ let env_map: std::collections::HashMap<String, String> = std::env::vars().collect();
+ let tx = app.app_event_tx.clone();
+ let logs_base_dir = app.config.codex_home.clone();
+ let sandbox_policy = app.config.sandbox_policy.clone();
+ Self::spawn_world_writable_scan(cwd, env_map, logs_base_dir, sandbox_policy, tx);
+ }
+ }
+
+ #[cfg(not(debug_assertions))]
+ if let Some(latest_version) = upgrade_version {
+ app.handle_event(
+ tui,
+ AppEvent::InsertHistoryCell(Box::new(UpdateAvailableHistoryCell::new(
+ latest_version,
+ crate::update_action::get_update_action(),
+ ))),
+ )
+ .await?;
+ }
+
+ let tui_events = tui.event_stream();
+ tokio::pin!(tui_events);
+
+ tui.frame_requester().schedule_frame();
+
+ while select! {
+ Some(event) = app_event_rx.recv() => {
+ app.handle_event(tui, event).await?
+ }
+ Some(event) = tui_events.next() => {
+ app.handle_tui_event(tui, event).await?
+ }
+ } {}
+ tui.terminal.clear()?;
+ Ok(AppExitInfo {
+ token_usage: app.token_usage(),
+ conversation_id: app.chat_widget.conversation_id(),
+ update_action: app.pending_update_action,
+ })
+ }
+
+ pub(crate) async fn handle_tui_event(
+ &mut self,
+ tui: &mut tui::Tui,
+ event: TuiEvent,
+ ) -> Result<bool> {
+ if self.overlay.is_some() {
+ let _ = self.handle_backtrack_overlay_event(tui, event).await?;
+ } else {
+ match event {
+ TuiEvent::Key(key_event) => {
+ self.handle_key_event(tui, key_event).await;
+ }
+ TuiEvent::Paste(pasted) => {
+ // Many terminals convert newlines to \r when pasting (e.g., iTerm2),
+ // but tui-textarea expects \n. Normalize CR to LF.
+ // [tui-textarea]: https://github.com/rhysd/tui-textarea/blob/4d18622eeac13b309e0ff6a55a46ac6706da68cf/src/textarea.rs#L782-L783
+ // [iTerm2]: https://github.com/gnachman/iTerm2/blob/5d0c0d9f68523cbd0494dad5422998964a2ecd8d/sources/iTermPasteHelper.m#L206-L216
+ let pasted = pasted.replace("\r", "\n");
+ self.chat_widget.handle_paste(pasted);
+ }
+ TuiEvent::Draw => {
+ self.chat_widget.maybe_post_pending_notification(tui);
+ if self
+ .chat_widget
+ .handle_paste_burst_tick(tui.frame_requester())
+ {
+ return Ok(true);
+ }
+ tui.draw(
+ self.chat_widget.desired_height(tui.terminal.size()?.width),
+ |frame| {
+ self.chat_widget.render(frame.area(), frame.buffer);
+ if let Some((x, y)) = self.chat_widget.cursor_pos(frame.area()) {
+ frame.set_cursor_position((x, y));
+ }
+ },
+ )?;
+ }
+ }
+ }
+ Ok(true)
+ }
+
+ async fn handle_event(&mut self, tui: &mut tui::Tui, event: AppEvent) -> Result<bool> {
+ let model_family = self
+ .server
+ .get_models_manager()
+ .construct_model_family(self.current_model.as_str(), &self.config)
+ .await;
+ match event {
+ AppEvent::NewSession => {
+ let summary = session_summary(
+ self.chat_widget.token_usage(),
+ self.chat_widget.conversation_id(),
+ );
+ self.shutdown_current_conversation().await;
+ let init = crate::chatwidget::ChatWidgetInit {
+ config: self.config.clone(),
+ frame_requester: tui.frame_requester(),
+ app_event_tx: self.app_event_tx.clone(),
+ initial_prompt: None,
+ initial_images: Vec::new(),
+ enhanced_keys_supported: self.enhanced_keys_supported,
+ auth_manager: self.auth_manager.clone(),
+ models_manager: self.server.get_models_manager(),
+ feedback: self.feedback.clone(),
+ skills: self.skills.clone(),
+ is_first_run: false,
+ model_family: model_family.clone(),
+ };
+ self.chat_widget = ChatWidget::new(init, self.server.clone());
+ self.current_model = model_family.get_model_slug().to_string();
+ if let Some(summary) = summary {
+ let mut lines: Vec<Line<'static>> = vec![summary.usage_line.clone().into()];
+ if let Some(command) = summary.resume_command {
+ let spans = vec!["To continue this session, run ".into(), command.cyan()];
+ lines.push(spans.into());
+ }
+ self.chat_widget.add_plain_history_lines(lines);
+ }
+ tui.frame_requester().schedule_frame();
+ }
+ AppEvent::OpenResumePicker => {
+ match crate::resume_picker::run_resume_picker(
+ tui,
+ &self.config.codex_home,
+ &self.config.model_provider_id,
+ false,
+ )
+ .await?
+ {
+ ResumeSelection::Resume(path) => {
+ let summary = session_summary(
+ self.chat_widget.token_usage(),
+ self.chat_widget.conversation_id(),
+ );
+ match self
+ .server
+ .resume_conversation_from_rollout(
+ self.config.clone(),
+ path.clone(),
+ self.auth_manager.clone(),
+ )
+ .await
+ {
+ Ok(resumed) => {
+ self.shutdown_current_conversation().await;
+ let init = crate::chatwidget::ChatWidgetInit {
+ config: self.config.clone(),
+ frame_requester: tui.frame_requester(),
+ app_event_tx: self.app_event_tx.clone(),
+ initial_prompt: None,
+ initial_images: Vec::new(),
+ enhanced_keys_supported: self.enhanced_keys_supported,
+ auth_manager: self.auth_manager.clone(),
+ models_manager: self.server.get_models_manager(),
+ feedback: self.feedback.clone(),
+ skills: self.skills.clone(),
+ is_first_run: false,
+ model_family: model_family.clone(),
+ };
+ self.chat_widget = ChatWidget::new_from_existing(
+ init,
+ resumed.conversation,
+ resumed.session_configured,
+ );
+ self.current_model = model_family.get_model_slug().to_string();
+ if let Some(summary) = summary {
+ let mut lines: Vec<Line<'static>> =
+ vec![summary.usage_line.clone().into()];
+ if let Some(command) = summary.resume_command {
+ let spans = vec![
+ "To continue this session, run ".into(),
+ command.cyan(),
+ ];
+ lines.push(spans.into());
+ }
+ self.chat_widget.add_plain_history_lines(lines);
+ }
+ }
+ Err(err) => {
+ self.chat_widget.add_error_message(format!(
+ "Failed to resume session from {}: {err}",
+ path.display()
+ ));
+ }
+ }
+ }
+ ResumeSelection::Exit | ResumeSelection::StartFresh => {}
+ }
+
+ // Leaving alt-screen may blank the inline viewport; force a redraw either way.
+ tui.frame_requester().schedule_frame();
+ }
+ AppEvent::InsertHistoryCell(cell) => {
+ let cell: Arc<dyn HistoryCell> = cell.into();
+ if let Some(Overlay::Transcript(t)) = &mut self.overlay {
+ t.insert_cell(cell.clone());
+ tui.frame_requester().schedule_frame();
+ }
+ self.transcript_cells.push(cell.clone());
+ let mut display = cell.display_lines(tui.terminal.last_known_screen_size.width);
+ if !display.is_empty() {
+ // Only insert a separating blank line for new cells that are not
+ // part of an ongoing stream. Streaming continuations should not
+ // accrue extra blank lines between chunks.
+ if !cell.is_stream_continuation() {
+ if self.has_emitted_history_lines {
+ display.insert(0, Line::from(""));
+ } else {
+ self.has_emitted_history_lines = true;
+ }
+ }
+ if self.overlay.is_some() {
+ self.deferred_history_lines.extend(display);
+ } else {
+ tui.insert_history_lines(display);
+ }
+ }
+ }
+ AppEvent::StartCommitAnimation => {
+ if self
+ .commit_anim_running
+ .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
+ .is_ok()
+ {
+ let tx = self.app_event_tx.clone();
+ let running = self.commit_anim_running.clone();
+ thread::spawn(move || {
+ while running.load(Ordering::Relaxed) {
+ thread::sleep(Duration::from_millis(50));
+ tx.send(AppEvent::CommitTick);
+ }
+ });
+ }
+ }
+ AppEvent::StopCommitAnimation => {
+ self.commit_anim_running.store(false, Ordering::Release);
+ }
+ AppEvent::CommitTick => {
+ self.chat_widget.on_commit_tick();
+ }
+ AppEvent::CodexEvent(event) => {
+ if self.suppress_shutdown_complete
+ && matches!(event.msg, EventMsg::ShutdownComplete)
+ {
+ self.suppress_shutdown_complete = false;
+ return Ok(true);
+ }
+ self.chat_widget.handle_codex_event(event);
+ }
+ AppEvent::ConversationHistory(ev) => {
+ self.on_conversation_history_for_backtrack(tui, ev).await?;
+ }
+ AppEvent::ExitRequest => {
+ return Ok(false);
+ }
+ AppEvent::CodexOp(op) => self.chat_widget.submit_op(op),
+ AppEvent::DiffResult(text) => {
+ // Clear the in-progress state in the bottom pane
+ self.chat_widget.on_diff_complete();
+ // Enter alternate screen using TUI helper and build pager lines
+ let _ = tui.enter_alt_screen();
+ let pager_lines: Vec<ratatui::text::Line<'static>> = if text.trim().is_empty() {
+ vec!["No changes detected.".italic().into()]
+ } else {
+ text.lines().map(ansi_escape_line).collect()
+ };
+ self.overlay = Some(Overlay::new_static_with_lines(
+ pager_lines,
+ "D I F F".to_string(),
+ ));
+ tui.frame_requester().schedule_frame();
+ }
+ AppEvent::StartFileSearch(query) => {
+ if !query.is_empty() {
+ self.file_search.on_user_query(query);
+ }
+ }
+ AppEvent::FileSearchResult { query, matches } => {
+ self.chat_widget.apply_file_search_result(query, matches);
+ }
+ AppEvent::RateLimitSnapshotFetched(snapshot) => {
+ self.chat_widget.on_rate_limit_snapshot(Some(snapshot));
+ }
+ AppEvent::UpdateReasoningEffort(effort) => {
+ self.on_update_reasoning_effort(effort);
+ }
+ AppEvent::UpdateModel(model) => {
+ let model_family = self
+ .server
+ .get_models_manager()
+ .construct_model_family(&model, &self.config)
+ .await;
+ self.chat_widget.set_model(&model, model_family);
+ self.current_model = model;
+ }
+ AppEvent::OpenReasoningPopup { model } => {
+ self.chat_widget.open_reasoning_popup(model);
+ }
+ AppEvent::OpenAllModelsPopup { models } => {
+ self.chat_widget.open_all_models_popup(models);
+ }
+ AppEvent::OpenFullAccessConfirmation { preset } => {
+ self.chat_widget.open_full_access_confirmation(preset);
+ }
+ AppEvent::OpenWorldWritableWarningConfirmation {
+ preset,
+ sample_paths,
+ extra_count,
+ failed_scan,
+ } => {
+ self.chat_widget.open_world_writable_warning_confirmation(
+ preset,
+ sample_paths,
+ extra_count,
+ failed_scan,
+ );
+ }
+ AppEvent::OpenFeedbackNote {
+ category,
+ include_logs,
+ } => {
+ self.chat_widget.open_feedback_note(category, include_logs);
+ }
+ AppEvent::OpenFeedbackConsent { category } => {
+ self.chat_widget.open_feedback_consent(category);
+ }
+ AppEvent::OpenWindowsSandboxEnablePrompt { preset } => {
+ self.chat_widget.open_windows_sandbox_enable_prompt(preset);
+ }
+ AppEvent::EnableWindowsSandboxForAgentMode { preset } => {
+ #[cfg(target_os = "windows")]
+ {
+ let profile = self.active_profile.as_deref();
+ let feature_key = Feature::WindowsSandbox.key();
+ match ConfigEditsBuilder::new(&self.config.codex_home)
+ .with_profile(profile)
+ .set_feature_enabled(feature_key, true)
+ .apply()
+ .await
+ {
+ Ok(()) => {
+ self.config.set_windows_sandbox_globally(true);
+ self.chat_widget.clear_forced_auto_mode_downgrade();
+ if let Some((sample_paths, extra_count, failed_scan)) =
+ self.chat_widget.world_writable_warning_details()
+ {
+ self.app_event_tx.send(
+ AppEvent::OpenWorldWritableWarningConfirmation {
+ preset: Some(preset.clone()),
+ sample_paths,
+ extra_count,
+ failed_scan,
+ },
+ );
+ } else {
+ self.app_event_tx.send(AppEvent::CodexOp(
+ Op::OverrideTurnContext {
+ cwd: None,
+ approval_policy: Some(preset.approval),
+ sandbox_policy: Some(preset.sandbox.clone()),
+ model: None,
+ effort: None,
+ summary: None,
+ },
+ ));
+ self.app_event_tx
+ .send(AppEvent::UpdateAskForApprovalPolicy(preset.approval));
+ self.app_event_tx
+ .send(AppEvent::UpdateSandboxPolicy(preset.sandbox.clone()));
+ self.chat_widget.add_info_message(
+ "Enabled experimental Windows sandbox.".to_string(),
+ None,
+ );
+ }
+ }
+ Err(err) => {
+ tracing::error!(
+ error = %err,
+ "failed to enable Windows sandbox feature"
+ );
+ self.chat_widget.add_error_message(format!(
+ "Failed to enable the Windows sandbox feature: {err}"
+ ));
+ }
+ }
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ let _ = preset;
+ }
+ }
+ AppEvent::PersistModelSelection { model, effort } => {
+ let profile = self.active_profile.as_deref();
+ match ConfigEditsBuilder::new(&self.config.codex_home)
+ .with_profile(profile)
+ .set_model(Some(model.as_str()), effort)
+ .apply()
+ .await
+ {
+ Ok(()) => {
+ let mut message = format!("Model changed to {model}");
+ if let Some(label) = Self::reasoning_label_for(&model, effort) {
+ message.push(' ');
+ message.push_str(label);
+ }
+ if let Some(profile) = profile {
+ message.push_str(" for ");
+ message.push_str(profile);
+ message.push_str(" profile");
+ }
+ self.chat_widget.add_info_message(message, None);
+ }
+ Err(err) => {
+ tracing::error!(
+ error = %err,
+ "failed to persist model selection"
+ );
+ if let Some(profile) = profile {
+ self.chat_widget.add_error_message(format!(
+ "Failed to save model for profile `{profile}`: {err}"
+ ));
+ } else {
+ self.chat_widget
+ .add_error_message(format!("Failed to save default model: {err}"));
+ }
+ }
+ }
+ }
+ AppEvent::UpdateAskForApprovalPolicy(policy) => {
+ self.chat_widget.set_approval_policy(policy);
+ }
+ AppEvent::UpdateSandboxPolicy(policy) => {
+ #[cfg(target_os = "windows")]
+ let policy_is_workspace_write_or_ro = matches!(
+ policy,
+ codex_core::protocol::SandboxPolicy::WorkspaceWrite { .. }
+ | codex_core::protocol::SandboxPolicy::ReadOnly
+ );
+
+ self.config.sandbox_policy = policy.clone();
+ #[cfg(target_os = "windows")]
+ if !matches!(policy, codex_core::protocol::SandboxPolicy::ReadOnly)
+ || codex_core::get_platform_sandbox().is_some()
+ {
+ self.config.forced_auto_mode_downgraded_on_windows = false;
+ }
+ self.chat_widget.set_sandbox_policy(policy);
+
+ // If sandbox policy becomes workspace-write or read-only, run the Windows world-writable scan.
+ #[cfg(target_os = "windows")]
+ {
+ // One-shot suppression if the user just confirmed continue.
+ if self.skip_world_writable_scan_once {
+ self.skip_world_writable_scan_once = false;
+ return Ok(true);
+ }
+
+ let should_check = codex_core::get_platform_sandbox().is_some()
+ && policy_is_workspace_write_or_ro
+ && !self.chat_widget.world_writable_warning_hidden();
+ if should_check {
+ let cwd = self.config.cwd.clone();
+ let env_map: std::collections::HashMap<String, String> =
+ std::env::vars().collect();
+ let tx = self.app_event_tx.clone();
+ let logs_base_dir = self.config.codex_home.clone();
+ let sandbox_policy = self.config.sandbox_policy.clone();
+ Self::spawn_world_writable_scan(
+ cwd,
+ env_map,
+ logs_base_dir,
+ sandbox_policy,
+ tx,
+ );
+ }
+ }
+ }
+ AppEvent::SkipNextWorldWritableScan => {
+ self.skip_world_writable_scan_once = true;
+ }
+ AppEvent::UpdateFullAccessWarningAcknowledged(ack) => {
+ self.chat_widget.set_full_access_warning_acknowledged(ack);
+ }
+ AppEvent::UpdateWorldWritableWarningAcknowledged(ack) => {
+ self.chat_widget
+ .set_world_writable_warning_acknowledged(ack);
+ }
+ AppEvent::UpdateRateLimitSwitchPromptHidden(hidden) => {
+ self.chat_widget.set_rate_limit_switch_prompt_hidden(hidden);
+ }
+ AppEvent::PersistFullAccessWarningAcknowledged => {
+ if let Err(err) = ConfigEditsBuilder::new(&self.config.codex_home)
+ .set_hide_full_access_warning(true)
+ .apply()
+ .await
+ {
+ tracing::error!(
+ error = %err,
+ "failed to persist full access warning acknowledgement"
+ );
+ self.chat_widget.add_error_message(format!(
+ "Failed to save full access confirmation preference: {err}"
+ ));
+ }
+ }
+ AppEvent::PersistWorldWritableWarningAcknowledged => {
+ if let Err(err) = ConfigEditsBuilder::new(&self.config.codex_home)
+ .set_hide_world_writable_warning(true)
+ .apply()
+ .await
+ {
+ tracing::error!(
+ error = %err,
+ "failed to persist world-writable warning acknowledgement"
+ );
+ self.chat_widget.add_error_message(format!(
+ "Failed to save Agent mode warning preference: {err}"
+ ));
+ }
+ }
+ AppEvent::PersistRateLimitSwitchPromptHidden => {
+ if let Err(err) = ConfigEditsBuilder::new(&self.config.codex_home)
+ .set_hide_rate_limit_model_nudge(true)
+ .apply()
+ .await
+ {
+ tracing::error!(
+ error = %err,
+ "failed to persist rate limit switch prompt preference"
+ );
+ self.chat_widget.add_error_message(format!(
+ "Failed to save rate limit reminder preference: {err}"
+ ));
+ }
+ }
+ AppEvent::PersistModelMigrationPromptAcknowledged { migration_config } => {
+ if let Err(err) = ConfigEditsBuilder::new(&self.config.codex_home)
+ .set_hide_model_migration_prompt(&migration_config, true)
+ .apply()
+ .await
+ {
+ tracing::error!(error = %err, "failed to persist model migration prompt acknowledgement");
+ self.chat_widget.add_error_message(format!(
+ "Failed to save model migration prompt preference: {err}"
+ ));
+ }
+ }
+ AppEvent::OpenApprovalsPopup => {
+ self.chat_widget.open_approvals_popup();
+ }
+ AppEvent::OpenReviewBranchPicker(cwd) => {
+ self.chat_widget.show_review_branch_picker(&cwd).await;
+ }
+ AppEvent::OpenReviewCommitPicker(cwd) => {
+ self.chat_widget.show_review_commit_picker(&cwd).await;
+ }
+ AppEvent::OpenReviewCustomPrompt => {
+ self.chat_widget.show_review_custom_prompt();
+ }
+ AppEvent::FullScreenApprovalRequest(request) => match request {
+ ApprovalRequest::ApplyPatch { cwd, changes, .. } => {
+ let _ = tui.enter_alt_screen();
+ let diff_summary = DiffSummary::new(changes, cwd);
+ self.overlay = Some(Overlay::new_static_with_renderables(
+ vec![diff_summary.into()],
+ "P A T C H".to_string(),
+ ));
+ }
+ ApprovalRequest::Exec { command, .. } => {
+ let _ = tui.enter_alt_screen();
+ let full_cmd = strip_bash_lc_and_escape(&command);
+ let full_cmd_lines = highlight_bash_to_lines(&full_cmd);
+ self.overlay = Some(Overlay::new_static_with_lines(
+ full_cmd_lines,
+ "E X E C".to_string(),
+ ));
+ }
+ ApprovalRequest::McpElicitation {
+ server_name,
+ message,
+ ..
+ } => {
+ let _ = tui.enter_alt_screen();
+ let paragraph = Paragraph::new(vec![
+ Line::from(vec!["Server: ".into(), server_name.bold()]),
+ Line::from(""),
+ Line::from(message),
+ ])
+ .wrap(Wrap { trim: false });
+ self.overlay = Some(Overlay::new_static_with_renderables(
+ vec![Box::new(paragraph)],
+ "E L I C I T A T I O N".to_string(),
+ ));
+ }
+ },
+ }
+ Ok(true)
+ }
+
+ fn reasoning_label(reasoning_effort: Option<ReasoningEffortConfig>) -> &'static str {
+ match reasoning_effort {
+ Some(ReasoningEffortConfig::Minimal) => "minimal",
+ Some(ReasoningEffortConfig::Low) => "low",
+ Some(ReasoningEffortConfig::Medium) => "medium",
+ Some(ReasoningEffortConfig::High) => "high",
+ Some(ReasoningEffortConfig::XHigh) => "xhigh",
+ None | Some(ReasoningEffortConfig::None) => "default",
+ }
+ }
+
+ fn reasoning_label_for(
+ model: &str,
+ reasoning_effort: Option<ReasoningEffortConfig>,
+ ) -> Option<&'static str> {
+ (!model.starts_with("codex-auto-")).then(|| Self::reasoning_label(reasoning_effort))
+ }
+
+ pub(crate) fn token_usage(&self) -> codex_core::protocol::TokenUsage {
+ self.chat_widget.token_usage()
+ }
+
+ fn on_update_reasoning_effort(&mut self, effort: Option<ReasoningEffortConfig>) {
+ self.chat_widget.set_reasoning_effort(effort);
+ self.config.model_reasoning_effort = effort;
+ }
+
+ async fn handle_key_event(&mut self, tui: &mut tui::Tui, key_event: KeyEvent) {
+ match key_event {
+ KeyEvent {
+ code: KeyCode::Char('t'),
+ modifiers: crossterm::event::KeyModifiers::CONTROL,
+ kind: KeyEventKind::Press,
+ ..
+ } => {
+ // Enter alternate screen and set viewport to full size.
+ let _ = tui.enter_alt_screen();
+ self.overlay = Some(Overlay::new_transcript(self.transcript_cells.clone()));
+ tui.frame_requester().schedule_frame();
+ }
+ // Esc primes/advances backtracking only in normal (not working) mode
+ // with the composer focused and empty. In any other state, forward
+ // Esc so the active UI (e.g. status indicator, modals, popups)
+ // handles it.
+ KeyEvent {
+ code: KeyCode::Esc,
+ kind: KeyEventKind::Press | KeyEventKind::Repeat,
+ ..
+ } => {
+ if self.chat_widget.is_normal_backtrack_mode()
+ && self.chat_widget.composer_is_empty()
+ {
+ self.handle_backtrack_esc_key(tui);
+ } else {
+ self.chat_widget.handle_key_event(key_event);
+ }
+ }
+ // Enter confirms backtrack when primed + count > 0. Otherwise pass to widget.
+ KeyEvent {
+ code: KeyCode::Enter,
+ kind: KeyEventKind::Press,
+ ..
+ } if self.backtrack.primed
+ && self.backtrack.nth_user_message != usize::MAX
+ && self.chat_widget.composer_is_empty() =>
+ {
+ // Delegate to helper for clarity; preserves behavior.
+ self.confirm_backtrack_from_main();
+ }
+ KeyEvent {
+ kind: KeyEventKind::Press | KeyEventKind::Repeat,
+ ..
+ } => {
+ // Any non-Esc key press should cancel a primed backtrack.
+ // This avoids stale "Esc-primed" state after the user starts typing
+ // (even if they later backspace to empty).
+ if key_event.code != KeyCode::Esc && self.backtrack.primed {
+ self.reset_backtrack_state();
+ }
+ self.chat_widget.handle_key_event(key_event);
+ }
+ _ => {
+ // Ignore Release key events.
+ }
+ };
+ }
+
+ #[cfg(target_os = "windows")]
+ fn spawn_world_writable_scan(
+ cwd: PathBuf,
+ env_map: std::collections::HashMap<String, String>,
+ logs_base_dir: PathBuf,
+ sandbox_policy: codex_core::protocol::SandboxPolicy,
+ tx: AppEventSender,
+ ) {
+ tokio::task::spawn_blocking(move || {
+ let result = codex_windows_sandbox::apply_world_writable_scan_and_denies(
+ &logs_base_dir,
+ &cwd,
+ &env_map,
+ &sandbox_policy,
+ Some(logs_base_dir.as_path()),
+ );
+ if result.is_err() {
+ // Scan failed: warn without examples.
+ tx.send(AppEvent::OpenWorldWritableWarningConfirmation {
+ preset: None,
+ sample_paths: Vec::new(),
+ extra_count: 0usize,
+ failed_scan: true,
+ });
+ }
+ });
+ }
+}
+
+fn migration_prompt_allowed_auth_modes(migration_config_key: &str) -> Option<&'static [AuthMode]> {
+ match migration_config_key {
+ HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG => Some(&GPT_5_1_MIGRATION_AUTH_MODES),
+ HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG => Some(&GPT_5_1_CODEX_MIGRATION_AUTH_MODES),
+ _ => None,
+ }
+}
+
+fn migration_prompt_allows_auth_mode(
+ auth_mode: Option<AuthMode>,
+ migration_config_key: &str,
+) -> bool {
+ if let Some(allowed_modes) = migration_prompt_allowed_auth_modes(migration_config_key) {
+ match auth_mode {
+ None => true,
+ Some(mode) => allowed_modes.contains(&mode),
+ }
+ } else {
+ auth_mode != Some(AuthMode::ApiKey)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::app_backtrack::BacktrackState;
+ use crate::app_backtrack::user_count;
+ use crate::chatwidget::tests::make_chatwidget_manual_with_sender;
+ use crate::file_search::FileSearchManager;
+ use crate::history_cell::AgentMessageCell;
+ use crate::history_cell::HistoryCell;
+ use crate::history_cell::UserHistoryCell;
+ use crate::history_cell::new_session_info;
+ use codex_core::AuthManager;
+ use codex_core::CodexAuth;
+ use codex_core::ConversationManager;
+ use codex_core::protocol::AskForApproval;
+ use codex_core::protocol::Event;
+ use codex_core::protocol::EventMsg;
+ use codex_core::protocol::SandboxPolicy;
+ use codex_core::protocol::SessionConfiguredEvent;
+ use codex_protocol::ConversationId;
+ use ratatui::prelude::Line;
+ use std::path::PathBuf;
+ use std::sync::Arc;
+ use std::sync::atomic::AtomicBool;
+
+ fn make_test_app() -> App {
+ let (chat_widget, app_event_tx, _rx, _op_rx) = make_chatwidget_manual_with_sender();
+ let config = chat_widget.config_ref().clone();
+ let current_model = chat_widget.get_model_family().get_model_slug().to_string();
+ let server = Arc::new(ConversationManager::with_models_provider(
+ CodexAuth::from_api_key("Test API Key"),
+ config.model_provider.clone(),
+ ));
+ let auth_manager =
+ AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key"));
+ let file_search = FileSearchManager::new(config.cwd.clone(), app_event_tx.clone());
+
+ App {
+ server,
+ app_event_tx,
+ chat_widget,
+ auth_manager,
+ config,
+ current_model,
+ active_profile: None,
+ file_search,
+ transcript_cells: Vec::new(),
+ overlay: None,
+ deferred_history_lines: Vec::new(),
+ has_emitted_history_lines: false,
+ enhanced_keys_supported: false,
+ commit_anim_running: Arc::new(AtomicBool::new(false)),
+ backtrack: BacktrackState::default(),
+ feedback: codex_feedback::CodexFeedback::new(),
+ pending_update_action: None,
+ suppress_shutdown_complete: false,
+ skip_world_writable_scan_once: false,
+ skills: None,
+ }
+ }
+
+ fn make_test_app_with_channels() -> (
+ App,
+ tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
+ tokio::sync::mpsc::UnboundedReceiver<Op>,
+ ) {
+ let (chat_widget, app_event_tx, rx, op_rx) = make_chatwidget_manual_with_sender();
+ let config = chat_widget.config_ref().clone();
+ let current_model = chat_widget.get_model_family().get_model_slug().to_string();
+ let server = Arc::new(ConversationManager::with_models_provider(
+ CodexAuth::from_api_key("Test API Key"),
+ config.model_provider.clone(),
+ ));
+ let auth_manager =
+ AuthManager::from_auth_for_testing(CodexAuth::from_api_key("Test API Key"));
+ let file_search = FileSearchManager::new(config.cwd.clone(), app_event_tx.clone());
+
+ (
+ App {
+ server,
+ app_event_tx,
+ chat_widget,
+ auth_manager,
+ config,
+ current_model,
+ active_profile: None,
+ file_search,
+ transcript_cells: Vec::new(),
+ overlay: None,
+ deferred_history_lines: Vec::new(),
+ has_emitted_history_lines: false,
+ enhanced_keys_supported: false,
+ commit_anim_running: Arc::new(AtomicBool::new(false)),
+ backtrack: BacktrackState::default(),
+ feedback: codex_feedback::CodexFeedback::new(),
+ pending_update_action: None,
+ suppress_shutdown_complete: false,
+ skip_world_writable_scan_once: false,
+ skills: None,
+ },
+ rx,
+ op_rx,
+ )
+ }
+
+ fn all_model_presets() -> Vec<ModelPreset> {
+ codex_core::openai_models::model_presets::all_model_presets().clone()
+ }
+
+ #[test]
+ fn model_migration_prompt_only_shows_for_deprecated_models() {
+ assert!(should_show_model_migration_prompt(
+ "gpt-5",
+ "gpt-5.1",
+ None,
+ all_model_presets()
+ ));
+ assert!(should_show_model_migration_prompt(
+ "gpt-5-codex",
+ "gpt-5.1-codex",
+ None,
+ all_model_presets()
+ ));
+ assert!(should_show_model_migration_prompt(
+ "gpt-5-codex-mini",
+ "gpt-5.1-codex-mini",
+ None,
+ all_model_presets()
+ ));
+ assert!(should_show_model_migration_prompt(
+ "gpt-5.1-codex",
+ "gpt-5.1-codex-max",
+ None,
+ all_model_presets()
+ ));
+ assert!(!should_show_model_migration_prompt(
+ "gpt-5.1-codex",
+ "gpt-5.1-codex",
+ None,
+ all_model_presets()
+ ));
+ }
+
+ #[test]
+ fn model_migration_prompt_respects_hide_flag_and_self_target() {
+ assert!(!should_show_model_migration_prompt(
+ "gpt-5",
+ "gpt-5.1",
+ Some(true),
+ all_model_presets()
+ ));
+ assert!(!should_show_model_migration_prompt(
+ "gpt-5.1",
+ "gpt-5.1",
+ None,
+ all_model_presets()
+ ));
+ }
+
+ #[test]
+ fn update_reasoning_effort_updates_config() {
+ let mut app = make_test_app();
+ app.config.model_reasoning_effort = Some(ReasoningEffortConfig::Medium);
+ app.chat_widget
+ .set_reasoning_effort(Some(ReasoningEffortConfig::Medium));
+
+ app.on_update_reasoning_effort(Some(ReasoningEffortConfig::High));
+
+ assert_eq!(
+ app.config.model_reasoning_effort,
+ Some(ReasoningEffortConfig::High)
+ );
+ assert_eq!(
+ app.chat_widget.config_ref().model_reasoning_effort,
+ Some(ReasoningEffortConfig::High)
+ );
+ }
+
+ #[test]
+ fn backtrack_selection_with_duplicate_history_targets_unique_turn() {
+ let mut app = make_test_app();
+
+ let user_cell = |text: &str| -> Arc<dyn HistoryCell> {
+ Arc::new(UserHistoryCell {
+ message: text.to_string(),
+ }) as Arc<dyn HistoryCell>
+ };
+ let agent_cell = |text: &str| -> Arc<dyn HistoryCell> {
+ Arc::new(AgentMessageCell::new(
+ vec![Line::from(text.to_string())],
+ true,
+ )) as Arc<dyn HistoryCell>
+ };
+
+ let make_header = |is_first| {
+ let event = SessionConfiguredEvent {
+ session_id: ConversationId::new(),
+ model: "gpt-test".to_string(),
+ model_provider_id: "test-provider".to_string(),
+ approval_policy: AskForApproval::Never,
+ sandbox_policy: SandboxPolicy::ReadOnly,
+ cwd: PathBuf::from("/home/user/project"),
+ reasoning_effort: None,
+ history_log_id: 0,
+ history_entry_count: 0,
+ initial_messages: None,
+ skill_load_outcome: None,
+ rollout_path: PathBuf::new(),
+ };
+ Arc::new(new_session_info(
+ app.chat_widget.config_ref(),
+ app.current_model.as_str(),
+ event,
+ is_first,
+ )) as Arc<dyn HistoryCell>
+ };
+
+ // Simulate the transcript after trimming for a fork, replaying history, and
+ // appending the edited turn. The session header separates the retained history
+ // from the forked conversation's replayed turns.
+ app.transcript_cells = vec![
+ make_header(true),
+ user_cell("first question"),
+ agent_cell("answer first"),
+ user_cell("follow-up"),
+ agent_cell("answer follow-up"),
+ make_header(false),
+ user_cell("first question"),
+ agent_cell("answer first"),
+ user_cell("follow-up (edited)"),
+ agent_cell("answer edited"),
+ ];
+
+ assert_eq!(user_count(&app.transcript_cells), 2);
+
+ app.backtrack.base_id = Some(ConversationId::new());
+ app.backtrack.primed = true;
+ app.backtrack.nth_user_message = user_count(&app.transcript_cells).saturating_sub(1);
+
+ app.confirm_backtrack_from_main();
+
+ let (_, nth, prefill) = app.backtrack.pending.clone().expect("pending backtrack");
+ assert_eq!(nth, 1);
+ assert_eq!(prefill, "follow-up (edited)");
+ }
+
+ #[tokio::test]
+ async fn new_session_requests_shutdown_for_previous_conversation() {
+ let (mut app, mut app_event_rx, mut op_rx) = make_test_app_with_channels();
+
+ let conversation_id = ConversationId::new();
+ let event = SessionConfiguredEvent {
+ session_id: conversation_id,
+ model: "gpt-test".to_string(),
+ model_provider_id: "test-provider".to_string(),
+ approval_policy: AskForApproval::Never,
+ sandbox_policy: SandboxPolicy::ReadOnly,
+ cwd: PathBuf::from("/home/user/project"),
+ reasoning_effort: None,
+ history_log_id: 0,
+ history_entry_count: 0,
+ initial_messages: None,
+ skill_load_outcome: None,
+ rollout_path: PathBuf::new(),
+ };
+
+ app.chat_widget.handle_codex_event(Event {
+ id: String::new(),
+ msg: EventMsg::SessionConfigured(event),
+ });
+
+ while app_event_rx.try_recv().is_ok() {}
+ while op_rx.try_recv().is_ok() {}
+
+ app.shutdown_current_conversation().await;
+
+ match op_rx.try_recv() {
+ Ok(Op::Shutdown) => {}
+ Ok(other) => panic!("expected Op::Shutdown, got {other:?}"),
+ Err(_) => panic!("expected shutdown op to be sent"),
+ }
+ }
+
+ #[test]
+ fn session_summary_skip_zero_usage() {
+ assert!(session_summary(TokenUsage::default(), None).is_none());
+ }
+
+ #[test]
+ fn session_summary_includes_resume_hint() {
+ let usage = TokenUsage {
+ input_tokens: 10,
+ output_tokens: 2,
+ total_tokens: 12,
+ ..Default::default()
+ };
+ let conversation =
+ ConversationId::from_string("123e4567-e89b-12d3-a456-426614174000").unwrap();
+
+ let summary = session_summary(usage, Some(conversation)).expect("summary");
+ assert_eq!(
+ summary.usage_line,
+ "Token usage: total=12 input=10 output=2"
+ );
+ assert_eq!(
+ summary.resume_command,
+ Some("codex resume 123e4567-e89b-12d3-a456-426614174000".to_string())
+ );
+ }
+
+ #[test]
+ fn gpt5_migration_allows_api_key_and_chatgpt() {
+ assert!(migration_prompt_allows_auth_mode(
+ Some(AuthMode::ApiKey),
+ HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG,
+ ));
+ assert!(migration_prompt_allows_auth_mode(
+ Some(AuthMode::ChatGPT),
+ HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG,
+ ));
+ }
+
+ #[test]
+ fn gpt_5_1_codex_max_migration_limits_to_chatgpt() {
+ assert!(migration_prompt_allows_auth_mode(
+ Some(AuthMode::ChatGPT),
+ HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG,
+ ));
+ assert!(migration_prompt_allows_auth_mode(
+ Some(AuthMode::ApiKey),
+ HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG,
+ ));
+ }
+
+ #[test]
+ fn other_migrations_block_api_key() {
+ assert!(!migration_prompt_allows_auth_mode(
+ Some(AuthMode::ApiKey),
+ "unknown"
+ ));
+ assert!(migration_prompt_allows_auth_mode(
+ Some(AuthMode::ChatGPT),
+ "unknown"
+ ));
+ }
+}
diff --git a/codex-rs/tui2/src/app_backtrack.rs b/codex-rs/tui2/src/app_backtrack.rs
new file mode 100644
index 0000000000..deb629765a
--- /dev/null
+++ b/codex-rs/tui2/src/app_backtrack.rs
@@ -0,0 +1,518 @@
+use std::any::TypeId;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use crate::app::App;
+use crate::history_cell::SessionInfoCell;
+use crate::history_cell::UserHistoryCell;
+use crate::pager_overlay::Overlay;
+use crate::tui;
+use crate::tui::TuiEvent;
+use codex_core::protocol::ConversationPathResponseEvent;
+use codex_protocol::ConversationId;
+use color_eyre::eyre::Result;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+
+/// Aggregates all backtrack-related state used by the App.
+#[derive(Default)]
+pub(crate) struct BacktrackState {
+ /// True when Esc has primed backtrack mode in the main view.
+ pub(crate) primed: bool,
+ /// Session id of the base conversation to fork from.
+ pub(crate) base_id: Option<ConversationId>,
+ /// Index in the transcript of the last user message.
+ pub(crate) nth_user_message: usize,
+ /// True when the transcript overlay is showing a backtrack preview.
+ pub(crate) overlay_preview_active: bool,
+ /// Pending fork request: (base_id, nth_user_message, prefill).
+ pub(crate) pending: Option<(ConversationId, usize, String)>,
+}
+
+impl App {
+ /// Route overlay events when transcript overlay is active.
+ /// - If backtrack preview is active: Esc steps selection; Enter confirms.
+ /// - Otherwise: Esc begins preview; all other events forward to overlay.
+ /// interactions (Esc to step target, Enter to confirm) and overlay lifecycle.
+ pub(crate) async fn handle_backtrack_overlay_event(
+ &mut self,
+ tui: &mut tui::Tui,
+ event: TuiEvent,
+ ) -> Result<bool> {
+ if self.backtrack.overlay_preview_active {
+ match event {
+ TuiEvent::Key(KeyEvent {
+ code: KeyCode::Esc,
+ kind: KeyEventKind::Press | KeyEventKind::Repeat,
+ ..
+ }) => {
+ self.overlay_step_backtrack(tui, event)?;
+ Ok(true)
+ }
+ TuiEvent::Key(KeyEvent {
+ code: KeyCode::Enter,
+ kind: KeyEventKind::Press,
+ ..
+ }) => {
+ self.overlay_confirm_backtrack(tui);
+ Ok(true)
+ }
+ // Catchall: forward any other events to the overlay widget.
+ _ => {
+ self.overlay_forward_event(tui, event)?;
+ Ok(true)
+ }
+ }
+ } else if let TuiEvent::Key(KeyEvent {
+ code: KeyCode::Esc,
+ kind: KeyEventKind::Press | KeyEventKind::Repeat,
+ ..
+ }) = event
+ {
+ // First Esc in transcript overlay: begin backtrack preview at latest user message.
+ self.begin_overlay_backtrack_preview(tui);
+ Ok(true)
+ } else {
+ // Not in backtrack mode: forward events to the overlay widget.
+ self.overlay_forward_event(tui, event)?;
+ Ok(true)
+ }
+ }
+
+ /// Handle global Esc presses for backtracking when no overlay is present.
+ pub(crate) fn handle_backtrack_esc_key(&mut self, tui: &mut tui::Tui) {
+ if !self.chat_widget.composer_is_empty() {
+ return;
+ }
+
+ if !self.backtrack.primed {
+ self.prime_backtrack();
+ } else if self.overlay.is_none() {
+ self.open_backtrack_preview(tui);
+ } else if self.backtrack.overlay_preview_active {
+ self.step_backtrack_and_highlight(tui);
+ }
+ }
+
+ /// Stage a backtrack and request conversation history from the agent.
+ pub(crate) fn request_backtrack(
+ &mut self,
+ prefill: String,
+ base_id: ConversationId,
+ nth_user_message: usize,
+ ) {
+ self.backtrack.pending = Some((base_id, nth_user_message, prefill));
+ if let Some(path) = self.chat_widget.rollout_path() {
+ let ev = ConversationPathResponseEvent {
+ conversation_id: base_id,
+ path,
+ };
+ self.app_event_tx
+ .send(crate::app_event::AppEvent::ConversationHistory(ev));
+ } else {
+ tracing::error!("rollout path unavailable; cannot backtrack");
+ }
+ }
+
+ /// Open transcript overlay (enters alternate screen and shows full transcript).
+ pub(crate) fn open_transcript_overlay(&mut self, tui: &mut tui::Tui) {
+ let _ = tui.enter_alt_screen();
+ self.overlay = Some(Overlay::new_transcript(self.transcript_cells.clone()));
+ tui.frame_requester().schedule_frame();
+ }
+
+ /// Close transcript overlay and restore normal UI.
+ pub(crate) fn close_transcript_overlay(&mut self, tui: &mut tui::Tui) {
+ let _ = tui.leave_alt_screen();
+ let was_backtrack = self.backtrack.overlay_preview_active;
+ if !self.deferred_history_lines.is_empty() {
+ let lines = std::mem::take(&mut self.deferred_history_lines);
+ tui.insert_history_lines(lines);
+ }
+ self.overlay = None;
+ self.backtrack.overlay_preview_active = false;
+ if was_backtrack {
+ // Ensure backtrack state is fully reset when overlay closes (e.g. via 'q').
+ self.reset_backtrack_state();
+ }
+ }
+
+ /// Re-render the full transcript into the terminal scrollback in one call.
+ /// Useful when switching sessions to ensure prior history remains visible.
+ pub(crate) fn render_transcript_once(&mut self, tui: &mut tui::Tui) {
+ if !self.transcript_cells.is_empty() {
+ let width = tui.terminal.last_known_screen_size.width;
+ for cell in &self.transcript_cells {
+ tui.insert_history_lines(cell.display_lines(width));
+ }
+ }
+ }
+
+ /// Initialize backtrack state and show composer hint.
+ fn prime_backtrack(&mut self) {
+ self.backtrack.primed = true;
+ self.backtrack.nth_user_message = usize::MAX;
+ self.backtrack.base_id = self.chat_widget.conversation_id();
+ self.chat_widget.show_esc_backtrack_hint();
+ }
+
+ /// Open overlay and begin backtrack preview flow (first step + highlight).
+ fn open_backtrack_preview(&mut self, tui: &mut tui::Tui) {
+ self.open_transcript_overlay(tui);
+ self.backtrack.overlay_preview_active = true;
+ // Composer is hidden by overlay; clear its hint.
+ self.chat_widget.clear_esc_backtrack_hint();
+ self.step_backtrack_and_highlight(tui);
+ }
+
+ /// When overlay is already open, begin preview mode and select latest user message.
+ fn begin_overlay_backtrack_preview(&mut self, tui: &mut tui::Tui) {
+ self.backtrack.primed = true;
+ self.backtrack.base_id = self.chat_widget.conversation_id();
+ self.backtrack.overlay_preview_active = true;
+ let count = user_count(&self.transcript_cells);
+ if let Some(last) = count.checked_sub(1) {
+ self.apply_backtrack_selection(last);
+ }
+ tui.frame_requester().schedule_frame();
+ }
+
+ /// Step selection to the next older user message and update overlay.
+ fn step_backtrack_and_highlight(&mut self, tui: &mut tui::Tui) {
+ let count = user_count(&self.transcript_cells);
+ if count == 0 {
+ return;
+ }
+
+ let last_index = count.saturating_sub(1);
+ let next_selection = if self.backtrack.nth_user_message == usize::MAX {
+ last_index
+ } else if self.backtrack.nth_user_message == 0 {
+ 0
+ } else {
+ self.backtrack
+ .nth_user_message
+ .saturating_sub(1)
+ .min(last_index)
+ };
+
+ self.apply_backtrack_selection(next_selection);
+ tui.frame_requester().schedule_frame();
+ }
+
+ /// Apply a computed backtrack selection to the overlay and internal counter.
+ fn apply_backtrack_selection(&mut self, nth_user_message: usize) {
+ if let Some(cell_idx) = nth_user_position(&self.transcript_cells, nth_user_message) {
+ self.backtrack.nth_user_message = nth_user_message;
+ if let Some(Overlay::Transcript(t)) = &mut self.overlay {
+ t.set_highlight_cell(Some(cell_idx));
+ }
+ } else {
+ self.backtrack.nth_user_message = usize::MAX;
+ if let Some(Overlay::Transcript(t)) = &mut self.overlay {
+ t.set_highlight_cell(None);
+ }
+ }
+ }
+
+ /// Forward any event to the overlay and close it if done.
+ fn overlay_forward_event(&mut self, tui: &mut tui::Tui, event: TuiEvent) -> Result<()> {
+ if let Some(overlay) = &mut self.overlay {
+ overlay.handle_event(tui, event)?;
+ if overlay.is_done() {
+ self.close_transcript_overlay(tui);
+ tui.frame_requester().schedule_frame();
+ }
+ }
+ Ok(())
+ }
+
+ /// Handle Enter in overlay backtrack preview: confirm selection and reset state.
+ fn overlay_confirm_backtrack(&mut self, tui: &mut tui::Tui) {
+ let nth_user_message = self.backtrack.nth_user_message;
+ if let Some(base_id) = self.backtrack.base_id {
+ let prefill = nth_user_position(&self.transcript_cells, nth_user_message)
+ .and_then(|idx| self.transcript_cells.get(idx))
+ .and_then(|cell| cell.as_any().downcast_ref::<UserHistoryCell>())
+ .map(|c| c.message.clone())
+ .unwrap_or_default();
+ self.close_transcript_overlay(tui);
+ self.request_backtrack(prefill, base_id, nth_user_message);
+ }
+ self.reset_backtrack_state();
+ }
+
+ /// Handle Esc in overlay backtrack preview: step selection if armed, else forward.
+ fn overlay_step_backtrack(&mut self, tui: &mut tui::Tui, event: TuiEvent) -> Result<()> {
+ if self.backtrack.base_id.is_some() {
+ self.step_backtrack_and_highlight(tui);
+ } else {
+ self.overlay_forward_event(tui, event)?;
+ }
+ Ok(())
+ }
+
+ /// Confirm a primed backtrack from the main view (no overlay visible).
+ /// Computes the prefill from the selected user message and requests history.
+ pub(crate) fn confirm_backtrack_from_main(&mut self) {
+ if let Some(base_id) = self.backtrack.base_id {
+ let prefill =
+ nth_user_position(&self.transcript_cells, self.backtrack.nth_user_message)
+ .and_then(|idx| self.transcript_cells.get(idx))
+ .and_then(|cell| cell.as_any().downcast_ref::<UserHistoryCell>())
+ .map(|c| c.message.clone())
+ .unwrap_or_default();
+ self.request_backtrack(prefill, base_id, self.backtrack.nth_user_message);
+ }
+ self.reset_backtrack_state();
+ }
+
+ /// Clear all backtrack-related state and composer hints.
+ pub(crate) fn reset_backtrack_state(&mut self) {
+ self.backtrack.primed = false;
+ self.backtrack.base_id = None;
+ self.backtrack.nth_user_message = usize::MAX;
+ // In case a hint is somehow still visible (e.g., race with overlay open/close).
+ self.chat_widget.clear_esc_backtrack_hint();
+ }
+
+ /// Handle a ConversationHistory response while a backtrack is pending.
+ /// If it matches the primed base session, fork and switch to the new conversation.
+ pub(crate) async fn on_conversation_history_for_backtrack(
+ &mut self,
+ tui: &mut tui::Tui,
+ ev: ConversationPathResponseEvent,
+ ) -> Result<()> {
+ if let Some((base_id, _, _)) = self.backtrack.pending.as_ref()
+ && ev.conversation_id == *base_id
+ && let Some((_, nth_user_message, prefill)) = self.backtrack.pending.take()
+ {
+ self.fork_and_switch_to_new_conversation(tui, ev, nth_user_message, prefill)
+ .await;
+ }
+ Ok(())
+ }
+
+ /// Fork the conversation using provided history and switch UI/state accordingly.
+ async fn fork_and_switch_to_new_conversation(
+ &mut self,
+ tui: &mut tui::Tui,
+ ev: ConversationPathResponseEvent,
+ nth_user_message: usize,
+ prefill: String,
+ ) {
+ let cfg = self.chat_widget.config_ref().clone();
+ // Perform the fork via a thin wrapper for clarity/testability.
+ let result = self
+ .perform_fork(ev.path.clone(), nth_user_message, cfg.clone())
+ .await;
+ match result {
+ Ok(new_conv) => {
+ self.install_forked_conversation(tui, cfg, new_conv, nth_user_message, &prefill)
+ }
+ Err(e) => tracing::error!("error forking conversation: {e:#}"),
+ }
+ }
+
+ /// Thin wrapper around ConversationManager::fork_conversation.
+ async fn perform_fork(
+ &self,
+ path: PathBuf,
+ nth_user_message: usize,
+ cfg: codex_core::config::Config,
+ ) -> codex_core::error::Result<codex_core::NewConversation> {
+ self.server
+ .fork_conversation(nth_user_message, cfg, path)
+ .await
+ }
+
+ /// Install a forked conversation into the ChatWidget and update UI to reflect selection.
+ fn install_forked_conversation(
+ &mut self,
+ tui: &mut tui::Tui,
+ cfg: codex_core::config::Config,
+ new_conv: codex_core::NewConversation,
+ nth_user_message: usize,
+ prefill: &str,
+ ) {
+ let conv = new_conv.conversation;
+ let session_configured = new_conv.session_configured;
+ let model_family = self.chat_widget.get_model_family();
+ let init = crate::chatwidget::ChatWidgetInit {
+ config: cfg,
+ model_family: model_family.clone(),
+ frame_requester: tui.frame_requester(),
+ app_event_tx: self.app_event_tx.clone(),
+ initial_prompt: None,
+ initial_images: Vec::new(),
+ enhanced_keys_supported: self.enhanced_keys_supported,
+ auth_manager: self.auth_manager.clone(),
+ models_manager: self.server.get_models_manager(),
+ feedback: self.feedback.clone(),
+ skills: self.skills.clone(),
+ is_first_run: false,
+ };
+ self.chat_widget =
+ crate::chatwidget::ChatWidget::new_from_existing(init, conv, session_configured);
+ self.current_model = model_family.get_model_slug().to_string();
+ // Trim transcript up to the selected user message and re-render it.
+ self.trim_transcript_for_backtrack(nth_user_message);
+ self.render_transcript_once(tui);
+ if !prefill.is_empty() {
+ self.chat_widget.set_composer_text(prefill.to_string());
+ }
+ tui.frame_requester().schedule_frame();
+ }
+
+ /// Trim transcript_cells to preserve only content up to the selected user message.
+ fn trim_transcript_for_backtrack(&mut self, nth_user_message: usize) {
+ trim_transcript_cells_to_nth_user(&mut self.transcript_cells, nth_user_message);
+ }
+}
+
+fn trim_transcript_cells_to_nth_user(
+ transcript_cells: &mut Vec<Arc<dyn crate::history_cell::HistoryCell>>,
+ nth_user_message: usize,
+) {
+ if nth_user_message == usize::MAX {
+ return;
+ }
+
+ if let Some(cut_idx) = nth_user_position(transcript_cells, nth_user_message) {
+ transcript_cells.truncate(cut_idx);
+ }
+}
+
+pub(crate) fn user_count(cells: &[Arc<dyn crate::history_cell::HistoryCell>]) -> usize {
+ user_positions_iter(cells).count()
+}
+
+fn nth_user_position(
+ cells: &[Arc<dyn crate::history_cell::HistoryCell>],
+ nth: usize,
+) -> Option<usize> {
+ user_positions_iter(cells)
+ .enumerate()
+ .find_map(|(i, idx)| (i == nth).then_some(idx))
+}
+
+fn user_positions_iter(
+ cells: &[Arc<dyn crate::history_cell::HistoryCell>],
+) -> impl Iterator<Item = usize> + '_ {
+ let session_start_type = TypeId::of::<SessionInfoCell>();
+ let user_type = TypeId::of::<UserHistoryCell>();
+ let type_of = |cell: &Arc<dyn crate::history_cell::HistoryCell>| cell.as_any().type_id();
+
+ let start = cells
+ .iter()
+ .rposition(|cell| type_of(cell) == session_start_type)
+ .map_or(0, |idx| idx + 1);
+
+ cells
+ .iter()
+ .enumerate()
+ .skip(start)
+ .filter_map(move |(idx, cell)| (type_of(cell) == user_type).then_some(idx))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::history_cell::AgentMessageCell;
+ use crate::history_cell::HistoryCell;
+ use ratatui::prelude::Line;
+ use std::sync::Arc;
+
+ #[test]
+ fn trim_transcript_for_first_user_drops_user_and_newer_cells() {
+ let mut cells: Vec<Arc<dyn HistoryCell>> = vec![
+ Arc::new(UserHistoryCell {
+ message: "first user".to_string(),
+ }) as Arc<dyn HistoryCell>,
+ Arc::new(AgentMessageCell::new(vec![Line::from("assistant")], true))
+ as Arc<dyn HistoryCell>,
+ ];
+ trim_transcript_cells_to_nth_user(&mut cells, 0);
+
+ assert!(cells.is_empty());
+ }
+
+ #[test]
+ fn trim_transcript_preserves_cells_before_selected_user() {
+ let mut cells: Vec<Arc<dyn HistoryCell>> = vec![
+ Arc::new(AgentMessageCell::new(vec![Line::from("intro")], true))
+ as Arc<dyn HistoryCell>,
+ Arc::new(UserHistoryCell {
+ message: "first".to_string(),
+ }) as Arc<dyn HistoryCell>,
+ Arc::new(AgentMessageCell::new(vec![Line::from("after")], false))
+ as Arc<dyn HistoryCell>,
+ ];
+ trim_transcript_cells_to_nth_user(&mut cells, 0);
+
+ assert_eq!(cells.len(), 1);
+ let agent = cells[0]
+ .as_any()
+ .downcast_ref::<AgentMessageCell>()
+ .expect("agent cell");
+ let agent_lines = agent.display_lines(u16::MAX);
+ assert_eq!(agent_lines.len(), 1);
+ let intro_text: String = agent_lines[0]
+ .spans
+ .iter()
+ .map(|span| span.content.as_ref())
+ .collect();
+ assert_eq!(intro_text, "• intro");
+ }
+
+ #[test]
+ fn trim_transcript_for_later_user_keeps_prior_history() {
+ let mut cells: Vec<Arc<dyn HistoryCell>> = vec![
+ Arc::new(AgentMessageCell::new(vec![Line::from("intro")], true))
+ as Arc<dyn HistoryCell>,
+ Arc::new(UserHistoryCell {
+ message: "first".to_string(),
+ }) as Arc<dyn HistoryCell>,
+ Arc::new(AgentMessageCell::new(vec![Line::from("between")], false))
+ as Arc<dyn HistoryCell>,
+ Arc::new(UserHistoryCell {
+ message: "second".to_string(),
+ }) as Arc<dyn HistoryCell>,
+ Arc::new(AgentMessageCell::new(vec![Line::from("tail")], false))
+ as Arc<dyn HistoryCell>,
+ ];
+ trim_transcript_cells_to_nth_user(&mut cells, 1);
+
+ assert_eq!(cells.len(), 3);
+ let agent_intro = cells[0]
+ .as_any()
+ .downcast_ref::<AgentMessageCell>()
+ .expect("intro agent");
+ let intro_lines = agent_intro.display_lines(u16::MAX);
+ let intro_text: String = intro_lines[0]
+ .spans
+ .iter()
+ .map(|span| span.content.as_ref())
+ .collect();
+ assert_eq!(intro_text, "• intro");
+
+ let user_first = cells[1]
+ .as_any()
+ .downcast_ref::<UserHistoryCell>()
+ .expect("first user");
+ assert_eq!(user_first.message, "first");
+
+ let agent_between = cells[2]
+ .as_any()
+ .downcast_ref::<AgentMessageCell>()
+ .expect("between agent");
+ let between_lines = agent_between.display_lines(u16::MAX);
+ let between_text: String = between_lines[0]
+ .spans
+ .iter()
+ .map(|span| span.content.as_ref())
+ .collect();
+ assert_eq!(between_text, " between");
+ }
+}
diff --git a/codex-rs/tui2/src/app_event.rs b/codex-rs/tui2/src/app_event.rs
new file mode 100644
index 0000000000..c92dab4b3a
--- /dev/null
+++ b/codex-rs/tui2/src/app_event.rs
@@ -0,0 +1,185 @@
+use std::path::PathBuf;
+
+use codex_common::approval_presets::ApprovalPreset;
+use codex_core::protocol::ConversationPathResponseEvent;
+use codex_core::protocol::Event;
+use codex_core::protocol::RateLimitSnapshot;
+use codex_file_search::FileMatch;
+use codex_protocol::openai_models::ModelPreset;
+
+use crate::bottom_pane::ApprovalRequest;
+use crate::history_cell::HistoryCell;
+
+use codex_core::protocol::AskForApproval;
+use codex_core::protocol::SandboxPolicy;
+use codex_protocol::openai_models::ReasoningEffort;
+
+#[allow(clippy::large_enum_variant)]
+#[derive(Debug)]
+pub(crate) enum AppEvent {
+ CodexEvent(Event),
+
+ /// Start a new session.
+ NewSession,
+
+ /// Open the resume picker inside the running TUI session.
+ OpenResumePicker,
+
+ /// Request to exit the application gracefully.
+ ExitRequest,
+
+ /// Forward an `Op` to the Agent. Using an `AppEvent` for this avoids
+ /// bubbling channels through layers of widgets.
+ CodexOp(codex_core::protocol::Op),
+
+ /// Kick off an asynchronous file search for the given query (text after
+ /// the `@`). Previous searches may be cancelled by the app layer so there
+ /// is at most one in-flight search.
+ StartFileSearch(String),
+
+ /// Result of a completed asynchronous file search. The `query` echoes the
+ /// original search term so the UI can decide whether the results are
+ /// still relevant.
+ FileSearchResult {
+ query: String,
+ matches: Vec<FileMatch>,
+ },
+
+ /// Result of refreshing rate limits
+ RateLimitSnapshotFetched(RateLimitSnapshot),
+
+ /// Result of computing a `/diff` command.
+ DiffResult(String),
+
+ InsertHistoryCell(Box<dyn HistoryCell>),
+
+ StartCommitAnimation,
+ StopCommitAnimation,
+ CommitTick,
+
+ /// Update the current reasoning effort in the running app and widget.
+ UpdateReasoningEffort(Option<ReasoningEffort>),
+
+ /// Update the current model slug in the running app and widget.
+ UpdateModel(String),
+
+ /// Persist the selected model and reasoning effort to the appropriate config.
+ PersistModelSelection {
+ model: String,
+ effort: Option<ReasoningEffort>,
+ },
+
+ /// Open the reasoning selection popup after picking a model.
+ OpenReasoningPopup {
+ model: ModelPreset,
+ },
+
+ /// Open the full model picker (non-auto models).
+ OpenAllModelsPopup {
+ models: Vec<ModelPreset>,
+ },
+
+ /// Open the confirmation prompt before enabling full access mode.
+ OpenFullAccessConfirmation {
+ preset: ApprovalPreset,
+ },
+
+ /// Open the Windows world-writable directories warning.
+ /// If `preset` is `Some`, the confirmation will apply the provided
+ /// approval/sandbox configuration on Continue; if `None`, it performs no
+ /// policy change and only acknowledges/dismisses the warning.
+ #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
+ OpenWorldWritableWarningConfirmation {
+ preset: Option<ApprovalPreset>,
+ /// Up to 3 sample world-writable directories to display in the warning.
+ sample_paths: Vec<String>,
+ /// If there are more than `sample_paths`, this carries the remaining count.
+ extra_count: usize,
+ /// True when the scan failed (e.g. ACL query error) and protections could not be verified.
+ failed_scan: bool,
+ },
+
+ /// Prompt to enable the Windows sandbox feature before using Agent mode.
+ #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
+ OpenWindowsSandboxEnablePrompt {
+ preset: ApprovalPreset,
+ },
+
+ /// Enable the Windows sandbox feature and switch to Agent mode.
+ #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
+ EnableWindowsSandboxForAgentMode {
+ preset: ApprovalPreset,
+ },
+
+ /// Update the current approval policy in the running app and widget.
+ UpdateAskForApprovalPolicy(AskForApproval),
+
+ /// Update the current sandbox policy in the running app and widget.
+ UpdateSandboxPolicy(SandboxPolicy),
+
+ /// Update whether the full access warning prompt has been acknowledged.
+ UpdateFullAccessWarningAcknowledged(bool),
+
+ /// Update whether the world-writable directories warning has been acknowledged.
+ #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
+ UpdateWorldWritableWarningAcknowledged(bool),
+
+ /// Update whether the rate limit switch prompt has been acknowledged for the session.
+ UpdateRateLimitSwitchPromptHidden(bool),
+
+ /// Persist the acknowledgement flag for the full access warning prompt.
+ PersistFullAccessWarningAcknowledged,
+
+ /// Persist the acknowledgement flag for the world-writable directories warning.
+ #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
+ PersistWorldWritableWarningAcknowledged,
+
+ /// Persist the acknowledgement flag for the rate limit switch prompt.
+ PersistRateLimitSwitchPromptHidden,
+
+ /// Persist the acknowledgement flag for the model migration prompt.
+ PersistModelMigrationPromptAcknowledged {
+ migration_config: String,
+ },
+
+ /// Skip the next world-writable scan (one-shot) after a user-confirmed continue.
+ #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
+ SkipNextWorldWritableScan,
+
+ /// Re-open the approval presets popup.
+ OpenApprovalsPopup,
+
+ /// Forwarded conversation history snapshot from the current conversation.
+ ConversationHistory(ConversationPathResponseEvent),
+
+ /// Open the branch picker option from the review popup.
+ OpenReviewBranchPicker(PathBuf),
+
+ /// Open the commit picker option from the review popup.
+ OpenReviewCommitPicker(PathBuf),
+
+ /// Open the custom prompt option from the review popup.
+ OpenReviewCustomPrompt,
+
+ /// Open the approval popup.
+ FullScreenApprovalRequest(ApprovalRequest),
+
+ /// Open the feedback note entry overlay after the user selects a category.
+ OpenFeedbackNote {
+ category: FeedbackCategory,
+ include_logs: bool,
+ },
+
+ /// Open the upload consent popup for feedback after selecting a category.
+ OpenFeedbackConsent {
+ category: FeedbackCategory,
+ },
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum FeedbackCategory {
+ BadResult,
+ GoodResult,
+ Bug,
+ Other,
+}
diff --git a/codex-rs/tui2/src/app_event_sender.rs b/codex-rs/tui2/src/app_event_sender.rs
new file mode 100644
index 0000000000..c1427b3ff0
--- /dev/null
+++ b/codex-rs/tui2/src/app_event_sender.rs
@@ -0,0 +1,28 @@
+use tokio::sync::mpsc::UnboundedSender;
+
+use crate::app_event::AppEvent;
+use crate::session_log;
+
+#[derive(Clone, Debug)]
+pub(crate) struct AppEventSender {
+ pub app_event_tx: UnboundedSender<AppEvent>,
+}
+
+impl AppEventSender {
+ pub(crate) fn new(app_event_tx: UnboundedSender<AppEvent>) -> Self {
+ Self { app_event_tx }
+ }
+
+ /// Send an event to the app event channel. If it fails, we swallow the
+ /// error and log it.
+ pub(crate) fn send(&self, event: AppEvent) {
+ // Record inbound events for high-fidelity session replay.
+ // Avoid double-logging Ops; those are logged at the point of submission.
+ if !matches!(event, AppEvent::CodexOp(_)) {
+ session_log::log_inbound_app_event(&event);
+ }
+ if let Err(e) = self.app_event_tx.send(event) {
+ tracing::error!("failed to send event: {e}");
+ }
+ }
+}
diff --git a/codex-rs/tui2/src/ascii_animation.rs b/codex-rs/tui2/src/ascii_animation.rs
new file mode 100644
index 0000000000..b2d9fc1d19
--- /dev/null
+++ b/codex-rs/tui2/src/ascii_animation.rs
@@ -0,0 +1,111 @@
+use std::convert::TryFrom;
+use std::time::Duration;
+use std::time::Instant;
+
+use rand::Rng as _;
+
+use crate::frames::ALL_VARIANTS;
+use crate::frames::FRAME_TICK_DEFAULT;
+use crate::tui::FrameRequester;
+
+/// Drives ASCII art animations shared across popups and onboarding widgets.
+pub(crate) struct AsciiAnimation {
+ request_frame: FrameRequester,
+ variants: &'static [&'static [&'static str]],
+ variant_idx: usize,
+ frame_tick: Duration,
+ start: Instant,
+}
+
+impl AsciiAnimation {
+ pub(crate) fn new(request_frame: FrameRequester) -> Self {
+ Self::with_variants(request_frame, ALL_VARIANTS, 0)
+ }
+
+ pub(crate) fn with_variants(
+ request_frame: FrameRequester,
+ variants: &'static [&'static [&'static str]],
+ variant_idx: usize,
+ ) -> Self {
+ assert!(
+ !variants.is_empty(),
+ "AsciiAnimation requires at least one animation variant",
+ );
+ let clamped_idx = variant_idx.min(variants.len() - 1);
+ Self {
+ request_frame,
+ variants,
+ variant_idx: clamped_idx,
+ frame_tick: FRAME_TICK_DEFAULT,
+ start: Instant::now(),
+ }
+ }
+
+ pub(crate) fn schedule_next_frame(&self) {
+ let tick_ms = self.frame_tick.as_millis();
+ if tick_ms == 0 {
+ self.request_frame.schedule_frame();
+ return;
+ }
+ let elapsed_ms = self.start.elapsed().as_millis();
+ let rem_ms = elapsed_ms % tick_ms;
+ let delay_ms = if rem_ms == 0 {
+ tick_ms
+ } else {
+ tick_ms - rem_ms
+ };
+ if let Ok(delay_ms_u64) = u64::try_from(delay_ms) {
+ self.request_frame
+ .schedule_frame_in(Duration::from_millis(delay_ms_u64));
+ } else {
+ self.request_frame.schedule_frame();
+ }
+ }
+
+ pub(crate) fn current_frame(&self) -> &'static str {
+ let frames = self.frames();
+ if frames.is_empty() {
+ return "";
+ }
+ let tick_ms = self.frame_tick.as_millis();
+ if tick_ms == 0 {
+ return frames[0];
+ }
+ let elapsed_ms = self.start.elapsed().as_millis();
+ let idx = ((elapsed_ms / tick_ms) % frames.len() as u128) as usize;
+ frames[idx]
+ }
+
+ pub(crate) fn pick_random_variant(&mut self) -> bool {
+ if self.variants.len() <= 1 {
+ return false;
+ }
+ let mut rng = rand::rng();
+ let mut next = self.variant_idx;
+ while next == self.variant_idx {
+ next = rng.random_range(0..self.variants.len());
+ }
+ self.variant_idx = next;
+ self.request_frame.schedule_frame();
+ true
+ }
+
+ #[allow(dead_code)]
+ pub(crate) fn request_frame(&self) {
+ self.request_frame.schedule_frame();
+ }
+
+ fn frames(&self) -> &'static [&'static str] {
+ self.variants[self.variant_idx]
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn frame_tick_must_be_nonzero() {
+ assert!(FRAME_TICK_DEFAULT.as_millis() > 0);
+ }
+}
diff --git a/codex-rs/tui2/src/bin/md-events2.rs b/codex-rs/tui2/src/bin/md-events2.rs
new file mode 100644
index 0000000000..f1117fad91
--- /dev/null
+++ b/codex-rs/tui2/src/bin/md-events2.rs
@@ -0,0 +1,15 @@
+use std::io::Read;
+use std::io::{self};
+
+fn main() {
+ let mut input = String::new();
+ if let Err(err) = io::stdin().read_to_string(&mut input) {
+ eprintln!("failed to read stdin: {err}");
+ std::process::exit(1);
+ }
+
+ let parser = pulldown_cmark::Parser::new(&input);
+ for event in parser {
+ println!("{event:?}");
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/approval_overlay.rs b/codex-rs/tui2/src/bottom_pane/approval_overlay.rs
new file mode 100644
index 0000000000..d42861eb1d
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/approval_overlay.rs
@@ -0,0 +1,717 @@
+use std::collections::HashMap;
+use std::path::PathBuf;
+
+use crate::app_event::AppEvent;
+use crate::app_event_sender::AppEventSender;
+use crate::bottom_pane::BottomPaneView;
+use crate::bottom_pane::CancellationEvent;
+use crate::bottom_pane::list_selection_view::ListSelectionView;
+use crate::bottom_pane::list_selection_view::SelectionItem;
+use crate::bottom_pane::list_selection_view::SelectionViewParams;
+use crate::diff_render::DiffSummary;
+use crate::exec_command::strip_bash_lc_and_escape;
+use crate::history_cell;
+use crate::key_hint;
+use crate::key_hint::KeyBinding;
+use crate::render::highlight::highlight_bash_to_lines;
+use crate::render::renderable::ColumnRenderable;
+use crate::render::renderable::Renderable;
+use codex_core::features::Feature;
+use codex_core::features::Features;
+use codex_core::protocol::ElicitationAction;
+use codex_core::protocol::ExecPolicyAmendment;
+use codex_core::protocol::FileChange;
+use codex_core::protocol::Op;
+use codex_core::protocol::ReviewDecision;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use crossterm::event::KeyModifiers;
+use mcp_types::RequestId;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::Wrap;
+
+/// Request coming from the agent that needs user approval.
+#[derive(Clone, Debug)]
+pub(crate) enum ApprovalRequest {
+ Exec {
+ id: String,
+ command: Vec<String>,
+ reason: Option<String>,
+ proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
+ },
+ ApplyPatch {
+ id: String,
+ reason: Option<String>,
+ cwd: PathBuf,
+ changes: HashMap<PathBuf, FileChange>,
+ },
+ McpElicitation {
+ server_name: String,
+ request_id: RequestId,
+ message: String,
+ },
+}
+
+/// Modal overlay asking the user to approve or deny one or more requests.
+pub(crate) struct ApprovalOverlay {
+ current_request: Option<ApprovalRequest>,
+ current_variant: Option<ApprovalVariant>,
+ queue: Vec<ApprovalRequest>,
+ app_event_tx: AppEventSender,
+ list: ListSelectionView,
+ options: Vec<ApprovalOption>,
+ current_complete: bool,
+ done: bool,
+ features: Features,
+}
+
+impl ApprovalOverlay {
+ pub fn new(request: ApprovalRequest, app_event_tx: AppEventSender, features: Features) -> Self {
+ let mut view = Self {
+ current_request: None,
+ current_variant: None,
+ queue: Vec::new(),
+ app_event_tx: app_event_tx.clone(),
+ list: ListSelectionView::new(Default::default(), app_event_tx),
+ options: Vec::new(),
+ current_complete: false,
+ done: false,
+ features,
+ };
+ view.set_current(request);
+ view
+ }
+
+ pub fn enqueue_request(&mut self, req: ApprovalRequest) {
+ self.queue.push(req);
+ }
+
+ fn set_current(&mut self, request: ApprovalRequest) {
+ self.current_request = Some(request.clone());
+ let ApprovalRequestState { variant, header } = ApprovalRequestState::from(request);
+ self.current_variant = Some(variant.clone());
+ self.current_complete = false;
+ let (options, params) = Self::build_options(variant, header, &self.features);
+ self.options = options;
+ self.list = ListSelectionView::new(params, self.app_event_tx.clone());
+ }
+
+ fn build_options(
+ variant: ApprovalVariant,
+ header: Box<dyn Renderable>,
+ features: &Features,
+ ) -> (Vec<ApprovalOption>, SelectionViewParams) {
+ let (options, title) = match &variant {
+ ApprovalVariant::Exec {
+ proposed_execpolicy_amendment,
+ ..
+ } => (
+ exec_options(proposed_execpolicy_amendment.clone(), features),
+ "Would you like to run the following command?".to_string(),
+ ),
+ ApprovalVariant::ApplyPatch { .. } => (
+ patch_options(),
+ "Would you like to make the following edits?".to_string(),
+ ),
+ ApprovalVariant::McpElicitation { server_name, .. } => (
+ elicitation_options(),
+ format!("{server_name} needs your approval."),
+ ),
+ };
+
+ let header = Box::new(ColumnRenderable::with([
+ Line::from(title.bold()).into(),
+ Line::from("").into(),
+ header,
+ ]));
+
+ let items = options
+ .iter()
+ .map(|opt| SelectionItem {
+ name: opt.label.clone(),
+ display_shortcut: opt
+ .display_shortcut
+ .or_else(|| opt.additional_shortcuts.first().copied()),
+ dismiss_on_select: false,
+ ..Default::default()
+ })
+ .collect();
+
+ let params = SelectionViewParams {
+ footer_hint: Some(Line::from(vec![
+ "Press ".into(),
+ key_hint::plain(KeyCode::Enter).into(),
+ " to confirm or ".into(),
+ key_hint::plain(KeyCode::Esc).into(),
+ " to cancel".into(),
+ ])),
+ items,
+ header,
+ ..Default::default()
+ };
+
+ (options, params)
+ }
+
+ fn apply_selection(&mut self, actual_idx: usize) {
+ if self.current_complete {
+ return;
+ }
+ let Some(option) = self.options.get(actual_idx) else {
+ return;
+ };
+ if let Some(variant) = self.current_variant.as_ref() {
+ match (variant, &option.decision) {
+ (ApprovalVariant::Exec { id, command, .. }, ApprovalDecision::Review(decision)) => {
+ self.handle_exec_decision(id, command, decision.clone());
+ }
+ (ApprovalVariant::ApplyPatch { id, .. }, ApprovalDecision::Review(decision)) => {
+ self.handle_patch_decision(id, decision.clone());
+ }
+ (
+ ApprovalVariant::McpElicitation {
+ server_name,
+ request_id,
+ },
+ ApprovalDecision::McpElicitation(decision),
+ ) => {
+ self.handle_elicitation_decision(server_name, request_id, *decision);
+ }
+ _ => {}
+ }
+ }
+
+ self.current_complete = true;
+ self.advance_queue();
+ }
+
+ fn handle_exec_decision(&self, id: &str, command: &[String], decision: ReviewDecision) {
+ let cell = history_cell::new_approval_decision_cell(command.to_vec(), decision.clone());
+ self.app_event_tx.send(AppEvent::InsertHistoryCell(cell));
+ self.app_event_tx.send(AppEvent::CodexOp(Op::ExecApproval {
+ id: id.to_string(),
+ decision,
+ }));
+ }
+
+ fn handle_patch_decision(&self, id: &str, decision: ReviewDecision) {
+ self.app_event_tx.send(AppEvent::CodexOp(Op::PatchApproval {
+ id: id.to_string(),
+ decision,
+ }));
+ }
+
+ fn handle_elicitation_decision(
+ &self,
+ server_name: &str,
+ request_id: &RequestId,
+ decision: ElicitationAction,
+ ) {
+ self.app_event_tx
+ .send(AppEvent::CodexOp(Op::ResolveElicitation {
+ server_name: server_name.to_string(),
+ request_id: request_id.clone(),
+ decision,
+ }));
+ }
+
+ fn advance_queue(&mut self) {
+ if let Some(next) = self.queue.pop() {
+ self.set_current(next);
+ } else {
+ self.done = true;
+ }
+ }
+
+ fn try_handle_shortcut(&mut self, key_event: &KeyEvent) -> bool {
+ match key_event {
+ KeyEvent {
+ kind: KeyEventKind::Press,
+ code: KeyCode::Char('a'),
+ modifiers,
+ ..
+ } if modifiers.contains(KeyModifiers::CONTROL) => {
+ if let Some(request) = self.current_request.as_ref() {
+ self.app_event_tx
+ .send(AppEvent::FullScreenApprovalRequest(request.clone()));
+ true
+ } else {
+ false
+ }
+ }
+ e => {
+ if let Some(idx) = self
+ .options
+ .iter()
+ .position(|opt| opt.shortcuts().any(|s| s.is_press(*e)))
+ {
+ self.apply_selection(idx);
+ true
+ } else {
+ false
+ }
+ }
+ }
+ }
+}
+
+impl BottomPaneView for ApprovalOverlay {
+ fn handle_key_event(&mut self, key_event: KeyEvent) {
+ if self.try_handle_shortcut(&key_event) {
+ return;
+ }
+ self.list.handle_key_event(key_event);
+ if let Some(idx) = self.list.take_last_selected_index() {
+ self.apply_selection(idx);
+ }
+ }
+
+ fn on_ctrl_c(&mut self) -> CancellationEvent {
+ if self.done {
+ return CancellationEvent::Handled;
+ }
+ if !self.current_complete
+ && let Some(variant) = self.current_variant.as_ref()
+ {
+ match &variant {
+ ApprovalVariant::Exec { id, command, .. } => {
+ self.handle_exec_decision(id, command, ReviewDecision::Abort);
+ }
+ ApprovalVariant::ApplyPatch { id, .. } => {
+ self.handle_patch_decision(id, ReviewDecision::Abort);
+ }
+ ApprovalVariant::McpElicitation {
+ server_name,
+ request_id,
+ } => {
+ self.handle_elicitation_decision(
+ server_name,
+ request_id,
+ ElicitationAction::Cancel,
+ );
+ }
+ }
+ }
+ self.queue.clear();
+ self.done = true;
+ CancellationEvent::Handled
+ }
+
+ fn is_complete(&self) -> bool {
+ self.done
+ }
+
+ fn try_consume_approval_request(
+ &mut self,
+ request: ApprovalRequest,
+ ) -> Option<ApprovalRequest> {
+ self.enqueue_request(request);
+ None
+ }
+}
+
+impl Renderable for ApprovalOverlay {
+ fn desired_height(&self, width: u16) -> u16 {
+ self.list.desired_height(width)
+ }
+
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ self.list.render(area, buf);
+ }
+
+ fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ self.list.cursor_pos(area)
+ }
+}
+
+struct ApprovalRequestState {
+ variant: ApprovalVariant,
+ header: Box<dyn Renderable>,
+}
+
+impl From<ApprovalRequest> for ApprovalRequestState {
+ fn from(value: ApprovalRequest) -> Self {
+ match value {
+ ApprovalRequest::Exec {
+ id,
+ command,
+ reason,
+ proposed_execpolicy_amendment,
+ } => {
+ let mut header: Vec<Line<'static>> = Vec::new();
+ if let Some(reason) = reason {
+ header.push(Line::from(vec!["Reason: ".into(), reason.italic()]));
+ header.push(Line::from(""));
+ }
+ let full_cmd = strip_bash_lc_and_escape(&command);
+ let mut full_cmd_lines = highlight_bash_to_lines(&full_cmd);
+ if let Some(first) = full_cmd_lines.first_mut() {
+ first.spans.insert(0, Span::from("$ "));
+ }
+ header.extend(full_cmd_lines);
+ Self {
+ variant: ApprovalVariant::Exec {
+ id,
+ command,
+ proposed_execpolicy_amendment,
+ },
+ header: Box::new(Paragraph::new(header).wrap(Wrap { trim: false })),
+ }
+ }
+ ApprovalRequest::ApplyPatch {
+ id,
+ reason,
+ cwd,
+ changes,
+ } => {
+ let mut header: Vec<Box<dyn Renderable>> = Vec::new();
+ if let Some(reason) = reason
+ && !reason.is_empty()
+ {
+ header.push(Box::new(
+ Paragraph::new(Line::from_iter(["Reason: ".into(), reason.italic()]))
+ .wrap(Wrap { trim: false }),
+ ));
+ header.push(Box::new(Line::from("")));
+ }
+ header.push(DiffSummary::new(changes, cwd).into());
+ Self {
+ variant: ApprovalVariant::ApplyPatch { id },
+ header: Box::new(ColumnRenderable::with(header)),
+ }
+ }
+ ApprovalRequest::McpElicitation {
+ server_name,
+ request_id,
+ message,
+ } => {
+ let header = Paragraph::new(vec![
+ Line::from(vec!["Server: ".into(), server_name.clone().bold()]),
+ Line::from(""),
+ Line::from(message),
+ ])
+ .wrap(Wrap { trim: false });
+ Self {
+ variant: ApprovalVariant::McpElicitation {
+ server_name,
+ request_id,
+ },
+ header: Box::new(header),
+ }
+ }
+ }
+ }
+}
+
+#[derive(Clone)]
+enum ApprovalVariant {
+ Exec {
+ id: String,
+ command: Vec<String>,
+ proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
+ },
+ ApplyPatch {
+ id: String,
+ },
+ McpElicitation {
+ server_name: String,
+ request_id: RequestId,
+ },
+}
+
+#[derive(Clone)]
+enum ApprovalDecision {
+ Review(ReviewDecision),
+ McpElicitation(ElicitationAction),
+}
+
+#[derive(Clone)]
+struct ApprovalOption {
+ label: String,
+ decision: ApprovalDecision,
+ display_shortcut: Option<KeyBinding>,
+ additional_shortcuts: Vec<KeyBinding>,
+}
+
+impl ApprovalOption {
+ fn shortcuts(&self) -> impl Iterator<Item = KeyBinding> + '_ {
+ self.display_shortcut
+ .into_iter()
+ .chain(self.additional_shortcuts.iter().copied())
+ }
+}
+
+fn exec_options(
+ proposed_execpolicy_amendment: Option<ExecPolicyAmendment>,
+ features: &Features,
+) -> Vec<ApprovalOption> {
+ vec![ApprovalOption {
+ label: "Yes, proceed".to_string(),
+ decision: ApprovalDecision::Review(ReviewDecision::Approved),
+ display_shortcut: None,
+ additional_shortcuts: vec![key_hint::plain(KeyCode::Char('y'))],
+ }]
+ .into_iter()
+ .chain(
+ proposed_execpolicy_amendment
+ .filter(|_| features.enabled(Feature::ExecPolicy))
+ .map(|prefix| {
+ let rendered_prefix = strip_bash_lc_and_escape(prefix.command());
+ ApprovalOption {
+ label: format!(
+ "Yes, and don't ask again for commands that start with `{rendered_prefix}`"
+ ),
+ decision: ApprovalDecision::Review(
+ ReviewDecision::ApprovedExecpolicyAmendment {
+ proposed_execpolicy_amendment: prefix,
+ },
+ ),
+ display_shortcut: None,
+ additional_shortcuts: vec![key_hint::plain(KeyCode::Char('p'))],
+ }
+ }),
+ )
+ .chain([ApprovalOption {
+ label: "No, and tell Codex what to do differently".to_string(),
+ decision: ApprovalDecision::Review(ReviewDecision::Abort),
+ display_shortcut: Some(key_hint::plain(KeyCode::Esc)),
+ additional_shortcuts: vec![key_hint::plain(KeyCode::Char('n'))],
+ }])
+ .collect()
+}
+
+fn patch_options() -> Vec<ApprovalOption> {
+ vec![
+ ApprovalOption {
+ label: "Yes, proceed".to_string(),
+ decision: ApprovalDecision::Review(ReviewDecision::Approved),
+ display_shortcut: None,
+ additional_shortcuts: vec![key_hint::plain(KeyCode::Char('y'))],
+ },
+ ApprovalOption {
+ label: "No, and tell Codex what to do differently".to_string(),
+ decision: ApprovalDecision::Review(ReviewDecision::Abort),
+ display_shortcut: Some(key_hint::plain(KeyCode::Esc)),
+ additional_shortcuts: vec![key_hint::plain(KeyCode::Char('n'))],
+ },
+ ]
+}
+
+fn elicitation_options() -> Vec<ApprovalOption> {
+ vec![
+ ApprovalOption {
+ label: "Yes, provide the requested info".to_string(),
+ decision: ApprovalDecision::McpElicitation(ElicitationAction::Accept),
+ display_shortcut: None,
+ additional_shortcuts: vec![key_hint::plain(KeyCode::Char('y'))],
+ },
+ ApprovalOption {
+ label: "No, but continue without it".to_string(),
+ decision: ApprovalDecision::McpElicitation(ElicitationAction::Decline),
+ display_shortcut: None,
+ additional_shortcuts: vec![key_hint::plain(KeyCode::Char('n'))],
+ },
+ ApprovalOption {
+ label: "Cancel this request".to_string(),
+ decision: ApprovalDecision::McpElicitation(ElicitationAction::Cancel),
+ display_shortcut: Some(key_hint::plain(KeyCode::Esc)),
+ additional_shortcuts: vec![key_hint::plain(KeyCode::Char('c'))],
+ },
+ ]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::app_event::AppEvent;
+ use pretty_assertions::assert_eq;
+ use tokio::sync::mpsc::unbounded_channel;
+
+ fn make_exec_request() -> ApprovalRequest {
+ ApprovalRequest::Exec {
+ id: "test".to_string(),
+ command: vec!["echo".to_string(), "hi".to_string()],
+ reason: Some("reason".to_string()),
+ proposed_execpolicy_amendment: None,
+ }
+ }
+
+ #[test]
+ fn ctrl_c_aborts_and_clears_queue() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx);
+ let mut view = ApprovalOverlay::new(make_exec_request(), tx, Features::with_defaults());
+ view.enqueue_request(make_exec_request());
+ assert_eq!(CancellationEvent::Handled, view.on_ctrl_c());
+ assert!(view.queue.is_empty());
+ assert!(view.is_complete());
+ }
+
+ #[test]
+ fn shortcut_triggers_selection() {
+ let (tx, mut rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx);
+ let mut view = ApprovalOverlay::new(make_exec_request(), tx, Features::with_defaults());
+ assert!(!view.is_complete());
+ view.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
+ // We expect at least one CodexOp message in the queue.
+ let mut saw_op = false;
+ while let Ok(ev) = rx.try_recv() {
+ if matches!(ev, AppEvent::CodexOp(_)) {
+ saw_op = true;
+ break;
+ }
+ }
+ assert!(saw_op, "expected approval decision to emit an op");
+ }
+
+ #[test]
+ fn exec_prefix_option_emits_execpolicy_amendment() {
+ let (tx, mut rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx);
+ let mut view = ApprovalOverlay::new(
+ ApprovalRequest::Exec {
+ id: "test".to_string(),
+ command: vec!["echo".to_string()],
+ reason: None,
+ proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![
+ "echo".to_string(),
+ ])),
+ },
+ tx,
+ Features::with_defaults(),
+ );
+ view.handle_key_event(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::NONE));
+ let mut saw_op = false;
+ while let Ok(ev) = rx.try_recv() {
+ if let AppEvent::CodexOp(Op::ExecApproval { decision, .. }) = ev {
+ assert_eq!(
+ decision,
+ ReviewDecision::ApprovedExecpolicyAmendment {
+ proposed_execpolicy_amendment: ExecPolicyAmendment::new(vec![
+ "echo".to_string()
+ ])
+ }
+ );
+ saw_op = true;
+ break;
+ }
+ }
+ assert!(
+ saw_op,
+ "expected approval decision to emit an op with command prefix"
+ );
+ }
+
+ #[test]
+ fn exec_prefix_option_hidden_when_execpolicy_disabled() {
+ let (tx, mut rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx);
+ let mut view = ApprovalOverlay::new(
+ ApprovalRequest::Exec {
+ id: "test".to_string(),
+ command: vec!["echo".to_string()],
+ reason: None,
+ proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![
+ "echo".to_string(),
+ ])),
+ },
+ tx,
+ {
+ let mut features = Features::with_defaults();
+ features.disable(Feature::ExecPolicy);
+ features
+ },
+ );
+ assert_eq!(view.options.len(), 2);
+ view.handle_key_event(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::NONE));
+ assert!(!view.is_complete());
+ assert!(rx.try_recv().is_err());
+ }
+
+ #[test]
+ fn header_includes_command_snippet() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx);
+ let command = vec!["echo".into(), "hello".into(), "world".into()];
+ let exec_request = ApprovalRequest::Exec {
+ id: "test".into(),
+ command,
+ reason: None,
+ proposed_execpolicy_amendment: None,
+ };
+
+ let view = ApprovalOverlay::new(exec_request, tx, Features::with_defaults());
+ let mut buf = Buffer::empty(Rect::new(0, 0, 80, view.desired_height(80)));
+ view.render(Rect::new(0, 0, 80, view.desired_height(80)), &mut buf);
+
+ let rendered: Vec<String> = (0..buf.area.height)
+ .map(|row| {
+ (0..buf.area.width)
+ .map(|col| buf[(col, row)].symbol().to_string())
+ .collect()
+ })
+ .collect();
+ assert!(
+ rendered
+ .iter()
+ .any(|line| line.contains("echo hello world")),
+ "expected header to include command snippet, got {rendered:?}"
+ );
+ }
+
+ #[test]
+ fn exec_history_cell_wraps_with_two_space_indent() {
+ let command = vec![
+ "/bin/zsh".into(),
+ "-lc".into(),
+ "git add tui/src/render/mod.rs tui/src/render/renderable.rs".into(),
+ ];
+ let cell = history_cell::new_approval_decision_cell(command, ReviewDecision::Approved);
+ let lines = cell.display_lines(28);
+ let rendered: Vec<String> = lines
+ .iter()
+ .map(|line| {
+ line.spans
+ .iter()
+ .map(|span| span.content.as_ref())
+ .collect::<String>()
+ })
+ .collect();
+ let expected = vec![
+ "✔ You approved codex to run".to_string(),
+ " git add tui/src/render/".to_string(),
+ " mod.rs tui/src/render/".to_string(),
+ " renderable.rs this time".to_string(),
+ ];
+ assert_eq!(rendered, expected);
+ }
+
+ #[test]
+ fn enter_sets_last_selected_index_without_dismissing() {
+ let (tx_raw, mut rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let mut view = ApprovalOverlay::new(make_exec_request(), tx, Features::with_defaults());
+ view.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ assert!(
+ view.is_complete(),
+ "exec approval should complete without queued requests"
+ );
+
+ let mut decision = None;
+ while let Ok(ev) = rx.try_recv() {
+ if let AppEvent::CodexOp(Op::ExecApproval { decision: d, .. }) = ev {
+ decision = Some(d);
+ break;
+ }
+ }
+ assert_eq!(decision, Some(ReviewDecision::Approved));
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/bottom_pane_view.rs b/codex-rs/tui2/src/bottom_pane/bottom_pane_view.rs
new file mode 100644
index 0000000000..499801cbb0
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/bottom_pane_view.rs
@@ -0,0 +1,37 @@
+use crate::bottom_pane::ApprovalRequest;
+use crate::render::renderable::Renderable;
+use crossterm::event::KeyEvent;
+
+use super::CancellationEvent;
+
+/// Trait implemented by every view that can be shown in the bottom pane.
+pub(crate) trait BottomPaneView: Renderable {
+ /// Handle a key event while the view is active. A redraw is always
+ /// scheduled after this call.
+ fn handle_key_event(&mut self, _key_event: KeyEvent) {}
+
+ /// Return `true` if the view has finished and should be removed.
+ fn is_complete(&self) -> bool {
+ false
+ }
+
+ /// Handle Ctrl-C while this view is active.
+ fn on_ctrl_c(&mut self) -> CancellationEvent {
+ CancellationEvent::NotHandled
+ }
+
+ /// Optional paste handler. Return true if the view modified its state and
+ /// needs a redraw.
+ fn handle_paste(&mut self, _pasted: String) -> bool {
+ false
+ }
+
+ /// Try to handle approval request; return the original value if not
+ /// consumed.
+ fn try_consume_approval_request(
+ &mut self,
+ request: ApprovalRequest,
+ ) -> Option<ApprovalRequest> {
+ Some(request)
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/chat_composer.rs b/codex-rs/tui2/src/bottom_pane/chat_composer.rs
new file mode 100644
index 0000000000..ed498e949c
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/chat_composer.rs
@@ -0,0 +1,3990 @@
+use crate::key_hint::has_ctrl_or_alt;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use crossterm::event::KeyModifiers;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Constraint;
+use ratatui::layout::Layout;
+use ratatui::layout::Margin;
+use ratatui::layout::Rect;
+use ratatui::style::Style;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::widgets::Block;
+use ratatui::widgets::StatefulWidgetRef;
+use ratatui::widgets::WidgetRef;
+
+use super::chat_composer_history::ChatComposerHistory;
+use super::command_popup::CommandItem;
+use super::command_popup::CommandPopup;
+use super::file_search_popup::FileSearchPopup;
+use super::footer::FooterMode;
+use super::footer::FooterProps;
+use super::footer::esc_hint_mode;
+use super::footer::footer_height;
+use super::footer::render_footer;
+use super::footer::reset_mode_after_activity;
+use super::footer::toggle_shortcut_mode;
+use super::paste_burst::CharDecision;
+use super::paste_burst::PasteBurst;
+use super::skill_popup::SkillPopup;
+use crate::bottom_pane::paste_burst::FlushResult;
+use crate::bottom_pane::prompt_args::expand_custom_prompt;
+use crate::bottom_pane::prompt_args::expand_if_numeric_with_positional_args;
+use crate::bottom_pane::prompt_args::parse_slash_name;
+use crate::bottom_pane::prompt_args::prompt_argument_names;
+use crate::bottom_pane::prompt_args::prompt_command_with_arg_placeholders;
+use crate::bottom_pane::prompt_args::prompt_has_numeric_placeholders;
+use crate::render::Insets;
+use crate::render::RectExt;
+use crate::render::renderable::Renderable;
+use crate::slash_command::SlashCommand;
+use crate::slash_command::built_in_slash_commands;
+use crate::style::user_message_style;
+use codex_protocol::custom_prompts::CustomPrompt;
+use codex_protocol::custom_prompts::PROMPTS_CMD_PREFIX;
+
+use crate::app_event::AppEvent;
+use crate::app_event_sender::AppEventSender;
+use crate::bottom_pane::textarea::TextArea;
+use crate::bottom_pane::textarea::TextAreaState;
+use crate::clipboard_paste::normalize_pasted_path;
+use crate::clipboard_paste::pasted_image_format;
+use crate::history_cell;
+use crate::ui_consts::LIVE_PREFIX_COLS;
+use codex_core::skills::model::SkillMetadata;
+use codex_file_search::FileMatch;
+use std::cell::RefCell;
+use std::collections::HashMap;
+use std::path::Path;
+use std::path::PathBuf;
+use std::time::Duration;
+use std::time::Instant;
+
+/// If the pasted content exceeds this number of characters, replace it with a
+/// placeholder in the UI.
+const LARGE_PASTE_CHAR_THRESHOLD: usize = 1000;
+
+/// Result returned when the user interacts with the text area.
+#[derive(Debug, PartialEq)]
+pub enum InputResult {
+ Submitted(String),
+ Command(SlashCommand),
+ None,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct AttachedImage {
+ placeholder: String,
+ path: PathBuf,
+}
+
+enum PromptSelectionMode {
+ Completion,
+ Submit,
+}
+
+enum PromptSelectionAction {
+ Insert { text: String, cursor: Option<usize> },
+ Submit { text: String },
+}
+
+pub(crate) struct ChatComposer {
+ textarea: TextArea,
+ textarea_state: RefCell<TextAreaState>,
+ active_popup: ActivePopup,
+ app_event_tx: AppEventSender,
+ history: ChatComposerHistory,
+ ctrl_c_quit_hint: bool,
+ esc_backtrack_hint: bool,
+ use_shift_enter_hint: bool,
+ dismissed_file_popup_token: Option<String>,
+ current_file_query: Option<String>,
+ pending_pastes: Vec<(String, String)>,
+ large_paste_counters: HashMap<usize, usize>,
+ has_focus: bool,
+ attached_images: Vec<AttachedImage>,
+ placeholder_text: String,
+ is_task_running: bool,
+ // Non-bracketed paste burst tracker.
+ paste_burst: PasteBurst,
+ // When true, disables paste-burst logic and inserts characters immediately.
+ disable_paste_burst: bool,
+ custom_prompts: Vec<CustomPrompt>,
+ footer_mode: FooterMode,
+ footer_hint_override: Option<Vec<(String, String)>>,
+ context_window_percent: Option<i64>,
+ context_window_used_tokens: Option<i64>,
+ skills: Option<Vec<SkillMetadata>>,
+ dismissed_skill_popup_token: Option<String>,
+}
+
+/// Popup state – at most one can be visible at any time.
+enum ActivePopup {
+ None,
+ Command(CommandPopup),
+ File(FileSearchPopup),
+ Skill(SkillPopup),
+}
+
+const FOOTER_SPACING_HEIGHT: u16 = 0;
+
+impl ChatComposer {
+ pub fn new(
+ has_input_focus: bool,
+ app_event_tx: AppEventSender,
+ enhanced_keys_supported: bool,
+ placeholder_text: String,
+ disable_paste_burst: bool,
+ ) -> Self {
+ let use_shift_enter_hint = enhanced_keys_supported;
+
+ let mut this = Self {
+ textarea: TextArea::new(),
+ textarea_state: RefCell::new(TextAreaState::default()),
+ active_popup: ActivePopup::None,
+ app_event_tx,
+ history: ChatComposerHistory::new(),
+ ctrl_c_quit_hint: false,
+ esc_backtrack_hint: false,
+ use_shift_enter_hint,
+ dismissed_file_popup_token: None,
+ current_file_query: None,
+ pending_pastes: Vec::new(),
+ large_paste_counters: HashMap::new(),
+ has_focus: has_input_focus,
+ attached_images: Vec::new(),
+ placeholder_text,
+ is_task_running: false,
+ paste_burst: PasteBurst::default(),
+ disable_paste_burst: false,
+ custom_prompts: Vec::new(),
+ footer_mode: FooterMode::ShortcutSummary,
+ footer_hint_override: None,
+ context_window_percent: None,
+ context_window_used_tokens: None,
+ skills: None,
+ dismissed_skill_popup_token: None,
+ };
+ // Apply configuration via the setter to keep side-effects centralized.
+ this.set_disable_paste_burst(disable_paste_burst);
+ this
+ }
+
+ pub fn set_skill_mentions(&mut self, skills: Option<Vec<SkillMetadata>>) {
+ self.skills = skills;
+ }
+
+ fn layout_areas(&self, area: Rect) -> [Rect; 3] {
+ let footer_props = self.footer_props();
+ let footer_hint_height = self
+ .custom_footer_height()
+ .unwrap_or_else(|| footer_height(footer_props));
+ let footer_spacing = Self::footer_spacing(footer_hint_height);
+ let footer_total_height = footer_hint_height + footer_spacing;
+ let popup_constraint = match &self.active_popup {
+ ActivePopup::Command(popup) => {
+ Constraint::Max(popup.calculate_required_height(area.width))
+ }
+ ActivePopup::File(popup) => Constraint::Max(popup.calculate_required_height()),
+ ActivePopup::Skill(popup) => {
+ Constraint::Max(popup.calculate_required_height(area.width))
+ }
+ ActivePopup::None => Constraint::Max(footer_total_height),
+ };
+ let [composer_rect, popup_rect] =
+ Layout::vertical([Constraint::Min(3), popup_constraint]).areas(area);
+ let textarea_rect = composer_rect.inset(Insets::tlbr(1, LIVE_PREFIX_COLS, 1, 1));
+ [composer_rect, textarea_rect, popup_rect]
+ }
+
+ fn footer_spacing(footer_hint_height: u16) -> u16 {
+ if footer_hint_height == 0 {
+ 0
+ } else {
+ FOOTER_SPACING_HEIGHT
+ }
+ }
+
+ /// Returns true if the composer currently contains no user input.
+ pub(crate) fn is_empty(&self) -> bool {
+ self.textarea.is_empty()
+ }
+
+ /// Record the history metadata advertised by `SessionConfiguredEvent` so
+ /// that the composer can navigate cross-session history.
+ pub(crate) fn set_history_metadata(&mut self, log_id: u64, entry_count: usize) {
+ self.history.set_metadata(log_id, entry_count);
+ }
+
+ /// Integrate an asynchronous response to an on-demand history lookup. If
+ /// the entry is present and the offset matches the current cursor we
+ /// immediately populate the textarea.
+ pub(crate) fn on_history_entry_response(
+ &mut self,
+ log_id: u64,
+ offset: usize,
+ entry: Option<String>,
+ ) -> bool {
+ let Some(text) = self.history.on_entry_response(log_id, offset, entry) else {
+ return false;
+ };
+ self.set_text_content(text);
+ true
+ }
+
+ pub fn handle_paste(&mut self, pasted: String) -> bool {
+ let char_count = pasted.chars().count();
+ if char_count > LARGE_PASTE_CHAR_THRESHOLD {
+ let placeholder = self.next_large_paste_placeholder(char_count);
+ self.textarea.insert_element(&placeholder);
+ self.pending_pastes.push((placeholder, pasted));
+ } else if char_count > 1 && self.handle_paste_image_path(pasted.clone()) {
+ self.textarea.insert_str(" ");
+ } else {
+ self.textarea.insert_str(&pasted);
+ }
+ // Explicit paste events should not trigger Enter suppression.
+ self.paste_burst.clear_after_explicit_paste();
+ self.sync_popups();
+ true
+ }
+
+ pub fn handle_paste_image_path(&mut self, pasted: String) -> bool {
+ let Some(path_buf) = normalize_pasted_path(&pasted) else {
+ return false;
+ };
+
+ // normalize_pasted_path already handles Windows → WSL path conversion,
+ // so we can directly try to read the image dimensions.
+ match image::image_dimensions(&path_buf) {
+ Ok((w, h)) => {
+ tracing::info!("OK: {pasted}");
+ let format_label = pasted_image_format(&path_buf).label();
+ self.attach_image(path_buf, w, h, format_label);
+ true
+ }
+ Err(err) => {
+ tracing::trace!("ERR: {err}");
+ false
+ }
+ }
+ }
+
+ pub(crate) fn set_disable_paste_burst(&mut self, disabled: bool) {
+ let was_disabled = self.disable_paste_burst;
+ self.disable_paste_burst = disabled;
+ if disabled && !was_disabled {
+ self.paste_burst.clear_window_after_non_char();
+ }
+ }
+
+ /// Override the footer hint items displayed beneath the composer. Passing
+ /// `None` restores the default shortcut footer.
+ pub(crate) fn set_footer_hint_override(&mut self, items: Option<Vec<(String, String)>>) {
+ self.footer_hint_override = items;
+ }
+
+ /// Replace the entire composer content with `text` and reset cursor.
+ pub(crate) fn set_text_content(&mut self, text: String) {
+ // Clear any existing content, placeholders, and attachments first.
+ self.textarea.set_text("");
+ self.pending_pastes.clear();
+ self.attached_images.clear();
+ self.textarea.set_text(&text);
+ self.textarea.set_cursor(0);
+ self.sync_popups();
+ }
+
+ pub(crate) fn clear_for_ctrl_c(&mut self) -> Option<String> {
+ if self.is_empty() {
+ return None;
+ }
+ let previous = self.current_text();
+ self.set_text_content(String::new());
+ self.history.reset_navigation();
+ self.history.record_local_submission(&previous);
+ Some(previous)
+ }
+
+ /// Get the current composer text.
+ pub(crate) fn current_text(&self) -> String {
+ self.textarea.text().to_string()
+ }
+
+ /// Attempt to start a burst by retro-capturing recent chars before the cursor.
+ pub fn attach_image(&mut self, path: PathBuf, width: u32, height: u32, _format_label: &str) {
+ let file_label = path
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_else(|| "image".to_string());
+ let placeholder = format!("[{file_label} {width}x{height}]");
+ // Insert as an element to match large paste placeholder behavior:
+ // styled distinctly and treated atomically for cursor/mutations.
+ self.textarea.insert_element(&placeholder);
+ self.attached_images
+ .push(AttachedImage { placeholder, path });
+ }
+
+ pub fn take_recent_submission_images(&mut self) -> Vec<PathBuf> {
+ let images = std::mem::take(&mut self.attached_images);
+ images.into_iter().map(|img| img.path).collect()
+ }
+
+ pub(crate) fn flush_paste_burst_if_due(&mut self) -> bool {
+ self.handle_paste_burst_flush(Instant::now())
+ }
+
+ pub(crate) fn is_in_paste_burst(&self) -> bool {
+ self.paste_burst.is_active()
+ }
+
+ pub(crate) fn recommended_paste_flush_delay() -> Duration {
+ PasteBurst::recommended_flush_delay()
+ }
+
+ /// Integrate results from an asynchronous file search.
+ pub(crate) fn on_file_search_result(&mut self, query: String, matches: Vec<FileMatch>) {
+ // Only apply if user is still editing a token starting with `query`.
+ let current_opt = Self::current_at_token(&self.textarea);
+ let Some(current_token) = current_opt else {
+ return;
+ };
+
+ if !current_token.starts_with(&query) {
+ return;
+ }
+
+ if let ActivePopup::File(popup) = &mut self.active_popup {
+ popup.set_matches(&query, matches);
+ }
+ }
+
+ pub fn set_ctrl_c_quit_hint(&mut self, show: bool, has_focus: bool) {
+ self.ctrl_c_quit_hint = show;
+ if show {
+ self.footer_mode = FooterMode::CtrlCReminder;
+ } else {
+ self.footer_mode = reset_mode_after_activity(self.footer_mode);
+ }
+ self.set_has_focus(has_focus);
+ }
+
+ fn next_large_paste_placeholder(&mut self, char_count: usize) -> String {
+ let base = format!("[Pasted Content {char_count} chars]");
+ let next_suffix = self.large_paste_counters.entry(char_count).or_insert(0);
+ *next_suffix += 1;
+ if *next_suffix == 1 {
+ base
+ } else {
+ format!("{base} #{next_suffix}")
+ }
+ }
+
+ pub(crate) fn insert_str(&mut self, text: &str) {
+ self.textarea.insert_str(text);
+ self.sync_popups();
+ }
+
+ /// Handle a key event coming from the main UI.
+ pub fn handle_key_event(&mut self, key_event: KeyEvent) -> (InputResult, bool) {
+ let result = match &mut self.active_popup {
+ ActivePopup::Command(_) => self.handle_key_event_with_slash_popup(key_event),
+ ActivePopup::File(_) => self.handle_key_event_with_file_popup(key_event),
+ ActivePopup::Skill(_) => self.handle_key_event_with_skill_popup(key_event),
+ ActivePopup::None => self.handle_key_event_without_popup(key_event),
+ };
+
+ // Update (or hide/show) popup after processing the key.
+ self.sync_popups();
+
+ result
+ }
+
+ /// Return true if either the slash-command popup or the file-search popup is active.
+ pub(crate) fn popup_active(&self) -> bool {
+ !matches!(self.active_popup, ActivePopup::None)
+ }
+
+ /// Handle key event when the slash-command popup is visible.
+ fn handle_key_event_with_slash_popup(&mut self, key_event: KeyEvent) -> (InputResult, bool) {
+ if self.handle_shortcut_overlay_key(&key_event) {
+ return (InputResult::None, true);
+ }
+ if key_event.code == KeyCode::Esc {
+ let next_mode = esc_hint_mode(self.footer_mode, self.is_task_running);
+ if next_mode != self.footer_mode {
+ self.footer_mode = next_mode;
+ return (InputResult::None, true);
+ }
+ } else {
+ self.footer_mode = reset_mode_after_activity(self.footer_mode);
+ }
+ let ActivePopup::Command(popup) = &mut self.active_popup else {
+ unreachable!();
+ };
+
+ match key_event {
+ KeyEvent {
+ code: KeyCode::Up, ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('p'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ popup.move_up();
+ (InputResult::None, true)
+ }
+ KeyEvent {
+ code: KeyCode::Down,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('n'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ popup.move_down();
+ (InputResult::None, true)
+ }
+ KeyEvent {
+ code: KeyCode::Esc, ..
+ } => {
+ // Dismiss the slash popup; keep the current input untouched.
+ self.active_popup = ActivePopup::None;
+ (InputResult::None, true)
+ }
+ KeyEvent {
+ code: KeyCode::Tab, ..
+ } => {
+ // Ensure popup filtering/selection reflects the latest composer text
+ // before applying completion.
+ let first_line = self.textarea.text().lines().next().unwrap_or("");
+ popup.on_composer_text_change(first_line.to_string());
+ if let Some(sel) = popup.selected_item() {
+ let mut cursor_target: Option<usize> = None;
+ match sel {
+ CommandItem::Builtin(cmd) => {
+ if cmd == SlashCommand::Skills {
+ self.textarea.set_text("");
+ return (InputResult::Command(cmd), true);
+ }
+
+ let starts_with_cmd = first_line
+ .trim_start()
+ .starts_with(&format!("/{}", cmd.command()));
+ if !starts_with_cmd {
+ self.textarea.set_text(&format!("/{} ", cmd.command()));
+ }
+ if !self.textarea.text().is_empty() {
+ cursor_target = Some(self.textarea.text().len());
+ }
+ }
+ CommandItem::UserPrompt(idx) => {
+ if let Some(prompt) = popup.prompt(idx) {
+ match prompt_selection_action(
+ prompt,
+ first_line,
+ PromptSelectionMode::Completion,
+ ) {
+ PromptSelectionAction::Insert { text, cursor } => {
+ let target = cursor.unwrap_or(text.len());
+ self.textarea.set_text(&text);
+ cursor_target = Some(target);
+ }
+ PromptSelectionAction::Submit { .. } => {}
+ }
+ }
+ }
+ }
+ if let Some(pos) = cursor_target {
+ self.textarea.set_cursor(pos);
+ }
+ }
+ (InputResult::None, true)
+ }
+ KeyEvent {
+ code: KeyCode::Enter,
+ modifiers: KeyModifiers::NONE,
+ ..
+ } => {
+ // If the current line starts with a custom prompt name and includes
+ // positional args for a numeric-style template, expand and submit
+ // immediately regardless of the popup selection.
+ let first_line = self.textarea.text().lines().next().unwrap_or("");
+ if let Some((name, _rest)) = parse_slash_name(first_line)
+ && let Some(prompt_name) = name.strip_prefix(&format!("{PROMPTS_CMD_PREFIX}:"))
+ && let Some(prompt) = self.custom_prompts.iter().find(|p| p.name == prompt_name)
+ && let Some(expanded) =
+ expand_if_numeric_with_positional_args(prompt, first_line)
+ {
+ self.textarea.set_text("");
+ return (InputResult::Submitted(expanded), true);
+ }
+
+ if let Some(sel) = popup.selected_item() {
+ match sel {
+ CommandItem::Builtin(cmd) => {
+ self.textarea.set_text("");
+ return (InputResult::Command(cmd), true);
+ }
+ CommandItem::UserPrompt(idx) => {
+ if let Some(prompt) = popup.prompt(idx) {
+ match prompt_selection_action(
+ prompt,
+ first_line,
+ PromptSelectionMode::Submit,
+ ) {
+ PromptSelectionAction::Submit { text } => {
+ self.textarea.set_text("");
+ return (InputResult::Submitted(text), true);
+ }
+ PromptSelectionAction::Insert { text, cursor } => {
+ let target = cursor.unwrap_or(text.len());
+ self.textarea.set_text(&text);
+ self.textarea.set_cursor(target);
+ return (InputResult::None, true);
+ }
+ }
+ }
+ return (InputResult::None, true);
+ }
+ }
+ }
+ // Fallback to default newline handling if no command selected.
+ self.handle_key_event_without_popup(key_event)
+ }
+ input => self.handle_input_basic(input),
+ }
+ }
+
+ #[inline]
+ fn clamp_to_char_boundary(text: &str, pos: usize) -> usize {
+ let mut p = pos.min(text.len());
+ if p < text.len() && !text.is_char_boundary(p) {
+ p = text
+ .char_indices()
+ .map(|(i, _)| i)
+ .take_while(|&i| i <= p)
+ .last()
+ .unwrap_or(0);
+ }
+ p
+ }
+
+ #[inline]
+ fn handle_non_ascii_char(&mut self, input: KeyEvent) -> (InputResult, bool) {
+ if let KeyEvent {
+ code: KeyCode::Char(ch),
+ ..
+ } = input
+ {
+ let now = Instant::now();
+ if self.paste_burst.try_append_char_if_active(ch, now) {
+ return (InputResult::None, true);
+ }
+ }
+ if let Some(pasted) = self.paste_burst.flush_before_modified_input() {
+ self.handle_paste(pasted);
+ }
+ self.textarea.input(input);
+ let text_after = self.textarea.text();
+ self.pending_pastes
+ .retain(|(placeholder, _)| text_after.contains(placeholder));
+ (InputResult::None, true)
+ }
+
+ /// Handle key events when file search popup is visible.
+ fn handle_key_event_with_file_popup(&mut self, key_event: KeyEvent) -> (InputResult, bool) {
+ if self.handle_shortcut_overlay_key(&key_event) {
+ return (InputResult::None, true);
+ }
+ if key_event.code == KeyCode::Esc {
+ let next_mode = esc_hint_mode(self.footer_mode, self.is_task_running);
+ if next_mode != self.footer_mode {
+ self.footer_mode = next_mode;
+ return (InputResult::None, true);
+ }
+ } else {
+ self.footer_mode = reset_mode_after_activity(self.footer_mode);
+ }
+ let ActivePopup::File(popup) = &mut self.active_popup else {
+ unreachable!();
+ };
+
+ match key_event {
+ KeyEvent {
+ code: KeyCode::Up, ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('p'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ popup.move_up();
+ (InputResult::None, true)
+ }
+ KeyEvent {
+ code: KeyCode::Down,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('n'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ popup.move_down();
+ (InputResult::None, true)
+ }
+ KeyEvent {
+ code: KeyCode::Esc, ..
+ } => {
+ // Hide popup without modifying text, remember token to avoid immediate reopen.
+ if let Some(tok) = Self::current_at_token(&self.textarea) {
+ self.dismissed_file_popup_token = Some(tok);
+ }
+ self.active_popup = ActivePopup::None;
+ (InputResult::None, true)
+ }
+ KeyEvent {
+ code: KeyCode::Tab, ..
+ }
+ | KeyEvent {
+ code: KeyCode::Enter,
+ modifiers: KeyModifiers::NONE,
+ ..
+ } => {
+ let Some(sel) = popup.selected_match() else {
+ self.active_popup = ActivePopup::None;
+ return (InputResult::None, true);
+ };
+
+ let sel_path = sel.to_string();
+ // If selected path looks like an image (png/jpeg), attach as image instead of inserting text.
+ let is_image = Self::is_image_path(&sel_path);
+ if is_image {
+ // Determine dimensions; if that fails fall back to normal path insertion.
+ let path_buf = PathBuf::from(&sel_path);
+ if let Ok((w, h)) = image::image_dimensions(&path_buf) {
+ // Remove the current @token (mirror logic from insert_selected_path without inserting text)
+ // using the flat text and byte-offset cursor API.
+ let cursor_offset = self.textarea.cursor();
+ let text = self.textarea.text();
+ // Clamp to a valid char boundary to avoid panics when slicing.
+ let safe_cursor = Self::clamp_to_char_boundary(text, cursor_offset);
+ let before_cursor = &text[..safe_cursor];
+ let after_cursor = &text[safe_cursor..];
+
+ // Determine token boundaries in the full text.
+ let start_idx = before_cursor
+ .char_indices()
+ .rfind(|(_, c)| c.is_whitespace())
+ .map(|(idx, c)| idx + c.len_utf8())
+ .unwrap_or(0);
+ let end_rel_idx = after_cursor
+ .char_indices()
+ .find(|(_, c)| c.is_whitespace())
+ .map(|(idx, _)| idx)
+ .unwrap_or(after_cursor.len());
+ let end_idx = safe_cursor + end_rel_idx;
+
+ self.textarea.replace_range(start_idx..end_idx, "");
+ self.textarea.set_cursor(start_idx);
+
+ let format_label = match Path::new(&sel_path)
+ .extension()
+ .and_then(|e| e.to_str())
+ .map(str::to_ascii_lowercase)
+ {
+ Some(ext) if ext == "png" => "PNG",
+ Some(ext) if ext == "jpg" || ext == "jpeg" => "JPEG",
+ _ => "IMG",
+ };
+ self.attach_image(path_buf, w, h, format_label);
+ // Add a trailing space to keep typing fluid.
+ self.textarea.insert_str(" ");
+ } else {
+ // Fallback to plain path insertion if metadata read fails.
+ self.insert_selected_path(&sel_path);
+ }
+ } else {
+ // Non-image: inserting file path.
+ self.insert_selected_path(&sel_path);
+ }
+ // No selection: treat Enter as closing the popup/session.
+ self.active_popup = ActivePopup::None;
+ (InputResult::None, true)
+ }
+ input => self.handle_input_basic(input),
+ }
+ }
+
+ fn handle_key_event_with_skill_popup(&mut self, key_event: KeyEvent) -> (InputResult, bool) {
+ if self.handle_shortcut_overlay_key(&key_event) {
+ return (InputResult::None, true);
+ }
+ if key_event.code == KeyCode::Esc {
+ let next_mode = esc_hint_mode(self.footer_mode, self.is_task_running);
+ if next_mode != self.footer_mode {
+ self.footer_mode = next_mode;
+ return (InputResult::None, true);
+ }
+ } else {
+ self.footer_mode = reset_mode_after_activity(self.footer_mode);
+ }
+
+ let ActivePopup::Skill(popup) = &mut self.active_popup else {
+ unreachable!();
+ };
+
+ match key_event {
+ KeyEvent {
+ code: KeyCode::Up, ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('p'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ popup.move_up();
+ (InputResult::None, true)
+ }
+ KeyEvent {
+ code: KeyCode::Down,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('n'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ popup.move_down();
+ (InputResult::None, true)
+ }
+ KeyEvent {
+ code: KeyCode::Esc, ..
+ } => {
+ if let Some(tok) = self.current_skill_token() {
+ self.dismissed_skill_popup_token = Some(tok);
+ }
+ self.active_popup = ActivePopup::None;
+ (InputResult::None, true)
+ }
+ KeyEvent {
+ code: KeyCode::Tab, ..
+ }
+ | KeyEvent {
+ code: KeyCode::Enter,
+ modifiers: KeyModifiers::NONE,
+ ..
+ } => {
+ let selected = popup.selected_skill().map(|skill| skill.name.clone());
+ if let Some(name) = selected {
+ self.insert_selected_skill(&name);
+ }
+ self.active_popup = ActivePopup::None;
+ (InputResult::None, true)
+ }
+ input => self.handle_input_basic(input),
+ }
+ }
+
+ fn is_image_path(path: &str) -> bool {
+ let lower = path.to_ascii_lowercase();
+ lower.ends_with(".png") || lower.ends_with(".jpg") || lower.ends_with(".jpeg")
+ }
+
+ fn skills_enabled(&self) -> bool {
+ self.skills.as_ref().is_some_and(|s| !s.is_empty())
+ }
+
+ /// Extract a token prefixed with `prefix` under the cursor, if any.
+ ///
+ /// The returned string **does not** include the prefix.
+ ///
+ /// Behavior:
+ /// - The cursor may be anywhere *inside* the token (including on the
+ /// leading prefix). It does **not** need to be at the end of the line.
+ /// - A token is delimited by ASCII whitespace (space, tab, newline).
+ /// - If the token under the cursor starts with `prefix`, that token is
+ /// returned without the leading prefix. When `allow_empty` is true, a
+ /// lone prefix character yields `Some(String::new())` to surface hints.
+ fn current_prefixed_token(
+ textarea: &TextArea,
+ prefix: char,
+ allow_empty: bool,
+ ) -> Option<String> {
+ let cursor_offset = textarea.cursor();
+ let text = textarea.text();
+
+ // Adjust the provided byte offset to the nearest valid char boundary at or before it.
+ let mut safe_cursor = cursor_offset.min(text.len());
+ // If we're not on a char boundary, move back to the start of the current char.
+ if safe_cursor < text.len() && !text.is_char_boundary(safe_cursor) {
+ // Find the last valid boundary <= cursor_offset.
+ safe_cursor = text
+ .char_indices()
+ .map(|(i, _)| i)
+ .take_while(|&i| i <= cursor_offset)
+ .last()
+ .unwrap_or(0);
+ }
+
+ // Split the line around the (now safe) cursor position.
+ let before_cursor = &text[..safe_cursor];
+ let after_cursor = &text[safe_cursor..];
+
+ // Detect whether we're on whitespace at the cursor boundary.
+ let at_whitespace = if safe_cursor < text.len() {
+ text[safe_cursor..]
+ .chars()
+ .next()
+ .map(char::is_whitespace)
+ .unwrap_or(false)
+ } else {
+ false
+ };
+
+ // Left candidate: token containing the cursor position.
+ let start_left = before_cursor
+ .char_indices()
+ .rfind(|(_, c)| c.is_whitespace())
+ .map(|(idx, c)| idx + c.len_utf8())
+ .unwrap_or(0);
+ let end_left_rel = after_cursor
+ .char_indices()
+ .find(|(_, c)| c.is_whitespace())
+ .map(|(idx, _)| idx)
+ .unwrap_or(after_cursor.len());
+ let end_left = safe_cursor + end_left_rel;
+ let token_left = if start_left < end_left {
+ Some(&text[start_left..end_left])
+ } else {
+ None
+ };
+
+ // Right candidate: token immediately after any whitespace from the cursor.
+ let ws_len_right: usize = after_cursor
+ .chars()
+ .take_while(|c| c.is_whitespace())
+ .map(char::len_utf8)
+ .sum();
+ let start_right = safe_cursor + ws_len_right;
+ let end_right_rel = text[start_right..]
+ .char_indices()
+ .find(|(_, c)| c.is_whitespace())
+ .map(|(idx, _)| idx)
+ .unwrap_or(text.len() - start_right);
+ let end_right = start_right + end_right_rel;
+ let token_right = if start_right < end_right {
+ Some(&text[start_right..end_right])
+ } else {
+ None
+ };
+
+ let prefix_str = prefix.to_string();
+ let left_match = token_left.filter(|t| t.starts_with(prefix));
+ let right_match = token_right.filter(|t| t.starts_with(prefix));
+
+ let left_prefixed = left_match.map(|t| t[prefix.len_utf8()..].to_string());
+ let right_prefixed = right_match.map(|t| t[prefix.len_utf8()..].to_string());
+
+ if at_whitespace {
+ if right_prefixed.is_some() {
+ return right_prefixed;
+ }
+ if token_left.is_some_and(|t| t == prefix_str) {
+ return allow_empty.then(String::new);
+ }
+ return left_prefixed;
+ }
+ if after_cursor.starts_with(prefix) {
+ return right_prefixed.or(left_prefixed);
+ }
+ left_prefixed.or(right_prefixed)
+ }
+
+ /// Extract the `@token` that the cursor is currently positioned on, if any.
+ ///
+ /// The returned string **does not** include the leading `@`.
+ fn current_at_token(textarea: &TextArea) -> Option<String> {
+ Self::current_prefixed_token(textarea, '@', false)
+ }
+
+ fn current_skill_token(&self) -> Option<String> {
+ if !self.skills_enabled() {
+ return None;
+ }
+ Self::current_prefixed_token(&self.textarea, '$', true)
+ }
+
+ /// Replace the active `@token` (the one under the cursor) with `path`.
+ ///
+ /// The algorithm mirrors `current_at_token` so replacement works no matter
+ /// where the cursor is within the token and regardless of how many
+ /// `@tokens` exist in the line.
+ fn insert_selected_path(&mut self, path: &str) {
+ let cursor_offset = self.textarea.cursor();
+ let text = self.textarea.text();
+ // Clamp to a valid char boundary to avoid panics when slicing.
+ let safe_cursor = Self::clamp_to_char_boundary(text, cursor_offset);
+
+ let before_cursor = &text[..safe_cursor];
+ let after_cursor = &text[safe_cursor..];
+
+ // Determine token boundaries.
+ let start_idx = before_cursor
+ .char_indices()
+ .rfind(|(_, c)| c.is_whitespace())
+ .map(|(idx, c)| idx + c.len_utf8())
+ .unwrap_or(0);
+
+ let end_rel_idx = after_cursor
+ .char_indices()
+ .find(|(_, c)| c.is_whitespace())
+ .map(|(idx, _)| idx)
+ .unwrap_or(after_cursor.len());
+ let end_idx = safe_cursor + end_rel_idx;
+
+ // If the path contains whitespace, wrap it in double quotes so the
+ // local prompt arg parser treats it as a single argument. Avoid adding
+ // quotes when the path already contains one to keep behavior simple.
+ let needs_quotes = path.chars().any(char::is_whitespace);
+ let inserted = if needs_quotes && !path.contains('"') {
+ format!("\"{path}\"")
+ } else {
+ path.to_string()
+ };
+
+ // Replace the slice `[start_idx, end_idx)` with the chosen path and a trailing space.
+ let mut new_text =
+ String::with_capacity(text.len() - (end_idx - start_idx) + inserted.len() + 1);
+ new_text.push_str(&text[..start_idx]);
+ new_text.push_str(&inserted);
+ new_text.push(' ');
+ new_text.push_str(&text[end_idx..]);
+
+ self.textarea.set_text(&new_text);
+ let new_cursor = start_idx.saturating_add(inserted.len()).saturating_add(1);
+ self.textarea.set_cursor(new_cursor);
+ }
+
+ fn insert_selected_skill(&mut self, skill_name: &str) {
+ let cursor_offset = self.textarea.cursor();
+ let text = self.textarea.text();
+ let safe_cursor = Self::clamp_to_char_boundary(text, cursor_offset);
+
+ let before_cursor = &text[..safe_cursor];
+ let after_cursor = &text[safe_cursor..];
+
+ let start_idx = before_cursor
+ .char_indices()
+ .rfind(|(_, c)| c.is_whitespace())
+ .map(|(idx, c)| idx + c.len_utf8())
+ .unwrap_or(0);
+
+ let end_rel_idx = after_cursor
+ .char_indices()
+ .find(|(_, c)| c.is_whitespace())
+ .map(|(idx, _)| idx)
+ .unwrap_or(after_cursor.len());
+ let end_idx = safe_cursor + end_rel_idx;
+
+ let inserted = format!("${skill_name}");
+
+ let mut new_text =
+ String::with_capacity(text.len() - (end_idx - start_idx) + inserted.len() + 1);
+ new_text.push_str(&text[..start_idx]);
+ new_text.push_str(&inserted);
+ new_text.push(' ');
+ new_text.push_str(&text[end_idx..]);
+
+ self.textarea.set_text(&new_text);
+ let new_cursor = start_idx.saturating_add(inserted.len()).saturating_add(1);
+ self.textarea.set_cursor(new_cursor);
+ }
+
+ /// Handle key event when no popup is visible.
+ fn handle_key_event_without_popup(&mut self, key_event: KeyEvent) -> (InputResult, bool) {
+ if self.handle_shortcut_overlay_key(&key_event) {
+ return (InputResult::None, true);
+ }
+ if key_event.code == KeyCode::Esc {
+ if self.is_empty() {
+ let next_mode = esc_hint_mode(self.footer_mode, self.is_task_running);
+ if next_mode != self.footer_mode {
+ self.footer_mode = next_mode;
+ return (InputResult::None, true);
+ }
+ }
+ } else {
+ self.footer_mode = reset_mode_after_activity(self.footer_mode);
+ }
+ match key_event {
+ KeyEvent {
+ code: KeyCode::Char('d'),
+ modifiers: crossterm::event::KeyModifiers::CONTROL,
+ kind: KeyEventKind::Press,
+ ..
+ } if self.is_empty() => {
+ self.app_event_tx.send(AppEvent::ExitRequest);
+ (InputResult::None, true)
+ }
+ // -------------------------------------------------------------
+ // History navigation (Up / Down) – only when the composer is not
+ // empty or when the cursor is at the correct position, to avoid
+ // interfering with normal cursor movement.
+ // -------------------------------------------------------------
+ KeyEvent {
+ code: KeyCode::Up | KeyCode::Down,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('p') | KeyCode::Char('n'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ if self
+ .history
+ .should_handle_navigation(self.textarea.text(), self.textarea.cursor())
+ {
+ let replace_text = match key_event.code {
+ KeyCode::Up => self.history.navigate_up(&self.app_event_tx),
+ KeyCode::Down => self.history.navigate_down(&self.app_event_tx),
+ KeyCode::Char('p') => self.history.navigate_up(&self.app_event_tx),
+ KeyCode::Char('n') => self.history.navigate_down(&self.app_event_tx),
+ _ => unreachable!(),
+ };
+ if let Some(text) = replace_text {
+ self.set_text_content(text);
+ return (InputResult::None, true);
+ }
+ }
+ self.handle_input_basic(key_event)
+ }
+ KeyEvent {
+ code: KeyCode::Enter,
+ modifiers: KeyModifiers::NONE,
+ ..
+ } => {
+ // If the first line is a bare built-in slash command (no args),
+ // dispatch it even when the slash popup isn't visible. This preserves
+ // the workflow: type a prefix ("/di"), press Tab to complete to
+ // "/diff ", then press Enter to run it. Tab moves the cursor beyond
+ // the '/name' token and our caret-based heuristic hides the popup,
+ // but Enter should still dispatch the command rather than submit
+ // literal text.
+ let first_line = self.textarea.text().lines().next().unwrap_or("");
+ if let Some((name, rest)) = parse_slash_name(first_line)
+ && rest.is_empty()
+ && let Some((_n, cmd)) = built_in_slash_commands()
+ .into_iter()
+ .find(|(n, _)| *n == name)
+ {
+ self.textarea.set_text("");
+ return (InputResult::Command(cmd), true);
+ }
+ // If we're in a paste-like burst capture, treat Enter as part of the burst
+ // and accumulate it rather than submitting or inserting immediately.
+ // Do not treat Enter as paste inside a slash-command context.
+ let in_slash_context = matches!(self.active_popup, ActivePopup::Command(_))
+ || self
+ .textarea
+ .text()
+ .lines()
+ .next()
+ .unwrap_or("")
+ .starts_with('/');
+ if self.paste_burst.is_active() && !in_slash_context {
+ let now = Instant::now();
+ if self.paste_burst.append_newline_if_active(now) {
+ return (InputResult::None, true);
+ }
+ }
+ // If we have pending placeholder pastes, replace them in the textarea text
+ // and continue to the normal submission flow to handle slash commands.
+ if !self.pending_pastes.is_empty() {
+ let mut text = self.textarea.text().to_string();
+ for (placeholder, actual) in &self.pending_pastes {
+ if text.contains(placeholder) {
+ text = text.replace(placeholder, actual);
+ }
+ }
+ self.textarea.set_text(&text);
+ self.pending_pastes.clear();
+ }
+
+ // During a paste-like burst, treat Enter as a newline instead of submit.
+ let now = Instant::now();
+ if self
+ .paste_burst
+ .newline_should_insert_instead_of_submit(now)
+ && !in_slash_context
+ {
+ self.textarea.insert_str("\n");
+ self.paste_burst.extend_window(now);
+ return (InputResult::None, true);
+ }
+ let mut text = self.textarea.text().to_string();
+ let original_input = text.clone();
+ let input_starts_with_space = original_input.starts_with(' ');
+ self.textarea.set_text("");
+
+ // Replace all pending pastes in the text
+ for (placeholder, actual) in &self.pending_pastes {
+ if text.contains(placeholder) {
+ text = text.replace(placeholder, actual);
+ }
+ }
+ self.pending_pastes.clear();
+
+ // If there is neither text nor attachments, suppress submission entirely.
+ let has_attachments = !self.attached_images.is_empty();
+ text = text.trim().to_string();
+ if let Some((name, _rest)) = parse_slash_name(&text) {
+ let treat_as_plain_text = input_starts_with_space || name.contains('/');
+ if !treat_as_plain_text {
+ let is_builtin = built_in_slash_commands()
+ .into_iter()
+ .any(|(command_name, _)| command_name == name);
+ let prompt_prefix = format!("{PROMPTS_CMD_PREFIX}:");
+ let is_known_prompt = name
+ .strip_prefix(&prompt_prefix)
+ .map(|prompt_name| {
+ self.custom_prompts
+ .iter()
+ .any(|prompt| prompt.name == prompt_name)
+ })
+ .unwrap_or(false);
+ if !is_builtin && !is_known_prompt {
+ let message = format!(
+ r#"Unrecognized command '/{name}'. Type "/" for a list of supported commands."#
+ );
+ self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
+ history_cell::new_info_event(message, None),
+ )));
+ self.textarea.set_text(&original_input);
+ self.textarea.set_cursor(original_input.len());
+ return (InputResult::None, true);
+ }
+ }
+ }
+
+ let expanded_prompt = match expand_custom_prompt(&text, &self.custom_prompts) {
+ Ok(expanded) => expanded,
+ Err(err) => {
+ self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
+ history_cell::new_error_event(err.user_message()),
+ )));
+ self.textarea.set_text(&original_input);
+ self.textarea.set_cursor(original_input.len());
+ return (InputResult::None, true);
+ }
+ };
+ if let Some(expanded) = expanded_prompt {
+ text = expanded;
+ }
+ if text.is_empty() && !has_attachments {
+ return (InputResult::None, true);
+ }
+ if !text.is_empty() {
+ self.history.record_local_submission(&text);
+ }
+ // Do not clear attached_images here; ChatWidget drains them via take_recent_submission_images().
+ (InputResult::Submitted(text), true)
+ }
+ input => self.handle_input_basic(input),
+ }
+ }
+
+ fn handle_paste_burst_flush(&mut self, now: Instant) -> bool {
+ match self.paste_burst.flush_if_due(now) {
+ FlushResult::Paste(pasted) => {
+ self.handle_paste(pasted);
+ true
+ }
+ FlushResult::Typed(ch) => {
+ // Mirror insert_str() behavior so popups stay in sync when a
+ // pending fast char flushes as normal typed input.
+ self.textarea.insert_str(ch.to_string().as_str());
+ self.sync_popups();
+ true
+ }
+ FlushResult::None => false,
+ }
+ }
+
+ /// Handle generic Input events that modify the textarea content.
+ fn handle_input_basic(&mut self, input: KeyEvent) -> (InputResult, bool) {
+ // If we have a buffered non-bracketed paste burst and enough time has
+ // elapsed since the last char, flush it before handling a new input.
+ let now = Instant::now();
+ self.handle_paste_burst_flush(now);
+
+ if !matches!(input.code, KeyCode::Esc) {
+ self.footer_mode = reset_mode_after_activity(self.footer_mode);
+ }
+
+ // If we're capturing a burst and receive Enter, accumulate it instead of inserting.
+ if matches!(input.code, KeyCode::Enter)
+ && self.paste_burst.is_active()
+ && self.paste_burst.append_newline_if_active(now)
+ {
+ return (InputResult::None, true);
+ }
+
+ // Intercept plain Char inputs to optionally accumulate into a burst buffer.
+ if let KeyEvent {
+ code: KeyCode::Char(ch),
+ modifiers,
+ ..
+ } = input
+ {
+ let has_ctrl_or_alt = has_ctrl_or_alt(modifiers);
+ if !has_ctrl_or_alt {
+ // Non-ASCII characters (e.g., from IMEs) can arrive in quick bursts and be
+ // misclassified by paste heuristics. Flush any active burst buffer and insert
+ // non-ASCII characters directly.
+ if !ch.is_ascii() {
+ return self.handle_non_ascii_char(input);
+ }
+
+ match self.paste_burst.on_plain_char(ch, now) {
+ CharDecision::BufferAppend => {
+ self.paste_burst.append_char_to_buffer(ch, now);
+ return (InputResult::None, true);
+ }
+ CharDecision::BeginBuffer { retro_chars } => {
+ let cur = self.textarea.cursor();
+ let txt = self.textarea.text();
+ let safe_cur = Self::clamp_to_char_boundary(txt, cur);
+ let before = &txt[..safe_cur];
+ if let Some(grab) =
+ self.paste_burst
+ .decide_begin_buffer(now, before, retro_chars as usize)
+ {
+ if !grab.grabbed.is_empty() {
+ self.textarea.replace_range(grab.start_byte..safe_cur, "");
+ }
+ self.paste_burst.begin_with_retro_grabbed(grab.grabbed, now);
+ self.paste_burst.append_char_to_buffer(ch, now);
+ return (InputResult::None, true);
+ }
+ // If decide_begin_buffer opted not to start buffering,
+ // fall through to normal insertion below.
+ }
+ CharDecision::BeginBufferFromPending => {
+ // First char was held; now append the current one.
+ self.paste_burst.append_char_to_buffer(ch, now);
+ return (InputResult::None, true);
+ }
+ CharDecision::RetainFirstChar => {
+ // Keep the first fast char pending momentarily.
+ return (InputResult::None, true);
+ }
+ }
+ }
+ if let Some(pasted) = self.paste_burst.flush_before_modified_input() {
+ self.handle_paste(pasted);
+ }
+ }
+
+ // For non-char inputs (or after flushing), handle normally.
+ // Special handling for backspace on placeholders
+ if let KeyEvent {
+ code: KeyCode::Backspace,
+ ..
+ } = input
+ && self.try_remove_any_placeholder_at_cursor()
+ {
+ return (InputResult::None, true);
+ }
+
+ // Normal input handling
+ self.textarea.input(input);
+ let text_after = self.textarea.text();
+
+ // Update paste-burst heuristic for plain Char (no Ctrl/Alt) events.
+ let crossterm::event::KeyEvent {
+ code, modifiers, ..
+ } = input;
+ match code {
+ KeyCode::Char(_) => {
+ let has_ctrl_or_alt = has_ctrl_or_alt(modifiers);
+ if has_ctrl_or_alt {
+ self.paste_burst.clear_window_after_non_char();
+ }
+ }
+ KeyCode::Enter => {
+ // Keep burst window alive (supports blank lines in paste).
+ }
+ _ => {
+ // Other keys: clear burst window (buffer should have been flushed above if needed).
+ self.paste_burst.clear_window_after_non_char();
+ }
+ }
+
+ // Check if any placeholders were removed and remove their corresponding pending pastes
+ self.pending_pastes
+ .retain(|(placeholder, _)| text_after.contains(placeholder));
+
+ // Keep attached images in proportion to how many matching placeholders exist in the text.
+ // This handles duplicate placeholders that share the same visible label.
+ if !self.attached_images.is_empty() {
+ let mut needed: HashMap<String, usize> = HashMap::new();
+ for img in &self.attached_images {
+ needed
+ .entry(img.placeholder.clone())
+ .or_insert_with(|| text_after.matches(&img.placeholder).count());
+ }
+
+ let mut used: HashMap<String, usize> = HashMap::new();
+ let mut kept: Vec<AttachedImage> = Vec::with_capacity(self.attached_images.len());
+ for img in self.attached_images.drain(..) {
+ let total_needed = *needed.get(&img.placeholder).unwrap_or(&0);
+ let used_count = used.entry(img.placeholder.clone()).or_insert(0);
+ if *used_count < total_needed {
+ kept.push(img);
+ *used_count += 1;
+ }
+ }
+ self.attached_images = kept;
+ }
+
+ (InputResult::None, true)
+ }
+
+ /// Attempts to remove an image or paste placeholder if the cursor is at the end of one.
+ /// Returns true if a placeholder was removed.
+ fn try_remove_any_placeholder_at_cursor(&mut self) -> bool {
+ // Clamp the cursor to a valid char boundary to avoid panics when slicing.
+ let text = self.textarea.text();
+ let p = Self::clamp_to_char_boundary(text, self.textarea.cursor());
+
+ // Try image placeholders first
+ let mut out: Option<(usize, String)> = None;
+ // Detect if the cursor is at the end of any image placeholder.
+ // If duplicates exist, remove the specific occurrence's mapping.
+ for (i, img) in self.attached_images.iter().enumerate() {
+ let ph = &img.placeholder;
+ if p < ph.len() {
+ continue;
+ }
+ let start = p - ph.len();
+ if text.get(start..p) != Some(ph.as_str()) {
+ continue;
+ }
+
+ // Count the number of occurrences of `ph` before `start`.
+ let mut occ_before = 0usize;
+ let mut search_pos = 0usize;
+ while search_pos < start {
+ let segment = match text.get(search_pos..start) {
+ Some(s) => s,
+ None => break,
+ };
+ if let Some(found) = segment.find(ph) {
+ occ_before += 1;
+ search_pos += found + ph.len();
+ } else {
+ break;
+ }
+ }
+
+ // Remove the occ_before-th attached image that shares this placeholder label.
+ out = if let Some((remove_idx, _)) = self
+ .attached_images
+ .iter()
+ .enumerate()
+ .filter(|(_, img2)| img2.placeholder == *ph)
+ .nth(occ_before)
+ {
+ Some((remove_idx, ph.clone()))
+ } else {
+ Some((i, ph.clone()))
+ };
+ break;
+ }
+ if let Some((idx, placeholder)) = out {
+ self.textarea.replace_range(p - placeholder.len()..p, "");
+ self.attached_images.remove(idx);
+ return true;
+ }
+
+ // Also handle when the cursor is at the START of an image placeholder.
+ // let result = 'out: {
+ let out: Option<(usize, String)> = 'out: {
+ for (i, img) in self.attached_images.iter().enumerate() {
+ let ph = &img.placeholder;
+ if p + ph.len() > text.len() {
+ continue;
+ }
+ if text.get(p..p + ph.len()) != Some(ph.as_str()) {
+ continue;
+ }
+
+ // Count occurrences of `ph` before `p`.
+ let mut occ_before = 0usize;
+ let mut search_pos = 0usize;
+ while search_pos < p {
+ let segment = match text.get(search_pos..p) {
+ Some(s) => s,
+ None => break 'out None,
+ };
+ if let Some(found) = segment.find(ph) {
+ occ_before += 1;
+ search_pos += found + ph.len();
+ } else {
+ break 'out None;
+ }
+ }
+
+ if let Some((remove_idx, _)) = self
+ .attached_images
+ .iter()
+ .enumerate()
+ .filter(|(_, img2)| img2.placeholder == *ph)
+ .nth(occ_before)
+ {
+ break 'out Some((remove_idx, ph.clone()));
+ } else {
+ break 'out Some((i, ph.clone()));
+ }
+ }
+ None
+ };
+
+ if let Some((idx, placeholder)) = out {
+ self.textarea.replace_range(p..p + placeholder.len(), "");
+ self.attached_images.remove(idx);
+ return true;
+ }
+
+ // Then try pasted-content placeholders
+ if let Some(placeholder) = self.pending_pastes.iter().find_map(|(ph, _)| {
+ if p < ph.len() {
+ return None;
+ }
+ let start = p - ph.len();
+ if text.get(start..p) == Some(ph.as_str()) {
+ Some(ph.clone())
+ } else {
+ None
+ }
+ }) {
+ self.textarea.replace_range(p - placeholder.len()..p, "");
+ self.pending_pastes.retain(|(ph, _)| ph != &placeholder);
+ return true;
+ }
+
+ // Also handle when the cursor is at the START of a pasted-content placeholder.
+ if let Some(placeholder) = self.pending_pastes.iter().find_map(|(ph, _)| {
+ if p + ph.len() > text.len() {
+ return None;
+ }
+ if text.get(p..p + ph.len()) == Some(ph.as_str()) {
+ Some(ph.clone())
+ } else {
+ None
+ }
+ }) {
+ self.textarea.replace_range(p..p + placeholder.len(), "");
+ self.pending_pastes.retain(|(ph, _)| ph != &placeholder);
+ return true;
+ }
+
+ false
+ }
+
+ fn handle_shortcut_overlay_key(&mut self, key_event: &KeyEvent) -> bool {
+ if key_event.kind != KeyEventKind::Press {
+ return false;
+ }
+
+ let toggles = matches!(key_event.code, KeyCode::Char('?'))
+ && !has_ctrl_or_alt(key_event.modifiers)
+ && self.is_empty();
+
+ if !toggles {
+ return false;
+ }
+
+ let next = toggle_shortcut_mode(self.footer_mode, self.ctrl_c_quit_hint);
+ let changed = next != self.footer_mode;
+ self.footer_mode = next;
+ changed
+ }
+
+ fn footer_props(&self) -> FooterProps {
+ FooterProps {
+ mode: self.footer_mode(),
+ esc_backtrack_hint: self.esc_backtrack_hint,
+ use_shift_enter_hint: self.use_shift_enter_hint,
+ is_task_running: self.is_task_running,
+ context_window_percent: self.context_window_percent,
+ context_window_used_tokens: self.context_window_used_tokens,
+ }
+ }
+
+ fn footer_mode(&self) -> FooterMode {
+ match self.footer_mode {
+ FooterMode::EscHint => FooterMode::EscHint,
+ FooterMode::ShortcutOverlay => FooterMode::ShortcutOverlay,
+ FooterMode::CtrlCReminder => FooterMode::CtrlCReminder,
+ FooterMode::ShortcutSummary if self.ctrl_c_quit_hint => FooterMode::CtrlCReminder,
+ FooterMode::ShortcutSummary if !self.is_empty() => FooterMode::ContextOnly,
+ other => other,
+ }
+ }
+
+ fn custom_footer_height(&self) -> Option<u16> {
+ self.footer_hint_override
+ .as_ref()
+ .map(|items| if items.is_empty() { 0 } else { 1 })
+ }
+
+ fn sync_popups(&mut self) {
+ let file_token = Self::current_at_token(&self.textarea);
+ let skill_token = self.current_skill_token();
+
+ let allow_command_popup = file_token.is_none() && skill_token.is_none();
+ self.sync_command_popup(allow_command_popup);
+
+ if matches!(self.active_popup, ActivePopup::Command(_)) {
+ self.dismissed_file_popup_token = None;
+ self.dismissed_skill_popup_token = None;
+ return;
+ }
+
+ if let Some(token) = skill_token {
+ self.sync_skill_popup(token);
+ return;
+ }
+ self.dismissed_skill_popup_token = None;
+
+ if let Some(token) = file_token {
+ self.sync_file_search_popup(token);
+ return;
+ }
+
+ self.dismissed_file_popup_token = None;
+ if matches!(
+ self.active_popup,
+ ActivePopup::File(_) | ActivePopup::Skill(_)
+ ) {
+ self.active_popup = ActivePopup::None;
+ }
+ }
+
+ /// If the cursor is currently within a slash command on the first line,
+ /// extract the command name and the rest of the line after it.
+ /// Returns None if the cursor is outside a slash command.
+ fn slash_command_under_cursor(first_line: &str, cursor: usize) -> Option<(&str, &str)> {
+ if !first_line.starts_with('/') {
+ return None;
+ }
+
+ let name_start = 1usize;
+ let name_end = first_line[name_start..]
+ .find(char::is_whitespace)
+ .map(|idx| name_start + idx)
+ .unwrap_or_else(|| first_line.len());
+
+ if cursor > name_end {
+ return None;
+ }
+
+ let name = &first_line[name_start..name_end];
+ let rest_start = first_line[name_end..]
+ .find(|c: char| !c.is_whitespace())
+ .map(|idx| name_end + idx)
+ .unwrap_or(name_end);
+ let rest = &first_line[rest_start..];
+
+ Some((name, rest))
+ }
+
+ /// Heuristic for whether the typed slash command looks like a valid
+ /// prefix for any known command (built-in or custom prompt).
+ /// Empty names only count when there is no extra content after the '/'.
+ fn looks_like_slash_prefix(&self, name: &str, rest_after_name: &str) -> bool {
+ if name.is_empty() {
+ return rest_after_name.is_empty();
+ }
+
+ let builtin_match = built_in_slash_commands()
+ .into_iter()
+ .any(|(cmd_name, _)| cmd_name.starts_with(name));
+
+ if builtin_match {
+ return true;
+ }
+
+ let prompt_prefix = format!("{PROMPTS_CMD_PREFIX}:");
+ self.custom_prompts
+ .iter()
+ .any(|p| format!("{prompt_prefix}{}", p.name).starts_with(name))
+ }
+
+ /// Synchronize `self.command_popup` with the current text in the
+ /// textarea. This must be called after every modification that can change
+ /// the text so the popup is shown/updated/hidden as appropriate.
+ fn sync_command_popup(&mut self, allow: bool) {
+ if !allow {
+ if matches!(self.active_popup, ActivePopup::Command(_)) {
+ self.active_popup = ActivePopup::None;
+ }
+ return;
+ }
+ // Determine whether the caret is inside the initial '/name' token on the first line.
+ let text = self.textarea.text();
+ let first_line_end = text.find('\n').unwrap_or(text.len());
+ let first_line = &text[..first_line_end];
+ let cursor = self.textarea.cursor();
+ let caret_on_first_line = cursor <= first_line_end;
+
+ let is_editing_slash_command_name = caret_on_first_line
+ && Self::slash_command_under_cursor(first_line, cursor)
+ .is_some_and(|(name, rest)| self.looks_like_slash_prefix(name, rest));
+
+ // If the cursor is currently positioned within an `@token`, prefer the
+ // file-search popup over the slash popup so users can insert a file path
+ // as an argument to the command (e.g., "/review @docs/...").
+ if Self::current_at_token(&self.textarea).is_some() {
+ if matches!(self.active_popup, ActivePopup::Command(_)) {
+ self.active_popup = ActivePopup::None;
+ }
+ return;
+ }
+ match &mut self.active_popup {
+ ActivePopup::Command(popup) => {
+ if is_editing_slash_command_name {
+ popup.on_composer_text_change(first_line.to_string());
+ } else {
+ self.active_popup = ActivePopup::None;
+ }
+ }
+ _ => {
+ if is_editing_slash_command_name {
+ let skills_enabled = self.skills_enabled();
+ let mut command_popup =
+ CommandPopup::new(self.custom_prompts.clone(), skills_enabled);
+ command_popup.on_composer_text_change(first_line.to_string());
+ self.active_popup = ActivePopup::Command(command_popup);
+ }
+ }
+ }
+ }
+
+ pub(crate) fn set_custom_prompts(&mut self, prompts: Vec<CustomPrompt>) {
+ self.custom_prompts = prompts.clone();
+ if let ActivePopup::Command(popup) = &mut self.active_popup {
+ popup.set_prompts(prompts);
+ }
+ }
+
+ /// Synchronize `self.file_search_popup` with the current text in the textarea.
+ /// Note this is only called when self.active_popup is NOT Command.
+ fn sync_file_search_popup(&mut self, query: String) {
+ // If user dismissed popup for this exact query, don't reopen until text changes.
+ if self.dismissed_file_popup_token.as_ref() == Some(&query) {
+ return;
+ }
+
+ if !query.is_empty() {
+ self.app_event_tx
+ .send(AppEvent::StartFileSearch(query.clone()));
+ }
+
+ match &mut self.active_popup {
+ ActivePopup::File(popup) => {
+ if query.is_empty() {
+ popup.set_empty_prompt();
+ } else {
+ popup.set_query(&query);
+ }
+ }
+ _ => {
+ let mut popup = FileSearchPopup::new();
+ if query.is_empty() {
+ popup.set_empty_prompt();
+ } else {
+ popup.set_query(&query);
+ }
+ self.active_popup = ActivePopup::File(popup);
+ }
+ }
+
+ self.current_file_query = Some(query);
+ self.dismissed_file_popup_token = None;
+ }
+
+ fn sync_skill_popup(&mut self, query: String) {
+ if self.dismissed_skill_popup_token.as_ref() == Some(&query) {
+ return;
+ }
+
+ let skills = match self.skills.as_ref() {
+ Some(skills) if !skills.is_empty() => skills.clone(),
+ _ => {
+ self.active_popup = ActivePopup::None;
+ return;
+ }
+ };
+
+ match &mut self.active_popup {
+ ActivePopup::Skill(popup) => {
+ popup.set_query(&query);
+ popup.set_skills(skills);
+ }
+ _ => {
+ let mut popup = SkillPopup::new(skills);
+ popup.set_query(&query);
+ self.active_popup = ActivePopup::Skill(popup);
+ }
+ }
+ }
+
+ fn set_has_focus(&mut self, has_focus: bool) {
+ self.has_focus = has_focus;
+ }
+
+ pub fn set_task_running(&mut self, running: bool) {
+ self.is_task_running = running;
+ }
+
+ pub(crate) fn set_context_window(&mut self, percent: Option<i64>, used_tokens: Option<i64>) {
+ if self.context_window_percent == percent && self.context_window_used_tokens == used_tokens
+ {
+ return;
+ }
+ self.context_window_percent = percent;
+ self.context_window_used_tokens = used_tokens;
+ }
+
+ pub(crate) fn set_esc_backtrack_hint(&mut self, show: bool) {
+ self.esc_backtrack_hint = show;
+ if show {
+ self.footer_mode = esc_hint_mode(self.footer_mode, self.is_task_running);
+ } else {
+ self.footer_mode = reset_mode_after_activity(self.footer_mode);
+ }
+ }
+}
+
+impl Renderable for ChatComposer {
+ fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ let [_, textarea_rect, _] = self.layout_areas(area);
+ let state = *self.textarea_state.borrow();
+ self.textarea.cursor_pos_with_state(textarea_rect, state)
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ let footer_props = self.footer_props();
+ let footer_hint_height = self
+ .custom_footer_height()
+ .unwrap_or_else(|| footer_height(footer_props));
+ let footer_spacing = Self::footer_spacing(footer_hint_height);
+ let footer_total_height = footer_hint_height + footer_spacing;
+ const COLS_WITH_MARGIN: u16 = LIVE_PREFIX_COLS + 1;
+ self.textarea
+ .desired_height(width.saturating_sub(COLS_WITH_MARGIN))
+ + 2
+ + match &self.active_popup {
+ ActivePopup::None => footer_total_height,
+ ActivePopup::Command(c) => c.calculate_required_height(width),
+ ActivePopup::File(c) => c.calculate_required_height(),
+ ActivePopup::Skill(c) => c.calculate_required_height(width),
+ }
+ }
+
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ let [composer_rect, textarea_rect, popup_rect] = self.layout_areas(area);
+ match &self.active_popup {
+ ActivePopup::Command(popup) => {
+ popup.render_ref(popup_rect, buf);
+ }
+ ActivePopup::File(popup) => {
+ popup.render_ref(popup_rect, buf);
+ }
+ ActivePopup::Skill(popup) => {
+ popup.render_ref(popup_rect, buf);
+ }
+ ActivePopup::None => {
+ let footer_props = self.footer_props();
+ let custom_height = self.custom_footer_height();
+ let footer_hint_height =
+ custom_height.unwrap_or_else(|| footer_height(footer_props));
+ let footer_spacing = Self::footer_spacing(footer_hint_height);
+ let hint_rect = if footer_spacing > 0 && footer_hint_height > 0 {
+ let [_, hint_rect] = Layout::vertical([
+ Constraint::Length(footer_spacing),
+ Constraint::Length(footer_hint_height),
+ ])
+ .areas(popup_rect);
+ hint_rect
+ } else {
+ popup_rect
+ };
+ if let Some(items) = self.footer_hint_override.as_ref() {
+ if !items.is_empty() {
+ let mut spans = Vec::with_capacity(items.len() * 4);
+ for (idx, (key, label)) in items.iter().enumerate() {
+ spans.push(" ".into());
+ spans.push(Span::styled(key.clone(), Style::default().bold()));
+ spans.push(format!(" {label}").into());
+ if idx + 1 != items.len() {
+ spans.push(" ".into());
+ }
+ }
+ let mut custom_rect = hint_rect;
+ if custom_rect.width > 2 {
+ custom_rect.x += 2;
+ custom_rect.width = custom_rect.width.saturating_sub(2);
+ }
+ Line::from(spans).render_ref(custom_rect, buf);
+ }
+ } else {
+ render_footer(hint_rect, buf, footer_props);
+ }
+ }
+ }
+ let style = user_message_style();
+ Block::default().style(style).render_ref(composer_rect, buf);
+ if !textarea_rect.is_empty() {
+ buf.set_span(
+ textarea_rect.x - LIVE_PREFIX_COLS,
+ textarea_rect.y,
+ &"›".bold(),
+ textarea_rect.width,
+ );
+ }
+
+ let mut state = self.textarea_state.borrow_mut();
+ StatefulWidgetRef::render_ref(&(&self.textarea), textarea_rect, buf, &mut state);
+ if self.textarea.text().is_empty() {
+ let placeholder = Span::from(self.placeholder_text.as_str()).dim();
+ Line::from(vec![placeholder]).render_ref(textarea_rect.inner(Margin::new(0, 0)), buf);
+ }
+ }
+}
+
+fn prompt_selection_action(
+ prompt: &CustomPrompt,
+ first_line: &str,
+ mode: PromptSelectionMode,
+) -> PromptSelectionAction {
+ let named_args = prompt_argument_names(&prompt.content);
+ let has_numeric = prompt_has_numeric_placeholders(&prompt.content);
+
+ match mode {
+ PromptSelectionMode::Completion => {
+ if !named_args.is_empty() {
+ let (text, cursor) =
+ prompt_command_with_arg_placeholders(&prompt.name, &named_args);
+ return PromptSelectionAction::Insert {
+ text,
+ cursor: Some(cursor),
+ };
+ }
+ if has_numeric {
+ let text = format!("/{PROMPTS_CMD_PREFIX}:{} ", prompt.name);
+ return PromptSelectionAction::Insert { text, cursor: None };
+ }
+ let text = format!("/{PROMPTS_CMD_PREFIX}:{}", prompt.name);
+ PromptSelectionAction::Insert { text, cursor: None }
+ }
+ PromptSelectionMode::Submit => {
+ if !named_args.is_empty() {
+ let (text, cursor) =
+ prompt_command_with_arg_placeholders(&prompt.name, &named_args);
+ return PromptSelectionAction::Insert {
+ text,
+ cursor: Some(cursor),
+ };
+ }
+ if has_numeric {
+ if let Some(expanded) = expand_if_numeric_with_positional_args(prompt, first_line) {
+ return PromptSelectionAction::Submit { text: expanded };
+ }
+ let text = format!("/{PROMPTS_CMD_PREFIX}:{} ", prompt.name);
+ return PromptSelectionAction::Insert { text, cursor: None };
+ }
+ PromptSelectionAction::Submit {
+ text: prompt.content.clone(),
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use image::ImageBuffer;
+ use image::Rgba;
+ use pretty_assertions::assert_eq;
+ use std::path::PathBuf;
+ use tempfile::tempdir;
+
+ use crate::app_event::AppEvent;
+ use crate::bottom_pane::AppEventSender;
+ use crate::bottom_pane::ChatComposer;
+ use crate::bottom_pane::InputResult;
+ use crate::bottom_pane::chat_composer::AttachedImage;
+ use crate::bottom_pane::chat_composer::LARGE_PASTE_CHAR_THRESHOLD;
+ use crate::bottom_pane::prompt_args::extract_positional_args_for_prompt_line;
+ use crate::bottom_pane::textarea::TextArea;
+ use tokio::sync::mpsc::unbounded_channel;
+
+ #[test]
+ fn footer_hint_row_is_separated_from_composer() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let area = Rect::new(0, 0, 40, 6);
+ let mut buf = Buffer::empty(area);
+ composer.render(area, &mut buf);
+
+ let row_to_string = |y: u16| {
+ let mut row = String::new();
+ for x in 0..area.width {
+ row.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
+ }
+ row
+ };
+
+ let mut hint_row: Option<(u16, String)> = None;
+ for y in 0..area.height {
+ let row = row_to_string(y);
+ if row.contains("? for shortcuts") {
+ hint_row = Some((y, row));
+ break;
+ }
+ }
+
+ let (hint_row_idx, hint_row_contents) =
+ hint_row.expect("expected footer hint row to be rendered");
+ assert_eq!(
+ hint_row_idx,
+ area.height - 1,
+ "hint row should occupy the bottom line: {hint_row_contents:?}",
+ );
+
+ assert!(
+ hint_row_idx > 0,
+ "expected a spacing row above the footer hints",
+ );
+
+ let spacing_row = row_to_string(hint_row_idx - 1);
+ assert_eq!(
+ spacing_row.trim(),
+ "",
+ "expected blank spacing row above hints but saw: {spacing_row:?}",
+ );
+ }
+
+ fn snapshot_composer_state<F>(name: &str, enhanced_keys_supported: bool, setup: F)
+ where
+ F: FnOnce(&mut ChatComposer),
+ {
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+
+ let width = 100;
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ enhanced_keys_supported,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+ setup(&mut composer);
+ let footer_props = composer.footer_props();
+ let footer_lines = footer_height(footer_props);
+ let footer_spacing = ChatComposer::footer_spacing(footer_lines);
+ let height = footer_lines + footer_spacing + 8;
+ let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
+ terminal
+ .draw(|f| composer.render(f.area(), f.buffer_mut()))
+ .unwrap();
+ insta::assert_snapshot!(name, terminal.backend());
+ }
+
+ #[test]
+ fn footer_mode_snapshots() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ snapshot_composer_state("footer_mode_shortcut_overlay", true, |composer| {
+ composer.set_esc_backtrack_hint(true);
+ let _ =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
+ });
+
+ snapshot_composer_state("footer_mode_ctrl_c_quit", true, |composer| {
+ composer.set_ctrl_c_quit_hint(true, true);
+ });
+
+ snapshot_composer_state("footer_mode_ctrl_c_interrupt", true, |composer| {
+ composer.set_task_running(true);
+ composer.set_ctrl_c_quit_hint(true, true);
+ });
+
+ snapshot_composer_state("footer_mode_ctrl_c_then_esc_hint", true, |composer| {
+ composer.set_ctrl_c_quit_hint(true, true);
+ let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+ });
+
+ snapshot_composer_state("footer_mode_esc_hint_from_overlay", true, |composer| {
+ let _ =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
+ let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+ });
+
+ snapshot_composer_state("footer_mode_esc_hint_backtrack", true, |composer| {
+ composer.set_esc_backtrack_hint(true);
+ let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+ });
+
+ snapshot_composer_state(
+ "footer_mode_overlay_then_external_esc_hint",
+ true,
+ |composer| {
+ let _ = composer
+ .handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
+ composer.set_esc_backtrack_hint(true);
+ },
+ );
+
+ snapshot_composer_state("footer_mode_hidden_while_typing", true, |composer| {
+ type_chars_humanlike(composer, &['h']);
+ });
+ }
+
+ #[test]
+ fn esc_hint_stays_hidden_with_draft_content() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ true,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ type_chars_humanlike(&mut composer, &['d']);
+
+ assert!(!composer.is_empty());
+ assert_eq!(composer.current_text(), "d");
+ assert_eq!(composer.footer_mode, FooterMode::ShortcutSummary);
+ assert!(matches!(composer.active_popup, ActivePopup::None));
+
+ let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+
+ assert_eq!(composer.footer_mode, FooterMode::ShortcutSummary);
+ assert!(!composer.esc_backtrack_hint);
+ }
+
+ #[test]
+ fn clear_for_ctrl_c_records_cleared_draft() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.set_text_content("draft text".to_string());
+ assert_eq!(composer.clear_for_ctrl_c(), Some("draft text".to_string()));
+ assert!(composer.is_empty());
+
+ assert_eq!(
+ composer.history.navigate_up(&composer.app_event_tx),
+ Some("draft text".to_string())
+ );
+ }
+
+ #[test]
+ fn question_mark_only_toggles_on_first_char() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let (result, needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
+ assert_eq!(result, InputResult::None);
+ assert!(needs_redraw, "toggling overlay should request redraw");
+ assert_eq!(composer.footer_mode, FooterMode::ShortcutOverlay);
+
+ // Toggle back to prompt mode so subsequent typing captures characters.
+ let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
+ assert_eq!(composer.footer_mode, FooterMode::ShortcutSummary);
+
+ type_chars_humanlike(&mut composer, &['h']);
+ assert_eq!(composer.textarea.text(), "h");
+ assert_eq!(composer.footer_mode(), FooterMode::ContextOnly);
+
+ let (result, needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
+ assert_eq!(result, InputResult::None);
+ assert!(needs_redraw, "typing should still mark the view dirty");
+ std::thread::sleep(ChatComposer::recommended_paste_flush_delay());
+ let _ = composer.flush_paste_burst_if_due();
+ assert_eq!(composer.textarea.text(), "h?");
+ assert_eq!(composer.footer_mode, FooterMode::ShortcutSummary);
+ assert_eq!(composer.footer_mode(), FooterMode::ContextOnly);
+ }
+
+ #[test]
+ fn shortcut_overlay_persists_while_task_running() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE));
+ assert_eq!(composer.footer_mode, FooterMode::ShortcutOverlay);
+
+ composer.set_task_running(true);
+
+ assert_eq!(composer.footer_mode, FooterMode::ShortcutOverlay);
+ assert_eq!(composer.footer_mode(), FooterMode::ShortcutOverlay);
+ }
+
+ #[test]
+ fn test_current_at_token_basic_cases() {
+ let test_cases = vec![
+ // Valid @ tokens
+ ("@hello", 3, Some("hello".to_string()), "Basic ASCII token"),
+ (
+ "@file.txt",
+ 4,
+ Some("file.txt".to_string()),
+ "ASCII with extension",
+ ),
+ (
+ "hello @world test",
+ 8,
+ Some("world".to_string()),
+ "ASCII token in middle",
+ ),
+ (
+ "@test123",
+ 5,
+ Some("test123".to_string()),
+ "ASCII with numbers",
+ ),
+ // Unicode examples
+ ("@İstanbul", 3, Some("İstanbul".to_string()), "Turkish text"),
+ (
+ "@testЙЦУ.rs",
+ 8,
+ Some("testЙЦУ.rs".to_string()),
+ "Mixed ASCII and Cyrillic",
+ ),
+ ("@诶", 2, Some("诶".to_string()), "Chinese character"),
+ ("@👍", 2, Some("👍".to_string()), "Emoji token"),
+ // Invalid cases (should return None)
+ ("hello", 2, None, "No @ symbol"),
+ (
+ "@",
+ 1,
+ Some("".to_string()),
+ "Only @ symbol triggers empty query",
+ ),
+ ("@ hello", 2, None, "@ followed by space"),
+ ("test @ world", 6, None, "@ with spaces around"),
+ ];
+
+ for (input, cursor_pos, expected, description) in test_cases {
+ let mut textarea = TextArea::new();
+ textarea.insert_str(input);
+ textarea.set_cursor(cursor_pos);
+
+ let result = ChatComposer::current_at_token(&textarea);
+ assert_eq!(
+ result, expected,
+ "Failed for case: {description} - input: '{input}', cursor: {cursor_pos}"
+ );
+ }
+ }
+
+ #[test]
+ fn test_current_at_token_cursor_positions() {
+ let test_cases = vec![
+ // Different cursor positions within a token
+ ("@test", 0, Some("test".to_string()), "Cursor at @"),
+ ("@test", 1, Some("test".to_string()), "Cursor after @"),
+ ("@test", 5, Some("test".to_string()), "Cursor at end"),
+ // Multiple tokens - cursor determines which token
+ ("@file1 @file2", 0, Some("file1".to_string()), "First token"),
+ (
+ "@file1 @file2",
+ 8,
+ Some("file2".to_string()),
+ "Second token",
+ ),
+ // Edge cases
+ ("@", 0, Some("".to_string()), "Only @ symbol"),
+ ("@a", 2, Some("a".to_string()), "Single character after @"),
+ ("", 0, None, "Empty input"),
+ ];
+
+ for (input, cursor_pos, expected, description) in test_cases {
+ let mut textarea = TextArea::new();
+ textarea.insert_str(input);
+ textarea.set_cursor(cursor_pos);
+
+ let result = ChatComposer::current_at_token(&textarea);
+ assert_eq!(
+ result, expected,
+ "Failed for cursor position case: {description} - input: '{input}', cursor: {cursor_pos}",
+ );
+ }
+ }
+
+ #[test]
+ fn test_current_at_token_whitespace_boundaries() {
+ let test_cases = vec![
+ // Space boundaries
+ (
+ "aaa@aaa",
+ 4,
+ None,
+ "Connected @ token - no completion by design",
+ ),
+ (
+ "aaa @aaa",
+ 5,
+ Some("aaa".to_string()),
+ "@ token after space",
+ ),
+ (
+ "test @file.txt",
+ 7,
+ Some("file.txt".to_string()),
+ "@ token after space",
+ ),
+ // Full-width space boundaries
+ (
+ "test @İstanbul",
+ 8,
+ Some("İstanbul".to_string()),
+ "@ token after full-width space",
+ ),
+ (
+ "@ЙЦУ @诶",
+ 10,
+ Some("诶".to_string()),
+ "Full-width space between Unicode tokens",
+ ),
+ // Tab and newline boundaries
+ (
+ "test\t@file",
+ 6,
+ Some("file".to_string()),
+ "@ token after tab",
+ ),
+ ];
+
+ for (input, cursor_pos, expected, description) in test_cases {
+ let mut textarea = TextArea::new();
+ textarea.insert_str(input);
+ textarea.set_cursor(cursor_pos);
+
+ let result = ChatComposer::current_at_token(&textarea);
+ assert_eq!(
+ result, expected,
+ "Failed for whitespace boundary case: {description} - input: '{input}', cursor: {cursor_pos}",
+ );
+ }
+ }
+
+ #[test]
+ fn ascii_prefix_survives_non_ascii_followup() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('1'), KeyModifiers::NONE));
+ assert!(composer.is_in_paste_burst());
+
+ let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char('あ'), KeyModifiers::NONE));
+
+ let (result, _) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ match result {
+ InputResult::Submitted(text) => assert_eq!(text, "1あ"),
+ _ => panic!("expected Submitted"),
+ }
+ }
+
+ #[test]
+ fn handle_paste_small_inserts_text() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let needs_redraw = composer.handle_paste("hello".to_string());
+ assert!(needs_redraw);
+ assert_eq!(composer.textarea.text(), "hello");
+ assert!(composer.pending_pastes.is_empty());
+
+ let (result, _) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ match result {
+ InputResult::Submitted(text) => assert_eq!(text, "hello"),
+ _ => panic!("expected Submitted"),
+ }
+ }
+
+ #[test]
+ fn empty_enter_returns_none() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Ensure composer is empty and press Enter.
+ assert!(composer.textarea.text().is_empty());
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ match result {
+ InputResult::None => {}
+ other => panic!("expected None for empty enter, got: {other:?}"),
+ }
+ }
+
+ #[test]
+ fn handle_paste_large_uses_placeholder_and_replaces_on_submit() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let large = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 10);
+ let needs_redraw = composer.handle_paste(large.clone());
+ assert!(needs_redraw);
+ let placeholder = format!("[Pasted Content {} chars]", large.chars().count());
+ assert_eq!(composer.textarea.text(), placeholder);
+ assert_eq!(composer.pending_pastes.len(), 1);
+ assert_eq!(composer.pending_pastes[0].0, placeholder);
+ assert_eq!(composer.pending_pastes[0].1, large);
+
+ let (result, _) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ match result {
+ InputResult::Submitted(text) => assert_eq!(text, large),
+ _ => panic!("expected Submitted"),
+ }
+ assert!(composer.pending_pastes.is_empty());
+ }
+
+ #[test]
+ fn edit_clears_pending_paste() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let large = "y".repeat(LARGE_PASTE_CHAR_THRESHOLD + 1);
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.handle_paste(large);
+ assert_eq!(composer.pending_pastes.len(), 1);
+
+ // Any edit that removes the placeholder should clear pending_paste
+ composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+ assert!(composer.pending_pastes.is_empty());
+ }
+
+ #[test]
+ fn ui_snapshots() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut terminal = match Terminal::new(TestBackend::new(100, 10)) {
+ Ok(t) => t,
+ Err(e) => panic!("Failed to create terminal: {e}"),
+ };
+
+ let test_cases = vec![
+ ("empty", None),
+ ("small", Some("short".to_string())),
+ ("large", Some("z".repeat(LARGE_PASTE_CHAR_THRESHOLD + 5))),
+ ("multiple_pastes", None),
+ ("backspace_after_pastes", None),
+ ];
+
+ for (name, input) in test_cases {
+ // Create a fresh composer for each test case
+ let mut composer = ChatComposer::new(
+ true,
+ sender.clone(),
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ if let Some(text) = input {
+ composer.handle_paste(text);
+ } else if name == "multiple_pastes" {
+ // First large paste
+ composer.handle_paste("x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 3));
+ // Second large paste
+ composer.handle_paste("y".repeat(LARGE_PASTE_CHAR_THRESHOLD + 7));
+ // Small paste
+ composer.handle_paste(" another short paste".to_string());
+ } else if name == "backspace_after_pastes" {
+ // Three large pastes
+ composer.handle_paste("a".repeat(LARGE_PASTE_CHAR_THRESHOLD + 2));
+ composer.handle_paste("b".repeat(LARGE_PASTE_CHAR_THRESHOLD + 4));
+ composer.handle_paste("c".repeat(LARGE_PASTE_CHAR_THRESHOLD + 6));
+ // Move cursor to end and press backspace
+ composer.textarea.set_cursor(composer.textarea.text().len());
+ composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+ }
+
+ terminal
+ .draw(|f| composer.render(f.area(), f.buffer_mut()))
+ .unwrap_or_else(|e| panic!("Failed to draw {name} composer: {e}"));
+
+ insta::assert_snapshot!(name, terminal.backend());
+ }
+ }
+
+ #[test]
+ fn slash_popup_model_first_for_mo_ui() {
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Type "/mo" humanlike so paste-burst doesn’t interfere.
+ type_chars_humanlike(&mut composer, &['/', 'm', 'o']);
+
+ let mut terminal = match Terminal::new(TestBackend::new(60, 5)) {
+ Ok(t) => t,
+ Err(e) => panic!("Failed to create terminal: {e}"),
+ };
+ terminal
+ .draw(|f| composer.render(f.area(), f.buffer_mut()))
+ .unwrap_or_else(|e| panic!("Failed to draw composer: {e}"));
+
+ // Visual snapshot should show the slash popup with /model as the first entry.
+ insta::assert_snapshot!("slash_popup_mo", terminal.backend());
+ }
+
+ #[test]
+ fn slash_popup_model_first_for_mo_logic() {
+ use super::super::command_popup::CommandItem;
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+ type_chars_humanlike(&mut composer, &['/', 'm', 'o']);
+
+ match &composer.active_popup {
+ ActivePopup::Command(popup) => match popup.selected_item() {
+ Some(CommandItem::Builtin(cmd)) => {
+ assert_eq!(cmd.command(), "model")
+ }
+ Some(CommandItem::UserPrompt(_)) => {
+ panic!("unexpected prompt selected for '/mo'")
+ }
+ None => panic!("no selected command for '/mo'"),
+ },
+ _ => panic!("slash popup not active after typing '/mo'"),
+ }
+ }
+
+ #[test]
+ fn slash_popup_resume_for_res_ui() {
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Type "/res" humanlike so paste-burst doesn’t interfere.
+ type_chars_humanlike(&mut composer, &['/', 'r', 'e', 's']);
+
+ let mut terminal = Terminal::new(TestBackend::new(60, 6)).expect("terminal");
+ terminal
+ .draw(|f| composer.render(f.area(), f.buffer_mut()))
+ .expect("draw composer");
+
+ // Snapshot should show /resume as the first entry for /res.
+ insta::assert_snapshot!("slash_popup_res", terminal.backend());
+ }
+
+ #[test]
+ fn slash_popup_resume_for_res_logic() {
+ use super::super::command_popup::CommandItem;
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+ type_chars_humanlike(&mut composer, &['/', 'r', 'e', 's']);
+
+ match &composer.active_popup {
+ ActivePopup::Command(popup) => match popup.selected_item() {
+ Some(CommandItem::Builtin(cmd)) => {
+ assert_eq!(cmd.command(), "resume")
+ }
+ Some(CommandItem::UserPrompt(_)) => {
+ panic!("unexpected prompt selected for '/res'")
+ }
+ None => panic!("no selected command for '/res'"),
+ },
+ _ => panic!("slash popup not active after typing '/res'"),
+ }
+ }
+
+ // Test helper: simulate human typing with a brief delay and flush the paste-burst buffer
+ fn type_chars_humanlike(composer: &mut ChatComposer, chars: &[char]) {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+ for &ch in chars {
+ let _ = composer.handle_key_event(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE));
+ std::thread::sleep(ChatComposer::recommended_paste_flush_delay());
+ let _ = composer.flush_paste_burst_if_due();
+ }
+ }
+
+ #[test]
+ fn slash_init_dispatches_command_and_does_not_submit_literal_text() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Type the slash command.
+ type_chars_humanlike(&mut composer, &['/', 'i', 'n', 'i', 't']);
+
+ // Press Enter to dispatch the selected command.
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ // When a slash command is dispatched, the composer should return a
+ // Command result (not submit literal text) and clear its textarea.
+ match result {
+ InputResult::Command(cmd) => {
+ assert_eq!(cmd.command(), "init");
+ }
+ InputResult::Submitted(text) => {
+ panic!("expected command dispatch, but composer submitted literal text: {text}")
+ }
+ InputResult::None => panic!("expected Command result for '/init'"),
+ }
+ assert!(composer.textarea.is_empty(), "composer should be cleared");
+ }
+
+ #[test]
+ fn extract_args_supports_quoted_paths_single_arg() {
+ let args = extract_positional_args_for_prompt_line(
+ "/prompts:review \"docs/My File.md\"",
+ "review",
+ );
+ assert_eq!(args, vec!["docs/My File.md".to_string()]);
+ }
+
+ #[test]
+ fn extract_args_supports_mixed_quoted_and_unquoted() {
+ let args =
+ extract_positional_args_for_prompt_line("/prompts:cmd \"with spaces\" simple", "cmd");
+ assert_eq!(args, vec!["with spaces".to_string(), "simple".to_string()]);
+ }
+
+ #[test]
+ fn slash_tab_completion_moves_cursor_to_end() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ type_chars_humanlike(&mut composer, &['/', 'c']);
+
+ let (_result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
+
+ assert_eq!(composer.textarea.text(), "/compact ");
+ assert_eq!(composer.textarea.cursor(), composer.textarea.text().len());
+ }
+
+ #[test]
+ fn slash_tab_then_enter_dispatches_builtin_command() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Type a prefix and complete with Tab, which inserts a trailing space
+ // and moves the cursor beyond the '/name' token (hides the popup).
+ type_chars_humanlike(&mut composer, &['/', 'd', 'i']);
+ let (_res, _redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
+ assert_eq!(composer.textarea.text(), "/diff ");
+
+ // Press Enter: should dispatch the command, not submit literal text.
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ match result {
+ InputResult::Command(cmd) => assert_eq!(cmd.command(), "diff"),
+ InputResult::Submitted(text) => {
+ panic!("expected command dispatch after Tab completion, got literal submit: {text}")
+ }
+ InputResult::None => panic!("expected Command result for '/diff'"),
+ }
+ assert!(composer.textarea.is_empty());
+ }
+
+ #[test]
+ fn slash_mention_dispatches_command_and_inserts_at() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ type_chars_humanlike(&mut composer, &['/', 'm', 'e', 'n', 't', 'i', 'o', 'n']);
+
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ match result {
+ InputResult::Command(cmd) => {
+ assert_eq!(cmd.command(), "mention");
+ }
+ InputResult::Submitted(text) => {
+ panic!("expected command dispatch, but composer submitted literal text: {text}")
+ }
+ InputResult::None => panic!("expected Command result for '/mention'"),
+ }
+ assert!(composer.textarea.is_empty(), "composer should be cleared");
+ composer.insert_str("@");
+ assert_eq!(composer.textarea.text(), "@");
+ }
+
+ #[test]
+ fn test_multiple_pastes_submission() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Define test cases: (paste content, is_large)
+ let test_cases = [
+ ("x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 3), true),
+ (" and ".to_string(), false),
+ ("y".repeat(LARGE_PASTE_CHAR_THRESHOLD + 7), true),
+ ];
+
+ // Expected states after each paste
+ let mut expected_text = String::new();
+ let mut expected_pending_count = 0;
+
+ // Apply all pastes and build expected state
+ let states: Vec<_> = test_cases
+ .iter()
+ .map(|(content, is_large)| {
+ composer.handle_paste(content.clone());
+ if *is_large {
+ let placeholder = format!("[Pasted Content {} chars]", content.chars().count());
+ expected_text.push_str(&placeholder);
+ expected_pending_count += 1;
+ } else {
+ expected_text.push_str(content);
+ }
+ (expected_text.clone(), expected_pending_count)
+ })
+ .collect();
+
+ // Verify all intermediate states were correct
+ assert_eq!(
+ states,
+ vec![
+ (
+ format!("[Pasted Content {} chars]", test_cases[0].0.chars().count()),
+ 1
+ ),
+ (
+ format!(
+ "[Pasted Content {} chars] and ",
+ test_cases[0].0.chars().count()
+ ),
+ 1
+ ),
+ (
+ format!(
+ "[Pasted Content {} chars] and [Pasted Content {} chars]",
+ test_cases[0].0.chars().count(),
+ test_cases[2].0.chars().count()
+ ),
+ 2
+ ),
+ ]
+ );
+
+ // Submit and verify final expansion
+ let (result, _) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ if let InputResult::Submitted(text) = result {
+ assert_eq!(text, format!("{} and {}", test_cases[0].0, test_cases[2].0));
+ } else {
+ panic!("expected Submitted");
+ }
+ }
+
+ #[test]
+ fn test_placeholder_deletion() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Define test cases: (content, is_large)
+ let test_cases = [
+ ("a".repeat(LARGE_PASTE_CHAR_THRESHOLD + 5), true),
+ (" and ".to_string(), false),
+ ("b".repeat(LARGE_PASTE_CHAR_THRESHOLD + 6), true),
+ ];
+
+ // Apply all pastes
+ let mut current_pos = 0;
+ let states: Vec<_> = test_cases
+ .iter()
+ .map(|(content, is_large)| {
+ composer.handle_paste(content.clone());
+ if *is_large {
+ let placeholder = format!("[Pasted Content {} chars]", content.chars().count());
+ current_pos += placeholder.len();
+ } else {
+ current_pos += content.len();
+ }
+ (
+ composer.textarea.text().to_string(),
+ composer.pending_pastes.len(),
+ current_pos,
+ )
+ })
+ .collect();
+
+ // Delete placeholders one by one and collect states
+ let mut deletion_states = vec![];
+
+ // First deletion
+ composer.textarea.set_cursor(states[0].2);
+ composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+ deletion_states.push((
+ composer.textarea.text().to_string(),
+ composer.pending_pastes.len(),
+ ));
+
+ // Second deletion
+ composer.textarea.set_cursor(composer.textarea.text().len());
+ composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+ deletion_states.push((
+ composer.textarea.text().to_string(),
+ composer.pending_pastes.len(),
+ ));
+
+ // Verify all states
+ assert_eq!(
+ deletion_states,
+ vec![
+ (" and [Pasted Content 1006 chars]".to_string(), 1),
+ (" and ".to_string(), 0),
+ ]
+ );
+ }
+
+ #[test]
+ fn deleting_duplicate_length_pastes_removes_only_target() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let paste = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 4);
+ let placeholder_base = format!("[Pasted Content {} chars]", paste.chars().count());
+ let placeholder_second = format!("{placeholder_base} #2");
+
+ composer.handle_paste(paste.clone());
+ composer.handle_paste(paste.clone());
+ assert_eq!(
+ composer.textarea.text(),
+ format!("{placeholder_base}{placeholder_second}")
+ );
+ assert_eq!(composer.pending_pastes.len(), 2);
+
+ composer.textarea.set_cursor(composer.textarea.text().len());
+ composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+
+ assert_eq!(composer.textarea.text(), placeholder_base);
+ assert_eq!(composer.pending_pastes.len(), 1);
+ assert_eq!(composer.pending_pastes[0].0, placeholder_base);
+ assert_eq!(composer.pending_pastes[0].1, paste);
+ }
+
+ #[test]
+ fn large_paste_numbering_does_not_reuse_after_deletion() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let paste = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 4);
+ let base = format!("[Pasted Content {} chars]", paste.chars().count());
+ let second = format!("{base} #2");
+ let third = format!("{base} #3");
+
+ composer.handle_paste(paste.clone());
+ composer.handle_paste(paste.clone());
+ assert_eq!(composer.textarea.text(), format!("{base}{second}"));
+
+ composer.textarea.set_cursor(base.len());
+ composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+ assert_eq!(composer.textarea.text(), second);
+ assert_eq!(composer.pending_pastes.len(), 1);
+ assert_eq!(composer.pending_pastes[0].0, second);
+
+ composer.textarea.set_cursor(composer.textarea.text().len());
+ composer.handle_paste(paste);
+
+ assert_eq!(composer.textarea.text(), format!("{second}{third}"));
+ assert_eq!(composer.pending_pastes.len(), 2);
+ assert_eq!(composer.pending_pastes[0].0, second);
+ assert_eq!(composer.pending_pastes[1].0, third);
+ }
+
+ #[test]
+ fn test_partial_placeholder_deletion() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Define test cases: (cursor_position_from_end, expected_pending_count)
+ let test_cases = [
+ 5, // Delete from middle - should clear tracking
+ 0, // Delete from end - should clear tracking
+ ];
+
+ let paste = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 4);
+ let placeholder = format!("[Pasted Content {} chars]", paste.chars().count());
+
+ let states: Vec<_> = test_cases
+ .into_iter()
+ .map(|pos_from_end| {
+ composer.handle_paste(paste.clone());
+ composer
+ .textarea
+ .set_cursor(placeholder.len() - pos_from_end);
+ composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+ let result = (
+ composer.textarea.text().contains(&placeholder),
+ composer.pending_pastes.len(),
+ );
+ composer.textarea.set_text("");
+ result
+ })
+ .collect();
+
+ assert_eq!(
+ states,
+ vec![
+ (false, 0), // After deleting from middle
+ (false, 0), // After deleting from end
+ ]
+ );
+ }
+
+ // --- Image attachment tests ---
+ #[test]
+ fn attach_image_and_submit_includes_image_paths() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+ let path = PathBuf::from("/tmp/image1.png");
+ composer.attach_image(path.clone(), 32, 16, "PNG");
+ composer.handle_paste(" hi".into());
+ let (result, _) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ match result {
+ InputResult::Submitted(text) => assert_eq!(text, "[image1.png 32x16] hi"),
+ _ => panic!("expected Submitted"),
+ }
+ let imgs = composer.take_recent_submission_images();
+ assert_eq!(vec![path], imgs);
+ }
+
+ #[test]
+ fn attach_image_without_text_submits_empty_text_and_images() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+ let path = PathBuf::from("/tmp/image2.png");
+ composer.attach_image(path.clone(), 10, 5, "PNG");
+ let (result, _) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ match result {
+ InputResult::Submitted(text) => assert_eq!(text, "[image2.png 10x5]"),
+ _ => panic!("expected Submitted"),
+ }
+ let imgs = composer.take_recent_submission_images();
+ assert_eq!(imgs.len(), 1);
+ assert_eq!(imgs[0], path);
+ assert!(composer.attached_images.is_empty());
+ }
+
+ #[test]
+ fn image_placeholder_backspace_behaves_like_text_placeholder() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+ let path = PathBuf::from("/tmp/image3.png");
+ composer.attach_image(path.clone(), 20, 10, "PNG");
+ let placeholder = composer.attached_images[0].placeholder.clone();
+
+ // Case 1: backspace at end
+ composer.textarea.move_cursor_to_end_of_line(false);
+ composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+ assert!(!composer.textarea.text().contains(&placeholder));
+ assert!(composer.attached_images.is_empty());
+
+ // Re-add and test backspace in middle: should break the placeholder string
+ // and drop the image mapping (same as text placeholder behavior).
+ composer.attach_image(path, 20, 10, "PNG");
+ let placeholder2 = composer.attached_images[0].placeholder.clone();
+ // Move cursor to roughly middle of placeholder
+ if let Some(start_pos) = composer.textarea.text().find(&placeholder2) {
+ let mid_pos = start_pos + (placeholder2.len() / 2);
+ composer.textarea.set_cursor(mid_pos);
+ composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+ assert!(!composer.textarea.text().contains(&placeholder2));
+ assert!(composer.attached_images.is_empty());
+ } else {
+ panic!("Placeholder not found in textarea");
+ }
+ }
+
+ #[test]
+ fn backspace_with_multibyte_text_before_placeholder_does_not_panic() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Insert an image placeholder at the start
+ let path = PathBuf::from("/tmp/image_multibyte.png");
+ composer.attach_image(path, 10, 5, "PNG");
+ // Add multibyte text after the placeholder
+ composer.textarea.insert_str("日本語");
+
+ // Cursor is at end; pressing backspace should delete the last character
+ // without panicking and leave the placeholder intact.
+ composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+
+ assert_eq!(composer.attached_images.len(), 1);
+ assert!(
+ composer
+ .textarea
+ .text()
+ .starts_with("[image_multibyte.png 10x5]")
+ );
+ }
+
+ #[test]
+ fn deleting_one_of_duplicate_image_placeholders_removes_matching_entry() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let path1 = PathBuf::from("/tmp/image_dup1.png");
+ let path2 = PathBuf::from("/tmp/image_dup2.png");
+
+ composer.attach_image(path1, 10, 5, "PNG");
+ // separate placeholders with a space for clarity
+ composer.handle_paste(" ".into());
+ composer.attach_image(path2.clone(), 10, 5, "PNG");
+
+ let placeholder1 = composer.attached_images[0].placeholder.clone();
+ let placeholder2 = composer.attached_images[1].placeholder.clone();
+ let text = composer.textarea.text().to_string();
+ let start1 = text.find(&placeholder1).expect("first placeholder present");
+ let end1 = start1 + placeholder1.len();
+ composer.textarea.set_cursor(end1);
+
+ // Backspace should delete the first placeholder and its mapping.
+ composer.handle_key_event(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
+
+ let new_text = composer.textarea.text().to_string();
+ assert_eq!(
+ 0,
+ new_text.matches(&placeholder1).count(),
+ "first placeholder removed"
+ );
+ assert_eq!(
+ 1,
+ new_text.matches(&placeholder2).count(),
+ "second placeholder remains"
+ );
+ assert_eq!(
+ vec![AttachedImage {
+ path: path2,
+ placeholder: "[image_dup2.png 10x5]".to_string()
+ }],
+ composer.attached_images,
+ "one image mapping remains"
+ );
+ }
+
+ #[test]
+ fn pasting_filepath_attaches_image() {
+ let tmp = tempdir().expect("create TempDir");
+ let tmp_path: PathBuf = tmp.path().join("codex_tui_test_paste_image.png");
+ let img: ImageBuffer<Rgba<u8>, Vec<u8>> =
+ ImageBuffer::from_fn(3, 2, |_x, _y| Rgba([1, 2, 3, 255]));
+ img.save(&tmp_path).expect("failed to write temp png");
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let needs_redraw = composer.handle_paste(tmp_path.to_string_lossy().to_string());
+ assert!(needs_redraw);
+ assert!(
+ composer
+ .textarea
+ .text()
+ .starts_with("[codex_tui_test_paste_image.png 3x2] ")
+ );
+
+ let imgs = composer.take_recent_submission_images();
+ assert_eq!(imgs, vec![tmp_path]);
+ }
+
+ #[test]
+ fn selecting_custom_prompt_without_args_submits_content() {
+ let prompt_text = "Hello from saved prompt";
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Inject prompts as if received via event.
+ composer.set_custom_prompts(vec![CustomPrompt {
+ name: "my-prompt".to_string(),
+ path: "/tmp/my-prompt.md".to_string().into(),
+ content: prompt_text.to_string(),
+ description: None,
+ argument_hint: None,
+ }]);
+
+ type_chars_humanlike(
+ &mut composer,
+ &[
+ '/', 'p', 'r', 'o', 'm', 'p', 't', 's', ':', 'm', 'y', '-', 'p', 'r', 'o', 'm',
+ 'p', 't',
+ ],
+ );
+
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ assert_eq!(InputResult::Submitted(prompt_text.to_string()), result);
+ assert!(composer.textarea.is_empty());
+ }
+
+ #[test]
+ fn custom_prompt_submission_expands_arguments() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.set_custom_prompts(vec![CustomPrompt {
+ name: "my-prompt".to_string(),
+ path: "/tmp/my-prompt.md".to_string().into(),
+ content: "Review $USER changes on $BRANCH".to_string(),
+ description: None,
+ argument_hint: None,
+ }]);
+
+ composer
+ .textarea
+ .set_text("/prompts:my-prompt USER=Alice BRANCH=main");
+
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ assert_eq!(
+ InputResult::Submitted("Review Alice changes on main".to_string()),
+ result
+ );
+ assert!(composer.textarea.is_empty());
+ }
+
+ #[test]
+ fn custom_prompt_submission_accepts_quoted_values() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.set_custom_prompts(vec![CustomPrompt {
+ name: "my-prompt".to_string(),
+ path: "/tmp/my-prompt.md".to_string().into(),
+ content: "Pair $USER with $BRANCH".to_string(),
+ description: None,
+ argument_hint: None,
+ }]);
+
+ composer
+ .textarea
+ .set_text("/prompts:my-prompt USER=\"Alice Smith\" BRANCH=dev-main");
+
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ assert_eq!(
+ InputResult::Submitted("Pair Alice Smith with dev-main".to_string()),
+ result
+ );
+ assert!(composer.textarea.is_empty());
+ }
+
+ #[test]
+ fn custom_prompt_with_large_paste_expands_correctly() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Create a custom prompt with positional args (no named args like $USER)
+ composer.set_custom_prompts(vec![CustomPrompt {
+ name: "code-review".to_string(),
+ path: "/tmp/code-review.md".to_string().into(),
+ content: "Please review the following code:\n\n$1".to_string(),
+ description: None,
+ argument_hint: None,
+ }]);
+
+ // Type the slash command
+ let command_text = "/prompts:code-review ";
+ composer.textarea.set_text(command_text);
+ composer.textarea.set_cursor(command_text.len());
+
+ // Paste large content (>3000 chars) to trigger placeholder
+ let large_content = "x".repeat(LARGE_PASTE_CHAR_THRESHOLD + 3000);
+ composer.handle_paste(large_content.clone());
+
+ // Verify placeholder was created
+ let placeholder = format!("[Pasted Content {} chars]", large_content.chars().count());
+ assert_eq!(
+ composer.textarea.text(),
+ format!("/prompts:code-review {}", placeholder)
+ );
+ assert_eq!(composer.pending_pastes.len(), 1);
+ assert_eq!(composer.pending_pastes[0].0, placeholder);
+ assert_eq!(composer.pending_pastes[0].1, large_content);
+
+ // Submit by pressing Enter
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ // Verify the custom prompt was expanded with the large content as positional arg
+ match result {
+ InputResult::Submitted(text) => {
+ // The prompt should be expanded, with the large content replacing $1
+ assert_eq!(
+ text,
+ format!("Please review the following code:\n\n{}", large_content),
+ "Expected prompt expansion with large content as $1"
+ );
+ }
+ _ => panic!("expected Submitted, got: {result:?}"),
+ }
+ assert!(composer.textarea.is_empty());
+ assert!(composer.pending_pastes.is_empty());
+ }
+
+ #[test]
+ fn slash_path_input_submits_without_command_error() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, mut rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer
+ .textarea
+ .set_text("/Users/example/project/src/main.rs");
+
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ if let InputResult::Submitted(text) = result {
+ assert_eq!(text, "/Users/example/project/src/main.rs");
+ } else {
+ panic!("expected Submitted");
+ }
+ assert!(composer.textarea.is_empty());
+ match rx.try_recv() {
+ Ok(event) => panic!("unexpected event: {event:?}"),
+ Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {}
+ Err(err) => panic!("unexpected channel state: {err:?}"),
+ }
+ }
+
+ #[test]
+ fn slash_with_leading_space_submits_as_text() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, mut rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.textarea.set_text(" /this-looks-like-a-command");
+
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ if let InputResult::Submitted(text) = result {
+ assert_eq!(text, "/this-looks-like-a-command");
+ } else {
+ panic!("expected Submitted");
+ }
+ assert!(composer.textarea.is_empty());
+ match rx.try_recv() {
+ Ok(event) => panic!("unexpected event: {event:?}"),
+ Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {}
+ Err(err) => panic!("unexpected channel state: {err:?}"),
+ }
+ }
+
+ #[test]
+ fn custom_prompt_invalid_args_reports_error() {
+ let (tx, mut rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.set_custom_prompts(vec![CustomPrompt {
+ name: "my-prompt".to_string(),
+ path: "/tmp/my-prompt.md".to_string().into(),
+ content: "Review $USER changes".to_string(),
+ description: None,
+ argument_hint: None,
+ }]);
+
+ composer
+ .textarea
+ .set_text("/prompts:my-prompt USER=Alice stray");
+
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ assert_eq!(InputResult::None, result);
+ assert_eq!(
+ "/prompts:my-prompt USER=Alice stray",
+ composer.textarea.text()
+ );
+
+ let mut found_error = false;
+ while let Ok(event) = rx.try_recv() {
+ if let AppEvent::InsertHistoryCell(cell) = event {
+ let message = cell
+ .display_lines(80)
+ .into_iter()
+ .map(|line| line.to_string())
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(message.contains("expected key=value"));
+ found_error = true;
+ break;
+ }
+ }
+ assert!(found_error, "expected error history cell to be sent");
+ }
+
+ #[test]
+ fn custom_prompt_missing_required_args_reports_error() {
+ let (tx, mut rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.set_custom_prompts(vec![CustomPrompt {
+ name: "my-prompt".to_string(),
+ path: "/tmp/my-prompt.md".to_string().into(),
+ content: "Review $USER changes on $BRANCH".to_string(),
+ description: None,
+ argument_hint: None,
+ }]);
+
+ // Provide only one of the required args
+ composer.textarea.set_text("/prompts:my-prompt USER=Alice");
+
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ assert_eq!(InputResult::None, result);
+ assert_eq!("/prompts:my-prompt USER=Alice", composer.textarea.text());
+
+ let mut found_error = false;
+ while let Ok(event) = rx.try_recv() {
+ if let AppEvent::InsertHistoryCell(cell) = event {
+ let message = cell
+ .display_lines(80)
+ .into_iter()
+ .map(|line| line.to_string())
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert!(message.to_lowercase().contains("missing required args"));
+ assert!(message.contains("BRANCH"));
+ found_error = true;
+ break;
+ }
+ }
+ assert!(
+ found_error,
+ "expected missing args error history cell to be sent"
+ );
+ }
+
+ #[test]
+ fn selecting_custom_prompt_with_args_expands_placeholders() {
+ // Support $1..$9 and $ARGUMENTS in prompt content.
+ let prompt_text = "Header: $1\nArgs: $ARGUMENTS\nNinth: $9\n";
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.set_custom_prompts(vec![CustomPrompt {
+ name: "my-prompt".to_string(),
+ path: "/tmp/my-prompt.md".to_string().into(),
+ content: prompt_text.to_string(),
+ description: None,
+ argument_hint: None,
+ }]);
+
+ // Type the slash command with two args and hit Enter to submit.
+ type_chars_humanlike(
+ &mut composer,
+ &[
+ '/', 'p', 'r', 'o', 'm', 'p', 't', 's', ':', 'm', 'y', '-', 'p', 'r', 'o', 'm',
+ 'p', 't', ' ', 'f', 'o', 'o', ' ', 'b', 'a', 'r',
+ ],
+ );
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ let expected = "Header: foo\nArgs: foo bar\nNinth: \n".to_string();
+ assert_eq!(InputResult::Submitted(expected), result);
+ }
+
+ #[test]
+ fn numeric_prompt_positional_args_does_not_error() {
+ // Ensure that a prompt with only numeric placeholders does not trigger
+ // key=value parsing errors when given positional arguments.
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.set_custom_prompts(vec![CustomPrompt {
+ name: "elegant".to_string(),
+ path: "/tmp/elegant.md".to_string().into(),
+ content: "Echo: $ARGUMENTS".to_string(),
+ description: None,
+ argument_hint: None,
+ }]);
+
+ // Type positional args; should submit with numeric expansion, no errors.
+ composer.textarea.set_text("/prompts:elegant hi");
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ assert_eq!(InputResult::Submitted("Echo: hi".to_string()), result);
+ assert!(composer.textarea.is_empty());
+ }
+
+ #[test]
+ fn selecting_custom_prompt_with_no_args_inserts_template() {
+ let prompt_text = "X:$1 Y:$2 All:[$ARGUMENTS]";
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.set_custom_prompts(vec![CustomPrompt {
+ name: "p".to_string(),
+ path: "/tmp/p.md".to_string().into(),
+ content: prompt_text.to_string(),
+ description: None,
+ argument_hint: None,
+ }]);
+
+ type_chars_humanlike(
+ &mut composer,
+ &['/', 'p', 'r', 'o', 'm', 'p', 't', 's', ':', 'p'],
+ );
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ // With no args typed, selecting the prompt inserts the command template
+ // and does not submit immediately.
+ assert_eq!(InputResult::None, result);
+ assert_eq!("/prompts:p ", composer.textarea.text());
+ }
+
+ #[test]
+ fn selecting_custom_prompt_preserves_literal_dollar_dollar() {
+ // '$$' should remain untouched.
+ let prompt_text = "Cost: $$ and first: $1";
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.set_custom_prompts(vec![CustomPrompt {
+ name: "price".to_string(),
+ path: "/tmp/price.md".to_string().into(),
+ content: prompt_text.to_string(),
+ description: None,
+ argument_hint: None,
+ }]);
+
+ type_chars_humanlike(
+ &mut composer,
+ &[
+ '/', 'p', 'r', 'o', 'm', 'p', 't', 's', ':', 'p', 'r', 'i', 'c', 'e', ' ', 'x',
+ ],
+ );
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ assert_eq!(
+ InputResult::Submitted("Cost: $$ and first: x".to_string()),
+ result
+ );
+ }
+
+ #[test]
+ fn selecting_custom_prompt_reuses_cached_arguments_join() {
+ let prompt_text = "First: $ARGUMENTS\nSecond: $ARGUMENTS";
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ composer.set_custom_prompts(vec![CustomPrompt {
+ name: "repeat".to_string(),
+ path: "/tmp/repeat.md".to_string().into(),
+ content: prompt_text.to_string(),
+ description: None,
+ argument_hint: None,
+ }]);
+
+ type_chars_humanlike(
+ &mut composer,
+ &[
+ '/', 'p', 'r', 'o', 'm', 'p', 't', 's', ':', 'r', 'e', 'p', 'e', 'a', 't', ' ',
+ 'o', 'n', 'e', ' ', 't', 'w', 'o',
+ ],
+ );
+ let (result, _needs_redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ let expected = "First: one two\nSecond: one two".to_string();
+ assert_eq!(InputResult::Submitted(expected), result);
+ }
+
+ #[test]
+ fn burst_paste_fast_small_buffers_and_flushes_on_stop() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let count = 32;
+ for _ in 0..count {
+ let _ =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE));
+ assert!(
+ composer.is_in_paste_burst(),
+ "expected active paste burst during fast typing"
+ );
+ assert!(
+ composer.textarea.text().is_empty(),
+ "text should not appear during burst"
+ );
+ }
+
+ assert!(
+ composer.textarea.text().is_empty(),
+ "text should remain empty until flush"
+ );
+ std::thread::sleep(ChatComposer::recommended_paste_flush_delay());
+ let flushed = composer.flush_paste_burst_if_due();
+ assert!(flushed, "expected buffered text to flush after stop");
+ assert_eq!(composer.textarea.text(), "a".repeat(count));
+ assert!(
+ composer.pending_pastes.is_empty(),
+ "no placeholder for small burst"
+ );
+ }
+
+ #[test]
+ fn burst_paste_fast_large_inserts_placeholder_on_flush() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let count = LARGE_PASTE_CHAR_THRESHOLD + 1; // > threshold to trigger placeholder
+ for _ in 0..count {
+ let _ =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
+ }
+
+ // Nothing should appear until we stop and flush
+ assert!(composer.textarea.text().is_empty());
+ std::thread::sleep(ChatComposer::recommended_paste_flush_delay());
+ let flushed = composer.flush_paste_burst_if_due();
+ assert!(flushed, "expected flush after stopping fast input");
+
+ let expected_placeholder = format!("[Pasted Content {count} chars]");
+ assert_eq!(composer.textarea.text(), expected_placeholder);
+ assert_eq!(composer.pending_pastes.len(), 1);
+ assert_eq!(composer.pending_pastes[0].0, expected_placeholder);
+ assert_eq!(composer.pending_pastes[0].1.len(), count);
+ assert!(composer.pending_pastes[0].1.chars().all(|c| c == 'x'));
+ }
+
+ #[test]
+ fn humanlike_typing_1000_chars_appears_live_no_placeholder() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ let count = LARGE_PASTE_CHAR_THRESHOLD; // 1000 in current config
+ let chars: Vec<char> = vec!['z'; count];
+ type_chars_humanlike(&mut composer, &chars);
+
+ assert_eq!(composer.textarea.text(), "z".repeat(count));
+ assert!(composer.pending_pastes.is_empty());
+ }
+
+ #[test]
+ fn slash_popup_not_activated_for_slash_space_text_history_like_input() {
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+ use tokio::sync::mpsc::unbounded_channel;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Simulate history-like content: "/ test"
+ composer.set_text_content("/ test".to_string());
+
+ // After set_text_content -> sync_popups is called; popup should NOT be Command.
+ assert!(
+ matches!(composer.active_popup, ActivePopup::None),
+ "expected no slash popup for '/ test'"
+ );
+
+ // Up should be handled by history navigation path, not slash popup handler.
+ let (result, _redraw) =
+ composer.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
+ assert_eq!(result, InputResult::None);
+ }
+
+ #[test]
+ fn slash_popup_activated_for_bare_slash_and_valid_prefixes() {
+ // use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
+ use tokio::sync::mpsc::unbounded_channel;
+
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let sender = AppEventSender::new(tx);
+ let mut composer = ChatComposer::new(
+ true,
+ sender,
+ false,
+ "Ask Codex to do anything".to_string(),
+ false,
+ );
+
+ // Case 1: bare "/"
+ composer.set_text_content("/".to_string());
+ assert!(
+ matches!(composer.active_popup, ActivePopup::Command(_)),
+ "bare '/' should activate slash popup"
+ );
+
+ // Case 2: valid prefix "/re" (matches /review, /resume, etc.)
+ composer.set_text_content("/re".to_string());
+ assert!(
+ matches!(composer.active_popup, ActivePopup::Command(_)),
+ "'/re' should activate slash popup via prefix match"
+ );
+
+ // Case 3: invalid prefix "/zzz" – still allowed to open popup if it
+ // matches no built-in command, our current logic will *not* open popup.
+ // Verify that explicitly.
+ composer.set_text_content("/zzz".to_string());
+ assert!(
+ matches!(composer.active_popup, ActivePopup::None),
+ "'/zzz' should not activate slash popup because it is not a prefix of any built-in command"
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/chat_composer_history.rs b/codex-rs/tui2/src/bottom_pane/chat_composer_history.rs
new file mode 100644
index 0000000000..991283a566
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/chat_composer_history.rs
@@ -0,0 +1,300 @@
+use std::collections::HashMap;
+
+use crate::app_event::AppEvent;
+use crate::app_event_sender::AppEventSender;
+use codex_core::protocol::Op;
+
+/// State machine that manages shell-style history navigation (Up/Down) inside
+/// the chat composer. This struct is intentionally decoupled from the
+/// rendering widget so the logic remains isolated and easier to test.
+pub(crate) struct ChatComposerHistory {
+ /// Identifier of the history log as reported by `SessionConfiguredEvent`.
+ history_log_id: Option<u64>,
+ /// Number of entries already present in the persistent cross-session
+ /// history file when the session started.
+ history_entry_count: usize,
+
+ /// Messages submitted by the user *during this UI session* (newest at END).
+ local_history: Vec<String>,
+
+ /// Cache of persistent history entries fetched on-demand.
+ fetched_history: HashMap<usize, String>,
+
+ /// Current cursor within the combined (persistent + local) history. `None`
+ /// indicates the user is *not* currently browsing history.
+ history_cursor: Option<isize>,
+
+ /// The text that was last inserted into the composer as a result of
+ /// history navigation. Used to decide if further Up/Down presses should be
+ /// treated as navigation versus normal cursor movement.
+ last_history_text: Option<String>,
+}
+
+impl ChatComposerHistory {
+ pub fn new() -> Self {
+ Self {
+ history_log_id: None,
+ history_entry_count: 0,
+ local_history: Vec::new(),
+ fetched_history: HashMap::new(),
+ history_cursor: None,
+ last_history_text: None,
+ }
+ }
+
+ /// Update metadata when a new session is configured.
+ pub fn set_metadata(&mut self, log_id: u64, entry_count: usize) {
+ self.history_log_id = Some(log_id);
+ self.history_entry_count = entry_count;
+ self.fetched_history.clear();
+ self.local_history.clear();
+ self.history_cursor = None;
+ self.last_history_text = None;
+ }
+
+ /// Record a message submitted by the user in the current session so it can
+ /// be recalled later.
+ pub fn record_local_submission(&mut self, text: &str) {
+ if text.is_empty() {
+ return;
+ }
+
+ self.history_cursor = None;
+ self.last_history_text = None;
+
+ // Avoid inserting a duplicate if identical to the previous entry.
+ if self.local_history.last().is_some_and(|prev| prev == text) {
+ return;
+ }
+
+ self.local_history.push(text.to_string());
+ }
+
+ /// Reset navigation tracking so the next Up key resumes from the latest entry.
+ pub fn reset_navigation(&mut self) {
+ self.history_cursor = None;
+ self.last_history_text = None;
+ }
+
+ /// Should Up/Down key presses be interpreted as history navigation given
+ /// the current content and cursor position of `textarea`?
+ pub fn should_handle_navigation(&self, text: &str, cursor: usize) -> bool {
+ if self.history_entry_count == 0 && self.local_history.is_empty() {
+ return false;
+ }
+
+ if text.is_empty() {
+ return true;
+ }
+
+ // Textarea is not empty – only navigate when cursor is at start and
+ // text matches last recalled history entry so regular editing is not
+ // hijacked.
+ if cursor != 0 {
+ return false;
+ }
+
+ matches!(&self.last_history_text, Some(prev) if prev == text)
+ }
+
+ /// Handle <Up>. Returns true when the key was consumed and the caller
+ /// should request a redraw.
+ pub fn navigate_up(&mut self, app_event_tx: &AppEventSender) -> Option<String> {
+ let total_entries = self.history_entry_count + self.local_history.len();
+ if total_entries == 0 {
+ return None;
+ }
+
+ let next_idx = match self.history_cursor {
+ None => (total_entries as isize) - 1,
+ Some(0) => return None, // already at oldest
+ Some(idx) => idx - 1,
+ };
+
+ self.history_cursor = Some(next_idx);
+ self.populate_history_at_index(next_idx as usize, app_event_tx)
+ }
+
+ /// Handle <Down>.
+ pub fn navigate_down(&mut self, app_event_tx: &AppEventSender) -> Option<String> {
+ let total_entries = self.history_entry_count + self.local_history.len();
+ if total_entries == 0 {
+ return None;
+ }
+
+ let next_idx_opt = match self.history_cursor {
+ None => return None, // not browsing
+ Some(idx) if (idx as usize) + 1 >= total_entries => None,
+ Some(idx) => Some(idx + 1),
+ };
+
+ match next_idx_opt {
+ Some(idx) => {
+ self.history_cursor = Some(idx);
+ self.populate_history_at_index(idx as usize, app_event_tx)
+ }
+ None => {
+ // Past newest – clear and exit browsing mode.
+ self.history_cursor = None;
+ self.last_history_text = None;
+ Some(String::new())
+ }
+ }
+ }
+
+ /// Integrate a GetHistoryEntryResponse event.
+ pub fn on_entry_response(
+ &mut self,
+ log_id: u64,
+ offset: usize,
+ entry: Option<String>,
+ ) -> Option<String> {
+ if self.history_log_id != Some(log_id) {
+ return None;
+ }
+ let text = entry?;
+ self.fetched_history.insert(offset, text.clone());
+
+ if self.history_cursor == Some(offset as isize) {
+ self.last_history_text = Some(text.clone());
+ return Some(text);
+ }
+ None
+ }
+
+ // ---------------------------------------------------------------------
+ // Internal helpers
+ // ---------------------------------------------------------------------
+
+ fn populate_history_at_index(
+ &mut self,
+ global_idx: usize,
+ app_event_tx: &AppEventSender,
+ ) -> Option<String> {
+ if global_idx >= self.history_entry_count {
+ // Local entry.
+ if let Some(text) = self
+ .local_history
+ .get(global_idx - self.history_entry_count)
+ {
+ self.last_history_text = Some(text.clone());
+ return Some(text.clone());
+ }
+ } else if let Some(text) = self.fetched_history.get(&global_idx) {
+ self.last_history_text = Some(text.clone());
+ return Some(text.clone());
+ } else if let Some(log_id) = self.history_log_id {
+ let op = Op::GetHistoryEntryRequest {
+ offset: global_idx,
+ log_id,
+ };
+ app_event_tx.send(AppEvent::CodexOp(op));
+ }
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::app_event::AppEvent;
+ use codex_core::protocol::Op;
+ use tokio::sync::mpsc::unbounded_channel;
+
+ #[test]
+ fn duplicate_submissions_are_not_recorded() {
+ let mut history = ChatComposerHistory::new();
+
+ // Empty submissions are ignored.
+ history.record_local_submission("");
+ assert_eq!(history.local_history.len(), 0);
+
+ // First entry is recorded.
+ history.record_local_submission("hello");
+ assert_eq!(history.local_history.len(), 1);
+ assert_eq!(history.local_history.last().unwrap(), "hello");
+
+ // Identical consecutive entry is skipped.
+ history.record_local_submission("hello");
+ assert_eq!(history.local_history.len(), 1);
+
+ // Different entry is recorded.
+ history.record_local_submission("world");
+ assert_eq!(history.local_history.len(), 2);
+ assert_eq!(history.local_history.last().unwrap(), "world");
+ }
+
+ #[test]
+ fn navigation_with_async_fetch() {
+ let (tx, mut rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx);
+
+ let mut history = ChatComposerHistory::new();
+ // Pretend there are 3 persistent entries.
+ history.set_metadata(1, 3);
+
+ // First Up should request offset 2 (latest) and await async data.
+ assert!(history.should_handle_navigation("", 0));
+ assert!(history.navigate_up(&tx).is_none()); // don't replace the text yet
+
+ // Verify that an AppEvent::CodexOp with the correct GetHistoryEntryRequest was sent.
+ let event = rx.try_recv().expect("expected AppEvent to be sent");
+ let AppEvent::CodexOp(history_request1) = event else {
+ panic!("unexpected event variant");
+ };
+ assert_eq!(
+ Op::GetHistoryEntryRequest {
+ log_id: 1,
+ offset: 2
+ },
+ history_request1
+ );
+
+ // Inject the async response.
+ assert_eq!(
+ Some("latest".into()),
+ history.on_entry_response(1, 2, Some("latest".into()))
+ );
+
+ // Next Up should move to offset 1.
+ assert!(history.navigate_up(&tx).is_none()); // don't replace the text yet
+
+ // Verify second CodexOp event for offset 1.
+ let event2 = rx.try_recv().expect("expected second event");
+ let AppEvent::CodexOp(history_request_2) = event2 else {
+ panic!("unexpected event variant");
+ };
+ assert_eq!(
+ Op::GetHistoryEntryRequest {
+ log_id: 1,
+ offset: 1
+ },
+ history_request_2
+ );
+
+ assert_eq!(
+ Some("older".into()),
+ history.on_entry_response(1, 1, Some("older".into()))
+ );
+ }
+
+ #[test]
+ fn reset_navigation_resets_cursor() {
+ let (tx, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx);
+
+ let mut history = ChatComposerHistory::new();
+ history.set_metadata(1, 3);
+ history.fetched_history.insert(1, "command2".into());
+ history.fetched_history.insert(2, "command3".into());
+
+ assert_eq!(Some("command3".into()), history.navigate_up(&tx));
+ assert_eq!(Some("command2".into()), history.navigate_up(&tx));
+
+ history.reset_navigation();
+ assert!(history.history_cursor.is_none());
+ assert!(history.last_history_text.is_none());
+
+ assert_eq!(Some("command3".into()), history.navigate_up(&tx));
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/command_popup.rs b/codex-rs/tui2/src/bottom_pane/command_popup.rs
new file mode 100644
index 0000000000..8aca5c4a62
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/command_popup.rs
@@ -0,0 +1,376 @@
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::widgets::WidgetRef;
+
+use super::popup_consts::MAX_POPUP_ROWS;
+use super::scroll_state::ScrollState;
+use super::selection_popup_common::GenericDisplayRow;
+use super::selection_popup_common::render_rows;
+use crate::render::Insets;
+use crate::render::RectExt;
+use crate::slash_command::SlashCommand;
+use crate::slash_command::built_in_slash_commands;
+use codex_common::fuzzy_match::fuzzy_match;
+use codex_protocol::custom_prompts::CustomPrompt;
+use codex_protocol::custom_prompts::PROMPTS_CMD_PREFIX;
+use std::collections::HashSet;
+
+/// A selectable item in the popup: either a built-in command or a user prompt.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum CommandItem {
+ Builtin(SlashCommand),
+ // Index into `prompts`
+ UserPrompt(usize),
+}
+
+pub(crate) struct CommandPopup {
+ command_filter: String,
+ builtins: Vec<(&'static str, SlashCommand)>,
+ prompts: Vec<CustomPrompt>,
+ state: ScrollState,
+}
+
+impl CommandPopup {
+ pub(crate) fn new(mut prompts: Vec<CustomPrompt>, skills_enabled: bool) -> Self {
+ let builtins: Vec<(&'static str, SlashCommand)> = built_in_slash_commands()
+ .into_iter()
+ .filter(|(_, cmd)| skills_enabled || *cmd != SlashCommand::Skills)
+ .collect();
+ // Exclude prompts that collide with builtin command names and sort by name.
+ let exclude: HashSet<String> = builtins.iter().map(|(n, _)| (*n).to_string()).collect();
+ prompts.retain(|p| !exclude.contains(&p.name));
+ prompts.sort_by(|a, b| a.name.cmp(&b.name));
+ Self {
+ command_filter: String::new(),
+ builtins,
+ prompts,
+ state: ScrollState::new(),
+ }
+ }
+
+ pub(crate) fn set_prompts(&mut self, mut prompts: Vec<CustomPrompt>) {
+ let exclude: HashSet<String> = self
+ .builtins
+ .iter()
+ .map(|(n, _)| (*n).to_string())
+ .collect();
+ prompts.retain(|p| !exclude.contains(&p.name));
+ prompts.sort_by(|a, b| a.name.cmp(&b.name));
+ self.prompts = prompts;
+ }
+
+ pub(crate) fn prompt(&self, idx: usize) -> Option<&CustomPrompt> {
+ self.prompts.get(idx)
+ }
+
+ /// Update the filter string based on the current composer text. The text
+ /// passed in is expected to start with a leading '/'. Everything after the
+ /// *first* '/" on the *first* line becomes the active filter that is used
+ /// to narrow down the list of available commands.
+ pub(crate) fn on_composer_text_change(&mut self, text: String) {
+ let first_line = text.lines().next().unwrap_or("");
+
+ if let Some(stripped) = first_line.strip_prefix('/') {
+ // Extract the *first* token (sequence of non-whitespace
+ // characters) after the slash so that `/clear something` still
+ // shows the help for `/clear`.
+ let token = stripped.trim_start();
+ let cmd_token = token.split_whitespace().next().unwrap_or("");
+
+ // Update the filter keeping the original case (commands are all
+ // lower-case for now but this may change in the future).
+ self.command_filter = cmd_token.to_string();
+ } else {
+ // The composer no longer starts with '/'. Reset the filter so the
+ // popup shows the *full* command list if it is still displayed
+ // for some reason.
+ self.command_filter.clear();
+ }
+
+ // Reset or clamp selected index based on new filtered list.
+ let matches_len = self.filtered_items().len();
+ self.state.clamp_selection(matches_len);
+ self.state
+ .ensure_visible(matches_len, MAX_POPUP_ROWS.min(matches_len));
+ }
+
+ /// Determine the preferred height of the popup for a given width.
+ /// Accounts for wrapped descriptions so that long tooltips don't overflow.
+ pub(crate) fn calculate_required_height(&self, width: u16) -> u16 {
+ use super::selection_popup_common::measure_rows_height;
+ let rows = self.rows_from_matches(self.filtered());
+
+ measure_rows_height(&rows, &self.state, MAX_POPUP_ROWS, width)
+ }
+
+ /// Compute fuzzy-filtered matches over built-in commands and user prompts,
+ /// paired with optional highlight indices and score. Sorted by ascending
+ /// score, then by name for stability.
+ fn filtered(&self) -> Vec<(CommandItem, Option<Vec<usize>>, i32)> {
+ let filter = self.command_filter.trim();
+ let mut out: Vec<(CommandItem, Option<Vec<usize>>, i32)> = Vec::new();
+ if filter.is_empty() {
+ // Built-ins first, in presentation order.
+ for (_, cmd) in self.builtins.iter() {
+ out.push((CommandItem::Builtin(*cmd), None, 0));
+ }
+ // Then prompts, already sorted by name.
+ for idx in 0..self.prompts.len() {
+ out.push((CommandItem::UserPrompt(idx), None, 0));
+ }
+ return out;
+ }
+
+ for (_, cmd) in self.builtins.iter() {
+ if let Some((indices, score)) = fuzzy_match(cmd.command(), filter) {
+ out.push((CommandItem::Builtin(*cmd), Some(indices), score));
+ }
+ }
+ // Support both search styles:
+ // - Typing "name" should surface "/prompts:name" results.
+ // - Typing "prompts:name" should also work.
+ for (idx, p) in self.prompts.iter().enumerate() {
+ let display = format!("{PROMPTS_CMD_PREFIX}:{}", p.name);
+ if let Some((indices, score)) = fuzzy_match(&display, filter) {
+ out.push((CommandItem::UserPrompt(idx), Some(indices), score));
+ }
+ }
+ // When filtering, sort by ascending score and then by name for stability.
+ out.sort_by(|a, b| {
+ a.2.cmp(&b.2).then_with(|| {
+ let an = match a.0 {
+ CommandItem::Builtin(c) => c.command(),
+ CommandItem::UserPrompt(i) => &self.prompts[i].name,
+ };
+ let bn = match b.0 {
+ CommandItem::Builtin(c) => c.command(),
+ CommandItem::UserPrompt(i) => &self.prompts[i].name,
+ };
+ an.cmp(bn)
+ })
+ });
+ out
+ }
+
+ fn filtered_items(&self) -> Vec<CommandItem> {
+ self.filtered().into_iter().map(|(c, _, _)| c).collect()
+ }
+
+ fn rows_from_matches(
+ &self,
+ matches: Vec<(CommandItem, Option<Vec<usize>>, i32)>,
+ ) -> Vec<GenericDisplayRow> {
+ matches
+ .into_iter()
+ .map(|(item, indices, _)| {
+ let (name, description) = match item {
+ CommandItem::Builtin(cmd) => {
+ (format!("/{}", cmd.command()), cmd.description().to_string())
+ }
+ CommandItem::UserPrompt(i) => {
+ let prompt = &self.prompts[i];
+ let description = prompt
+ .description
+ .clone()
+ .unwrap_or_else(|| "send saved prompt".to_string());
+ (
+ format!("/{PROMPTS_CMD_PREFIX}:{}", prompt.name),
+ description,
+ )
+ }
+ };
+ GenericDisplayRow {
+ name,
+ match_indices: indices.map(|v| v.into_iter().map(|i| i + 1).collect()),
+ display_shortcut: None,
+ description: Some(description),
+ wrap_indent: None,
+ }
+ })
+ .collect()
+ }
+
+ /// Move the selection cursor one step up.
+ pub(crate) fn move_up(&mut self) {
+ let len = self.filtered_items().len();
+ self.state.move_up_wrap(len);
+ self.state.ensure_visible(len, MAX_POPUP_ROWS.min(len));
+ }
+
+ /// Move the selection cursor one step down.
+ pub(crate) fn move_down(&mut self) {
+ let matches_len = self.filtered_items().len();
+ self.state.move_down_wrap(matches_len);
+ self.state
+ .ensure_visible(matches_len, MAX_POPUP_ROWS.min(matches_len));
+ }
+
+ /// Return currently selected command, if any.
+ pub(crate) fn selected_item(&self) -> Option<CommandItem> {
+ let matches = self.filtered_items();
+ self.state
+ .selected_idx
+ .and_then(|idx| matches.get(idx).copied())
+ }
+}
+
+impl WidgetRef for CommandPopup {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ let rows = self.rows_from_matches(self.filtered());
+ render_rows(
+ area.inset(Insets::tlbr(0, 2, 0, 0)),
+ buf,
+ &rows,
+ &self.state,
+ MAX_POPUP_ROWS,
+ "no matches",
+ );
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use pretty_assertions::assert_eq;
+
+ #[test]
+ fn filter_includes_init_when_typing_prefix() {
+ let mut popup = CommandPopup::new(Vec::new(), false);
+ // Simulate the composer line starting with '/in' so the popup filters
+ // matching commands by prefix.
+ popup.on_composer_text_change("/in".to_string());
+
+ // Access the filtered list via the selected command and ensure that
+ // one of the matches is the new "init" command.
+ let matches = popup.filtered_items();
+ let has_init = matches.iter().any(|item| match item {
+ CommandItem::Builtin(cmd) => cmd.command() == "init",
+ CommandItem::UserPrompt(_) => false,
+ });
+ assert!(
+ has_init,
+ "expected '/init' to appear among filtered commands"
+ );
+ }
+
+ #[test]
+ fn selecting_init_by_exact_match() {
+ let mut popup = CommandPopup::new(Vec::new(), false);
+ popup.on_composer_text_change("/init".to_string());
+
+ // When an exact match exists, the selected command should be that
+ // command by default.
+ let selected = popup.selected_item();
+ match selected {
+ Some(CommandItem::Builtin(cmd)) => assert_eq!(cmd.command(), "init"),
+ Some(CommandItem::UserPrompt(_)) => panic!("unexpected prompt selected for '/init'"),
+ None => panic!("expected a selected command for exact match"),
+ }
+ }
+
+ #[test]
+ fn model_is_first_suggestion_for_mo() {
+ let mut popup = CommandPopup::new(Vec::new(), false);
+ popup.on_composer_text_change("/mo".to_string());
+ let matches = popup.filtered_items();
+ match matches.first() {
+ Some(CommandItem::Builtin(cmd)) => assert_eq!(cmd.command(), "model"),
+ Some(CommandItem::UserPrompt(_)) => {
+ panic!("unexpected prompt ranked before '/model' for '/mo'")
+ }
+ None => panic!("expected at least one match for '/mo'"),
+ }
+ }
+
+ #[test]
+ fn prompt_discovery_lists_custom_prompts() {
+ let prompts = vec![
+ CustomPrompt {
+ name: "foo".to_string(),
+ path: "/tmp/foo.md".to_string().into(),
+ content: "hello from foo".to_string(),
+ description: None,
+ argument_hint: None,
+ },
+ CustomPrompt {
+ name: "bar".to_string(),
+ path: "/tmp/bar.md".to_string().into(),
+ content: "hello from bar".to_string(),
+ description: None,
+ argument_hint: None,
+ },
+ ];
+ let popup = CommandPopup::new(prompts, false);
+ let items = popup.filtered_items();
+ let mut prompt_names: Vec<String> = items
+ .into_iter()
+ .filter_map(|it| match it {
+ CommandItem::UserPrompt(i) => popup.prompt(i).map(|p| p.name.clone()),
+ _ => None,
+ })
+ .collect();
+ prompt_names.sort();
+ assert_eq!(prompt_names, vec!["bar".to_string(), "foo".to_string()]);
+ }
+
+ #[test]
+ fn prompt_name_collision_with_builtin_is_ignored() {
+ // Create a prompt named like a builtin (e.g. "init").
+ let popup = CommandPopup::new(
+ vec![CustomPrompt {
+ name: "init".to_string(),
+ path: "/tmp/init.md".to_string().into(),
+ content: "should be ignored".to_string(),
+ description: None,
+ argument_hint: None,
+ }],
+ false,
+ );
+ let items = popup.filtered_items();
+ let has_collision_prompt = items.into_iter().any(|it| match it {
+ CommandItem::UserPrompt(i) => popup.prompt(i).is_some_and(|p| p.name == "init"),
+ _ => false,
+ });
+ assert!(
+ !has_collision_prompt,
+ "prompt with builtin name should be ignored"
+ );
+ }
+
+ #[test]
+ fn prompt_description_uses_frontmatter_metadata() {
+ let popup = CommandPopup::new(
+ vec![CustomPrompt {
+ name: "draftpr".to_string(),
+ path: "/tmp/draftpr.md".to_string().into(),
+ content: "body".to_string(),
+ description: Some("Create feature branch, commit and open draft PR.".to_string()),
+ argument_hint: None,
+ }],
+ false,
+ );
+ let rows = popup.rows_from_matches(vec![(CommandItem::UserPrompt(0), None, 0)]);
+ let description = rows.first().and_then(|row| row.description.as_deref());
+ assert_eq!(
+ description,
+ Some("Create feature branch, commit and open draft PR.")
+ );
+ }
+
+ #[test]
+ fn prompt_description_falls_back_when_missing() {
+ let popup = CommandPopup::new(
+ vec![CustomPrompt {
+ name: "foo".to_string(),
+ path: "/tmp/foo.md".to_string().into(),
+ content: "body".to_string(),
+ description: None,
+ argument_hint: None,
+ }],
+ false,
+ );
+ let rows = popup.rows_from_matches(vec![(CommandItem::UserPrompt(0), None, 0)]);
+ let description = rows.first().and_then(|row| row.description.as_deref());
+ assert_eq!(description, Some("send saved prompt"));
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/custom_prompt_view.rs b/codex-rs/tui2/src/bottom_pane/custom_prompt_view.rs
new file mode 100644
index 0000000000..e9f0ee697f
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/custom_prompt_view.rs
@@ -0,0 +1,247 @@
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyModifiers;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::widgets::Clear;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::StatefulWidgetRef;
+use ratatui::widgets::Widget;
+use std::cell::RefCell;
+
+use crate::render::renderable::Renderable;
+
+use super::popup_consts::standard_popup_hint_line;
+
+use super::CancellationEvent;
+use super::bottom_pane_view::BottomPaneView;
+use super::textarea::TextArea;
+use super::textarea::TextAreaState;
+
+/// Callback invoked when the user submits a custom prompt.
+pub(crate) type PromptSubmitted = Box<dyn Fn(String) + Send + Sync>;
+
+/// Minimal multi-line text input view to collect custom review instructions.
+pub(crate) struct CustomPromptView {
+ title: String,
+ placeholder: String,
+ context_label: Option<String>,
+ on_submit: PromptSubmitted,
+
+ // UI state
+ textarea: TextArea,
+ textarea_state: RefCell<TextAreaState>,
+ complete: bool,
+}
+
+impl CustomPromptView {
+ pub(crate) fn new(
+ title: String,
+ placeholder: String,
+ context_label: Option<String>,
+ on_submit: PromptSubmitted,
+ ) -> Self {
+ Self {
+ title,
+ placeholder,
+ context_label,
+ on_submit,
+ textarea: TextArea::new(),
+ textarea_state: RefCell::new(TextAreaState::default()),
+ complete: false,
+ }
+ }
+}
+
+impl BottomPaneView for CustomPromptView {
+ fn handle_key_event(&mut self, key_event: KeyEvent) {
+ match key_event {
+ KeyEvent {
+ code: KeyCode::Esc, ..
+ } => {
+ self.on_ctrl_c();
+ }
+ KeyEvent {
+ code: KeyCode::Enter,
+ modifiers: KeyModifiers::NONE,
+ ..
+ } => {
+ let text = self.textarea.text().trim().to_string();
+ if !text.is_empty() {
+ (self.on_submit)(text);
+ self.complete = true;
+ }
+ }
+ KeyEvent {
+ code: KeyCode::Enter,
+ ..
+ } => {
+ self.textarea.input(key_event);
+ }
+ other => {
+ self.textarea.input(other);
+ }
+ }
+ }
+
+ fn on_ctrl_c(&mut self) -> CancellationEvent {
+ self.complete = true;
+ CancellationEvent::Handled
+ }
+
+ fn is_complete(&self) -> bool {
+ self.complete
+ }
+
+ fn handle_paste(&mut self, pasted: String) -> bool {
+ if pasted.is_empty() {
+ return false;
+ }
+ self.textarea.insert_str(&pasted);
+ true
+ }
+}
+
+impl Renderable for CustomPromptView {
+ fn desired_height(&self, width: u16) -> u16 {
+ let extra_top: u16 = if self.context_label.is_some() { 1 } else { 0 };
+ 1u16 + extra_top + self.input_height(width) + 3u16
+ }
+
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ if area.height == 0 || area.width == 0 {
+ return;
+ }
+
+ let input_height = self.input_height(area.width);
+
+ // Title line
+ let title_area = Rect {
+ x: area.x,
+ y: area.y,
+ width: area.width,
+ height: 1,
+ };
+ let title_spans: Vec<Span<'static>> = vec![gutter(), self.title.clone().bold()];
+ Paragraph::new(Line::from(title_spans)).render(title_area, buf);
+
+ // Optional context line
+ let mut input_y = area.y.saturating_add(1);
+ if let Some(context_label) = &self.context_label {
+ let context_area = Rect {
+ x: area.x,
+ y: input_y,
+ width: area.width,
+ height: 1,
+ };
+ let spans: Vec<Span<'static>> = vec![gutter(), context_label.clone().cyan()];
+ Paragraph::new(Line::from(spans)).render(context_area, buf);
+ input_y = input_y.saturating_add(1);
+ }
+
+ // Input line
+ let input_area = Rect {
+ x: area.x,
+ y: input_y,
+ width: area.width,
+ height: input_height,
+ };
+ if input_area.width >= 2 {
+ for row in 0..input_area.height {
+ Paragraph::new(Line::from(vec![gutter()])).render(
+ Rect {
+ x: input_area.x,
+ y: input_area.y.saturating_add(row),
+ width: 2,
+ height: 1,
+ },
+ buf,
+ );
+ }
+
+ let text_area_height = input_area.height.saturating_sub(1);
+ if text_area_height > 0 {
+ if input_area.width > 2 {
+ let blank_rect = Rect {
+ x: input_area.x.saturating_add(2),
+ y: input_area.y,
+ width: input_area.width.saturating_sub(2),
+ height: 1,
+ };
+ Clear.render(blank_rect, buf);
+ }
+ let textarea_rect = Rect {
+ x: input_area.x.saturating_add(2),
+ y: input_area.y.saturating_add(1),
+ width: input_area.width.saturating_sub(2),
+ height: text_area_height,
+ };
+ let mut state = self.textarea_state.borrow_mut();
+ StatefulWidgetRef::render_ref(&(&self.textarea), textarea_rect, buf, &mut state);
+ if self.textarea.text().is_empty() {
+ Paragraph::new(Line::from(self.placeholder.clone().dim()))
+ .render(textarea_rect, buf);
+ }
+ }
+ }
+
+ let hint_blank_y = input_area.y.saturating_add(input_height);
+ if hint_blank_y < area.y.saturating_add(area.height) {
+ let blank_area = Rect {
+ x: area.x,
+ y: hint_blank_y,
+ width: area.width,
+ height: 1,
+ };
+ Clear.render(blank_area, buf);
+ }
+
+ let hint_y = hint_blank_y.saturating_add(1);
+ if hint_y < area.y.saturating_add(area.height) {
+ Paragraph::new(standard_popup_hint_line()).render(
+ Rect {
+ x: area.x,
+ y: hint_y,
+ width: area.width,
+ height: 1,
+ },
+ buf,
+ );
+ }
+ }
+
+ fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ if area.height < 2 || area.width <= 2 {
+ return None;
+ }
+ let text_area_height = self.input_height(area.width).saturating_sub(1);
+ if text_area_height == 0 {
+ return None;
+ }
+ let extra_offset: u16 = if self.context_label.is_some() { 1 } else { 0 };
+ let top_line_count = 1u16 + extra_offset;
+ let textarea_rect = Rect {
+ x: area.x.saturating_add(2),
+ y: area.y.saturating_add(top_line_count).saturating_add(1),
+ width: area.width.saturating_sub(2),
+ height: text_area_height,
+ };
+ let state = *self.textarea_state.borrow();
+ self.textarea.cursor_pos_with_state(textarea_rect, state)
+ }
+}
+
+impl CustomPromptView {
+ fn input_height(&self, width: u16) -> u16 {
+ let usable_width = width.saturating_sub(2);
+ let text_height = self.textarea.desired_height(usable_width).clamp(1, 8);
+ text_height.saturating_add(1).min(9)
+ }
+}
+
+fn gutter() -> Span<'static> {
+ "▌ ".cyan()
+}
diff --git a/codex-rs/tui2/src/bottom_pane/feedback_view.rs b/codex-rs/tui2/src/bottom_pane/feedback_view.rs
new file mode 100644
index 0000000000..c563ab8e90
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/feedback_view.rs
@@ -0,0 +1,559 @@
+use std::cell::RefCell;
+use std::path::PathBuf;
+
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyModifiers;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::widgets::Clear;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::StatefulWidgetRef;
+use ratatui::widgets::Widget;
+
+use crate::app_event::AppEvent;
+use crate::app_event::FeedbackCategory;
+use crate::app_event_sender::AppEventSender;
+use crate::history_cell;
+use crate::render::renderable::Renderable;
+use codex_core::protocol::SessionSource;
+
+use super::CancellationEvent;
+use super::bottom_pane_view::BottomPaneView;
+use super::popup_consts::standard_popup_hint_line;
+use super::textarea::TextArea;
+use super::textarea::TextAreaState;
+
+const BASE_BUG_ISSUE_URL: &str =
+ "https://github.com/openai/codex/issues/new?template=2-bug-report.yml";
+
+/// Minimal input overlay to collect an optional feedback note, then upload
+/// both logs and rollout with classification + metadata.
+pub(crate) struct FeedbackNoteView {
+ category: FeedbackCategory,
+ snapshot: codex_feedback::CodexLogSnapshot,
+ rollout_path: Option<PathBuf>,
+ app_event_tx: AppEventSender,
+ include_logs: bool,
+
+ // UI state
+ textarea: TextArea,
+ textarea_state: RefCell<TextAreaState>,
+ complete: bool,
+}
+
+impl FeedbackNoteView {
+ pub(crate) fn new(
+ category: FeedbackCategory,
+ snapshot: codex_feedback::CodexLogSnapshot,
+ rollout_path: Option<PathBuf>,
+ app_event_tx: AppEventSender,
+ include_logs: bool,
+ ) -> Self {
+ Self {
+ category,
+ snapshot,
+ rollout_path,
+ app_event_tx,
+ include_logs,
+ textarea: TextArea::new(),
+ textarea_state: RefCell::new(TextAreaState::default()),
+ complete: false,
+ }
+ }
+
+ fn submit(&mut self) {
+ let note = self.textarea.text().trim().to_string();
+ let reason_opt = if note.is_empty() {
+ None
+ } else {
+ Some(note.as_str())
+ };
+ let rollout_path_ref = self.rollout_path.as_deref();
+ let classification = feedback_classification(self.category);
+
+ let mut thread_id = self.snapshot.thread_id.clone();
+
+ let result = self.snapshot.upload_feedback(
+ classification,
+ reason_opt,
+ self.include_logs,
+ if self.include_logs {
+ rollout_path_ref
+ } else {
+ None
+ },
+ Some(SessionSource::Cli),
+ );
+
+ match result {
+ Ok(()) => {
+ let prefix = if self.include_logs {
+ "• Feedback uploaded."
+ } else {
+ "• Feedback recorded (no logs)."
+ };
+ let issue_url = issue_url_for_category(self.category, &thread_id);
+ let mut lines = vec![Line::from(match issue_url.as_ref() {
+ Some(_) => format!("{prefix} Please open an issue using the following URL:"),
+ None => format!("{prefix} Thanks for the feedback!"),
+ })];
+ if let Some(url) = issue_url {
+ lines.extend([
+ "".into(),
+ Line::from(vec![" ".into(), url.cyan().underlined()]),
+ "".into(),
+ Line::from(vec![
+ " Or mention your thread ID ".into(),
+ std::mem::take(&mut thread_id).bold(),
+ " in an existing issue.".into(),
+ ]),
+ ]);
+ } else {
+ lines.extend([
+ "".into(),
+ Line::from(vec![
+ " Thread ID: ".into(),
+ std::mem::take(&mut thread_id).bold(),
+ ]),
+ ]);
+ }
+ self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
+ history_cell::PlainHistoryCell::new(lines),
+ )));
+ }
+ Err(e) => {
+ self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
+ history_cell::new_error_event(format!("Failed to upload feedback: {e}")),
+ )));
+ }
+ }
+ self.complete = true;
+ }
+}
+
+impl BottomPaneView for FeedbackNoteView {
+ fn handle_key_event(&mut self, key_event: KeyEvent) {
+ match key_event {
+ KeyEvent {
+ code: KeyCode::Esc, ..
+ } => {
+ self.on_ctrl_c();
+ }
+ KeyEvent {
+ code: KeyCode::Enter,
+ modifiers: KeyModifiers::NONE,
+ ..
+ } => {
+ self.submit();
+ }
+ KeyEvent {
+ code: KeyCode::Enter,
+ ..
+ } => {
+ self.textarea.input(key_event);
+ }
+ other => {
+ self.textarea.input(other);
+ }
+ }
+ }
+
+ fn on_ctrl_c(&mut self) -> CancellationEvent {
+ self.complete = true;
+ CancellationEvent::Handled
+ }
+
+ fn is_complete(&self) -> bool {
+ self.complete
+ }
+
+ fn handle_paste(&mut self, pasted: String) -> bool {
+ if pasted.is_empty() {
+ return false;
+ }
+ self.textarea.insert_str(&pasted);
+ true
+ }
+}
+
+impl Renderable for FeedbackNoteView {
+ fn desired_height(&self, width: u16) -> u16 {
+ 1u16 + self.input_height(width) + 3u16
+ }
+
+ fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ if area.height < 2 || area.width <= 2 {
+ return None;
+ }
+ let text_area_height = self.input_height(area.width).saturating_sub(1);
+ if text_area_height == 0 {
+ return None;
+ }
+ let top_line_count = 1u16; // title only
+ let textarea_rect = Rect {
+ x: area.x.saturating_add(2),
+ y: area.y.saturating_add(top_line_count).saturating_add(1),
+ width: area.width.saturating_sub(2),
+ height: text_area_height,
+ };
+ let state = *self.textarea_state.borrow();
+ self.textarea.cursor_pos_with_state(textarea_rect, state)
+ }
+
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ if area.height == 0 || area.width == 0 {
+ return;
+ }
+
+ let (title, placeholder) = feedback_title_and_placeholder(self.category);
+ let input_height = self.input_height(area.width);
+
+ // Title line
+ let title_area = Rect {
+ x: area.x,
+ y: area.y,
+ width: area.width,
+ height: 1,
+ };
+ let title_spans: Vec<Span<'static>> = vec![gutter(), title.bold()];
+ Paragraph::new(Line::from(title_spans)).render(title_area, buf);
+
+ // Input line
+ let input_area = Rect {
+ x: area.x,
+ y: area.y.saturating_add(1),
+ width: area.width,
+ height: input_height,
+ };
+ if input_area.width >= 2 {
+ for row in 0..input_area.height {
+ Paragraph::new(Line::from(vec![gutter()])).render(
+ Rect {
+ x: input_area.x,
+ y: input_area.y.saturating_add(row),
+ width: 2,
+ height: 1,
+ },
+ buf,
+ );
+ }
+
+ let text_area_height = input_area.height.saturating_sub(1);
+ if text_area_height > 0 {
+ if input_area.width > 2 {
+ let blank_rect = Rect {
+ x: input_area.x.saturating_add(2),
+ y: input_area.y,
+ width: input_area.width.saturating_sub(2),
+ height: 1,
+ };
+ Clear.render(blank_rect, buf);
+ }
+ let textarea_rect = Rect {
+ x: input_area.x.saturating_add(2),
+ y: input_area.y.saturating_add(1),
+ width: input_area.width.saturating_sub(2),
+ height: text_area_height,
+ };
+ let mut state = self.textarea_state.borrow_mut();
+ StatefulWidgetRef::render_ref(&(&self.textarea), textarea_rect, buf, &mut state);
+ if self.textarea.text().is_empty() {
+ Paragraph::new(Line::from(placeholder.dim())).render(textarea_rect, buf);
+ }
+ }
+ }
+
+ let hint_blank_y = input_area.y.saturating_add(input_height);
+ if hint_blank_y < area.y.saturating_add(area.height) {
+ let blank_area = Rect {
+ x: area.x,
+ y: hint_blank_y,
+ width: area.width,
+ height: 1,
+ };
+ Clear.render(blank_area, buf);
+ }
+
+ let hint_y = hint_blank_y.saturating_add(1);
+ if hint_y < area.y.saturating_add(area.height) {
+ Paragraph::new(standard_popup_hint_line()).render(
+ Rect {
+ x: area.x,
+ y: hint_y,
+ width: area.width,
+ height: 1,
+ },
+ buf,
+ );
+ }
+ }
+}
+
+impl FeedbackNoteView {
+ fn input_height(&self, width: u16) -> u16 {
+ let usable_width = width.saturating_sub(2);
+ let text_height = self.textarea.desired_height(usable_width).clamp(1, 8);
+ text_height.saturating_add(1).min(9)
+ }
+}
+
+fn gutter() -> Span<'static> {
+ "▌ ".cyan()
+}
+
+fn feedback_title_and_placeholder(category: FeedbackCategory) -> (String, String) {
+ match category {
+ FeedbackCategory::BadResult => (
+ "Tell us more (bad result)".to_string(),
+ "(optional) Write a short description to help us further".to_string(),
+ ),
+ FeedbackCategory::GoodResult => (
+ "Tell us more (good result)".to_string(),
+ "(optional) Write a short description to help us further".to_string(),
+ ),
+ FeedbackCategory::Bug => (
+ "Tell us more (bug)".to_string(),
+ "(optional) Write a short description to help us further".to_string(),
+ ),
+ FeedbackCategory::Other => (
+ "Tell us more (other)".to_string(),
+ "(optional) Write a short description to help us further".to_string(),
+ ),
+ }
+}
+
+fn feedback_classification(category: FeedbackCategory) -> &'static str {
+ match category {
+ FeedbackCategory::BadResult => "bad_result",
+ FeedbackCategory::GoodResult => "good_result",
+ FeedbackCategory::Bug => "bug",
+ FeedbackCategory::Other => "other",
+ }
+}
+
+fn issue_url_for_category(category: FeedbackCategory, thread_id: &str) -> Option<String> {
+ match category {
+ FeedbackCategory::Bug | FeedbackCategory::BadResult | FeedbackCategory::Other => Some(
+ format!("{BASE_BUG_ISSUE_URL}&steps=Uploaded%20thread:%20{thread_id}"),
+ ),
+ FeedbackCategory::GoodResult => None,
+ }
+}
+
+// Build the selection popup params for feedback categories.
+pub(crate) fn feedback_selection_params(
+ app_event_tx: AppEventSender,
+) -> super::SelectionViewParams {
+ super::SelectionViewParams {
+ title: Some("How was this?".to_string()),
+ items: vec![
+ make_feedback_item(
+ app_event_tx.clone(),
+ "bug",
+ "Crash, error message, hang, or broken UI/behavior.",
+ FeedbackCategory::Bug,
+ ),
+ make_feedback_item(
+ app_event_tx.clone(),
+ "bad result",
+ "Output was off-target, incorrect, incomplete, or unhelpful.",
+ FeedbackCategory::BadResult,
+ ),
+ make_feedback_item(
+ app_event_tx.clone(),
+ "good result",
+ "Helpful, correct, high‑quality, or delightful result worth celebrating.",
+ FeedbackCategory::GoodResult,
+ ),
+ make_feedback_item(
+ app_event_tx,
+ "other",
+ "Slowness, feature suggestion, UX feedback, or anything else.",
+ FeedbackCategory::Other,
+ ),
+ ],
+ ..Default::default()
+ }
+}
+
+fn make_feedback_item(
+ app_event_tx: AppEventSender,
+ name: &str,
+ description: &str,
+ category: FeedbackCategory,
+) -> super::SelectionItem {
+ let action: super::SelectionAction = Box::new(move |_sender: &AppEventSender| {
+ app_event_tx.send(AppEvent::OpenFeedbackConsent { category });
+ });
+ super::SelectionItem {
+ name: name.to_string(),
+ description: Some(description.to_string()),
+ actions: vec![action],
+ dismiss_on_select: true,
+ ..Default::default()
+ }
+}
+
+/// Build the upload consent popup params for a given feedback category.
+pub(crate) fn feedback_upload_consent_params(
+ app_event_tx: AppEventSender,
+ category: FeedbackCategory,
+ rollout_path: Option<std::path::PathBuf>,
+) -> super::SelectionViewParams {
+ use super::popup_consts::standard_popup_hint_line;
+ let yes_action: super::SelectionAction = Box::new({
+ let tx = app_event_tx.clone();
+ move |sender: &AppEventSender| {
+ let _ = sender;
+ tx.send(AppEvent::OpenFeedbackNote {
+ category,
+ include_logs: true,
+ });
+ }
+ });
+
+ let no_action: super::SelectionAction = Box::new({
+ let tx = app_event_tx;
+ move |sender: &AppEventSender| {
+ let _ = sender;
+ tx.send(AppEvent::OpenFeedbackNote {
+ category,
+ include_logs: false,
+ });
+ }
+ });
+
+ // Build header listing files that would be sent if user consents.
+ let mut header_lines: Vec<Box<dyn crate::render::renderable::Renderable>> = vec![
+ Line::from("Upload logs?".bold()).into(),
+ Line::from("").into(),
+ Line::from("The following files will be sent:".dim()).into(),
+ Line::from(vec![" • ".into(), "codex-logs.log".into()]).into(),
+ ];
+ if let Some(path) = rollout_path.as_deref()
+ && let Some(name) = path.file_name().map(|s| s.to_string_lossy().to_string())
+ {
+ header_lines.push(Line::from(vec![" • ".into(), name.into()]).into());
+ }
+
+ super::SelectionViewParams {
+ footer_hint: Some(standard_popup_hint_line()),
+ items: vec![
+ super::SelectionItem {
+ name: "Yes".to_string(),
+ description: Some(
+ "Share the current Codex session logs with the team for troubleshooting."
+ .to_string(),
+ ),
+ actions: vec![yes_action],
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ super::SelectionItem {
+ name: "No".to_string(),
+ description: Some("".to_string()),
+ actions: vec![no_action],
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ ],
+ header: Box::new(crate::render::renderable::ColumnRenderable::with(
+ header_lines,
+ )),
+ ..Default::default()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::app_event::AppEvent;
+ use crate::app_event_sender::AppEventSender;
+
+ fn render(view: &FeedbackNoteView, width: u16) -> String {
+ let height = view.desired_height(width);
+ let area = Rect::new(0, 0, width, height);
+ let mut buf = Buffer::empty(area);
+ view.render(area, &mut buf);
+
+ let mut lines: Vec<String> = (0..area.height)
+ .map(|row| {
+ let mut line = String::new();
+ for col in 0..area.width {
+ let symbol = buf[(area.x + col, area.y + row)].symbol();
+ if symbol.is_empty() {
+ line.push(' ');
+ } else {
+ line.push_str(symbol);
+ }
+ }
+ line.trim_end().to_string()
+ })
+ .collect();
+
+ while lines.first().is_some_and(|l| l.trim().is_empty()) {
+ lines.remove(0);
+ }
+ while lines.last().is_some_and(|l| l.trim().is_empty()) {
+ lines.pop();
+ }
+ lines.join("\n")
+ }
+
+ fn make_view(category: FeedbackCategory) -> FeedbackNoteView {
+ let (tx_raw, _rx) = tokio::sync::mpsc::unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let snapshot = codex_feedback::CodexFeedback::new().snapshot(None);
+ FeedbackNoteView::new(category, snapshot, None, tx, true)
+ }
+
+ #[test]
+ fn feedback_view_bad_result() {
+ let view = make_view(FeedbackCategory::BadResult);
+ let rendered = render(&view, 60);
+ insta::assert_snapshot!("feedback_view_bad_result", rendered);
+ }
+
+ #[test]
+ fn feedback_view_good_result() {
+ let view = make_view(FeedbackCategory::GoodResult);
+ let rendered = render(&view, 60);
+ insta::assert_snapshot!("feedback_view_good_result", rendered);
+ }
+
+ #[test]
+ fn feedback_view_bug() {
+ let view = make_view(FeedbackCategory::Bug);
+ let rendered = render(&view, 60);
+ insta::assert_snapshot!("feedback_view_bug", rendered);
+ }
+
+ #[test]
+ fn feedback_view_other() {
+ let view = make_view(FeedbackCategory::Other);
+ let rendered = render(&view, 60);
+ insta::assert_snapshot!("feedback_view_other", rendered);
+ }
+
+ #[test]
+ fn issue_url_available_for_bug_bad_result_and_other() {
+ let bug_url = issue_url_for_category(FeedbackCategory::Bug, "thread-1");
+ assert!(
+ bug_url
+ .as_deref()
+ .is_some_and(|url| url.contains("template=2-bug-report"))
+ );
+
+ let bad_result_url = issue_url_for_category(FeedbackCategory::BadResult, "thread-2");
+ assert!(bad_result_url.is_some());
+
+ let other_url = issue_url_for_category(FeedbackCategory::Other, "thread-3");
+ assert!(other_url.is_some());
+
+ assert!(issue_url_for_category(FeedbackCategory::GoodResult, "t").is_none());
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/file_search_popup.rs b/codex-rs/tui2/src/bottom_pane/file_search_popup.rs
new file mode 100644
index 0000000000..064e4f0137
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/file_search_popup.rs
@@ -0,0 +1,154 @@
+use codex_file_search::FileMatch;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::widgets::WidgetRef;
+
+use crate::render::Insets;
+use crate::render::RectExt;
+
+use super::popup_consts::MAX_POPUP_ROWS;
+use super::scroll_state::ScrollState;
+use super::selection_popup_common::GenericDisplayRow;
+use super::selection_popup_common::render_rows;
+
+/// Visual state for the file-search popup.
+pub(crate) struct FileSearchPopup {
+ /// Query corresponding to the `matches` currently shown.
+ display_query: String,
+ /// Latest query typed by the user. May differ from `display_query` when
+ /// a search is still in-flight.
+ pending_query: String,
+ /// When `true` we are still waiting for results for `pending_query`.
+ waiting: bool,
+ /// Cached matches; paths relative to the search dir.
+ matches: Vec<FileMatch>,
+ /// Shared selection/scroll state.
+ state: ScrollState,
+}
+
+impl FileSearchPopup {
+ pub(crate) fn new() -> Self {
+ Self {
+ display_query: String::new(),
+ pending_query: String::new(),
+ waiting: true,
+ matches: Vec::new(),
+ state: ScrollState::new(),
+ }
+ }
+
+ /// Update the query and reset state to *waiting*.
+ pub(crate) fn set_query(&mut self, query: &str) {
+ if query == self.pending_query {
+ return;
+ }
+
+ // Determine if current matches are still relevant.
+ let keep_existing = query.starts_with(&self.display_query);
+
+ self.pending_query.clear();
+ self.pending_query.push_str(query);
+
+ self.waiting = true; // waiting for new results
+
+ if !keep_existing {
+ self.matches.clear();
+ self.state.reset();
+ }
+ }
+
+ /// Put the popup into an "idle" state used for an empty query (just "@").
+ /// Shows a hint instead of matches until the user types more characters.
+ pub(crate) fn set_empty_prompt(&mut self) {
+ self.display_query.clear();
+ self.pending_query.clear();
+ self.waiting = false;
+ self.matches.clear();
+ // Reset selection/scroll state when showing the empty prompt.
+ self.state.reset();
+ }
+
+ /// Replace matches when a `FileSearchResult` arrives.
+ /// Replace matches. Only applied when `query` matches `pending_query`.
+ pub(crate) fn set_matches(&mut self, query: &str, matches: Vec<FileMatch>) {
+ if query != self.pending_query {
+ return; // stale
+ }
+
+ self.display_query = query.to_string();
+ self.matches = matches;
+ self.waiting = false;
+ let len = self.matches.len();
+ self.state.clamp_selection(len);
+ self.state.ensure_visible(len, len.min(MAX_POPUP_ROWS));
+ }
+
+ /// Move selection cursor up.
+ pub(crate) fn move_up(&mut self) {
+ let len = self.matches.len();
+ self.state.move_up_wrap(len);
+ self.state.ensure_visible(len, len.min(MAX_POPUP_ROWS));
+ }
+
+ /// Move selection cursor down.
+ pub(crate) fn move_down(&mut self) {
+ let len = self.matches.len();
+ self.state.move_down_wrap(len);
+ self.state.ensure_visible(len, len.min(MAX_POPUP_ROWS));
+ }
+
+ pub(crate) fn selected_match(&self) -> Option<&str> {
+ self.state
+ .selected_idx
+ .and_then(|idx| self.matches.get(idx))
+ .map(|file_match| file_match.path.as_str())
+ }
+
+ pub(crate) fn calculate_required_height(&self) -> u16 {
+ // Row count depends on whether we already have matches. If no matches
+ // yet (e.g. initial search or query with no results) reserve a single
+ // row so the popup is still visible. When matches are present we show
+ // up to MAX_RESULTS regardless of the waiting flag so the list
+ // remains stable while a newer search is in-flight.
+
+ self.matches.len().clamp(1, MAX_POPUP_ROWS) as u16
+ }
+}
+
+impl WidgetRef for &FileSearchPopup {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ // Convert matches to GenericDisplayRow, translating indices to usize at the UI boundary.
+ let rows_all: Vec<GenericDisplayRow> = if self.matches.is_empty() {
+ Vec::new()
+ } else {
+ self.matches
+ .iter()
+ .map(|m| GenericDisplayRow {
+ name: m.path.clone(),
+ match_indices: m
+ .indices
+ .as_ref()
+ .map(|v| v.iter().map(|&i| i as usize).collect()),
+ display_shortcut: None,
+ description: None,
+ wrap_indent: None,
+ })
+ .collect()
+ };
+
+ let empty_message = if self.waiting {
+ "loading..."
+ } else {
+ "no matches"
+ };
+
+ render_rows(
+ area.inset(Insets::tlbr(0, 2, 0, 0)),
+ buf,
+ &rows_all,
+ &self.state,
+ MAX_POPUP_ROWS,
+ empty_message,
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/footer.rs b/codex-rs/tui2/src/bottom_pane/footer.rs
new file mode 100644
index 0000000000..d47ffec98b
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/footer.rs
@@ -0,0 +1,530 @@
+#[cfg(target_os = "linux")]
+use crate::clipboard_paste::is_probably_wsl;
+use crate::key_hint;
+use crate::key_hint::KeyBinding;
+use crate::render::line_utils::prefix_lines;
+use crate::status::format_tokens_compact;
+use crate::ui_consts::FOOTER_INDENT_COLS;
+use crossterm::event::KeyCode;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::Widget;
+
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct FooterProps {
+ pub(crate) mode: FooterMode,
+ pub(crate) esc_backtrack_hint: bool,
+ pub(crate) use_shift_enter_hint: bool,
+ pub(crate) is_task_running: bool,
+ pub(crate) context_window_percent: Option<i64>,
+ pub(crate) context_window_used_tokens: Option<i64>,
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) enum FooterMode {
+ CtrlCReminder,
+ ShortcutSummary,
+ ShortcutOverlay,
+ EscHint,
+ ContextOnly,
+}
+
+pub(crate) fn toggle_shortcut_mode(current: FooterMode, ctrl_c_hint: bool) -> FooterMode {
+ if ctrl_c_hint && matches!(current, FooterMode::CtrlCReminder) {
+ return current;
+ }
+
+ match current {
+ FooterMode::ShortcutOverlay | FooterMode::CtrlCReminder => FooterMode::ShortcutSummary,
+ _ => FooterMode::ShortcutOverlay,
+ }
+}
+
+pub(crate) fn esc_hint_mode(current: FooterMode, is_task_running: bool) -> FooterMode {
+ if is_task_running {
+ current
+ } else {
+ FooterMode::EscHint
+ }
+}
+
+pub(crate) fn reset_mode_after_activity(current: FooterMode) -> FooterMode {
+ match current {
+ FooterMode::EscHint
+ | FooterMode::ShortcutOverlay
+ | FooterMode::CtrlCReminder
+ | FooterMode::ContextOnly => FooterMode::ShortcutSummary,
+ other => other,
+ }
+}
+
+pub(crate) fn footer_height(props: FooterProps) -> u16 {
+ footer_lines(props).len() as u16
+}
+
+pub(crate) fn render_footer(area: Rect, buf: &mut Buffer, props: FooterProps) {
+ Paragraph::new(prefix_lines(
+ footer_lines(props),
+ " ".repeat(FOOTER_INDENT_COLS).into(),
+ " ".repeat(FOOTER_INDENT_COLS).into(),
+ ))
+ .render(area, buf);
+}
+
+fn footer_lines(props: FooterProps) -> Vec<Line<'static>> {
+ // Show the context indicator on the left, appended after the primary hint
+ // (e.g., "? for shortcuts"). Keep it visible even when typing (i.e., when
+ // the shortcut hint is hidden). Hide it only for the multi-line
+ // ShortcutOverlay.
+ match props.mode {
+ FooterMode::CtrlCReminder => vec![ctrl_c_reminder_line(CtrlCReminderState {
+ is_task_running: props.is_task_running,
+ })],
+ FooterMode::ShortcutSummary => {
+ let mut line = context_window_line(
+ props.context_window_percent,
+ props.context_window_used_tokens,
+ );
+ line.push_span(" · ".dim());
+ line.extend(vec![
+ key_hint::plain(KeyCode::Char('?')).into(),
+ " for shortcuts".dim(),
+ ]);
+ vec![line]
+ }
+ FooterMode::ShortcutOverlay => {
+ #[cfg(target_os = "linux")]
+ let is_wsl = is_probably_wsl();
+ #[cfg(not(target_os = "linux"))]
+ let is_wsl = false;
+
+ let state = ShortcutsState {
+ use_shift_enter_hint: props.use_shift_enter_hint,
+ esc_backtrack_hint: props.esc_backtrack_hint,
+ is_wsl,
+ };
+ shortcut_overlay_lines(state)
+ }
+ FooterMode::EscHint => vec![esc_hint_line(props.esc_backtrack_hint)],
+ FooterMode::ContextOnly => vec![context_window_line(
+ props.context_window_percent,
+ props.context_window_used_tokens,
+ )],
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+struct CtrlCReminderState {
+ is_task_running: bool,
+}
+
+#[derive(Clone, Copy, Debug)]
+struct ShortcutsState {
+ use_shift_enter_hint: bool,
+ esc_backtrack_hint: bool,
+ is_wsl: bool,
+}
+
+fn ctrl_c_reminder_line(state: CtrlCReminderState) -> Line<'static> {
+ let action = if state.is_task_running {
+ "interrupt"
+ } else {
+ "quit"
+ };
+ Line::from(vec![
+ key_hint::ctrl(KeyCode::Char('c')).into(),
+ format!(" again to {action}").into(),
+ ])
+ .dim()
+}
+
+fn esc_hint_line(esc_backtrack_hint: bool) -> Line<'static> {
+ let esc = key_hint::plain(KeyCode::Esc);
+ if esc_backtrack_hint {
+ Line::from(vec![esc.into(), " again to edit previous message".into()]).dim()
+ } else {
+ Line::from(vec![
+ esc.into(),
+ " ".into(),
+ esc.into(),
+ " to edit previous message".into(),
+ ])
+ .dim()
+ }
+}
+
+fn shortcut_overlay_lines(state: ShortcutsState) -> Vec<Line<'static>> {
+ let mut commands = Line::from("");
+ let mut newline = Line::from("");
+ let mut file_paths = Line::from("");
+ let mut paste_image = Line::from("");
+ let mut edit_previous = Line::from("");
+ let mut quit = Line::from("");
+ let mut show_transcript = Line::from("");
+
+ for descriptor in SHORTCUTS {
+ if let Some(text) = descriptor.overlay_entry(state) {
+ match descriptor.id {
+ ShortcutId::Commands => commands = text,
+ ShortcutId::InsertNewline => newline = text,
+ ShortcutId::FilePaths => file_paths = text,
+ ShortcutId::PasteImage => paste_image = text,
+ ShortcutId::EditPrevious => edit_previous = text,
+ ShortcutId::Quit => quit = text,
+ ShortcutId::ShowTranscript => show_transcript = text,
+ }
+ }
+ }
+
+ let ordered = vec![
+ commands,
+ newline,
+ file_paths,
+ paste_image,
+ edit_previous,
+ quit,
+ Line::from(""),
+ show_transcript,
+ ];
+
+ build_columns(ordered)
+}
+
+fn build_columns(entries: Vec<Line<'static>>) -> Vec<Line<'static>> {
+ if entries.is_empty() {
+ return Vec::new();
+ }
+
+ const COLUMNS: usize = 2;
+ const COLUMN_PADDING: [usize; COLUMNS] = [4, 4];
+ const COLUMN_GAP: usize = 4;
+
+ let rows = entries.len().div_ceil(COLUMNS);
+ let target_len = rows * COLUMNS;
+ let mut entries = entries;
+ if entries.len() < target_len {
+ entries.extend(std::iter::repeat_n(
+ Line::from(""),
+ target_len - entries.len(),
+ ));
+ }
+
+ let mut column_widths = [0usize; COLUMNS];
+
+ for (idx, entry) in entries.iter().enumerate() {
+ let column = idx % COLUMNS;
+ column_widths[column] = column_widths[column].max(entry.width());
+ }
+
+ for (idx, width) in column_widths.iter_mut().enumerate() {
+ *width += COLUMN_PADDING[idx];
+ }
+
+ entries
+ .chunks(COLUMNS)
+ .map(|chunk| {
+ let mut line = Line::from("");
+ for (col, entry) in chunk.iter().enumerate() {
+ line.extend(entry.spans.clone());
+ if col < COLUMNS - 1 {
+ let target_width = column_widths[col];
+ let padding = target_width.saturating_sub(entry.width()) + COLUMN_GAP;
+ line.push_span(Span::from(" ".repeat(padding)));
+ }
+ }
+ line.dim()
+ })
+ .collect()
+}
+
+fn context_window_line(percent: Option<i64>, used_tokens: Option<i64>) -> Line<'static> {
+ if let Some(percent) = percent {
+ let percent = percent.clamp(0, 100);
+ return Line::from(vec![Span::from(format!("{percent}% context left")).dim()]);
+ }
+
+ if let Some(tokens) = used_tokens {
+ let used_fmt = format_tokens_compact(tokens);
+ return Line::from(vec![Span::from(format!("{used_fmt} used")).dim()]);
+ }
+
+ Line::from(vec![Span::from("100% context left").dim()])
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum ShortcutId {
+ Commands,
+ InsertNewline,
+ FilePaths,
+ PasteImage,
+ EditPrevious,
+ Quit,
+ ShowTranscript,
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+struct ShortcutBinding {
+ key: KeyBinding,
+ condition: DisplayCondition,
+}
+
+impl ShortcutBinding {
+ fn matches(&self, state: ShortcutsState) -> bool {
+ self.condition.matches(state)
+ }
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum DisplayCondition {
+ Always,
+ WhenShiftEnterHint,
+ WhenNotShiftEnterHint,
+ WhenUnderWSL,
+}
+
+impl DisplayCondition {
+ fn matches(self, state: ShortcutsState) -> bool {
+ match self {
+ DisplayCondition::Always => true,
+ DisplayCondition::WhenShiftEnterHint => state.use_shift_enter_hint,
+ DisplayCondition::WhenNotShiftEnterHint => !state.use_shift_enter_hint,
+ DisplayCondition::WhenUnderWSL => state.is_wsl,
+ }
+ }
+}
+
+struct ShortcutDescriptor {
+ id: ShortcutId,
+ bindings: &'static [ShortcutBinding],
+ prefix: &'static str,
+ label: &'static str,
+}
+
+impl ShortcutDescriptor {
+ fn binding_for(&self, state: ShortcutsState) -> Option<&'static ShortcutBinding> {
+ self.bindings.iter().find(|binding| binding.matches(state))
+ }
+
+ fn overlay_entry(&self, state: ShortcutsState) -> Option<Line<'static>> {
+ let binding = self.binding_for(state)?;
+ let mut line = Line::from(vec![self.prefix.into(), binding.key.into()]);
+ match self.id {
+ ShortcutId::EditPrevious => {
+ if state.esc_backtrack_hint {
+ line.push_span(" again to edit previous message");
+ } else {
+ line.extend(vec![
+ " ".into(),
+ key_hint::plain(KeyCode::Esc).into(),
+ " to edit previous message".into(),
+ ]);
+ }
+ }
+ _ => line.push_span(self.label),
+ };
+ Some(line)
+ }
+}
+
+const SHORTCUTS: &[ShortcutDescriptor] = &[
+ ShortcutDescriptor {
+ id: ShortcutId::Commands,
+ bindings: &[ShortcutBinding {
+ key: key_hint::plain(KeyCode::Char('/')),
+ condition: DisplayCondition::Always,
+ }],
+ prefix: "",
+ label: " for commands",
+ },
+ ShortcutDescriptor {
+ id: ShortcutId::InsertNewline,
+ bindings: &[
+ ShortcutBinding {
+ key: key_hint::shift(KeyCode::Enter),
+ condition: DisplayCondition::WhenShiftEnterHint,
+ },
+ ShortcutBinding {
+ key: key_hint::ctrl(KeyCode::Char('j')),
+ condition: DisplayCondition::WhenNotShiftEnterHint,
+ },
+ ],
+ prefix: "",
+ label: " for newline",
+ },
+ ShortcutDescriptor {
+ id: ShortcutId::FilePaths,
+ bindings: &[ShortcutBinding {
+ key: key_hint::plain(KeyCode::Char('@')),
+ condition: DisplayCondition::Always,
+ }],
+ prefix: "",
+ label: " for file paths",
+ },
+ ShortcutDescriptor {
+ id: ShortcutId::PasteImage,
+ // Show Ctrl+Alt+V when running under WSL (terminals often intercept plain
+ // Ctrl+V); otherwise fall back to Ctrl+V.
+ bindings: &[
+ ShortcutBinding {
+ key: key_hint::ctrl_alt(KeyCode::Char('v')),
+ condition: DisplayCondition::WhenUnderWSL,
+ },
+ ShortcutBinding {
+ key: key_hint::ctrl(KeyCode::Char('v')),
+ condition: DisplayCondition::Always,
+ },
+ ],
+ prefix: "",
+ label: " to paste images",
+ },
+ ShortcutDescriptor {
+ id: ShortcutId::EditPrevious,
+ bindings: &[ShortcutBinding {
+ key: key_hint::plain(KeyCode::Esc),
+ condition: DisplayCondition::Always,
+ }],
+ prefix: "",
+ label: "",
+ },
+ ShortcutDescriptor {
+ id: ShortcutId::Quit,
+ bindings: &[ShortcutBinding {
+ key: key_hint::ctrl(KeyCode::Char('c')),
+ condition: DisplayCondition::Always,
+ }],
+ prefix: "",
+ label: " to exit",
+ },
+ ShortcutDescriptor {
+ id: ShortcutId::ShowTranscript,
+ bindings: &[ShortcutBinding {
+ key: key_hint::ctrl(KeyCode::Char('t')),
+ condition: DisplayCondition::Always,
+ }],
+ prefix: "",
+ label: " to view transcript",
+ },
+];
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use insta::assert_snapshot;
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+
+ fn snapshot_footer(name: &str, props: FooterProps) {
+ let height = footer_height(props).max(1);
+ let mut terminal = Terminal::new(TestBackend::new(80, height)).unwrap();
+ terminal
+ .draw(|f| {
+ let area = Rect::new(0, 0, f.area().width, height);
+ render_footer(area, f.buffer_mut(), props);
+ })
+ .unwrap();
+ assert_snapshot!(name, terminal.backend());
+ }
+
+ #[test]
+ fn footer_snapshots() {
+ snapshot_footer(
+ "footer_shortcuts_default",
+ FooterProps {
+ mode: FooterMode::ShortcutSummary,
+ esc_backtrack_hint: false,
+ use_shift_enter_hint: false,
+ is_task_running: false,
+ context_window_percent: None,
+ context_window_used_tokens: None,
+ },
+ );
+
+ snapshot_footer(
+ "footer_shortcuts_shift_and_esc",
+ FooterProps {
+ mode: FooterMode::ShortcutOverlay,
+ esc_backtrack_hint: true,
+ use_shift_enter_hint: true,
+ is_task_running: false,
+ context_window_percent: None,
+ context_window_used_tokens: None,
+ },
+ );
+
+ snapshot_footer(
+ "footer_ctrl_c_quit_idle",
+ FooterProps {
+ mode: FooterMode::CtrlCReminder,
+ esc_backtrack_hint: false,
+ use_shift_enter_hint: false,
+ is_task_running: false,
+ context_window_percent: None,
+ context_window_used_tokens: None,
+ },
+ );
+
+ snapshot_footer(
+ "footer_ctrl_c_quit_running",
+ FooterProps {
+ mode: FooterMode::CtrlCReminder,
+ esc_backtrack_hint: false,
+ use_shift_enter_hint: false,
+ is_task_running: true,
+ context_window_percent: None,
+ context_window_used_tokens: None,
+ },
+ );
+
+ snapshot_footer(
+ "footer_esc_hint_idle",
+ FooterProps {
+ mode: FooterMode::EscHint,
+ esc_backtrack_hint: false,
+ use_shift_enter_hint: false,
+ is_task_running: false,
+ context_window_percent: None,
+ context_window_used_tokens: None,
+ },
+ );
+
+ snapshot_footer(
+ "footer_esc_hint_primed",
+ FooterProps {
+ mode: FooterMode::EscHint,
+ esc_backtrack_hint: true,
+ use_shift_enter_hint: false,
+ is_task_running: false,
+ context_window_percent: None,
+ context_window_used_tokens: None,
+ },
+ );
+
+ snapshot_footer(
+ "footer_shortcuts_context_running",
+ FooterProps {
+ mode: FooterMode::ShortcutSummary,
+ esc_backtrack_hint: false,
+ use_shift_enter_hint: false,
+ is_task_running: true,
+ context_window_percent: Some(72),
+ context_window_used_tokens: None,
+ },
+ );
+
+ snapshot_footer(
+ "footer_context_tokens_used",
+ FooterProps {
+ mode: FooterMode::ShortcutSummary,
+ esc_backtrack_hint: false,
+ use_shift_enter_hint: false,
+ is_task_running: false,
+ context_window_percent: None,
+ context_window_used_tokens: Some(123_456),
+ },
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/list_selection_view.rs b/codex-rs/tui2/src/bottom_pane/list_selection_view.rs
new file mode 100644
index 0000000000..d23fd8ed3b
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/list_selection_view.rs
@@ -0,0 +1,794 @@
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyModifiers;
+use itertools::Itertools as _;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Constraint;
+use ratatui::layout::Layout;
+use ratatui::layout::Rect;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::widgets::Block;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::Widget;
+
+use crate::app_event_sender::AppEventSender;
+use crate::key_hint::KeyBinding;
+use crate::render::Insets;
+use crate::render::RectExt as _;
+use crate::render::renderable::ColumnRenderable;
+use crate::render::renderable::Renderable;
+use crate::style::user_message_style;
+
+use super::CancellationEvent;
+use super::bottom_pane_view::BottomPaneView;
+use super::popup_consts::MAX_POPUP_ROWS;
+use super::scroll_state::ScrollState;
+use super::selection_popup_common::GenericDisplayRow;
+use super::selection_popup_common::measure_rows_height;
+use super::selection_popup_common::render_rows;
+use unicode_width::UnicodeWidthStr;
+
+/// One selectable item in the generic selection list.
+pub(crate) type SelectionAction = Box<dyn Fn(&AppEventSender) + Send + Sync>;
+
+#[derive(Default)]
+pub(crate) struct SelectionItem {
+ pub name: String,
+ pub display_shortcut: Option<KeyBinding>,
+ pub description: Option<String>,
+ pub selected_description: Option<String>,
+ pub is_current: bool,
+ pub actions: Vec<SelectionAction>,
+ pub dismiss_on_select: bool,
+ pub search_value: Option<String>,
+}
+
+pub(crate) struct SelectionViewParams {
+ pub title: Option<String>,
+ pub subtitle: Option<String>,
+ pub footer_hint: Option<Line<'static>>,
+ pub items: Vec<SelectionItem>,
+ pub is_searchable: bool,
+ pub search_placeholder: Option<String>,
+ pub header: Box<dyn Renderable>,
+ pub initial_selected_idx: Option<usize>,
+}
+
+impl Default for SelectionViewParams {
+ fn default() -> Self {
+ Self {
+ title: None,
+ subtitle: None,
+ footer_hint: None,
+ items: Vec::new(),
+ is_searchable: false,
+ search_placeholder: None,
+ header: Box::new(()),
+ initial_selected_idx: None,
+ }
+ }
+}
+
+pub(crate) struct ListSelectionView {
+ footer_hint: Option<Line<'static>>,
+ items: Vec<SelectionItem>,
+ state: ScrollState,
+ complete: bool,
+ app_event_tx: AppEventSender,
+ is_searchable: bool,
+ search_query: String,
+ search_placeholder: Option<String>,
+ filtered_indices: Vec<usize>,
+ last_selected_actual_idx: Option<usize>,
+ header: Box<dyn Renderable>,
+ initial_selected_idx: Option<usize>,
+}
+
+impl ListSelectionView {
+ pub fn new(params: SelectionViewParams, app_event_tx: AppEventSender) -> Self {
+ let mut header = params.header;
+ if params.title.is_some() || params.subtitle.is_some() {
+ let title = params.title.map(|title| Line::from(title.bold()));
+ let subtitle = params.subtitle.map(|subtitle| Line::from(subtitle.dim()));
+ header = Box::new(ColumnRenderable::with([
+ header,
+ Box::new(title),
+ Box::new(subtitle),
+ ]));
+ }
+ let mut s = Self {
+ footer_hint: params.footer_hint,
+ items: params.items,
+ state: ScrollState::new(),
+ complete: false,
+ app_event_tx,
+ is_searchable: params.is_searchable,
+ search_query: String::new(),
+ search_placeholder: if params.is_searchable {
+ params.search_placeholder
+ } else {
+ None
+ },
+ filtered_indices: Vec::new(),
+ last_selected_actual_idx: None,
+ header,
+ initial_selected_idx: params.initial_selected_idx,
+ };
+ s.apply_filter();
+ s
+ }
+
+ fn visible_len(&self) -> usize {
+ self.filtered_indices.len()
+ }
+
+ fn max_visible_rows(len: usize) -> usize {
+ MAX_POPUP_ROWS.min(len.max(1))
+ }
+
+ fn apply_filter(&mut self) {
+ let previously_selected = self
+ .state
+ .selected_idx
+ .and_then(|visible_idx| self.filtered_indices.get(visible_idx).copied())
+ .or_else(|| {
+ (!self.is_searchable)
+ .then(|| self.items.iter().position(|item| item.is_current))
+ .flatten()
+ })
+ .or_else(|| self.initial_selected_idx.take());
+
+ if self.is_searchable && !self.search_query.is_empty() {
+ let query_lower = self.search_query.to_lowercase();
+ self.filtered_indices = self
+ .items
+ .iter()
+ .positions(|item| {
+ item.search_value
+ .as_ref()
+ .is_some_and(|v| v.to_lowercase().contains(&query_lower))
+ })
+ .collect();
+ } else {
+ self.filtered_indices = (0..self.items.len()).collect();
+ }
+
+ let len = self.filtered_indices.len();
+ self.state.selected_idx = self
+ .state
+ .selected_idx
+ .and_then(|visible_idx| {
+ self.filtered_indices
+ .get(visible_idx)
+ .and_then(|idx| self.filtered_indices.iter().position(|cur| cur == idx))
+ })
+ .or_else(|| {
+ previously_selected.and_then(|actual_idx| {
+ self.filtered_indices
+ .iter()
+ .position(|idx| *idx == actual_idx)
+ })
+ })
+ .or_else(|| (len > 0).then_some(0));
+
+ let visible = Self::max_visible_rows(len);
+ self.state.clamp_selection(len);
+ self.state.ensure_visible(len, visible);
+ }
+
+ fn build_rows(&self) -> Vec<GenericDisplayRow> {
+ self.filtered_indices
+ .iter()
+ .enumerate()
+ .filter_map(|(visible_idx, actual_idx)| {
+ self.items.get(*actual_idx).map(|item| {
+ let is_selected = self.state.selected_idx == Some(visible_idx);
+ let prefix = if is_selected { '›' } else { ' ' };
+ let name = item.name.as_str();
+ let name_with_marker = if item.is_current {
+ format!("{name} (current)")
+ } else {
+ item.name.clone()
+ };
+ let n = visible_idx + 1;
+ let wrap_prefix = if self.is_searchable {
+ // The number keys don't work when search is enabled (since we let the
+ // numbers be used for the search query).
+ format!("{prefix} ")
+ } else {
+ format!("{prefix} {n}. ")
+ };
+ let wrap_prefix_width = UnicodeWidthStr::width(wrap_prefix.as_str());
+ let display_name = format!("{wrap_prefix}{name_with_marker}");
+ let description = is_selected
+ .then(|| item.selected_description.clone())
+ .flatten()
+ .or_else(|| item.description.clone());
+ let wrap_indent = description.is_none().then_some(wrap_prefix_width);
+ GenericDisplayRow {
+ name: display_name,
+ display_shortcut: item.display_shortcut,
+ match_indices: None,
+ description,
+ wrap_indent,
+ }
+ })
+ })
+ .collect()
+ }
+
+ fn move_up(&mut self) {
+ let len = self.visible_len();
+ self.state.move_up_wrap(len);
+ let visible = Self::max_visible_rows(len);
+ self.state.ensure_visible(len, visible);
+ }
+
+ fn move_down(&mut self) {
+ let len = self.visible_len();
+ self.state.move_down_wrap(len);
+ let visible = Self::max_visible_rows(len);
+ self.state.ensure_visible(len, visible);
+ }
+
+ fn accept(&mut self) {
+ if let Some(idx) = self.state.selected_idx
+ && let Some(actual_idx) = self.filtered_indices.get(idx)
+ && let Some(item) = self.items.get(*actual_idx)
+ {
+ self.last_selected_actual_idx = Some(*actual_idx);
+ for act in &item.actions {
+ act(&self.app_event_tx);
+ }
+ if item.dismiss_on_select {
+ self.complete = true;
+ }
+ } else {
+ self.complete = true;
+ }
+ }
+
+ #[cfg(test)]
+ pub(crate) fn set_search_query(&mut self, query: String) {
+ self.search_query = query;
+ self.apply_filter();
+ }
+
+ pub(crate) fn take_last_selected_index(&mut self) -> Option<usize> {
+ self.last_selected_actual_idx.take()
+ }
+
+ fn rows_width(total_width: u16) -> u16 {
+ total_width.saturating_sub(2)
+ }
+}
+
+impl BottomPaneView for ListSelectionView {
+ fn handle_key_event(&mut self, key_event: KeyEvent) {
+ match key_event {
+ // Some terminals (or configurations) send Control key chords as
+ // C0 control characters without reporting the CONTROL modifier.
+ // Handle fallbacks for Ctrl-P/N here so navigation works everywhere.
+ KeyEvent {
+ code: KeyCode::Up, ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('p'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('\u{0010}'),
+ modifiers: KeyModifiers::NONE,
+ ..
+ } /* ^P */ => self.move_up(),
+ KeyEvent {
+ code: KeyCode::Char('k'),
+ modifiers: KeyModifiers::NONE,
+ ..
+ } if !self.is_searchable => self.move_up(),
+ KeyEvent {
+ code: KeyCode::Down,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('n'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('\u{000e}'),
+ modifiers: KeyModifiers::NONE,
+ ..
+ } /* ^N */ => self.move_down(),
+ KeyEvent {
+ code: KeyCode::Char('j'),
+ modifiers: KeyModifiers::NONE,
+ ..
+ } if !self.is_searchable => self.move_down(),
+ KeyEvent {
+ code: KeyCode::Backspace,
+ ..
+ } if self.is_searchable => {
+ self.search_query.pop();
+ self.apply_filter();
+ }
+ KeyEvent {
+ code: KeyCode::Esc, ..
+ } => {
+ self.on_ctrl_c();
+ }
+ KeyEvent {
+ code: KeyCode::Char(c),
+ modifiers,
+ ..
+ } if self.is_searchable
+ && !modifiers.contains(KeyModifiers::CONTROL)
+ && !modifiers.contains(KeyModifiers::ALT) =>
+ {
+ self.search_query.push(c);
+ self.apply_filter();
+ }
+ KeyEvent {
+ code: KeyCode::Char(c),
+ modifiers,
+ ..
+ } if !self.is_searchable
+ && !modifiers.contains(KeyModifiers::CONTROL)
+ && !modifiers.contains(KeyModifiers::ALT) =>
+ {
+ if let Some(idx) = c
+ .to_digit(10)
+ .map(|d| d as usize)
+ .and_then(|d| d.checked_sub(1))
+ && idx < self.items.len()
+ {
+ self.state.selected_idx = Some(idx);
+ self.accept();
+ }
+ }
+ KeyEvent {
+ code: KeyCode::Enter,
+ modifiers: KeyModifiers::NONE,
+ ..
+ } => self.accept(),
+ _ => {}
+ }
+ }
+
+ fn is_complete(&self) -> bool {
+ self.complete
+ }
+
+ fn on_ctrl_c(&mut self) -> CancellationEvent {
+ self.complete = true;
+ CancellationEvent::Handled
+ }
+}
+
+impl Renderable for ListSelectionView {
+ fn desired_height(&self, width: u16) -> u16 {
+ // Measure wrapped height for up to MAX_POPUP_ROWS items at the given width.
+ // Build the same display rows used by the renderer so wrapping math matches.
+ let rows = self.build_rows();
+ let rows_width = Self::rows_width(width);
+ let rows_height = measure_rows_height(
+ &rows,
+ &self.state,
+ MAX_POPUP_ROWS,
+ rows_width.saturating_add(1),
+ );
+
+ // Subtract 4 for the padding on the left and right of the header.
+ let mut height = self.header.desired_height(width.saturating_sub(4));
+ height = height.saturating_add(rows_height + 3);
+ if self.is_searchable {
+ height = height.saturating_add(1);
+ }
+ if self.footer_hint.is_some() {
+ height = height.saturating_add(1);
+ }
+ height
+ }
+
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ if area.height == 0 || area.width == 0 {
+ return;
+ }
+
+ let [content_area, footer_area] = Layout::vertical([
+ Constraint::Fill(1),
+ Constraint::Length(if self.footer_hint.is_some() { 1 } else { 0 }),
+ ])
+ .areas(area);
+
+ Block::default()
+ .style(user_message_style())
+ .render(content_area, buf);
+
+ let header_height = self
+ .header
+ // Subtract 4 for the padding on the left and right of the header.
+ .desired_height(content_area.width.saturating_sub(4));
+ let rows = self.build_rows();
+ let rows_width = Self::rows_width(content_area.width);
+ let rows_height = measure_rows_height(
+ &rows,
+ &self.state,
+ MAX_POPUP_ROWS,
+ rows_width.saturating_add(1),
+ );
+ let [header_area, _, search_area, list_area] = Layout::vertical([
+ Constraint::Max(header_height),
+ Constraint::Max(1),
+ Constraint::Length(if self.is_searchable { 1 } else { 0 }),
+ Constraint::Length(rows_height),
+ ])
+ .areas(content_area.inset(Insets::vh(1, 2)));
+
+ if header_area.height < header_height {
+ let [header_area, elision_area] =
+ Layout::vertical([Constraint::Fill(1), Constraint::Length(1)]).areas(header_area);
+ self.header.render(header_area, buf);
+ Paragraph::new(vec![
+ Line::from(format!("[… {header_height} lines] ctrl + a view all")).dim(),
+ ])
+ .render(elision_area, buf);
+ } else {
+ self.header.render(header_area, buf);
+ }
+
+ if self.is_searchable {
+ Line::from(self.search_query.clone()).render(search_area, buf);
+ let query_span: Span<'static> = if self.search_query.is_empty() {
+ self.search_placeholder
+ .as_ref()
+ .map(|placeholder| placeholder.clone().dim())
+ .unwrap_or_else(|| "".into())
+ } else {
+ self.search_query.clone().into()
+ };
+ Line::from(query_span).render(search_area, buf);
+ }
+
+ if list_area.height > 0 {
+ let render_area = Rect {
+ x: list_area.x.saturating_sub(2),
+ y: list_area.y,
+ width: rows_width.max(1),
+ height: list_area.height,
+ };
+ render_rows(
+ render_area,
+ buf,
+ &rows,
+ &self.state,
+ render_area.height as usize,
+ "no matches",
+ );
+ }
+
+ if let Some(hint) = &self.footer_hint {
+ let hint_area = Rect {
+ x: footer_area.x + 2,
+ y: footer_area.y,
+ width: footer_area.width.saturating_sub(2),
+ height: footer_area.height,
+ };
+ hint.clone().dim().render(hint_area, buf);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::app_event::AppEvent;
+ use crate::bottom_pane::popup_consts::standard_popup_hint_line;
+ use insta::assert_snapshot;
+ use ratatui::layout::Rect;
+ use tokio::sync::mpsc::unbounded_channel;
+
+ fn make_selection_view(subtitle: Option<&str>) -> ListSelectionView {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let items = vec![
+ SelectionItem {
+ name: "Read Only".to_string(),
+ description: Some("Codex can read files".to_string()),
+ is_current: true,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "Full Access".to_string(),
+ description: Some("Codex can edit files".to_string()),
+ is_current: false,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ ];
+ ListSelectionView::new(
+ SelectionViewParams {
+ title: Some("Select Approval Mode".to_string()),
+ subtitle: subtitle.map(str::to_string),
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ ..Default::default()
+ },
+ tx,
+ )
+ }
+
+ fn render_lines(view: &ListSelectionView) -> String {
+ render_lines_with_width(view, 48)
+ }
+
+ fn render_lines_with_width(view: &ListSelectionView, width: u16) -> String {
+ let height = view.desired_height(width);
+ let area = Rect::new(0, 0, width, height);
+ let mut buf = Buffer::empty(area);
+ view.render(area, &mut buf);
+
+ let lines: Vec<String> = (0..area.height)
+ .map(|row| {
+ let mut line = String::new();
+ for col in 0..area.width {
+ let symbol = buf[(area.x + col, area.y + row)].symbol();
+ if symbol.is_empty() {
+ line.push(' ');
+ } else {
+ line.push_str(symbol);
+ }
+ }
+ line
+ })
+ .collect();
+ lines.join("\n")
+ }
+
+ #[test]
+ fn renders_blank_line_between_title_and_items_without_subtitle() {
+ let view = make_selection_view(None);
+ assert_snapshot!(
+ "list_selection_spacing_without_subtitle",
+ render_lines(&view)
+ );
+ }
+
+ #[test]
+ fn renders_blank_line_between_subtitle_and_items() {
+ let view = make_selection_view(Some("Switch between Codex approval presets"));
+ assert_snapshot!("list_selection_spacing_with_subtitle", render_lines(&view));
+ }
+
+ #[test]
+ fn renders_search_query_line_when_enabled() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let items = vec![SelectionItem {
+ name: "Read Only".to_string(),
+ description: Some("Codex can read files".to_string()),
+ is_current: false,
+ dismiss_on_select: true,
+ ..Default::default()
+ }];
+ let mut view = ListSelectionView::new(
+ SelectionViewParams {
+ title: Some("Select Approval Mode".to_string()),
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ is_searchable: true,
+ search_placeholder: Some("Type to search branches".to_string()),
+ ..Default::default()
+ },
+ tx,
+ );
+ view.set_search_query("filters".to_string());
+
+ let lines = render_lines(&view);
+ assert!(
+ lines.contains("filters"),
+ "expected search query line to include rendered query, got {lines:?}"
+ );
+ }
+
+ #[test]
+ fn wraps_long_option_without_overflowing_columns() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let items = vec![
+ SelectionItem {
+ name: "Yes, proceed".to_string(),
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "Yes, and don't ask again for commands that start with `python -mpre_commit run --files eslint-plugin/no-mixed-const-enum-exports.js`".to_string(),
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ ];
+ let view = ListSelectionView::new(
+ SelectionViewParams {
+ title: Some("Approval".to_string()),
+ items,
+ ..Default::default()
+ },
+ tx,
+ );
+
+ let rendered = render_lines_with_width(&view, 60);
+ let command_line = rendered
+ .lines()
+ .find(|line| line.contains("python -mpre_commit run"))
+ .expect("rendered lines should include wrapped command");
+ assert!(
+ command_line.starts_with(" `python -mpre_commit run"),
+ "wrapped command line should align under the numbered prefix:\n{rendered}"
+ );
+ assert!(
+ rendered.contains("eslint-plugin/no-")
+ && rendered.contains("mixed-const-enum-exports.js"),
+ "long command should not be truncated even when wrapped:\n{rendered}"
+ );
+ }
+
+ #[test]
+ fn width_changes_do_not_hide_rows() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let items = vec![
+ SelectionItem {
+ name: "gpt-5.1-codex".to_string(),
+ description: Some(
+ "Optimized for Codex. Balance of reasoning quality and coding ability."
+ .to_string(),
+ ),
+ is_current: true,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "gpt-5.1-codex-mini".to_string(),
+ description: Some(
+ "Optimized for Codex. Cheaper, faster, but less capable.".to_string(),
+ ),
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "gpt-4.1-codex".to_string(),
+ description: Some(
+ "Legacy model. Use when you need compatibility with older automations."
+ .to_string(),
+ ),
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ ];
+ let view = ListSelectionView::new(
+ SelectionViewParams {
+ title: Some("Select Model and Effort".to_string()),
+ items,
+ ..Default::default()
+ },
+ tx,
+ );
+ let mut missing: Vec<u16> = Vec::new();
+ for width in 60..=90 {
+ let rendered = render_lines_with_width(&view, width);
+ if !rendered.contains("3.") {
+ missing.push(width);
+ }
+ }
+ assert!(
+ missing.is_empty(),
+ "third option missing at widths {missing:?}"
+ );
+ }
+
+ #[test]
+ fn narrow_width_keeps_all_rows_visible() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let desc = "x".repeat(10);
+ let items: Vec<SelectionItem> = (1..=3)
+ .map(|idx| SelectionItem {
+ name: format!("Item {idx}"),
+ description: Some(desc.clone()),
+ dismiss_on_select: true,
+ ..Default::default()
+ })
+ .collect();
+ let view = ListSelectionView::new(
+ SelectionViewParams {
+ title: Some("Debug".to_string()),
+ items,
+ ..Default::default()
+ },
+ tx,
+ );
+ let rendered = render_lines_with_width(&view, 24);
+ assert!(
+ rendered.contains("3."),
+ "third option missing for width 24:\n{rendered}"
+ );
+ }
+
+ #[test]
+ fn snapshot_model_picker_width_80() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let items = vec![
+ SelectionItem {
+ name: "gpt-5.1-codex".to_string(),
+ description: Some(
+ "Optimized for Codex. Balance of reasoning quality and coding ability."
+ .to_string(),
+ ),
+ is_current: true,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "gpt-5.1-codex-mini".to_string(),
+ description: Some(
+ "Optimized for Codex. Cheaper, faster, but less capable.".to_string(),
+ ),
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "gpt-4.1-codex".to_string(),
+ description: Some(
+ "Legacy model. Use when you need compatibility with older automations."
+ .to_string(),
+ ),
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ ];
+ let view = ListSelectionView::new(
+ SelectionViewParams {
+ title: Some("Select Model and Effort".to_string()),
+ items,
+ ..Default::default()
+ },
+ tx,
+ );
+ assert_snapshot!(
+ "list_selection_model_picker_width_80",
+ render_lines_with_width(&view, 80)
+ );
+ }
+
+ #[test]
+ fn snapshot_narrow_width_preserves_third_option() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let desc = "x".repeat(10);
+ let items: Vec<SelectionItem> = (1..=3)
+ .map(|idx| SelectionItem {
+ name: format!("Item {idx}"),
+ description: Some(desc.clone()),
+ dismiss_on_select: true,
+ ..Default::default()
+ })
+ .collect();
+ let view = ListSelectionView::new(
+ SelectionViewParams {
+ title: Some("Debug".to_string()),
+ items,
+ ..Default::default()
+ },
+ tx,
+ );
+ assert_snapshot!(
+ "list_selection_narrow_width_preserves_rows",
+ render_lines_with_width(&view, 24)
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/mod.rs b/codex-rs/tui2/src/bottom_pane/mod.rs
new file mode 100644
index 0000000000..554810de7f
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/mod.rs
@@ -0,0 +1,814 @@
+//! Bottom pane: shows the ChatComposer or a BottomPaneView, if one is active.
+use std::path::PathBuf;
+
+use crate::app_event_sender::AppEventSender;
+use crate::bottom_pane::queued_user_messages::QueuedUserMessages;
+use crate::render::renderable::FlexRenderable;
+use crate::render::renderable::Renderable;
+use crate::render::renderable::RenderableItem;
+use crate::tui::FrameRequester;
+use bottom_pane_view::BottomPaneView;
+use codex_core::features::Features;
+use codex_core::skills::model::SkillMetadata;
+use codex_file_search::FileMatch;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use std::time::Duration;
+
+mod approval_overlay;
+pub(crate) use approval_overlay::ApprovalOverlay;
+pub(crate) use approval_overlay::ApprovalRequest;
+mod bottom_pane_view;
+mod chat_composer;
+mod chat_composer_history;
+mod command_popup;
+pub mod custom_prompt_view;
+mod file_search_popup;
+mod footer;
+mod list_selection_view;
+mod prompt_args;
+mod skill_popup;
+pub(crate) use list_selection_view::SelectionViewParams;
+mod feedback_view;
+pub(crate) use feedback_view::feedback_selection_params;
+pub(crate) use feedback_view::feedback_upload_consent_params;
+mod paste_burst;
+pub mod popup_consts;
+mod queued_user_messages;
+mod scroll_state;
+mod selection_popup_common;
+mod textarea;
+pub(crate) use feedback_view::FeedbackNoteView;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum CancellationEvent {
+ Handled,
+ NotHandled,
+}
+
+pub(crate) use chat_composer::ChatComposer;
+pub(crate) use chat_composer::InputResult;
+use codex_protocol::custom_prompts::CustomPrompt;
+
+use crate::status_indicator_widget::StatusIndicatorWidget;
+pub(crate) use list_selection_view::SelectionAction;
+pub(crate) use list_selection_view::SelectionItem;
+
+/// Pane displayed in the lower half of the chat UI.
+pub(crate) struct BottomPane {
+ /// Composer is retained even when a BottomPaneView is displayed so the
+ /// input state is retained when the view is closed.
+ composer: ChatComposer,
+
+ /// Stack of views displayed instead of the composer (e.g. popups/modals).
+ view_stack: Vec<Box<dyn BottomPaneView>>,
+
+ app_event_tx: AppEventSender,
+ frame_requester: FrameRequester,
+
+ has_input_focus: bool,
+ is_task_running: bool,
+ ctrl_c_quit_hint: bool,
+ esc_backtrack_hint: bool,
+ animations_enabled: bool,
+
+ /// Inline status indicator shown above the composer while a task is running.
+ status: Option<StatusIndicatorWidget>,
+ /// Queued user messages to show above the composer while a turn is running.
+ queued_user_messages: QueuedUserMessages,
+ context_window_percent: Option<i64>,
+ context_window_used_tokens: Option<i64>,
+}
+
+pub(crate) struct BottomPaneParams {
+ pub(crate) app_event_tx: AppEventSender,
+ pub(crate) frame_requester: FrameRequester,
+ pub(crate) has_input_focus: bool,
+ pub(crate) enhanced_keys_supported: bool,
+ pub(crate) placeholder_text: String,
+ pub(crate) disable_paste_burst: bool,
+ pub(crate) animations_enabled: bool,
+ pub(crate) skills: Option<Vec<SkillMetadata>>,
+}
+
+impl BottomPane {
+ pub fn new(params: BottomPaneParams) -> Self {
+ let BottomPaneParams {
+ app_event_tx,
+ frame_requester,
+ has_input_focus,
+ enhanced_keys_supported,
+ placeholder_text,
+ disable_paste_burst,
+ animations_enabled,
+ skills,
+ } = params;
+ let mut composer = ChatComposer::new(
+ has_input_focus,
+ app_event_tx.clone(),
+ enhanced_keys_supported,
+ placeholder_text,
+ disable_paste_burst,
+ );
+ composer.set_skill_mentions(skills);
+
+ Self {
+ composer,
+ view_stack: Vec::new(),
+ app_event_tx,
+ frame_requester,
+ has_input_focus,
+ is_task_running: false,
+ ctrl_c_quit_hint: false,
+ status: None,
+ queued_user_messages: QueuedUserMessages::new(),
+ esc_backtrack_hint: false,
+ animations_enabled,
+ context_window_percent: None,
+ context_window_used_tokens: None,
+ }
+ }
+
+ pub fn status_widget(&self) -> Option<&StatusIndicatorWidget> {
+ self.status.as_ref()
+ }
+
+ #[cfg(test)]
+ pub(crate) fn context_window_percent(&self) -> Option<i64> {
+ self.context_window_percent
+ }
+
+ #[cfg(test)]
+ pub(crate) fn context_window_used_tokens(&self) -> Option<i64> {
+ self.context_window_used_tokens
+ }
+
+ fn active_view(&self) -> Option<&dyn BottomPaneView> {
+ self.view_stack.last().map(std::convert::AsRef::as_ref)
+ }
+
+ fn push_view(&mut self, view: Box<dyn BottomPaneView>) {
+ self.view_stack.push(view);
+ self.request_redraw();
+ }
+
+ /// Forward a key event to the active view or the composer.
+ pub fn handle_key_event(&mut self, key_event: KeyEvent) -> InputResult {
+ // If a modal/view is active, handle it here; otherwise forward to composer.
+ if let Some(view) = self.view_stack.last_mut() {
+ if key_event.code == KeyCode::Esc
+ && matches!(view.on_ctrl_c(), CancellationEvent::Handled)
+ && view.is_complete()
+ {
+ self.view_stack.pop();
+ self.on_active_view_complete();
+ } else {
+ view.handle_key_event(key_event);
+ if view.is_complete() {
+ self.view_stack.clear();
+ self.on_active_view_complete();
+ }
+ }
+ self.request_redraw();
+ InputResult::None
+ } else {
+ // If a task is running and a status line is visible, allow Esc to
+ // send an interrupt even while the composer has focus.
+ if matches!(key_event.code, crossterm::event::KeyCode::Esc)
+ && self.is_task_running
+ && let Some(status) = &self.status
+ {
+ // Send Op::Interrupt
+ status.interrupt();
+ self.request_redraw();
+ return InputResult::None;
+ }
+ let (input_result, needs_redraw) = self.composer.handle_key_event(key_event);
+ if needs_redraw {
+ self.request_redraw();
+ }
+ if self.composer.is_in_paste_burst() {
+ self.request_redraw_in(ChatComposer::recommended_paste_flush_delay());
+ }
+ input_result
+ }
+ }
+
+ /// Handle Ctrl-C in the bottom pane. If a modal view is active it gets a
+ /// chance to consume the event (e.g. to dismiss itself).
+ pub(crate) fn on_ctrl_c(&mut self) -> CancellationEvent {
+ if let Some(view) = self.view_stack.last_mut() {
+ let event = view.on_ctrl_c();
+ if matches!(event, CancellationEvent::Handled) {
+ if view.is_complete() {
+ self.view_stack.pop();
+ self.on_active_view_complete();
+ }
+ self.show_ctrl_c_quit_hint();
+ }
+ event
+ } else if self.composer_is_empty() {
+ CancellationEvent::NotHandled
+ } else {
+ self.view_stack.pop();
+ self.clear_composer_for_ctrl_c();
+ self.show_ctrl_c_quit_hint();
+ CancellationEvent::Handled
+ }
+ }
+
+ pub fn handle_paste(&mut self, pasted: String) {
+ if let Some(view) = self.view_stack.last_mut() {
+ let needs_redraw = view.handle_paste(pasted);
+ if view.is_complete() {
+ self.on_active_view_complete();
+ }
+ if needs_redraw {
+ self.request_redraw();
+ }
+ } else {
+ let needs_redraw = self.composer.handle_paste(pasted);
+ if needs_redraw {
+ self.request_redraw();
+ }
+ }
+ }
+
+ pub(crate) fn insert_str(&mut self, text: &str) {
+ self.composer.insert_str(text);
+ self.request_redraw();
+ }
+
+ /// Replace the composer text with `text`.
+ pub(crate) fn set_composer_text(&mut self, text: String) {
+ self.composer.set_text_content(text);
+ self.request_redraw();
+ }
+
+ pub(crate) fn clear_composer_for_ctrl_c(&mut self) {
+ self.composer.clear_for_ctrl_c();
+ self.request_redraw();
+ }
+
+ /// Get the current composer text (for tests and programmatic checks).
+ pub(crate) fn composer_text(&self) -> String {
+ self.composer.current_text()
+ }
+
+ /// Update the animated header shown to the left of the brackets in the
+ /// status indicator (defaults to "Working"). No-ops if the status
+ /// indicator is not active.
+ pub(crate) fn update_status_header(&mut self, header: String) {
+ if let Some(status) = self.status.as_mut() {
+ status.update_header(header);
+ self.request_redraw();
+ }
+ }
+
+ pub(crate) fn show_ctrl_c_quit_hint(&mut self) {
+ self.ctrl_c_quit_hint = true;
+ self.composer
+ .set_ctrl_c_quit_hint(true, self.has_input_focus);
+ self.request_redraw();
+ }
+
+ pub(crate) fn clear_ctrl_c_quit_hint(&mut self) {
+ if self.ctrl_c_quit_hint {
+ self.ctrl_c_quit_hint = false;
+ self.composer
+ .set_ctrl_c_quit_hint(false, self.has_input_focus);
+ self.request_redraw();
+ }
+ }
+
+ #[cfg(test)]
+ pub(crate) fn ctrl_c_quit_hint_visible(&self) -> bool {
+ self.ctrl_c_quit_hint
+ }
+
+ #[cfg(test)]
+ pub(crate) fn status_indicator_visible(&self) -> bool {
+ self.status.is_some()
+ }
+
+ pub(crate) fn show_esc_backtrack_hint(&mut self) {
+ self.esc_backtrack_hint = true;
+ self.composer.set_esc_backtrack_hint(true);
+ self.request_redraw();
+ }
+
+ pub(crate) fn clear_esc_backtrack_hint(&mut self) {
+ if self.esc_backtrack_hint {
+ self.esc_backtrack_hint = false;
+ self.composer.set_esc_backtrack_hint(false);
+ self.request_redraw();
+ }
+ }
+
+ // esc_backtrack_hint_visible removed; hints are controlled internally.
+
+ pub fn set_task_running(&mut self, running: bool) {
+ let was_running = self.is_task_running;
+ self.is_task_running = running;
+ self.composer.set_task_running(running);
+
+ if running {
+ if !was_running {
+ if self.status.is_none() {
+ self.status = Some(StatusIndicatorWidget::new(
+ self.app_event_tx.clone(),
+ self.frame_requester.clone(),
+ self.animations_enabled,
+ ));
+ }
+ if let Some(status) = self.status.as_mut() {
+ status.set_interrupt_hint_visible(true);
+ }
+ self.request_redraw();
+ }
+ } else {
+ // Hide the status indicator when a task completes, but keep other modal views.
+ self.hide_status_indicator();
+ }
+ }
+
+ /// Hide the status indicator while leaving task-running state untouched.
+ pub(crate) fn hide_status_indicator(&mut self) {
+ if self.status.take().is_some() {
+ self.request_redraw();
+ }
+ }
+
+ pub(crate) fn ensure_status_indicator(&mut self) {
+ if self.status.is_none() {
+ self.status = Some(StatusIndicatorWidget::new(
+ self.app_event_tx.clone(),
+ self.frame_requester.clone(),
+ self.animations_enabled,
+ ));
+ self.request_redraw();
+ }
+ }
+
+ pub(crate) fn set_interrupt_hint_visible(&mut self, visible: bool) {
+ if let Some(status) = self.status.as_mut() {
+ status.set_interrupt_hint_visible(visible);
+ self.request_redraw();
+ }
+ }
+
+ pub(crate) fn set_context_window(&mut self, percent: Option<i64>, used_tokens: Option<i64>) {
+ if self.context_window_percent == percent && self.context_window_used_tokens == used_tokens
+ {
+ return;
+ }
+
+ self.context_window_percent = percent;
+ self.context_window_used_tokens = used_tokens;
+ self.composer
+ .set_context_window(percent, self.context_window_used_tokens);
+ self.request_redraw();
+ }
+
+ /// Show a generic list selection view with the provided items.
+ pub(crate) fn show_selection_view(&mut self, params: list_selection_view::SelectionViewParams) {
+ let view = list_selection_view::ListSelectionView::new(params, self.app_event_tx.clone());
+ self.push_view(Box::new(view));
+ }
+
+ /// Update the queued messages preview shown above the composer.
+ pub(crate) fn set_queued_user_messages(&mut self, queued: Vec<String>) {
+ self.queued_user_messages.messages = queued;
+ self.request_redraw();
+ }
+
+ /// Update custom prompts available for the slash popup.
+ pub(crate) fn set_custom_prompts(&mut self, prompts: Vec<CustomPrompt>) {
+ self.composer.set_custom_prompts(prompts);
+ self.request_redraw();
+ }
+
+ pub(crate) fn composer_is_empty(&self) -> bool {
+ self.composer.is_empty()
+ }
+
+ pub(crate) fn is_task_running(&self) -> bool {
+ self.is_task_running
+ }
+
+ /// Return true when the pane is in the regular composer state without any
+ /// overlays or popups and not running a task. This is the safe context to
+ /// use Esc-Esc for backtracking from the main view.
+ pub(crate) fn is_normal_backtrack_mode(&self) -> bool {
+ !self.is_task_running && self.view_stack.is_empty() && !self.composer.popup_active()
+ }
+
+ pub(crate) fn show_view(&mut self, view: Box<dyn BottomPaneView>) {
+ self.push_view(view);
+ }
+
+ /// Called when the agent requests user approval.
+ pub fn push_approval_request(&mut self, request: ApprovalRequest, features: &Features) {
+ let request = if let Some(view) = self.view_stack.last_mut() {
+ match view.try_consume_approval_request(request) {
+ Some(request) => request,
+ None => {
+ self.request_redraw();
+ return;
+ }
+ }
+ } else {
+ request
+ };
+
+ // Otherwise create a new approval modal overlay.
+ let modal = ApprovalOverlay::new(request, self.app_event_tx.clone(), features.clone());
+ self.pause_status_timer_for_modal();
+ self.push_view(Box::new(modal));
+ }
+
+ fn on_active_view_complete(&mut self) {
+ self.resume_status_timer_after_modal();
+ }
+
+ fn pause_status_timer_for_modal(&mut self) {
+ if let Some(status) = self.status.as_mut() {
+ status.pause_timer();
+ }
+ }
+
+ fn resume_status_timer_after_modal(&mut self) {
+ if let Some(status) = self.status.as_mut() {
+ status.resume_timer();
+ }
+ }
+
+ /// Height (terminal rows) required by the current bottom pane.
+ pub(crate) fn request_redraw(&self) {
+ self.frame_requester.schedule_frame();
+ }
+
+ pub(crate) fn request_redraw_in(&self, dur: Duration) {
+ self.frame_requester.schedule_frame_in(dur);
+ }
+
+ // --- History helpers ---
+
+ pub(crate) fn set_history_metadata(&mut self, log_id: u64, entry_count: usize) {
+ self.composer.set_history_metadata(log_id, entry_count);
+ }
+
+ pub(crate) fn flush_paste_burst_if_due(&mut self) -> bool {
+ self.composer.flush_paste_burst_if_due()
+ }
+
+ pub(crate) fn is_in_paste_burst(&self) -> bool {
+ self.composer.is_in_paste_burst()
+ }
+
+ pub(crate) fn on_history_entry_response(
+ &mut self,
+ log_id: u64,
+ offset: usize,
+ entry: Option<String>,
+ ) {
+ let updated = self
+ .composer
+ .on_history_entry_response(log_id, offset, entry);
+
+ if updated {
+ self.request_redraw();
+ }
+ }
+
+ pub(crate) fn on_file_search_result(&mut self, query: String, matches: Vec<FileMatch>) {
+ self.composer.on_file_search_result(query, matches);
+ self.request_redraw();
+ }
+
+ pub(crate) fn attach_image(
+ &mut self,
+ path: PathBuf,
+ width: u32,
+ height: u32,
+ format_label: &str,
+ ) {
+ if self.view_stack.is_empty() {
+ self.composer
+ .attach_image(path, width, height, format_label);
+ self.request_redraw();
+ }
+ }
+
+ pub(crate) fn take_recent_submission_images(&mut self) -> Vec<PathBuf> {
+ self.composer.take_recent_submission_images()
+ }
+
+ fn as_renderable(&'_ self) -> RenderableItem<'_> {
+ if let Some(view) = self.active_view() {
+ RenderableItem::Borrowed(view)
+ } else {
+ let mut flex = FlexRenderable::new();
+ if let Some(status) = &self.status {
+ flex.push(0, RenderableItem::Borrowed(status));
+ }
+ flex.push(1, RenderableItem::Borrowed(&self.queued_user_messages));
+ if self.status.is_some() || !self.queued_user_messages.messages.is_empty() {
+ flex.push(0, RenderableItem::Owned("".into()));
+ }
+ let mut flex2 = FlexRenderable::new();
+ flex2.push(1, RenderableItem::Owned(flex.into()));
+ flex2.push(0, RenderableItem::Borrowed(&self.composer));
+ RenderableItem::Owned(Box::new(flex2))
+ }
+ }
+}
+
+impl Renderable for BottomPane {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ self.as_renderable().render(area, buf);
+ }
+ fn desired_height(&self, width: u16) -> u16 {
+ self.as_renderable().desired_height(width)
+ }
+ fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ self.as_renderable().cursor_pos(area)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::app_event::AppEvent;
+ use insta::assert_snapshot;
+ use ratatui::buffer::Buffer;
+ use ratatui::layout::Rect;
+ use tokio::sync::mpsc::unbounded_channel;
+
+ fn snapshot_buffer(buf: &Buffer) -> String {
+ let mut lines = Vec::new();
+ for y in 0..buf.area().height {
+ let mut row = String::new();
+ for x in 0..buf.area().width {
+ row.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
+ }
+ lines.push(row);
+ }
+ lines.join("\n")
+ }
+
+ fn render_snapshot(pane: &BottomPane, area: Rect) -> String {
+ let mut buf = Buffer::empty(area);
+ pane.render(area, &mut buf);
+ snapshot_buffer(&buf)
+ }
+
+ fn exec_request() -> ApprovalRequest {
+ ApprovalRequest::Exec {
+ id: "1".to_string(),
+ command: vec!["echo".into(), "ok".into()],
+ reason: None,
+ proposed_execpolicy_amendment: None,
+ }
+ }
+
+ #[test]
+ fn ctrl_c_on_modal_consumes_and_shows_quit_hint() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let features = Features::with_defaults();
+ let mut pane = BottomPane::new(BottomPaneParams {
+ app_event_tx: tx,
+ frame_requester: FrameRequester::test_dummy(),
+ has_input_focus: true,
+ enhanced_keys_supported: false,
+ placeholder_text: "Ask Codex to do anything".to_string(),
+ disable_paste_burst: false,
+ animations_enabled: true,
+ skills: Some(Vec::new()),
+ });
+ pane.push_approval_request(exec_request(), &features);
+ assert_eq!(CancellationEvent::Handled, pane.on_ctrl_c());
+ assert!(pane.ctrl_c_quit_hint_visible());
+ assert_eq!(CancellationEvent::NotHandled, pane.on_ctrl_c());
+ }
+
+ // live ring removed; related tests deleted.
+
+ #[test]
+ fn overlay_not_shown_above_approval_modal() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let features = Features::with_defaults();
+ let mut pane = BottomPane::new(BottomPaneParams {
+ app_event_tx: tx,
+ frame_requester: FrameRequester::test_dummy(),
+ has_input_focus: true,
+ enhanced_keys_supported: false,
+ placeholder_text: "Ask Codex to do anything".to_string(),
+ disable_paste_burst: false,
+ animations_enabled: true,
+ skills: Some(Vec::new()),
+ });
+
+ // Create an approval modal (active view).
+ pane.push_approval_request(exec_request(), &features);
+
+ // Render and verify the top row does not include an overlay.
+ let area = Rect::new(0, 0, 60, 6);
+ let mut buf = Buffer::empty(area);
+ pane.render(area, &mut buf);
+
+ let mut r0 = String::new();
+ for x in 0..area.width {
+ r0.push(buf[(x, 0)].symbol().chars().next().unwrap_or(' '));
+ }
+ assert!(
+ !r0.contains("Working"),
+ "overlay should not render above modal"
+ );
+ }
+
+ #[test]
+ fn composer_shown_after_denied_while_task_running() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let features = Features::with_defaults();
+ let mut pane = BottomPane::new(BottomPaneParams {
+ app_event_tx: tx,
+ frame_requester: FrameRequester::test_dummy(),
+ has_input_focus: true,
+ enhanced_keys_supported: false,
+ placeholder_text: "Ask Codex to do anything".to_string(),
+ disable_paste_burst: false,
+ animations_enabled: true,
+ skills: Some(Vec::new()),
+ });
+
+ // Start a running task so the status indicator is active above the composer.
+ pane.set_task_running(true);
+
+ // Push an approval modal (e.g., command approval) which should hide the status view.
+ pane.push_approval_request(exec_request(), &features);
+
+ // Simulate pressing 'n' (No) on the modal.
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+ pane.handle_key_event(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE));
+
+ // After denial, since the task is still running, the status indicator should be
+ // visible above the composer. The modal should be gone.
+ assert!(
+ pane.view_stack.is_empty(),
+ "no active modal view after denial"
+ );
+
+ // Render and ensure the top row includes the Working header and a composer line below.
+ // Give the animation thread a moment to tick.
+ std::thread::sleep(Duration::from_millis(120));
+ let area = Rect::new(0, 0, 40, 6);
+ let mut buf = Buffer::empty(area);
+ pane.render(area, &mut buf);
+ let mut row0 = String::new();
+ for x in 0..area.width {
+ row0.push(buf[(x, 0)].symbol().chars().next().unwrap_or(' '));
+ }
+ assert!(
+ row0.contains("Working"),
+ "expected Working header after denial on row 0: {row0:?}"
+ );
+
+ // Composer placeholder should be visible somewhere below.
+ let mut found_composer = false;
+ for y in 1..area.height {
+ let mut row = String::new();
+ for x in 0..area.width {
+ row.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
+ }
+ if row.contains("Ask Codex") {
+ found_composer = true;
+ break;
+ }
+ }
+ assert!(
+ found_composer,
+ "expected composer visible under status line"
+ );
+ }
+
+ #[test]
+ fn status_indicator_visible_during_command_execution() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let mut pane = BottomPane::new(BottomPaneParams {
+ app_event_tx: tx,
+ frame_requester: FrameRequester::test_dummy(),
+ has_input_focus: true,
+ enhanced_keys_supported: false,
+ placeholder_text: "Ask Codex to do anything".to_string(),
+ disable_paste_burst: false,
+ animations_enabled: true,
+ skills: Some(Vec::new()),
+ });
+
+ // Begin a task: show initial status.
+ pane.set_task_running(true);
+
+ // Use a height that allows the status line to be visible above the composer.
+ let area = Rect::new(0, 0, 40, 6);
+ let mut buf = Buffer::empty(area);
+ pane.render(area, &mut buf);
+
+ let bufs = snapshot_buffer(&buf);
+ assert!(bufs.contains("• Working"), "expected Working header");
+ }
+
+ #[test]
+ fn status_and_composer_fill_height_without_bottom_padding() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let mut pane = BottomPane::new(BottomPaneParams {
+ app_event_tx: tx,
+ frame_requester: FrameRequester::test_dummy(),
+ has_input_focus: true,
+ enhanced_keys_supported: false,
+ placeholder_text: "Ask Codex to do anything".to_string(),
+ disable_paste_burst: false,
+ animations_enabled: true,
+ skills: Some(Vec::new()),
+ });
+
+ // Activate spinner (status view replaces composer) with no live ring.
+ pane.set_task_running(true);
+
+ // Use height == desired_height; expect spacer + status + composer rows without trailing padding.
+ let height = pane.desired_height(30);
+ assert!(
+ height >= 3,
+ "expected at least 3 rows to render spacer, status, and composer; got {height}"
+ );
+ let area = Rect::new(0, 0, 30, height);
+ assert_snapshot!(
+ "status_and_composer_fill_height_without_bottom_padding",
+ render_snapshot(&pane, area)
+ );
+ }
+
+ #[test]
+ fn queued_messages_visible_when_status_hidden_snapshot() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let mut pane = BottomPane::new(BottomPaneParams {
+ app_event_tx: tx,
+ frame_requester: FrameRequester::test_dummy(),
+ has_input_focus: true,
+ enhanced_keys_supported: false,
+ placeholder_text: "Ask Codex to do anything".to_string(),
+ disable_paste_burst: false,
+ animations_enabled: true,
+ skills: Some(Vec::new()),
+ });
+
+ pane.set_task_running(true);
+ pane.set_queued_user_messages(vec!["Queued follow-up question".to_string()]);
+ pane.hide_status_indicator();
+
+ let width = 48;
+ let height = pane.desired_height(width);
+ let area = Rect::new(0, 0, width, height);
+ assert_snapshot!(
+ "queued_messages_visible_when_status_hidden_snapshot",
+ render_snapshot(&pane, area)
+ );
+ }
+
+ #[test]
+ fn status_and_queued_messages_snapshot() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let mut pane = BottomPane::new(BottomPaneParams {
+ app_event_tx: tx,
+ frame_requester: FrameRequester::test_dummy(),
+ has_input_focus: true,
+ enhanced_keys_supported: false,
+ placeholder_text: "Ask Codex to do anything".to_string(),
+ disable_paste_burst: false,
+ animations_enabled: true,
+ skills: Some(Vec::new()),
+ });
+
+ pane.set_task_running(true);
+ pane.set_queued_user_messages(vec!["Queued follow-up question".to_string()]);
+
+ let width = 48;
+ let height = pane.desired_height(width);
+ let area = Rect::new(0, 0, width, height);
+ assert_snapshot!(
+ "status_and_queued_messages_snapshot",
+ render_snapshot(&pane, area)
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/paste_burst.rs b/codex-rs/tui2/src/bottom_pane/paste_burst.rs
new file mode 100644
index 0000000000..49377cb21c
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/paste_burst.rs
@@ -0,0 +1,267 @@
+use std::time::Duration;
+use std::time::Instant;
+
+// Heuristic thresholds for detecting paste-like input bursts.
+// Detect quickly to avoid showing typed prefix before paste is recognized
+const PASTE_BURST_MIN_CHARS: u16 = 3;
+const PASTE_BURST_CHAR_INTERVAL: Duration = Duration::from_millis(8);
+const PASTE_ENTER_SUPPRESS_WINDOW: Duration = Duration::from_millis(120);
+
+#[derive(Default)]
+pub(crate) struct PasteBurst {
+ last_plain_char_time: Option<Instant>,
+ consecutive_plain_char_burst: u16,
+ burst_window_until: Option<Instant>,
+ buffer: String,
+ active: bool,
+ // Hold first fast char briefly to avoid rendering flicker
+ pending_first_char: Option<(char, Instant)>,
+}
+
+pub(crate) enum CharDecision {
+ /// Start buffering and retroactively capture some already-inserted chars.
+ BeginBuffer { retro_chars: u16 },
+ /// We are currently buffering; append the current char into the buffer.
+ BufferAppend,
+ /// Do not insert/render this char yet; temporarily save the first fast
+ /// char while we wait to see if a paste-like burst follows.
+ RetainFirstChar,
+ /// Begin buffering using the previously saved first char (no retro grab needed).
+ BeginBufferFromPending,
+}
+
+pub(crate) struct RetroGrab {
+ pub start_byte: usize,
+ pub grabbed: String,
+}
+
+pub(crate) enum FlushResult {
+ Paste(String),
+ Typed(char),
+ None,
+}
+
+impl PasteBurst {
+ /// Recommended delay to wait between simulated keypresses (or before
+ /// scheduling a UI tick) so that a pending fast keystroke is flushed
+ /// out of the burst detector as normal typed input.
+ ///
+ /// Primarily used by tests and by the TUI to reliably cross the
+ /// paste-burst timing threshold.
+ pub fn recommended_flush_delay() -> Duration {
+ PASTE_BURST_CHAR_INTERVAL + Duration::from_millis(1)
+ }
+
+ /// Entry point: decide how to treat a plain char with current timing.
+ pub fn on_plain_char(&mut self, ch: char, now: Instant) -> CharDecision {
+ match self.last_plain_char_time {
+ Some(prev) if now.duration_since(prev) <= PASTE_BURST_CHAR_INTERVAL => {
+ self.consecutive_plain_char_burst =
+ self.consecutive_plain_char_burst.saturating_add(1)
+ }
+ _ => self.consecutive_plain_char_burst = 1,
+ }
+ self.last_plain_char_time = Some(now);
+
+ if self.active {
+ self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
+ return CharDecision::BufferAppend;
+ }
+
+ // If we already held a first char and receive a second fast char,
+ // start buffering without retro-grabbing (we never rendered the first).
+ if let Some((held, held_at)) = self.pending_first_char
+ && now.duration_since(held_at) <= PASTE_BURST_CHAR_INTERVAL
+ {
+ self.active = true;
+ // take() to clear pending; we already captured the held char above
+ let _ = self.pending_first_char.take();
+ self.buffer.push(held);
+ self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
+ return CharDecision::BeginBufferFromPending;
+ }
+
+ if self.consecutive_plain_char_burst >= PASTE_BURST_MIN_CHARS {
+ return CharDecision::BeginBuffer {
+ retro_chars: self.consecutive_plain_char_burst.saturating_sub(1),
+ };
+ }
+
+ // Save the first fast char very briefly to see if a burst follows.
+ self.pending_first_char = Some((ch, now));
+ CharDecision::RetainFirstChar
+ }
+
+ /// Flush the buffered burst if the inter-key timeout has elapsed.
+ ///
+ /// Returns Some(String) when either:
+ /// - We were actively buffering paste-like input and the buffer is now
+ /// emitted as a single pasted string; or
+ /// - We had saved a single fast first-char with no subsequent burst and we
+ /// now emit that char as normal typed input.
+ ///
+ /// Returns None if the timeout has not elapsed or there is nothing to flush.
+ pub fn flush_if_due(&mut self, now: Instant) -> FlushResult {
+ let timed_out = self
+ .last_plain_char_time
+ .is_some_and(|t| now.duration_since(t) > PASTE_BURST_CHAR_INTERVAL);
+ if timed_out && self.is_active_internal() {
+ self.active = false;
+ let out = std::mem::take(&mut self.buffer);
+ FlushResult::Paste(out)
+ } else if timed_out {
+ // If we were saving a single fast char and no burst followed,
+ // flush it as normal typed input.
+ if let Some((ch, _at)) = self.pending_first_char.take() {
+ FlushResult::Typed(ch)
+ } else {
+ FlushResult::None
+ }
+ } else {
+ FlushResult::None
+ }
+ }
+
+ /// While bursting: accumulate a newline into the buffer instead of
+ /// submitting the textarea.
+ ///
+ /// Returns true if a newline was appended (we are in a burst context),
+ /// false otherwise.
+ pub fn append_newline_if_active(&mut self, now: Instant) -> bool {
+ if self.is_active() {
+ self.buffer.push('\n');
+ self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
+ true
+ } else {
+ false
+ }
+ }
+
+ /// Decide if Enter should insert a newline (burst context) vs submit.
+ pub fn newline_should_insert_instead_of_submit(&self, now: Instant) -> bool {
+ let in_burst_window = self.burst_window_until.is_some_and(|until| now <= until);
+ self.is_active() || in_burst_window
+ }
+
+ /// Keep the burst window alive.
+ pub fn extend_window(&mut self, now: Instant) {
+ self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
+ }
+
+ /// Begin buffering with retroactively grabbed text.
+ pub fn begin_with_retro_grabbed(&mut self, grabbed: String, now: Instant) {
+ if !grabbed.is_empty() {
+ self.buffer.push_str(&grabbed);
+ }
+ self.active = true;
+ self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
+ }
+
+ /// Append a char into the burst buffer.
+ pub fn append_char_to_buffer(&mut self, ch: char, now: Instant) {
+ self.buffer.push(ch);
+ self.burst_window_until = Some(now + PASTE_ENTER_SUPPRESS_WINDOW);
+ }
+
+ /// Try to append a char into the burst buffer only if a burst is already active.
+ ///
+ /// Returns true when the char was captured into the existing burst, false otherwise.
+ pub fn try_append_char_if_active(&mut self, ch: char, now: Instant) -> bool {
+ if self.active || !self.buffer.is_empty() {
+ self.append_char_to_buffer(ch, now);
+ true
+ } else {
+ false
+ }
+ }
+
+ /// Decide whether to begin buffering by retroactively capturing recent
+ /// chars from the slice before the cursor.
+ ///
+ /// Heuristic: if the retro-grabbed slice contains any whitespace or is
+ /// sufficiently long (>= 16 characters), treat it as paste-like to avoid
+ /// rendering the typed prefix momentarily before the paste is recognized.
+ /// This favors responsiveness and prevents flicker for typical pastes
+ /// (URLs, file paths, multiline text) while not triggering on short words.
+ ///
+ /// Returns Some(RetroGrab) with the start byte and grabbed text when we
+ /// decide to buffer retroactively; otherwise None.
+ pub fn decide_begin_buffer(
+ &mut self,
+ now: Instant,
+ before: &str,
+ retro_chars: usize,
+ ) -> Option<RetroGrab> {
+ let start_byte = retro_start_index(before, retro_chars);
+ let grabbed = before[start_byte..].to_string();
+ let looks_pastey =
+ grabbed.chars().any(char::is_whitespace) || grabbed.chars().count() >= 16;
+ if looks_pastey {
+ // Note: caller is responsible for removing this slice from UI text.
+ self.begin_with_retro_grabbed(grabbed.clone(), now);
+ Some(RetroGrab {
+ start_byte,
+ grabbed,
+ })
+ } else {
+ None
+ }
+ }
+
+ /// Before applying modified/non-char input: flush buffered burst immediately.
+ pub fn flush_before_modified_input(&mut self) -> Option<String> {
+ if !self.is_active() {
+ return None;
+ }
+ self.active = false;
+ let mut out = std::mem::take(&mut self.buffer);
+ if let Some((ch, _at)) = self.pending_first_char.take() {
+ out.push(ch);
+ }
+ Some(out)
+ }
+
+ /// Clear only the timing window and any pending first-char.
+ ///
+ /// Does not emit or clear the buffered text itself; callers should have
+ /// already flushed (if needed) via one of the flush methods above.
+ pub fn clear_window_after_non_char(&mut self) {
+ self.consecutive_plain_char_burst = 0;
+ self.last_plain_char_time = None;
+ self.burst_window_until = None;
+ self.active = false;
+ self.pending_first_char = None;
+ }
+
+ /// Returns true if we are in any paste-burst related transient state
+ /// (actively buffering, have a non-empty buffer, or have saved the first
+ /// fast char while waiting for a potential burst).
+ pub fn is_active(&self) -> bool {
+ self.is_active_internal() || self.pending_first_char.is_some()
+ }
+
+ fn is_active_internal(&self) -> bool {
+ self.active || !self.buffer.is_empty()
+ }
+
+ pub fn clear_after_explicit_paste(&mut self) {
+ self.last_plain_char_time = None;
+ self.consecutive_plain_char_burst = 0;
+ self.burst_window_until = None;
+ self.active = false;
+ self.buffer.clear();
+ self.pending_first_char = None;
+ }
+}
+
+pub(crate) fn retro_start_index(before: &str, retro_chars: usize) -> usize {
+ if retro_chars == 0 {
+ return before.len();
+ }
+ before
+ .char_indices()
+ .rev()
+ .nth(retro_chars.saturating_sub(1))
+ .map(|(idx, _)| idx)
+ .unwrap_or(0)
+}
diff --git a/codex-rs/tui2/src/bottom_pane/popup_consts.rs b/codex-rs/tui2/src/bottom_pane/popup_consts.rs
new file mode 100644
index 0000000000..2cabe389b1
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/popup_consts.rs
@@ -0,0 +1,21 @@
+//! Shared popup-related constants for bottom pane widgets.
+
+use crossterm::event::KeyCode;
+use ratatui::text::Line;
+
+use crate::key_hint;
+
+/// Maximum number of rows any popup should attempt to display.
+/// Keep this consistent across all popups for a uniform feel.
+pub(crate) const MAX_POPUP_ROWS: usize = 8;
+
+/// Standard footer hint text used by popups.
+pub(crate) fn standard_popup_hint_line() -> Line<'static> {
+ Line::from(vec![
+ "Press ".into(),
+ key_hint::plain(KeyCode::Enter).into(),
+ " to confirm or ".into(),
+ key_hint::plain(KeyCode::Esc).into(),
+ " to go back".into(),
+ ])
+}
diff --git a/codex-rs/tui2/src/bottom_pane/prompt_args.rs b/codex-rs/tui2/src/bottom_pane/prompt_args.rs
new file mode 100644
index 0000000000..48c3cedfab
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/prompt_args.rs
@@ -0,0 +1,406 @@
+use codex_protocol::custom_prompts::CustomPrompt;
+use codex_protocol::custom_prompts::PROMPTS_CMD_PREFIX;
+use lazy_static::lazy_static;
+use regex_lite::Regex;
+use shlex::Shlex;
+use std::collections::HashMap;
+use std::collections::HashSet;
+
+lazy_static! {
+ static ref PROMPT_ARG_REGEX: Regex =
+ Regex::new(r"\$[A-Z][A-Z0-9_]*").unwrap_or_else(|_| std::process::abort());
+}
+
+#[derive(Debug)]
+pub enum PromptArgsError {
+ MissingAssignment { token: String },
+ MissingKey { token: String },
+}
+
+impl PromptArgsError {
+ fn describe(&self, command: &str) -> String {
+ match self {
+ PromptArgsError::MissingAssignment { token } => format!(
+ "Could not parse {command}: expected key=value but found '{token}'. Wrap values in double quotes if they contain spaces."
+ ),
+ PromptArgsError::MissingKey { token } => {
+ format!("Could not parse {command}: expected a name before '=' in '{token}'.")
+ }
+ }
+ }
+}
+
+#[derive(Debug)]
+pub enum PromptExpansionError {
+ Args {
+ command: String,
+ error: PromptArgsError,
+ },
+ MissingArgs {
+ command: String,
+ missing: Vec<String>,
+ },
+}
+
+impl PromptExpansionError {
+ pub fn user_message(&self) -> String {
+ match self {
+ PromptExpansionError::Args { command, error } => error.describe(command),
+ PromptExpansionError::MissingArgs { command, missing } => {
+ let list = missing.join(", ");
+ format!(
+ "Missing required args for {command}: {list}. Provide as key=value (quote values with spaces)."
+ )
+ }
+ }
+ }
+}
+
+/// Parse a first-line slash command of the form `/name <rest>`.
+/// Returns `(name, rest_after_name)` if the line begins with `/` and contains
+/// a non-empty name; otherwise returns `None`.
+pub fn parse_slash_name(line: &str) -> Option<(&str, &str)> {
+ let stripped = line.strip_prefix('/')?;
+ let mut name_end = stripped.len();
+ for (idx, ch) in stripped.char_indices() {
+ if ch.is_whitespace() {
+ name_end = idx;
+ break;
+ }
+ }
+ let name = &stripped[..name_end];
+ if name.is_empty() {
+ return None;
+ }
+ let rest = stripped[name_end..].trim_start();
+ Some((name, rest))
+}
+
+/// Parse positional arguments using shlex semantics (supports quoted tokens).
+pub fn parse_positional_args(rest: &str) -> Vec<String> {
+ Shlex::new(rest).collect()
+}
+
+/// Extracts the unique placeholder variable names from a prompt template.
+///
+/// A placeholder is any token that matches the pattern `$[A-Z][A-Z0-9_]*`
+/// (for example `$USER`). The function returns the variable names without
+/// the leading `$`, de-duplicated and in the order of first appearance.
+pub fn prompt_argument_names(content: &str) -> Vec<String> {
+ let mut seen = HashSet::new();
+ let mut names = Vec::new();
+ for m in PROMPT_ARG_REGEX.find_iter(content) {
+ if m.start() > 0 && content.as_bytes()[m.start() - 1] == b'$' {
+ continue;
+ }
+ let name = &content[m.start() + 1..m.end()];
+ // Exclude special positional aggregate token from named args.
+ if name == "ARGUMENTS" {
+ continue;
+ }
+ let name = name.to_string();
+ if seen.insert(name.clone()) {
+ names.push(name);
+ }
+ }
+ names
+}
+
+/// Parses the `key=value` pairs that follow a custom prompt name.
+///
+/// The input is split using shlex rules, so quoted values are supported
+/// (for example `USER="Alice Smith"`). The function returns a map of parsed
+/// arguments, or an error if a token is missing `=` or if the key is empty.
+pub fn parse_prompt_inputs(rest: &str) -> Result<HashMap<String, String>, PromptArgsError> {
+ let mut map = HashMap::new();
+ if rest.trim().is_empty() {
+ return Ok(map);
+ }
+
+ for token in Shlex::new(rest) {
+ let Some((key, value)) = token.split_once('=') else {
+ return Err(PromptArgsError::MissingAssignment { token });
+ };
+ if key.is_empty() {
+ return Err(PromptArgsError::MissingKey { token });
+ }
+ map.insert(key.to_string(), value.to_string());
+ }
+ Ok(map)
+}
+
+/// Expands a message of the form `/prompts:name [value] [value] …` using a matching saved prompt.
+///
+/// If the text does not start with `/prompts:`, or if no prompt named `name` exists,
+/// the function returns `Ok(None)`. On success it returns
+/// `Ok(Some(expanded))`; otherwise it returns a descriptive error.
+pub fn expand_custom_prompt(
+ text: &str,
+ custom_prompts: &[CustomPrompt],
+) -> Result<Option<String>, PromptExpansionError> {
+ let Some((name, rest)) = parse_slash_name(text) else {
+ return Ok(None);
+ };
+
+ // Only handle custom prompts when using the explicit prompts prefix with a colon.
+ let Some(prompt_name) = name.strip_prefix(&format!("{PROMPTS_CMD_PREFIX}:")) else {
+ return Ok(None);
+ };
+
+ let prompt = match custom_prompts.iter().find(|p| p.name == prompt_name) {
+ Some(prompt) => prompt,
+ None => return Ok(None),
+ };
+ // If there are named placeholders, expect key=value inputs.
+ let required = prompt_argument_names(&prompt.content);
+ if !required.is_empty() {
+ let inputs = parse_prompt_inputs(rest).map_err(|error| PromptExpansionError::Args {
+ command: format!("/{name}"),
+ error,
+ })?;
+ let missing: Vec<String> = required
+ .into_iter()
+ .filter(|k| !inputs.contains_key(k))
+ .collect();
+ if !missing.is_empty() {
+ return Err(PromptExpansionError::MissingArgs {
+ command: format!("/{name}"),
+ missing,
+ });
+ }
+ let content = &prompt.content;
+ let replaced = PROMPT_ARG_REGEX.replace_all(content, |caps: &regex_lite::Captures<'_>| {
+ if let Some(matched) = caps.get(0)
+ && matched.start() > 0
+ && content.as_bytes()[matched.start() - 1] == b'$'
+ {
+ return matched.as_str().to_string();
+ }
+ let whole = &caps[0];
+ let key = &whole[1..];
+ inputs
+ .get(key)
+ .cloned()
+ .unwrap_or_else(|| whole.to_string())
+ });
+ return Ok(Some(replaced.into_owned()));
+ }
+
+ // Otherwise, treat it as numeric/positional placeholder prompt (or none).
+ let pos_args: Vec<String> = Shlex::new(rest).collect();
+ let expanded = expand_numeric_placeholders(&prompt.content, &pos_args);
+ Ok(Some(expanded))
+}
+
+/// Detect whether `content` contains numeric placeholders ($1..$9) or `$ARGUMENTS`.
+pub fn prompt_has_numeric_placeholders(content: &str) -> bool {
+ if content.contains("$ARGUMENTS") {
+ return true;
+ }
+ let bytes = content.as_bytes();
+ let mut i = 0;
+ while i + 1 < bytes.len() {
+ if bytes[i] == b'$' {
+ let b1 = bytes[i + 1];
+ if (b'1'..=b'9').contains(&b1) {
+ return true;
+ }
+ }
+ i += 1;
+ }
+ false
+}
+
+/// Extract positional arguments from a composer first line like "/name a b" for a given prompt name.
+/// Returns empty when the command name does not match or when there are no args.
+pub fn extract_positional_args_for_prompt_line(line: &str, prompt_name: &str) -> Vec<String> {
+ let trimmed = line.trim_start();
+ let Some(rest) = trimmed.strip_prefix('/') else {
+ return Vec::new();
+ };
+ // Require the explicit prompts prefix for custom prompt invocations.
+ let Some(after_prefix) = rest.strip_prefix(&format!("{PROMPTS_CMD_PREFIX}:")) else {
+ return Vec::new();
+ };
+ let mut parts = after_prefix.splitn(2, char::is_whitespace);
+ let cmd = parts.next().unwrap_or("");
+ if cmd != prompt_name {
+ return Vec::new();
+ }
+ let args_str = parts.next().unwrap_or("").trim();
+ if args_str.is_empty() {
+ return Vec::new();
+ }
+ parse_positional_args(args_str)
+}
+
+/// If the prompt only uses numeric placeholders and the first line contains
+/// positional args for it, expand and return Some(expanded); otherwise None.
+pub fn expand_if_numeric_with_positional_args(
+ prompt: &CustomPrompt,
+ first_line: &str,
+) -> Option<String> {
+ if !prompt_argument_names(&prompt.content).is_empty() {
+ return None;
+ }
+ if !prompt_has_numeric_placeholders(&prompt.content) {
+ return None;
+ }
+ let args = extract_positional_args_for_prompt_line(first_line, &prompt.name);
+ if args.is_empty() {
+ return None;
+ }
+ Some(expand_numeric_placeholders(&prompt.content, &args))
+}
+
+/// Expand `$1..$9` and `$ARGUMENTS` in `content` with values from `args`.
+pub fn expand_numeric_placeholders(content: &str, args: &[String]) -> String {
+ let mut out = String::with_capacity(content.len());
+ let mut i = 0;
+ let mut cached_joined_args: Option<String> = None;
+ while let Some(off) = content[i..].find('$') {
+ let j = i + off;
+ out.push_str(&content[i..j]);
+ let rest = &content[j..];
+ let bytes = rest.as_bytes();
+ if bytes.len() >= 2 {
+ match bytes[1] {
+ b'$' => {
+ out.push_str("$$");
+ i = j + 2;
+ continue;
+ }
+ b'1'..=b'9' => {
+ let idx = (bytes[1] - b'1') as usize;
+ if let Some(val) = args.get(idx) {
+ out.push_str(val);
+ }
+ i = j + 2;
+ continue;
+ }
+ _ => {}
+ }
+ }
+ if rest.len() > "ARGUMENTS".len() && rest[1..].starts_with("ARGUMENTS") {
+ if !args.is_empty() {
+ let joined = cached_joined_args.get_or_insert_with(|| args.join(" "));
+ out.push_str(joined);
+ }
+ i = j + 1 + "ARGUMENTS".len();
+ continue;
+ }
+ out.push('$');
+ i = j + 1;
+ }
+ out.push_str(&content[i..]);
+ out
+}
+
+/// Constructs a command text for a custom prompt with arguments.
+/// Returns the text and the cursor position (inside the first double quote).
+pub fn prompt_command_with_arg_placeholders(name: &str, args: &[String]) -> (String, usize) {
+ let mut text = format!("/{PROMPTS_CMD_PREFIX}:{name}");
+ let mut cursor: usize = text.len();
+ for (i, arg) in args.iter().enumerate() {
+ text.push_str(format!(" {arg}=\"\"").as_str());
+ if i == 0 {
+ cursor = text.len() - 1; // inside first ""
+ }
+ }
+ (text, cursor)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn expand_arguments_basic() {
+ let prompts = vec![CustomPrompt {
+ name: "my-prompt".to_string(),
+ path: "/tmp/my-prompt.md".to_string().into(),
+ content: "Review $USER changes on $BRANCH".to_string(),
+ description: None,
+ argument_hint: None,
+ }];
+
+ let out =
+ expand_custom_prompt("/prompts:my-prompt USER=Alice BRANCH=main", &prompts).unwrap();
+ assert_eq!(out, Some("Review Alice changes on main".to_string()));
+ }
+
+ #[test]
+ fn quoted_values_ok() {
+ let prompts = vec![CustomPrompt {
+ name: "my-prompt".to_string(),
+ path: "/tmp/my-prompt.md".to_string().into(),
+ content: "Pair $USER with $BRANCH".to_string(),
+ description: None,
+ argument_hint: None,
+ }];
+
+ let out = expand_custom_prompt(
+ "/prompts:my-prompt USER=\"Alice Smith\" BRANCH=dev-main",
+ &prompts,
+ )
+ .unwrap();
+ assert_eq!(out, Some("Pair Alice Smith with dev-main".to_string()));
+ }
+
+ #[test]
+ fn invalid_arg_token_reports_error() {
+ let prompts = vec![CustomPrompt {
+ name: "my-prompt".to_string(),
+ path: "/tmp/my-prompt.md".to_string().into(),
+ content: "Review $USER changes".to_string(),
+ description: None,
+ argument_hint: None,
+ }];
+ let err = expand_custom_prompt("/prompts:my-prompt USER=Alice stray", &prompts)
+ .unwrap_err()
+ .user_message();
+ assert!(err.contains("expected key=value"));
+ }
+
+ #[test]
+ fn missing_required_args_reports_error() {
+ let prompts = vec![CustomPrompt {
+ name: "my-prompt".to_string(),
+ path: "/tmp/my-prompt.md".to_string().into(),
+ content: "Review $USER changes on $BRANCH".to_string(),
+ description: None,
+ argument_hint: None,
+ }];
+ let err = expand_custom_prompt("/prompts:my-prompt USER=Alice", &prompts)
+ .unwrap_err()
+ .user_message();
+ assert!(err.to_lowercase().contains("missing required args"));
+ assert!(err.contains("BRANCH"));
+ }
+
+ #[test]
+ fn escaped_placeholder_is_ignored() {
+ assert_eq!(
+ prompt_argument_names("literal $$USER"),
+ Vec::<String>::new()
+ );
+ assert_eq!(
+ prompt_argument_names("literal $$USER and $REAL"),
+ vec!["REAL".to_string()]
+ );
+ }
+
+ #[test]
+ fn escaped_placeholder_remains_literal() {
+ let prompts = vec![CustomPrompt {
+ name: "my-prompt".to_string(),
+ path: "/tmp/my-prompt.md".to_string().into(),
+ content: "literal $$USER".to_string(),
+ description: None,
+ argument_hint: None,
+ }];
+
+ let out = expand_custom_prompt("/prompts:my-prompt", &prompts).unwrap();
+ assert_eq!(out, Some("literal $$USER".to_string()));
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/queued_user_messages.rs b/codex-rs/tui2/src/bottom_pane/queued_user_messages.rs
new file mode 100644
index 0000000000..ae33aeada4
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/queued_user_messages.rs
@@ -0,0 +1,157 @@
+use crossterm::event::KeyCode;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::widgets::Paragraph;
+
+use crate::key_hint;
+use crate::render::renderable::Renderable;
+use crate::wrapping::RtOptions;
+use crate::wrapping::word_wrap_lines;
+
+/// Widget that displays a list of user messages queued while a turn is in progress.
+pub(crate) struct QueuedUserMessages {
+ pub messages: Vec<String>,
+}
+
+impl QueuedUserMessages {
+ pub(crate) fn new() -> Self {
+ Self {
+ messages: Vec::new(),
+ }
+ }
+
+ fn as_renderable(&self, width: u16) -> Box<dyn Renderable> {
+ if self.messages.is_empty() || width < 4 {
+ return Box::new(());
+ }
+
+ let mut lines = vec![];
+
+ for message in &self.messages {
+ let wrapped = word_wrap_lines(
+ message.lines().map(|line| line.dim().italic()),
+ RtOptions::new(width as usize)
+ .initial_indent(Line::from(" ↳ ".dim()))
+ .subsequent_indent(Line::from(" ")),
+ );
+ let len = wrapped.len();
+ for line in wrapped.into_iter().take(3) {
+ lines.push(line);
+ }
+ if len > 3 {
+ lines.push(Line::from(" …".dim().italic()));
+ }
+ }
+
+ lines.push(
+ Line::from(vec![
+ " ".into(),
+ key_hint::alt(KeyCode::Up).into(),
+ " edit".into(),
+ ])
+ .dim(),
+ );
+
+ Paragraph::new(lines).into()
+ }
+}
+
+impl Renderable for QueuedUserMessages {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ if area.is_empty() {
+ return;
+ }
+
+ self.as_renderable(area.width).render(area, buf);
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ self.as_renderable(width).desired_height(width)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use insta::assert_snapshot;
+ use pretty_assertions::assert_eq;
+
+ #[test]
+ fn desired_height_empty() {
+ let queue = QueuedUserMessages::new();
+ assert_eq!(queue.desired_height(40), 0);
+ }
+
+ #[test]
+ fn desired_height_one_message() {
+ let mut queue = QueuedUserMessages::new();
+ queue.messages.push("Hello, world!".to_string());
+ assert_eq!(queue.desired_height(40), 2);
+ }
+
+ #[test]
+ fn render_one_message() {
+ let mut queue = QueuedUserMessages::new();
+ queue.messages.push("Hello, world!".to_string());
+ let width = 40;
+ let height = queue.desired_height(width);
+ let mut buf = Buffer::empty(Rect::new(0, 0, width, height));
+ queue.render(Rect::new(0, 0, width, height), &mut buf);
+ assert_snapshot!("render_one_message", format!("{buf:?}"));
+ }
+
+ #[test]
+ fn render_two_messages() {
+ let mut queue = QueuedUserMessages::new();
+ queue.messages.push("Hello, world!".to_string());
+ queue.messages.push("This is another message".to_string());
+ let width = 40;
+ let height = queue.desired_height(width);
+ let mut buf = Buffer::empty(Rect::new(0, 0, width, height));
+ queue.render(Rect::new(0, 0, width, height), &mut buf);
+ assert_snapshot!("render_two_messages", format!("{buf:?}"));
+ }
+
+ #[test]
+ fn render_more_than_three_messages() {
+ let mut queue = QueuedUserMessages::new();
+ queue.messages.push("Hello, world!".to_string());
+ queue.messages.push("This is another message".to_string());
+ queue.messages.push("This is a third message".to_string());
+ queue.messages.push("This is a fourth message".to_string());
+ let width = 40;
+ let height = queue.desired_height(width);
+ let mut buf = Buffer::empty(Rect::new(0, 0, width, height));
+ queue.render(Rect::new(0, 0, width, height), &mut buf);
+ assert_snapshot!("render_more_than_three_messages", format!("{buf:?}"));
+ }
+
+ #[test]
+ fn render_wrapped_message() {
+ let mut queue = QueuedUserMessages::new();
+ queue
+ .messages
+ .push("This is a longer message that should be wrapped".to_string());
+ queue.messages.push("This is another message".to_string());
+ let width = 40;
+ let height = queue.desired_height(width);
+ let mut buf = Buffer::empty(Rect::new(0, 0, width, height));
+ queue.render(Rect::new(0, 0, width, height), &mut buf);
+ assert_snapshot!("render_wrapped_message", format!("{buf:?}"));
+ }
+
+ #[test]
+ fn render_many_line_message() {
+ let mut queue = QueuedUserMessages::new();
+ queue
+ .messages
+ .push("This is\na message\nwith many\nlines".to_string());
+ let width = 40;
+ let height = queue.desired_height(width);
+ let mut buf = Buffer::empty(Rect::new(0, 0, width, height));
+ queue.render(Rect::new(0, 0, width, height), &mut buf);
+ assert_snapshot!("render_many_line_message", format!("{buf:?}"));
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/scroll_state.rs b/codex-rs/tui2/src/bottom_pane/scroll_state.rs
new file mode 100644
index 0000000000..a9728d1a0d
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/scroll_state.rs
@@ -0,0 +1,115 @@
+/// Generic scroll/selection state for a vertical list menu.
+///
+/// Encapsulates the common behavior of a selectable list that supports:
+/// - Optional selection (None when list is empty)
+/// - Wrap-around navigation on Up/Down
+/// - Maintaining a scroll window (`scroll_top`) so the selected row stays visible
+#[derive(Debug, Default, Clone, Copy)]
+pub(crate) struct ScrollState {
+ pub selected_idx: Option<usize>,
+ pub scroll_top: usize,
+}
+
+impl ScrollState {
+ pub fn new() -> Self {
+ Self {
+ selected_idx: None,
+ scroll_top: 0,
+ }
+ }
+
+ /// Reset selection and scroll.
+ pub fn reset(&mut self) {
+ self.selected_idx = None;
+ self.scroll_top = 0;
+ }
+
+ /// Clamp selection to be within the [0, len-1] range, or None when empty.
+ pub fn clamp_selection(&mut self, len: usize) {
+ self.selected_idx = match len {
+ 0 => None,
+ _ => Some(self.selected_idx.unwrap_or(0).min(len - 1)),
+ };
+ if len == 0 {
+ self.scroll_top = 0;
+ }
+ }
+
+ /// Move selection up by one, wrapping to the bottom when necessary.
+ pub fn move_up_wrap(&mut self, len: usize) {
+ if len == 0 {
+ self.selected_idx = None;
+ self.scroll_top = 0;
+ return;
+ }
+ self.selected_idx = Some(match self.selected_idx {
+ Some(idx) if idx > 0 => idx - 1,
+ Some(_) => len - 1,
+ None => 0,
+ });
+ }
+
+ /// Move selection down by one, wrapping to the top when necessary.
+ pub fn move_down_wrap(&mut self, len: usize) {
+ if len == 0 {
+ self.selected_idx = None;
+ self.scroll_top = 0;
+ return;
+ }
+ self.selected_idx = Some(match self.selected_idx {
+ Some(idx) if idx + 1 < len => idx + 1,
+ _ => 0,
+ });
+ }
+
+ /// Adjust `scroll_top` so that the current `selected_idx` is visible within
+ /// the window of `visible_rows`.
+ pub fn ensure_visible(&mut self, len: usize, visible_rows: usize) {
+ if len == 0 || visible_rows == 0 {
+ self.scroll_top = 0;
+ return;
+ }
+ if let Some(sel) = self.selected_idx {
+ if sel < self.scroll_top {
+ self.scroll_top = sel;
+ } else {
+ let bottom = self.scroll_top + visible_rows - 1;
+ if sel > bottom {
+ self.scroll_top = sel + 1 - visible_rows;
+ }
+ }
+ } else {
+ self.scroll_top = 0;
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::ScrollState;
+
+ #[test]
+ fn wrap_navigation_and_visibility() {
+ let mut s = ScrollState::new();
+ let len = 10;
+ let vis = 5;
+
+ s.clamp_selection(len);
+ assert_eq!(s.selected_idx, Some(0));
+ s.ensure_visible(len, vis);
+ assert_eq!(s.scroll_top, 0);
+
+ s.move_up_wrap(len);
+ s.ensure_visible(len, vis);
+ assert_eq!(s.selected_idx, Some(len - 1));
+ match s.selected_idx {
+ Some(sel) => assert!(s.scroll_top <= sel),
+ None => panic!("expected Some(selected_idx) after wrap"),
+ }
+
+ s.move_down_wrap(len);
+ s.ensure_visible(len, vis);
+ assert_eq!(s.selected_idx, Some(0));
+ assert_eq!(s.scroll_top, 0);
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/selection_popup_common.rs b/codex-rs/tui2/src/bottom_pane/selection_popup_common.rs
new file mode 100644
index 0000000000..5107ab0ca9
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/selection_popup_common.rs
@@ -0,0 +1,269 @@
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+// Note: Table-based layout previously used Constraint; the manual renderer
+// below no longer requires it.
+use ratatui::style::Color;
+use ratatui::style::Style;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::widgets::Widget;
+use unicode_width::UnicodeWidthChar;
+
+use crate::key_hint::KeyBinding;
+
+use super::scroll_state::ScrollState;
+
+/// A generic representation of a display row for selection popups.
+pub(crate) struct GenericDisplayRow {
+ pub name: String,
+ pub display_shortcut: Option<KeyBinding>,
+ pub match_indices: Option<Vec<usize>>, // indices to bold (char positions)
+ pub description: Option<String>, // optional grey text after the name
+ pub wrap_indent: Option<usize>, // optional indent for wrapped lines
+}
+
+/// Compute a shared description-column start based on the widest visible name
+/// plus two spaces of padding. Ensures at least one column is left for the
+/// description.
+fn compute_desc_col(
+ rows_all: &[GenericDisplayRow],
+ start_idx: usize,
+ visible_items: usize,
+ content_width: u16,
+) -> usize {
+ let visible_range = start_idx..(start_idx + visible_items);
+ let max_name_width = rows_all
+ .iter()
+ .enumerate()
+ .filter(|(i, _)| visible_range.contains(i))
+ .map(|(_, r)| Line::from(r.name.clone()).width())
+ .max()
+ .unwrap_or(0);
+ let mut desc_col = max_name_width.saturating_add(2);
+ if (desc_col as u16) >= content_width {
+ desc_col = content_width.saturating_sub(1) as usize;
+ }
+ desc_col
+}
+
+/// Determine how many spaces to indent wrapped lines for a row.
+fn wrap_indent(row: &GenericDisplayRow, desc_col: usize, max_width: u16) -> usize {
+ let max_indent = max_width.saturating_sub(1) as usize;
+ let indent = row.wrap_indent.unwrap_or_else(|| {
+ if row.description.is_some() {
+ desc_col
+ } else {
+ 0
+ }
+ });
+ indent.min(max_indent)
+}
+
+/// Build the full display line for a row with the description padded to start
+/// at `desc_col`. Applies fuzzy-match bolding when indices are present and
+/// dims the description.
+fn build_full_line(row: &GenericDisplayRow, desc_col: usize) -> Line<'static> {
+ // Enforce single-line name: allow at most desc_col - 2 cells for name,
+ // reserving two spaces before the description column.
+ let name_limit = row
+ .description
+ .as_ref()
+ .map(|_| desc_col.saturating_sub(2))
+ .unwrap_or(usize::MAX);
+
+ let mut name_spans: Vec<Span> = Vec::with_capacity(row.name.len());
+ let mut used_width = 0usize;
+ let mut truncated = false;
+
+ if let Some(idxs) = row.match_indices.as_ref() {
+ let mut idx_iter = idxs.iter().peekable();
+ for (char_idx, ch) in row.name.chars().enumerate() {
+ let ch_w = UnicodeWidthChar::width(ch).unwrap_or(0);
+ let next_width = used_width.saturating_add(ch_w);
+ if next_width > name_limit {
+ truncated = true;
+ break;
+ }
+ used_width = next_width;
+
+ if idx_iter.peek().is_some_and(|next| **next == char_idx) {
+ idx_iter.next();
+ name_spans.push(ch.to_string().bold());
+ } else {
+ name_spans.push(ch.to_string().into());
+ }
+ }
+ } else {
+ for ch in row.name.chars() {
+ let ch_w = UnicodeWidthChar::width(ch).unwrap_or(0);
+ let next_width = used_width.saturating_add(ch_w);
+ if next_width > name_limit {
+ truncated = true;
+ break;
+ }
+ used_width = next_width;
+ name_spans.push(ch.to_string().into());
+ }
+ }
+
+ if truncated {
+ // If there is at least one cell available, add an ellipsis.
+ // When name_limit is 0, we still show an ellipsis to indicate truncation.
+ name_spans.push("…".into());
+ }
+
+ let this_name_width = Line::from(name_spans.clone()).width();
+ let mut full_spans: Vec<Span> = name_spans;
+ if let Some(display_shortcut) = row.display_shortcut {
+ full_spans.push(" (".into());
+ full_spans.push(display_shortcut.into());
+ full_spans.push(")".into());
+ }
+ if let Some(desc) = row.description.as_ref() {
+ let gap = desc_col.saturating_sub(this_name_width);
+ if gap > 0 {
+ full_spans.push(" ".repeat(gap).into());
+ }
+ full_spans.push(desc.clone().dim());
+ }
+ Line::from(full_spans)
+}
+
+/// Render a list of rows using the provided ScrollState, with shared styling
+/// and behavior for selection popups.
+pub(crate) fn render_rows(
+ area: Rect,
+ buf: &mut Buffer,
+ rows_all: &[GenericDisplayRow],
+ state: &ScrollState,
+ max_results: usize,
+ empty_message: &str,
+) {
+ if rows_all.is_empty() {
+ if area.height > 0 {
+ Line::from(empty_message.dim().italic()).render(area, buf);
+ }
+ return;
+ }
+
+ // Determine which logical rows (items) are visible given the selection and
+ // the max_results clamp. Scrolling is still item-based for simplicity.
+ let visible_items = max_results
+ .min(rows_all.len())
+ .min(area.height.max(1) as usize);
+
+ let mut start_idx = state.scroll_top.min(rows_all.len().saturating_sub(1));
+ if let Some(sel) = state.selected_idx {
+ if sel < start_idx {
+ start_idx = sel;
+ } else if visible_items > 0 {
+ let bottom = start_idx + visible_items - 1;
+ if sel > bottom {
+ start_idx = sel + 1 - visible_items;
+ }
+ }
+ }
+
+ let desc_col = compute_desc_col(rows_all, start_idx, visible_items, area.width);
+
+ // Render items, wrapping descriptions and aligning wrapped lines under the
+ // shared description column. Stop when we run out of vertical space.
+ let mut cur_y = area.y;
+ for (i, row) in rows_all
+ .iter()
+ .enumerate()
+ .skip(start_idx)
+ .take(visible_items)
+ {
+ if cur_y >= area.y + area.height {
+ break;
+ }
+
+ let mut full_line = build_full_line(row, desc_col);
+ if Some(i) == state.selected_idx {
+ // Match previous behavior: cyan + bold for the selected row.
+ // Reset the style first to avoid inheriting dim from keyboard shortcuts.
+ full_line.spans.iter_mut().for_each(|span| {
+ span.style = Style::default().fg(Color::Cyan).bold();
+ });
+ }
+
+ // Wrap with subsequent indent aligned to the description column.
+ use crate::wrapping::RtOptions;
+ use crate::wrapping::word_wrap_line;
+ let continuation_indent = wrap_indent(row, desc_col, area.width);
+ let options = RtOptions::new(area.width as usize)
+ .initial_indent(Line::from(""))
+ .subsequent_indent(Line::from(" ".repeat(continuation_indent)));
+ let wrapped = word_wrap_line(&full_line, options);
+
+ // Render the wrapped lines.
+ for line in wrapped {
+ if cur_y >= area.y + area.height {
+ break;
+ }
+ line.render(
+ Rect {
+ x: area.x,
+ y: cur_y,
+ width: area.width,
+ height: 1,
+ },
+ buf,
+ );
+ cur_y = cur_y.saturating_add(1);
+ }
+ }
+}
+
+/// Compute the number of terminal rows required to render up to `max_results`
+/// items from `rows_all` given the current scroll/selection state and the
+/// available `width`. Accounts for description wrapping and alignment so the
+/// caller can allocate sufficient vertical space.
+pub(crate) fn measure_rows_height(
+ rows_all: &[GenericDisplayRow],
+ state: &ScrollState,
+ max_results: usize,
+ width: u16,
+) -> u16 {
+ if rows_all.is_empty() {
+ return 1; // placeholder "no matches" line
+ }
+
+ let content_width = width.saturating_sub(1).max(1);
+
+ let visible_items = max_results.min(rows_all.len());
+ let mut start_idx = state.scroll_top.min(rows_all.len().saturating_sub(1));
+ if let Some(sel) = state.selected_idx {
+ if sel < start_idx {
+ start_idx = sel;
+ } else if visible_items > 0 {
+ let bottom = start_idx + visible_items - 1;
+ if sel > bottom {
+ start_idx = sel + 1 - visible_items;
+ }
+ }
+ }
+
+ let desc_col = compute_desc_col(rows_all, start_idx, visible_items, content_width);
+
+ use crate::wrapping::RtOptions;
+ use crate::wrapping::word_wrap_line;
+ let mut total: u16 = 0;
+ for row in rows_all
+ .iter()
+ .enumerate()
+ .skip(start_idx)
+ .take(visible_items)
+ .map(|(_, r)| r)
+ {
+ let full_line = build_full_line(row, desc_col);
+ let continuation_indent = wrap_indent(row, desc_col, content_width);
+ let opts = RtOptions::new(content_width as usize)
+ .initial_indent(Line::from(""))
+ .subsequent_indent(Line::from(" ".repeat(continuation_indent)));
+ total = total.saturating_add(word_wrap_line(&full_line, opts).len() as u16);
+ }
+ total.max(1)
+}
diff --git a/codex-rs/tui2/src/bottom_pane/skill_popup.rs b/codex-rs/tui2/src/bottom_pane/skill_popup.rs
new file mode 100644
index 0000000000..3e0f79f84b
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/skill_popup.rs
@@ -0,0 +1,142 @@
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::widgets::WidgetRef;
+
+use super::popup_consts::MAX_POPUP_ROWS;
+use super::scroll_state::ScrollState;
+use super::selection_popup_common::GenericDisplayRow;
+use super::selection_popup_common::measure_rows_height;
+use super::selection_popup_common::render_rows;
+use crate::render::Insets;
+use crate::render::RectExt;
+use codex_common::fuzzy_match::fuzzy_match;
+use codex_core::skills::model::SkillMetadata;
+
+pub(crate) struct SkillPopup {
+ query: String,
+ skills: Vec<SkillMetadata>,
+ state: ScrollState,
+}
+
+impl SkillPopup {
+ pub(crate) fn new(skills: Vec<SkillMetadata>) -> Self {
+ Self {
+ query: String::new(),
+ skills,
+ state: ScrollState::new(),
+ }
+ }
+
+ pub(crate) fn set_skills(&mut self, skills: Vec<SkillMetadata>) {
+ self.skills = skills;
+ self.clamp_selection();
+ }
+
+ pub(crate) fn set_query(&mut self, query: &str) {
+ self.query = query.to_string();
+ self.clamp_selection();
+ }
+
+ pub(crate) fn calculate_required_height(&self, width: u16) -> u16 {
+ let rows = self.rows_from_matches(self.filtered());
+ measure_rows_height(&rows, &self.state, MAX_POPUP_ROWS, width)
+ }
+
+ pub(crate) fn move_up(&mut self) {
+ let len = self.filtered_items().len();
+ self.state.move_up_wrap(len);
+ self.state.ensure_visible(len, MAX_POPUP_ROWS.min(len));
+ }
+
+ pub(crate) fn move_down(&mut self) {
+ let len = self.filtered_items().len();
+ self.state.move_down_wrap(len);
+ self.state.ensure_visible(len, MAX_POPUP_ROWS.min(len));
+ }
+
+ pub(crate) fn selected_skill(&self) -> Option<&SkillMetadata> {
+ let matches = self.filtered_items();
+ let idx = self.state.selected_idx?;
+ let skill_idx = matches.get(idx)?;
+ self.skills.get(*skill_idx)
+ }
+
+ fn clamp_selection(&mut self) {
+ let len = self.filtered_items().len();
+ self.state.clamp_selection(len);
+ self.state.ensure_visible(len, MAX_POPUP_ROWS.min(len));
+ }
+
+ fn filtered_items(&self) -> Vec<usize> {
+ self.filtered().into_iter().map(|(idx, _, _)| idx).collect()
+ }
+
+ fn rows_from_matches(
+ &self,
+ matches: Vec<(usize, Option<Vec<usize>>, i32)>,
+ ) -> Vec<GenericDisplayRow> {
+ matches
+ .into_iter()
+ .map(|(idx, indices, _score)| {
+ let skill = &self.skills[idx];
+ let slug = skill
+ .path
+ .parent()
+ .and_then(|p| p.file_name())
+ .and_then(|n| n.to_str())
+ .unwrap_or(&skill.name);
+ let name = format!("{} ({slug})", skill.name);
+ let description = skill.description.clone();
+ GenericDisplayRow {
+ name,
+ match_indices: indices,
+ display_shortcut: None,
+ description: Some(description),
+ wrap_indent: None,
+ }
+ })
+ .collect()
+ }
+
+ fn filtered(&self) -> Vec<(usize, Option<Vec<usize>>, i32)> {
+ let filter = self.query.trim();
+ let mut out: Vec<(usize, Option<Vec<usize>>, i32)> = Vec::new();
+
+ if filter.is_empty() {
+ for (idx, _skill) in self.skills.iter().enumerate() {
+ out.push((idx, None, 0));
+ }
+ return out;
+ }
+
+ for (idx, skill) in self.skills.iter().enumerate() {
+ if let Some((indices, score)) = fuzzy_match(&skill.name, filter) {
+ out.push((idx, Some(indices), score));
+ }
+ }
+
+ out.sort_by(|a, b| {
+ a.2.cmp(&b.2).then_with(|| {
+ let an = &self.skills[a.0].name;
+ let bn = &self.skills[b.0].name;
+ an.cmp(bn)
+ })
+ });
+
+ out
+ }
+}
+
+impl WidgetRef for SkillPopup {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ let rows = self.rows_from_matches(self.filtered());
+ render_rows(
+ area.inset(Insets::tlbr(0, 2, 0, 0)),
+ buf,
+ &rows,
+ &self.state,
+ MAX_POPUP_ROWS,
+ "no skills",
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__backspace_after_pastes.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__backspace_after_pastes.snap
new file mode 100644
index 0000000000..00821b7910
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__backspace_after_pastes.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› [Pasted Content 1002 chars][Pasted Content 1004 chars] "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__empty.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__empty.snap
new file mode 100644
index 0000000000..1a34b29f92
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__empty.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left · ? for shortcuts "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_interrupt.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_interrupt.snap
new file mode 100644
index 0000000000..d323fda148
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_interrupt.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" ctrl + c again to interrupt "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_quit.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_quit.snap
new file mode 100644
index 0000000000..d9395f2b05
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_quit.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" ctrl + c again to quit "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_then_esc_hint.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_then_esc_hint.snap
new file mode 100644
index 0000000000..9e93b8d683
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_then_esc_hint.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" esc esc to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_esc_hint_backtrack.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_esc_hint_backtrack.snap
new file mode 100644
index 0000000000..1d16779b01
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_esc_hint_backtrack.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" esc again to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_esc_hint_from_overlay.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_esc_hint_from_overlay.snap
new file mode 100644
index 0000000000..9e93b8d683
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_esc_hint_from_overlay.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" esc esc to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap
new file mode 100644
index 0000000000..0aa72ca002
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› h "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_overlay_then_external_esc_hint.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_overlay_then_external_esc_hint.snap
new file mode 100644
index 0000000000..1d16779b01
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_overlay_then_external_esc_hint.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" esc again to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_shortcut_overlay.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_shortcut_overlay.snap
new file mode 100644
index 0000000000..178182bfd7
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__footer_mode_shortcut_overlay.snap
@@ -0,0 +1,16 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" / for commands shift + enter for newline "
+" @ for file paths ctrl + v to paste images "
+" esc again to edit previous message ctrl + c to exit "
+" ctrl + t to view transcript "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__large.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__large.snap
new file mode 100644
index 0000000000..3b7711d75f
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__large.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› [Pasted Content 1005 chars] "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__multiple_pastes.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__multiple_pastes.snap
new file mode 100644
index 0000000000..426afbec6e
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__multiple_pastes.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› [Pasted Content 1003 chars][Pasted Content 1007 chars] another short paste "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__slash_popup_mo.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__slash_popup_mo.snap
new file mode 100644
index 0000000000..dc66d149e4
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__slash_popup_mo.snap
@@ -0,0 +1,9 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› /mo "
+" "
+" /model choose what model and reasoning effort to use "
+" /mention mention a file "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__slash_popup_res.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__slash_popup_res.snap
new file mode 100644
index 0000000000..daedb3d888
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__slash_popup_res.snap
@@ -0,0 +1,10 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› /res "
+" "
+" "
+" "
+" /resume resume a saved chat "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__small.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__small.snap
new file mode 100644
index 0000000000..8f669e1cb9
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__chat_composer__tests__small.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› short "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_bad_result.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_bad_result.snap
new file mode 100644
index 0000000000..f3c3a319bc
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_bad_result.snap
@@ -0,0 +1,9 @@
+---
+source: tui2/src/bottom_pane/feedback_view.rs
+expression: rendered
+---
+▌ Tell us more (bad result)
+▌
+▌ (optional) Write a short description to help us further
+
+Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_bug.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_bug.snap
new file mode 100644
index 0000000000..2ab262c229
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_bug.snap
@@ -0,0 +1,9 @@
+---
+source: tui2/src/bottom_pane/feedback_view.rs
+expression: rendered
+---
+▌ Tell us more (bug)
+▌
+▌ (optional) Write a short description to help us further
+
+Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_good_result.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_good_result.snap
new file mode 100644
index 0000000000..6bd6846202
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_good_result.snap
@@ -0,0 +1,9 @@
+---
+source: tui2/src/bottom_pane/feedback_view.rs
+expression: rendered
+---
+▌ Tell us more (good result)
+▌
+▌ (optional) Write a short description to help us further
+
+Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_other.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_other.snap
new file mode 100644
index 0000000000..1ec33c54ee
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__feedback_view__tests__feedback_view_other.snap
@@ -0,0 +1,9 @@
+---
+source: tui2/src/bottom_pane/feedback_view.rs
+expression: rendered
+---
+▌ Tell us more (other)
+▌
+▌ (optional) Write a short description to help us further
+
+Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_context_tokens_used.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_context_tokens_used.snap
new file mode 100644
index 0000000000..e31cf10f06
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_context_tokens_used.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" 123K used · ? for shortcuts "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_ctrl_c_quit_idle.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_ctrl_c_quit_idle.snap
new file mode 100644
index 0000000000..157853e73d
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_ctrl_c_quit_idle.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" ctrl + c again to quit "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_ctrl_c_quit_running.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_ctrl_c_quit_running.snap
new file mode 100644
index 0000000000..98bc87b38e
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_ctrl_c_quit_running.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" ctrl + c again to interrupt "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_esc_hint_idle.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_esc_hint_idle.snap
new file mode 100644
index 0000000000..201bec4f62
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_esc_hint_idle.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" esc esc to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_esc_hint_primed.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_esc_hint_primed.snap
new file mode 100644
index 0000000000..0bc46a989a
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_esc_hint_primed.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" esc again to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_shortcuts_context_running.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_shortcuts_context_running.snap
new file mode 100644
index 0000000000..2dd8738fe0
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_shortcuts_context_running.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" 72% context left · ? for shortcuts "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_shortcuts_default.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_shortcuts_default.snap
new file mode 100644
index 0000000000..286acadd8b
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_shortcuts_default.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" 100% context left · ? for shortcuts "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_shortcuts_shift_and_esc.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_shortcuts_shift_and_esc.snap
new file mode 100644
index 0000000000..47508f3240
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__footer__tests__footer_shortcuts_shift_and_esc.snap
@@ -0,0 +1,8 @@
+---
+source: tui2/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" / for commands shift + enter for newline "
+" @ for file paths ctrl + v to paste images "
+" esc again to edit previous message ctrl + c to exit "
+" ctrl + t to view transcript "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_model_picker_width_80.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_model_picker_width_80.snap
new file mode 100644
index 0000000000..b46a229ad4
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_model_picker_width_80.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/bottom_pane/list_selection_view.rs
+expression: "render_lines_with_width(&view, 80)"
+---
+
+ Select Model and Effort
+
+› 1. gpt-5.1-codex (current) Optimized for Codex. Balance of reasoning
+ quality and coding ability.
+ 2. gpt-5.1-codex-mini Optimized for Codex. Cheaper, faster, but less
+ capable.
+ 3. gpt-4.1-codex Legacy model. Use when you need compatibility
+ with older automations.
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_narrow_width_preserves_rows.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_narrow_width_preserves_rows.snap
new file mode 100644
index 0000000000..bcdc8a3561
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_narrow_width_preserves_rows.snap
@@ -0,0 +1,16 @@
+---
+source: tui2/src/bottom_pane/list_selection_view.rs
+expression: "render_lines_with_width(&view, 24)"
+---
+
+ Debug
+
+› 1. Item 1
+ xxxxxxxxx
+ x
+ 2. Item 2
+ xxxxxxxxx
+ x
+ 3. Item 3
+ xxxxxxxxx
+ x
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap
new file mode 100644
index 0000000000..2cc2578c56
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap
@@ -0,0 +1,12 @@
+---
+source: tui2/src/bottom_pane/list_selection_view.rs
+expression: render_lines(&view)
+---
+
+ Select Approval Mode
+ Switch between Codex approval presets
+
+› 1. Read Only (current) Codex can read files
+ 2. Full Access Codex can edit files
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap
new file mode 100644
index 0000000000..88a5d14932
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap
@@ -0,0 +1,11 @@
+---
+source: tui2/src/bottom_pane/list_selection_view.rs
+expression: render_lines(&view)
+---
+
+ Select Approval Mode
+
+› 1. Read Only (current) Codex can read files
+ 2. Full Access Codex can edit files
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_many_line_message.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_many_line_message.snap
new file mode 100644
index 0000000000..c715e81c9a
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_many_line_message.snap
@@ -0,0 +1,27 @@
+---
+source: tui2/src/bottom_pane/queued_user_messages.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 5 },
+ content: [
+ " ↳ This is ",
+ " a message ",
+ " with many ",
+ " … ",
+ " ⌥ + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 11, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 4, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 13, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 4, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 13, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 5, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 14, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_more_than_three_messages.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_more_than_three_messages.snap
new file mode 100644
index 0000000000..1e88bfb5b1
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_more_than_three_messages.snap
@@ -0,0 +1,30 @@
+---
+source: tui2/src/bottom_pane/queued_user_messages.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 5 },
+ content: [
+ " ↳ Hello, world! ",
+ " ↳ This is another message ",
+ " ↳ This is a third message ",
+ " ↳ This is a fourth message ",
+ " ⌥ + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 17, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 27, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 27, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 28, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 14, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_one_message.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_one_message.snap
new file mode 100644
index 0000000000..8160a886db
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_one_message.snap
@@ -0,0 +1,18 @@
+---
+source: tui2/src/bottom_pane/queued_user_messages.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 2 },
+ content: [
+ " ↳ Hello, world! ",
+ " ⌥ + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 17, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 14, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_two_messages.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_two_messages.snap
new file mode 100644
index 0000000000..9b1ef9e5c6
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_two_messages.snap
@@ -0,0 +1,22 @@
+---
+source: tui2/src/bottom_pane/queued_user_messages.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 3 },
+ content: [
+ " ↳ Hello, world! ",
+ " ↳ This is another message ",
+ " ⌥ + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 17, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 27, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 14, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_wrapped_message.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_wrapped_message.snap
new file mode 100644
index 0000000000..f46cf990fa
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__queued_user_messages__tests__render_wrapped_message.snap
@@ -0,0 +1,25 @@
+---
+source: tui2/src/bottom_pane/queued_user_messages.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 4 },
+ content: [
+ " ↳ This is a longer message that should",
+ " be wrapped ",
+ " ↳ This is another message ",
+ " ⌥ + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 4, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 14, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 27, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 14, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__tests__queued_messages_visible_when_status_hidden_snapshot.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__tests__queued_messages_visible_when_status_hidden_snapshot.snap
new file mode 100644
index 0000000000..71504561db
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__tests__queued_messages_visible_when_status_hidden_snapshot.snap
@@ -0,0 +1,11 @@
+---
+source: tui2/src/bottom_pane/mod.rs
+expression: "render_snapshot(&pane, area)"
+---
+ ↳ Queued follow-up question
+ ⌥ + ↑ edit
+
+
+› Ask Codex to do anything
+
+ 100% context left · ? for shortcuts
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap
new file mode 100644
index 0000000000..f6c157922a
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap
@@ -0,0 +1,10 @@
+---
+source: tui2/src/bottom_pane/mod.rs
+expression: "render_snapshot(&pane, area)"
+---
+• Working (0s • esc to interru
+
+
+› Ask Codex to do anything
+
+ 100% context left · ? for sh
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__tests__status_and_queued_messages_snapshot.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__tests__status_and_queued_messages_snapshot.snap
new file mode 100644
index 0000000000..6ac4296833
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui2__bottom_pane__tests__status_and_queued_messages_snapshot.snap
@@ -0,0 +1,12 @@
+---
+source: tui2/src/bottom_pane/mod.rs
+expression: "render_snapshot(&pane, area)"
+---
+• Working (0s • esc to interrupt)
+ ↳ Queued follow-up question
+ ⌥ + ↑ edit
+
+
+› Ask Codex to do anything
+
+ 100% context left · ? for shortcuts
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap
new file mode 100644
index 0000000000..e4cc9ffefd
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__backspace_after_pastes.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› [Pasted Content 1002 chars][Pasted Content 1004 chars] "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap
new file mode 100644
index 0000000000..53e0aee4cf
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__empty.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left · ? for shortcuts "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_interrupt.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_interrupt.snap
new file mode 100644
index 0000000000..49ffb0d4c8
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_interrupt.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" ctrl + c again to interrupt "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_quit.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_quit.snap
new file mode 100644
index 0000000000..7ecc5bba71
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_quit.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" ctrl + c again to quit "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_then_esc_hint.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_then_esc_hint.snap
new file mode 100644
index 0000000000..9cad17b864
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_ctrl_c_then_esc_hint.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" esc esc to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_backtrack.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_backtrack.snap
new file mode 100644
index 0000000000..2fce42cc26
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_backtrack.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" esc again to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_from_overlay.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_from_overlay.snap
new file mode 100644
index 0000000000..9cad17b864
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_esc_hint_from_overlay.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" esc esc to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap
new file mode 100644
index 0000000000..67e616e917
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_hidden_while_typing.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› h "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_overlay_then_external_esc_hint.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_overlay_then_external_esc_hint.snap
new file mode 100644
index 0000000000..2fce42cc26
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_overlay_then_external_esc_hint.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" esc again to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_shortcut_overlay.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_shortcut_overlay.snap
new file mode 100644
index 0000000000..3b6782d06d
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__footer_mode_shortcut_overlay.snap
@@ -0,0 +1,16 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› Ask Codex to do anything "
+" "
+" "
+" "
+" "
+" "
+" "
+" / for commands shift + enter for newline "
+" @ for file paths ctrl + v to paste images "
+" esc again to edit previous message ctrl + c to exit "
+" ctrl + t to view transcript "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap
new file mode 100644
index 0000000000..6b018021ec
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__large.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› [Pasted Content 1005 chars] "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap
new file mode 100644
index 0000000000..40098faee0
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__multiple_pastes.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› [Pasted Content 1003 chars][Pasted Content 1007 chars] another short paste "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_mo.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_mo.snap
new file mode 100644
index 0000000000..661e82e3ad
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_mo.snap
@@ -0,0 +1,9 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› /mo "
+" "
+" /model choose what model and reasoning effort to use "
+" /mention mention a file "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_res.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_res.snap
new file mode 100644
index 0000000000..df8ea36e63
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__slash_popup_res.snap
@@ -0,0 +1,11 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+assertion_line: 2385
+expression: terminal.backend()
+---
+" "
+"› /res "
+" "
+" "
+" "
+" /resume resume a saved chat "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap
new file mode 100644
index 0000000000..498ed76936
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__chat_composer__tests__small.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/bottom_pane/chat_composer.rs
+expression: terminal.backend()
+---
+" "
+"› short "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" 100% context left "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bad_result.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bad_result.snap
new file mode 100644
index 0000000000..465f0f9c4f
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bad_result.snap
@@ -0,0 +1,9 @@
+---
+source: tui/src/bottom_pane/feedback_view.rs
+expression: rendered
+---
+▌ Tell us more (bad result)
+▌
+▌ (optional) Write a short description to help us further
+
+Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bug.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bug.snap
new file mode 100644
index 0000000000..a0b5660135
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bug.snap
@@ -0,0 +1,9 @@
+---
+source: tui/src/bottom_pane/feedback_view.rs
+expression: rendered
+---
+▌ Tell us more (bug)
+▌
+▌ (optional) Write a short description to help us further
+
+Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_good_result.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_good_result.snap
new file mode 100644
index 0000000000..73074d61fa
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_good_result.snap
@@ -0,0 +1,9 @@
+---
+source: tui/src/bottom_pane/feedback_view.rs
+expression: rendered
+---
+▌ Tell us more (good result)
+▌
+▌ (optional) Write a short description to help us further
+
+Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_other.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_other.snap
new file mode 100644
index 0000000000..80e4ffeffe
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_other.snap
@@ -0,0 +1,9 @@
+---
+source: tui/src/bottom_pane/feedback_view.rs
+expression: rendered
+---
+▌ Tell us more (other)
+▌
+▌ (optional) Write a short description to help us further
+
+Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_render.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_render.snap
new file mode 100644
index 0000000000..bafa94b09d
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_render.snap
@@ -0,0 +1,17 @@
+---
+source: tui/src/bottom_pane/feedback_view.rs
+expression: rendered
+---
+ Do you want to upload logs before reporting issue?
+
+ Logs may include the full conversation history of this Codex process
+ These logs are retained for 90 days and are used solely for troubles
+
+ You can review the exact content of the logs before they’re uploaded
+ <LOG_PATH>
+
+
+› 1. Yes Share the current Codex session logs with the team for
+ troubleshooting.
+ 2. No
+ 3. Cancel
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_tokens_used.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_tokens_used.snap
new file mode 100644
index 0000000000..a77ca5565b
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_context_tokens_used.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" 123K used · ? for shortcuts "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_idle.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_idle.snap
new file mode 100644
index 0000000000..31a1b743b8
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_idle.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" ctrl + c again to quit "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_running.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_running.snap
new file mode 100644
index 0000000000..9979372a1b
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_ctrl_c_quit_running.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" ctrl + c again to interrupt "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_idle.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_idle.snap
new file mode 100644
index 0000000000..b2333b025f
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_idle.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" esc esc to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_primed.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_primed.snap
new file mode 100644
index 0000000000..20f9b178b4
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_esc_hint_primed.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" esc again to edit previous message "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_context_running.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_context_running.snap
new file mode 100644
index 0000000000..d05ac90a91
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_context_running.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" 72% context left · ? for shortcuts "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_default.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_default.snap
new file mode 100644
index 0000000000..c95a5dc0b3
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_default.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" 100% context left · ? for shortcuts "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_shift_and_esc.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_shift_and_esc.snap
new file mode 100644
index 0000000000..264515a6c2
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__footer__tests__footer_shortcuts_shift_and_esc.snap
@@ -0,0 +1,8 @@
+---
+source: tui/src/bottom_pane/footer.rs
+expression: terminal.backend()
+---
+" / for commands shift + enter for newline "
+" @ for file paths ctrl + v to paste images "
+" esc again to edit previous message ctrl + c to exit "
+" ctrl + t to view transcript "
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_model_picker_width_80.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_model_picker_width_80.snap
new file mode 100644
index 0000000000..be81978c89
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_model_picker_width_80.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/bottom_pane/list_selection_view.rs
+expression: "render_lines_with_width(&view, 80)"
+---
+
+ Select Model and Effort
+
+› 1. gpt-5.1-codex (current) Optimized for Codex. Balance of reasoning
+ quality and coding ability.
+ 2. gpt-5.1-codex-mini Optimized for Codex. Cheaper, faster, but less
+ capable.
+ 3. gpt-4.1-codex Legacy model. Use when you need compatibility
+ with older automations.
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_narrow_width_preserves_rows.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_narrow_width_preserves_rows.snap
new file mode 100644
index 0000000000..3ce6a3c45f
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_narrow_width_preserves_rows.snap
@@ -0,0 +1,16 @@
+---
+source: tui/src/bottom_pane/list_selection_view.rs
+expression: "render_lines_with_width(&view, 24)"
+---
+
+ Debug
+
+› 1. Item 1
+ xxxxxxxxx
+ x
+ 2. Item 2
+ xxxxxxxxx
+ x
+ 3. Item 3
+ xxxxxxxxx
+ x
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap
new file mode 100644
index 0000000000..512f6bbca6
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_with_subtitle.snap
@@ -0,0 +1,12 @@
+---
+source: tui/src/bottom_pane/list_selection_view.rs
+expression: render_lines(&view)
+---
+
+ Select Approval Mode
+ Switch between Codex approval presets
+
+› 1. Read Only (current) Codex can read files
+ 2. Full Access Codex can edit files
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap
new file mode 100644
index 0000000000..ddd0f90cd8
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_spacing_without_subtitle.snap
@@ -0,0 +1,11 @@
+---
+source: tui/src/bottom_pane/list_selection_view.rs
+expression: render_lines(&view)
+---
+
+ Select Approval Mode
+
+› 1. Read Only (current) Codex can read files
+ 2. Full Access Codex can edit files
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_many_line_message.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_many_line_message.snap
new file mode 100644
index 0000000000..cf1f7248b3
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_many_line_message.snap
@@ -0,0 +1,27 @@
+---
+source: tui/src/bottom_pane/message_queue.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 5 },
+ content: [
+ " ↳ This is ",
+ " a message ",
+ " with many ",
+ " … ",
+ " alt + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 11, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 4, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 13, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 4, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 13, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 5, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 16, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_one_message.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_one_message.snap
new file mode 100644
index 0000000000..5e403e1bdd
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_one_message.snap
@@ -0,0 +1,18 @@
+---
+source: tui/src/bottom_pane/message_queue.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 2 },
+ content: [
+ " ↳ Hello, world! ",
+ " alt + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 17, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 16, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_two_messages.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_two_messages.snap
new file mode 100644
index 0000000000..4484509695
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_two_messages.snap
@@ -0,0 +1,22 @@
+---
+source: tui/src/bottom_pane/message_queue.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 3 },
+ content: [
+ " ↳ Hello, world! ",
+ " ↳ This is another message ",
+ " alt + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 17, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 27, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 16, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_wrapped_message.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_wrapped_message.snap
new file mode 100644
index 0000000000..16d6361257
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__message_queue__tests__render_wrapped_message.snap
@@ -0,0 +1,25 @@
+---
+source: tui/src/bottom_pane/message_queue.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 4 },
+ content: [
+ " ↳ This is a longer message that should",
+ " be wrapped ",
+ " ↳ This is another message ",
+ " alt + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 4, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 14, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 27, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 16, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_many_line_message.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_many_line_message.snap
new file mode 100644
index 0000000000..d2afbf7dbd
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_many_line_message.snap
@@ -0,0 +1,27 @@
+---
+source: tui/src/bottom_pane/queued_user_messages.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 5 },
+ content: [
+ " ↳ This is ",
+ " a message ",
+ " with many ",
+ " … ",
+ " ⌥ + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 11, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 4, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 13, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 4, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 13, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 5, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 14, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_more_than_three_messages.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_more_than_three_messages.snap
new file mode 100644
index 0000000000..9d7527d16f
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_more_than_three_messages.snap
@@ -0,0 +1,30 @@
+---
+source: tui/src/bottom_pane/queued_user_messages.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 5 },
+ content: [
+ " ↳ Hello, world! ",
+ " ↳ This is another message ",
+ " ↳ This is a third message ",
+ " ↳ This is a fourth message ",
+ " ⌥ + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 17, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 27, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 27, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 28, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 14, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_one_message.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_one_message.snap
new file mode 100644
index 0000000000..d47fa97863
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_one_message.snap
@@ -0,0 +1,18 @@
+---
+source: tui/src/bottom_pane/queued_user_messages.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 2 },
+ content: [
+ " ↳ Hello, world! ",
+ " ⌥ + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 17, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 14, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_two_messages.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_two_messages.snap
new file mode 100644
index 0000000000..1f020fec64
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_two_messages.snap
@@ -0,0 +1,22 @@
+---
+source: tui/src/bottom_pane/queued_user_messages.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 3 },
+ content: [
+ " ↳ Hello, world! ",
+ " ↳ This is another message ",
+ " ⌥ + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 17, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 27, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 14, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_wrapped_message.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_wrapped_message.snap
new file mode 100644
index 0000000000..4f2917a6c4
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__queued_user_messages__tests__render_wrapped_message.snap
@@ -0,0 +1,25 @@
+---
+source: tui/src/bottom_pane/queued_user_messages.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 40, height: 4 },
+ content: [
+ " ↳ This is a longer message that should",
+ " be wrapped ",
+ " ↳ This is another message ",
+ " ⌥ + ↑ edit ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 0, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 4, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 14, y: 1, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 4, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: DIM | ITALIC,
+ x: 27, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 14, y: 3, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ ]
+}
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__queued_messages_visible_when_status_hidden_snapshot.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__queued_messages_visible_when_status_hidden_snapshot.snap
new file mode 100644
index 0000000000..123a5eb3a3
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__queued_messages_visible_when_status_hidden_snapshot.snap
@@ -0,0 +1,11 @@
+---
+source: tui/src/bottom_pane/mod.rs
+expression: "render_snapshot(&pane, area)"
+---
+ ↳ Queued follow-up question
+ ⌥ + ↑ edit
+
+
+› Ask Codex to do anything
+
+ 100% context left · ? for shortcuts
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap
new file mode 100644
index 0000000000..86e3da4573
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_composer_fill_height_without_bottom_padding.snap
@@ -0,0 +1,10 @@
+---
+source: tui/src/bottom_pane/mod.rs
+expression: "render_snapshot(&pane, area)"
+---
+• Working (0s • esc to interru
+
+
+› Ask Codex to do anything
+
+ 100% context left · ? for sh
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_queued_messages_snapshot.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_queued_messages_snapshot.snap
new file mode 100644
index 0000000000..27df671e4d
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_and_queued_messages_snapshot.snap
@@ -0,0 +1,12 @@
+---
+source: tui/src/bottom_pane/mod.rs
+expression: "render_snapshot(&pane, area)"
+---
+• Working (0s • esc to interrupt)
+ ↳ Queued follow-up question
+ ⌥ + ↑ edit
+
+
+› Ask Codex to do anything
+
+ 100% context left · ? for shortcuts
diff --git a/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_hidden_when_height_too_small_height_1.snap b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_hidden_when_height_too_small_height_1.snap
new file mode 100644
index 0000000000..52f96e8557
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/snapshots/codex_tui__bottom_pane__tests__status_hidden_when_height_too_small_height_1.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/bottom_pane/mod.rs
+expression: "render_snapshot(&pane, area1)"
+---
+› Ask Codex to do a
diff --git a/codex-rs/tui2/src/bottom_pane/textarea.rs b/codex-rs/tui2/src/bottom_pane/textarea.rs
new file mode 100644
index 0000000000..2fd415c7f6
--- /dev/null
+++ b/codex-rs/tui2/src/bottom_pane/textarea.rs
@@ -0,0 +1,2015 @@
+use crate::key_hint::is_altgr;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyModifiers;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::style::Color;
+use ratatui::style::Style;
+use ratatui::widgets::StatefulWidgetRef;
+use ratatui::widgets::WidgetRef;
+use std::cell::Ref;
+use std::cell::RefCell;
+use std::ops::Range;
+use textwrap::Options;
+use unicode_segmentation::UnicodeSegmentation;
+use unicode_width::UnicodeWidthStr;
+
+const WORD_SEPARATORS: &str = "`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?";
+
+fn is_word_separator(ch: char) -> bool {
+ WORD_SEPARATORS.contains(ch)
+}
+
+#[derive(Debug, Clone)]
+struct TextElement {
+ range: Range<usize>,
+}
+
+#[derive(Debug)]
+pub(crate) struct TextArea {
+ text: String,
+ cursor_pos: usize,
+ wrap_cache: RefCell<Option<WrapCache>>,
+ preferred_col: Option<usize>,
+ elements: Vec<TextElement>,
+ kill_buffer: String,
+}
+
+#[derive(Debug, Clone)]
+struct WrapCache {
+ width: u16,
+ lines: Vec<Range<usize>>,
+}
+
+#[derive(Debug, Default, Clone, Copy)]
+pub(crate) struct TextAreaState {
+ /// Index into wrapped lines of the first visible line.
+ scroll: u16,
+}
+
+impl TextArea {
+ pub fn new() -> Self {
+ Self {
+ text: String::new(),
+ cursor_pos: 0,
+ wrap_cache: RefCell::new(None),
+ preferred_col: None,
+ elements: Vec::new(),
+ kill_buffer: String::new(),
+ }
+ }
+
+ pub fn set_text(&mut self, text: &str) {
+ self.text = text.to_string();
+ self.cursor_pos = self.cursor_pos.clamp(0, self.text.len());
+ self.wrap_cache.replace(None);
+ self.preferred_col = None;
+ self.elements.clear();
+ self.kill_buffer.clear();
+ }
+
+ pub fn text(&self) -> &str {
+ &self.text
+ }
+
+ pub fn insert_str(&mut self, text: &str) {
+ self.insert_str_at(self.cursor_pos, text);
+ }
+
+ pub fn insert_str_at(&mut self, pos: usize, text: &str) {
+ let pos = self.clamp_pos_for_insertion(pos);
+ self.text.insert_str(pos, text);
+ self.wrap_cache.replace(None);
+ if pos <= self.cursor_pos {
+ self.cursor_pos += text.len();
+ }
+ self.shift_elements(pos, 0, text.len());
+ self.preferred_col = None;
+ }
+
+ pub fn replace_range(&mut self, range: std::ops::Range<usize>, text: &str) {
+ let range = self.expand_range_to_element_boundaries(range);
+ self.replace_range_raw(range, text);
+ }
+
+ fn replace_range_raw(&mut self, range: std::ops::Range<usize>, text: &str) {
+ assert!(range.start <= range.end);
+ let start = range.start.clamp(0, self.text.len());
+ let end = range.end.clamp(0, self.text.len());
+ let removed_len = end - start;
+ let inserted_len = text.len();
+ if removed_len == 0 && inserted_len == 0 {
+ return;
+ }
+ let diff = inserted_len as isize - removed_len as isize;
+
+ self.text.replace_range(range, text);
+ self.wrap_cache.replace(None);
+ self.preferred_col = None;
+ self.update_elements_after_replace(start, end, inserted_len);
+
+ // Update the cursor position to account for the edit.
+ self.cursor_pos = if self.cursor_pos < start {
+ // Cursor was before the edited range – no shift.
+ self.cursor_pos
+ } else if self.cursor_pos <= end {
+ // Cursor was inside the replaced range – move to end of the new text.
+ start + inserted_len
+ } else {
+ // Cursor was after the replaced range – shift by the length diff.
+ ((self.cursor_pos as isize) + diff) as usize
+ }
+ .min(self.text.len());
+
+ // Ensure cursor is not inside an element
+ self.cursor_pos = self.clamp_pos_to_nearest_boundary(self.cursor_pos);
+ }
+
+ pub fn cursor(&self) -> usize {
+ self.cursor_pos
+ }
+
+ pub fn set_cursor(&mut self, pos: usize) {
+ self.cursor_pos = pos.clamp(0, self.text.len());
+ self.cursor_pos = self.clamp_pos_to_nearest_boundary(self.cursor_pos);
+ self.preferred_col = None;
+ }
+
+ pub fn desired_height(&self, width: u16) -> u16 {
+ self.wrapped_lines(width).len() as u16
+ }
+
+ #[cfg_attr(not(test), allow(dead_code))]
+ pub fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ self.cursor_pos_with_state(area, TextAreaState::default())
+ }
+
+ /// Compute the on-screen cursor position taking scrolling into account.
+ pub fn cursor_pos_with_state(&self, area: Rect, state: TextAreaState) -> Option<(u16, u16)> {
+ let lines = self.wrapped_lines(area.width);
+ let effective_scroll = self.effective_scroll(area.height, &lines, state.scroll);
+ let i = Self::wrapped_line_index_by_start(&lines, self.cursor_pos)?;
+ let ls = &lines[i];
+ let col = self.text[ls.start..self.cursor_pos].width() as u16;
+ let screen_row = i
+ .saturating_sub(effective_scroll as usize)
+ .try_into()
+ .unwrap_or(0);
+ Some((area.x + col, area.y + screen_row))
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.text.is_empty()
+ }
+
+ fn current_display_col(&self) -> usize {
+ let bol = self.beginning_of_current_line();
+ self.text[bol..self.cursor_pos].width()
+ }
+
+ fn wrapped_line_index_by_start(lines: &[Range<usize>], pos: usize) -> Option<usize> {
+ // partition_point returns the index of the first element for which
+ // the predicate is false, i.e. the count of elements with start <= pos.
+ let idx = lines.partition_point(|r| r.start <= pos);
+ if idx == 0 { None } else { Some(idx - 1) }
+ }
+
+ fn move_to_display_col_on_line(
+ &mut self,
+ line_start: usize,
+ line_end: usize,
+ target_col: usize,
+ ) {
+ let mut width_so_far = 0usize;
+ for (i, g) in self.text[line_start..line_end].grapheme_indices(true) {
+ width_so_far += g.width();
+ if width_so_far > target_col {
+ self.cursor_pos = line_start + i;
+ // Avoid landing inside an element; round to nearest boundary
+ self.cursor_pos = self.clamp_pos_to_nearest_boundary(self.cursor_pos);
+ return;
+ }
+ }
+ self.cursor_pos = line_end;
+ self.cursor_pos = self.clamp_pos_to_nearest_boundary(self.cursor_pos);
+ }
+
+ fn beginning_of_line(&self, pos: usize) -> usize {
+ self.text[..pos].rfind('\n').map(|i| i + 1).unwrap_or(0)
+ }
+ fn beginning_of_current_line(&self) -> usize {
+ self.beginning_of_line(self.cursor_pos)
+ }
+
+ fn end_of_line(&self, pos: usize) -> usize {
+ self.text[pos..]
+ .find('\n')
+ .map(|i| i + pos)
+ .unwrap_or(self.text.len())
+ }
+ fn end_of_current_line(&self) -> usize {
+ self.end_of_line(self.cursor_pos)
+ }
+
+ pub fn input(&mut self, event: KeyEvent) {
+ match event {
+ // Some terminals (or configurations) send Control key chords as
+ // C0 control characters without reporting the CONTROL modifier.
+ // Handle common fallbacks for Ctrl-B/F/P/N here so they don't get
+ // inserted as literal control bytes.
+ KeyEvent { code: KeyCode::Char('\u{0002}'), modifiers: KeyModifiers::NONE, .. } /* ^B */ => {
+ self.move_cursor_left();
+ }
+ KeyEvent { code: KeyCode::Char('\u{0006}'), modifiers: KeyModifiers::NONE, .. } /* ^F */ => {
+ self.move_cursor_right();
+ }
+ KeyEvent { code: KeyCode::Char('\u{0010}'), modifiers: KeyModifiers::NONE, .. } /* ^P */ => {
+ self.move_cursor_up();
+ }
+ KeyEvent { code: KeyCode::Char('\u{000e}'), modifiers: KeyModifiers::NONE, .. } /* ^N */ => {
+ self.move_cursor_down();
+ }
+ KeyEvent {
+ code: KeyCode::Char(c),
+ // Insert plain characters (and Shift-modified). Do NOT insert when ALT is held,
+ // because many terminals map Option/Meta combos to ALT+<char> (e.g. ESC f/ESC b)
+ // for word navigation. Those are handled explicitly below.
+ modifiers: KeyModifiers::NONE | KeyModifiers::SHIFT,
+ ..
+ } => self.insert_str(&c.to_string()),
+ KeyEvent {
+ code: KeyCode::Char('j' | 'm'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Enter,
+ ..
+ } => self.insert_str("\n"),
+ KeyEvent {
+ code: KeyCode::Char('h'),
+ modifiers,
+ ..
+ } if modifiers == (KeyModifiers::CONTROL | KeyModifiers::ALT) => {
+ self.delete_backward_word()
+ },
+ // Windows AltGr generates ALT|CONTROL; treat as a plain character input unless
+ // we match a specific Control+Alt binding above.
+ KeyEvent {
+ code: KeyCode::Char(c),
+ modifiers,
+ ..
+ } if is_altgr(modifiers) => self.insert_str(&c.to_string()),
+ KeyEvent {
+ code: KeyCode::Backspace,
+ modifiers: KeyModifiers::ALT,
+ ..
+ } => self.delete_backward_word(),
+ KeyEvent {
+ code: KeyCode::Backspace,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('h'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => self.delete_backward(1),
+ KeyEvent {
+ code: KeyCode::Delete,
+ modifiers: KeyModifiers::ALT,
+ ..
+ } => self.delete_forward_word(),
+ KeyEvent {
+ code: KeyCode::Delete,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('d'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => self.delete_forward(1),
+
+ KeyEvent {
+ code: KeyCode::Char('w'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.delete_backward_word();
+ }
+ // Meta-b -> move to beginning of previous word
+ // Meta-f -> move to end of next word
+ // Many terminals map Option (macOS) to Alt. Some send Alt|Shift, so match contains(ALT).
+ KeyEvent {
+ code: KeyCode::Char('b'),
+ modifiers: KeyModifiers::ALT,
+ ..
+ } => {
+ self.set_cursor(self.beginning_of_previous_word());
+ }
+ KeyEvent {
+ code: KeyCode::Char('f'),
+ modifiers: KeyModifiers::ALT,
+ ..
+ } => {
+ self.set_cursor(self.end_of_next_word());
+ }
+ KeyEvent {
+ code: KeyCode::Char('u'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.kill_to_beginning_of_line();
+ }
+ KeyEvent {
+ code: KeyCode::Char('k'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.kill_to_end_of_line();
+ }
+ KeyEvent {
+ code: KeyCode::Char('y'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.yank();
+ }
+
+ // Cursor movement
+ KeyEvent {
+ code: KeyCode::Left,
+ modifiers: KeyModifiers::NONE,
+ ..
+ } => {
+ self.move_cursor_left();
+ }
+ KeyEvent {
+ code: KeyCode::Right,
+ modifiers: KeyModifiers::NONE,
+ ..
+ } => {
+ self.move_cursor_right();
+ }
+ KeyEvent {
+ code: KeyCode::Char('b'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.move_cursor_left();
+ }
+ KeyEvent {
+ code: KeyCode::Char('f'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.move_cursor_right();
+ }
+ KeyEvent {
+ code: KeyCode::Char('p'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.move_cursor_up();
+ }
+ KeyEvent {
+ code: KeyCode::Char('n'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.move_cursor_down();
+ }
+ // Some terminals send Alt+Arrow for word-wise movement:
+ // Option/Left -> Alt+Left (previous word start)
+ // Option/Right -> Alt+Right (next word end)
+ KeyEvent {
+ code: KeyCode::Left,
+ modifiers: KeyModifiers::ALT,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Left,
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.set_cursor(self.beginning_of_previous_word());
+ }
+ KeyEvent {
+ code: KeyCode::Right,
+ modifiers: KeyModifiers::ALT,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Right,
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.set_cursor(self.end_of_next_word());
+ }
+ KeyEvent {
+ code: KeyCode::Up, ..
+ } => {
+ self.move_cursor_up();
+ }
+ KeyEvent {
+ code: KeyCode::Down,
+ ..
+ } => {
+ self.move_cursor_down();
+ }
+ KeyEvent {
+ code: KeyCode::Home,
+ ..
+ } => {
+ self.move_cursor_to_beginning_of_line(false);
+ }
+ KeyEvent {
+ code: KeyCode::Char('a'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.move_cursor_to_beginning_of_line(true);
+ }
+
+ KeyEvent {
+ code: KeyCode::End, ..
+ } => {
+ self.move_cursor_to_end_of_line(false);
+ }
+ KeyEvent {
+ code: KeyCode::Char('e'),
+ modifiers: KeyModifiers::CONTROL,
+ ..
+ } => {
+ self.move_cursor_to_end_of_line(true);
+ }
+ _o => {
+ #[cfg(feature = "debug-logs")]
+ tracing::debug!("Unhandled key event in TextArea: {:?}", _o);
+ }
+ }
+ }
+
+ // ####### Input Functions #######
+ pub fn delete_backward(&mut self, n: usize) {
+ if n == 0 || self.cursor_pos == 0 {
+ return;
+ }
+ let mut target = self.cursor_pos;
+ for _ in 0..n {
+ target = self.prev_atomic_boundary(target);
+ if target == 0 {
+ break;
+ }
+ }
+ self.replace_range(target..self.cursor_pos, "");
+ }
+
+ pub fn delete_forward(&mut self, n: usize) {
+ if n == 0 || self.cursor_pos >= self.text.len() {
+ return;
+ }
+ let mut target = self.cursor_pos;
+ for _ in 0..n {
+ target = self.next_atomic_boundary(target);
+ if target >= self.text.len() {
+ break;
+ }
+ }
+ self.replace_range(self.cursor_pos..target, "");
+ }
+
+ pub fn delete_backward_word(&mut self) {
+ let start = self.beginning_of_previous_word();
+ self.kill_range(start..self.cursor_pos);
+ }
+
+ /// Delete text to the right of the cursor using "word" semantics.
+ ///
+ /// Deletes from the current cursor position through the end of the next word as determined
+ /// by `end_of_next_word()`. Any whitespace (including newlines) between the cursor and that
+ /// word is included in the deletion.
+ pub fn delete_forward_word(&mut self) {
+ let end = self.end_of_next_word();
+ if end > self.cursor_pos {
+ self.kill_range(self.cursor_pos..end);
+ }
+ }
+
+ pub fn kill_to_end_of_line(&mut self) {
+ let eol = self.end_of_current_line();
+ let range = if self.cursor_pos == eol {
+ if eol < self.text.len() {
+ Some(self.cursor_pos..eol + 1)
+ } else {
+ None
+ }
+ } else {
+ Some(self.cursor_pos..eol)
+ };
+
+ if let Some(range) = range {
+ self.kill_range(range);
+ }
+ }
+
+ pub fn kill_to_beginning_of_line(&mut self) {
+ let bol = self.beginning_of_current_line();
+ let range = if self.cursor_pos == bol {
+ if bol > 0 { Some(bol - 1..bol) } else { None }
+ } else {
+ Some(bol..self.cursor_pos)
+ };
+
+ if let Some(range) = range {
+ self.kill_range(range);
+ }
+ }
+
+ pub fn yank(&mut self) {
+ if self.kill_buffer.is_empty() {
+ return;
+ }
+ let text = self.kill_buffer.clone();
+ self.insert_str(&text);
+ }
+
+ fn kill_range(&mut self, range: Range<usize>) {
+ let range = self.expand_range_to_element_boundaries(range);
+ if range.start >= range.end {
+ return;
+ }
+
+ let removed = self.text[range.clone()].to_string();
+ if removed.is_empty() {
+ return;
+ }
+
+ self.kill_buffer = removed;
+ self.replace_range_raw(range, "");
+ }
+
+ /// Move the cursor left by a single grapheme cluster.
+ pub fn move_cursor_left(&mut self) {
+ self.cursor_pos = self.prev_atomic_boundary(self.cursor_pos);
+ self.preferred_col = None;
+ }
+
+ /// Move the cursor right by a single grapheme cluster.
+ pub fn move_cursor_right(&mut self) {
+ self.cursor_pos = self.next_atomic_boundary(self.cursor_pos);
+ self.preferred_col = None;
+ }
+
+ pub fn move_cursor_up(&mut self) {
+ // If we have a wrapping cache, prefer navigating across wrapped (visual) lines.
+ if let Some((target_col, maybe_line)) = {
+ let cache_ref = self.wrap_cache.borrow();
+ if let Some(cache) = cache_ref.as_ref() {
+ let lines = &cache.lines;
+ if let Some(idx) = Self::wrapped_line_index_by_start(lines, self.cursor_pos) {
+ let cur_range = &lines[idx];
+ let target_col = self
+ .preferred_col
+ .unwrap_or_else(|| self.text[cur_range.start..self.cursor_pos].width());
+ if idx > 0 {
+ let prev = &lines[idx - 1];
+ let line_start = prev.start;
+ let line_end = prev.end.saturating_sub(1);
+ Some((target_col, Some((line_start, line_end))))
+ } else {
+ Some((target_col, None))
+ }
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ } {
+ // We had wrapping info. Apply movement accordingly.
+ match maybe_line {
+ Some((line_start, line_end)) => {
+ if self.preferred_col.is_none() {
+ self.preferred_col = Some(target_col);
+ }
+ self.move_to_display_col_on_line(line_start, line_end, target_col);
+ return;
+ }
+ None => {
+ // Already at first visual line -> move to start
+ self.cursor_pos = 0;
+ self.preferred_col = None;
+ return;
+ }
+ }
+ }
+
+ // Fallback to logical line navigation if we don't have wrapping info yet.
+ if let Some(prev_nl) = self.text[..self.cursor_pos].rfind('\n') {
+ let target_col = match self.preferred_col {
+ Some(c) => c,
+ None => {
+ let c = self.current_display_col();
+ self.preferred_col = Some(c);
+ c
+ }
+ };
+ let prev_line_start = self.text[..prev_nl].rfind('\n').map(|i| i + 1).unwrap_or(0);
+ let prev_line_end = prev_nl;
+ self.move_to_display_col_on_line(prev_line_start, prev_line_end, target_col);
+ } else {
+ self.cursor_pos = 0;
+ self.preferred_col = None;
+ }
+ }
+
+ pub fn move_cursor_down(&mut self) {
+ // If we have a wrapping cache, prefer navigating across wrapped (visual) lines.
+ if let Some((target_col, move_to_last)) = {
+ let cache_ref = self.wrap_cache.borrow();
+ if let Some(cache) = cache_ref.as_ref() {
+ let lines = &cache.lines;
+ if let Some(idx) = Self::wrapped_line_index_by_start(lines, self.cursor_pos) {
+ let cur_range = &lines[idx];
+ let target_col = self
+ .preferred_col
+ .unwrap_or_else(|| self.text[cur_range.start..self.cursor_pos].width());
+ if idx + 1 < lines.len() {
+ let next = &lines[idx + 1];
+ let line_start = next.start;
+ let line_end = next.end.saturating_sub(1);
+ Some((target_col, Some((line_start, line_end))))
+ } else {
+ Some((target_col, None))
+ }
+ } else {
+ None
+ }
+ } else {
+ None
+ }
+ } {
+ match move_to_last {
+ Some((line_start, line_end)) => {
+ if self.preferred_col.is_none() {
+ self.preferred_col = Some(target_col);
+ }
+ self.move_to_display_col_on_line(line_start, line_end, target_col);
+ return;
+ }
+ None => {
+ // Already on last visual line -> move to end
+ self.cursor_pos = self.text.len();
+ self.preferred_col = None;
+ return;
+ }
+ }
+ }
+
+ // Fallback to logical line navigation if we don't have wrapping info yet.
+ let target_col = match self.preferred_col {
+ Some(c) => c,
+ None => {
+ let c = self.current_display_col();
+ self.preferred_col = Some(c);
+ c
+ }
+ };
+ if let Some(next_nl) = self.text[self.cursor_pos..]
+ .find('\n')
+ .map(|i| i + self.cursor_pos)
+ {
+ let next_line_start = next_nl + 1;
+ let next_line_end = self.text[next_line_start..]
+ .find('\n')
+ .map(|i| i + next_line_start)
+ .unwrap_or(self.text.len());
+ self.move_to_display_col_on_line(next_line_start, next_line_end, target_col);
+ } else {
+ self.cursor_pos = self.text.len();
+ self.preferred_col = None;
+ }
+ }
+
+ pub fn move_cursor_to_beginning_of_line(&mut self, move_up_at_bol: bool) {
+ let bol = self.beginning_of_current_line();
+ if move_up_at_bol && self.cursor_pos == bol {
+ self.set_cursor(self.beginning_of_line(self.cursor_pos.saturating_sub(1)));
+ } else {
+ self.set_cursor(bol);
+ }
+ self.preferred_col = None;
+ }
+
+ pub fn move_cursor_to_end_of_line(&mut self, move_down_at_eol: bool) {
+ let eol = self.end_of_current_line();
+ if move_down_at_eol && self.cursor_pos == eol {
+ let next_pos = (self.cursor_pos.saturating_add(1)).min(self.text.len());
+ self.set_cursor(self.end_of_line(next_pos));
+ } else {
+ self.set_cursor(eol);
+ }
+ }
+
+ // ===== Text elements support =====
+
+ pub fn insert_element(&mut self, text: &str) {
+ let start = self.clamp_pos_for_insertion(self.cursor_pos);
+ self.insert_str_at(start, text);
+ let end = start + text.len();
+ self.add_element(start..end);
+ // Place cursor at end of inserted element
+ self.set_cursor(end);
+ }
+
+ fn add_element(&mut self, range: Range<usize>) {
+ let elem = TextElement { range };
+ self.elements.push(elem);
+ self.elements.sort_by_key(|e| e.range.start);
+ }
+
+ fn find_element_containing(&self, pos: usize) -> Option<usize> {
+ self.elements
+ .iter()
+ .position(|e| pos > e.range.start && pos < e.range.end)
+ }
+
+ fn clamp_pos_to_nearest_boundary(&self, mut pos: usize) -> usize {
+ if pos > self.text.len() {
+ pos = self.text.len();
+ }
+ if let Some(idx) = self.find_element_containing(pos) {
+ let e = &self.elements[idx];
+ let dist_start = pos.saturating_sub(e.range.start);
+ let dist_end = e.range.end.saturating_sub(pos);
+ if dist_start <= dist_end {
+ e.range.start
+ } else {
+ e.range.end
+ }
+ } else {
+ pos
+ }
+ }
+
+ fn clamp_pos_for_insertion(&self, pos: usize) -> usize {
+ // Do not allow inserting into the middle of an element
+ if let Some(idx) = self.find_element_containing(pos) {
+ let e = &self.elements[idx];
+ // Choose closest edge for insertion
+ let dist_start = pos.saturating_sub(e.range.start);
+ let dist_end = e.range.end.saturating_sub(pos);
+ if dist_start <= dist_end {
+ e.range.start
+ } else {
+ e.range.end
+ }
+ } else {
+ pos
+ }
+ }
+
+ fn expand_range_to_element_boundaries(&self, mut range: Range<usize>) -> Range<usize> {
+ // Expand to include any intersecting elements fully
+ loop {
+ let mut changed = false;
+ for e in &self.elements {
+ if e.range.start < range.end && e.range.end > range.start {
+ let new_start = range.start.min(e.range.start);
+ let new_end = range.end.max(e.range.end);
+ if new_start != range.start || new_end != range.end {
+ range.start = new_start;
+ range.end = new_end;
+ changed = true;
+ }
+ }
+ }
+ if !changed {
+ break;
+ }
+ }
+ range
+ }
+
+ fn shift_elements(&mut self, at: usize, removed: usize, inserted: usize) {
+ // Generic shift: for pure insert, removed = 0; for delete, inserted = 0.
+ let end = at + removed;
+ let diff = inserted as isize - removed as isize;
+ // Remove elements fully deleted by the operation and shift the rest
+ self.elements
+ .retain(|e| !(e.range.start >= at && e.range.end <= end));
+ for e in &mut self.elements {
+ if e.range.end <= at {
+ // before edit
+ } else if e.range.start >= end {
+ // after edit
+ e.range.start = ((e.range.start as isize) + diff) as usize;
+ e.range.end = ((e.range.end as isize) + diff) as usize;
+ } else {
+ // Overlap with element but not fully contained (shouldn't happen when using
+ // element-aware replace, but degrade gracefully by snapping element to new bounds)
+ let new_start = at.min(e.range.start);
+ let new_end = at + inserted.max(e.range.end.saturating_sub(end));
+ e.range.start = new_start;
+ e.range.end = new_end;
+ }
+ }
+ }
+
+ fn update_elements_after_replace(&mut self, start: usize, end: usize, inserted_len: usize) {
+ self.shift_elements(start, end.saturating_sub(start), inserted_len);
+ }
+
+ fn prev_atomic_boundary(&self, pos: usize) -> usize {
+ if pos == 0 {
+ return 0;
+ }
+ // If currently at an element end or inside, jump to start of that element.
+ if let Some(idx) = self
+ .elements
+ .iter()
+ .position(|e| pos > e.range.start && pos <= e.range.end)
+ {
+ return self.elements[idx].range.start;
+ }
+ let mut gc = unicode_segmentation::GraphemeCursor::new(pos, self.text.len(), false);
+ match gc.prev_boundary(&self.text, 0) {
+ Ok(Some(b)) => {
+ if let Some(idx) = self.find_element_containing(b) {
+ self.elements[idx].range.start
+ } else {
+ b
+ }
+ }
+ Ok(None) => 0,
+ Err(_) => pos.saturating_sub(1),
+ }
+ }
+
+ fn next_atomic_boundary(&self, pos: usize) -> usize {
+ if pos >= self.text.len() {
+ return self.text.len();
+ }
+ // If currently at an element start or inside, jump to end of that element.
+ if let Some(idx) = self
+ .elements
+ .iter()
+ .position(|e| pos >= e.range.start && pos < e.range.end)
+ {
+ return self.elements[idx].range.end;
+ }
+ let mut gc = unicode_segmentation::GraphemeCursor::new(pos, self.text.len(), false);
+ match gc.next_boundary(&self.text, 0) {
+ Ok(Some(b)) => {
+ if let Some(idx) = self.find_element_containing(b) {
+ self.elements[idx].range.end
+ } else {
+ b
+ }
+ }
+ Ok(None) => self.text.len(),
+ Err(_) => pos.saturating_add(1),
+ }
+ }
+
+ pub(crate) fn beginning_of_previous_word(&self) -> usize {
+ let prefix = &self.text[..self.cursor_pos];
+ let Some((first_non_ws_idx, ch)) = prefix
+ .char_indices()
+ .rev()
+ .find(|&(_, ch)| !ch.is_whitespace())
+ else {
+ return 0;
+ };
+ let is_separator = is_word_separator(ch);
+ let mut start = first_non_ws_idx;
+ for (idx, ch) in prefix[..first_non_ws_idx].char_indices().rev() {
+ if ch.is_whitespace() || is_word_separator(ch) != is_separator {
+ start = idx + ch.len_utf8();
+ break;
+ }
+ start = idx;
+ }
+ self.adjust_pos_out_of_elements(start, true)
+ }
+
+ pub(crate) fn end_of_next_word(&self) -> usize {
+ let Some(first_non_ws) = self.text[self.cursor_pos..].find(|c: char| !c.is_whitespace())
+ else {
+ return self.text.len();
+ };
+ let word_start = self.cursor_pos + first_non_ws;
+ let mut iter = self.text[word_start..].char_indices();
+ let Some((_, first_ch)) = iter.next() else {
+ return word_start;
+ };
+ let is_separator = is_word_separator(first_ch);
+ let mut end = self.text.len();
+ for (idx, ch) in iter {
+ if ch.is_whitespace() || is_word_separator(ch) != is_separator {
+ end = word_start + idx;
+ break;
+ }
+ }
+ self.adjust_pos_out_of_elements(end, false)
+ }
+
+ fn adjust_pos_out_of_elements(&self, pos: usize, prefer_start: bool) -> usize {
+ if let Some(idx) = self.find_element_containing(pos) {
+ let e = &self.elements[idx];
+ if prefer_start {
+ e.range.start
+ } else {
+ e.range.end
+ }
+ } else {
+ pos
+ }
+ }
+
+ #[expect(clippy::unwrap_used)]
+ fn wrapped_lines(&self, width: u16) -> Ref<'_, Vec<Range<usize>>> {
+ // Ensure cache is ready (potentially mutably borrow, then drop)
+ {
+ let mut cache = self.wrap_cache.borrow_mut();
+ let needs_recalc = match cache.as_ref() {
+ Some(c) => c.width != width,
+ None => true,
+ };
+ if needs_recalc {
+ let lines = crate::wrapping::wrap_ranges(
+ &self.text,
+ Options::new(width as usize).wrap_algorithm(textwrap::WrapAlgorithm::FirstFit),
+ );
+ *cache = Some(WrapCache { width, lines });
+ }
+ }
+
+ let cache = self.wrap_cache.borrow();
+ Ref::map(cache, |c| &c.as_ref().unwrap().lines)
+ }
+
+ /// Calculate the scroll offset that should be used to satisfy the
+ /// invariants given the current area size and wrapped lines.
+ ///
+ /// - Cursor is always on screen.
+ /// - No scrolling if content fits in the area.
+ fn effective_scroll(
+ &self,
+ area_height: u16,
+ lines: &[Range<usize>],
+ current_scroll: u16,
+ ) -> u16 {
+ let total_lines = lines.len() as u16;
+ if area_height >= total_lines {
+ return 0;
+ }
+
+ // Where is the cursor within wrapped lines? Prefer assigning boundary positions
+ // (where pos equals the start of a wrapped line) to that later line.
+ let cursor_line_idx =
+ Self::wrapped_line_index_by_start(lines, self.cursor_pos).unwrap_or(0) as u16;
+
+ let max_scroll = total_lines.saturating_sub(area_height);
+ let mut scroll = current_scroll.min(max_scroll);
+
+ // Ensure cursor is visible within [scroll, scroll + area_height)
+ if cursor_line_idx < scroll {
+ scroll = cursor_line_idx;
+ } else if cursor_line_idx >= scroll + area_height {
+ scroll = cursor_line_idx + 1 - area_height;
+ }
+ scroll
+ }
+}
+
+impl WidgetRef for &TextArea {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ let lines = self.wrapped_lines(area.width);
+ self.render_lines(area, buf, &lines, 0..lines.len());
+ }
+}
+
+impl StatefulWidgetRef for &TextArea {
+ type State = TextAreaState;
+
+ fn render_ref(&self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
+ let lines = self.wrapped_lines(area.width);
+ let scroll = self.effective_scroll(area.height, &lines, state.scroll);
+ state.scroll = scroll;
+
+ let start = scroll as usize;
+ let end = (scroll + area.height).min(lines.len() as u16) as usize;
+ self.render_lines(area, buf, &lines, start..end);
+ }
+}
+
+impl TextArea {
+ fn render_lines(
+ &self,
+ area: Rect,
+ buf: &mut Buffer,
+ lines: &[Range<usize>],
+ range: std::ops::Range<usize>,
+ ) {
+ for (row, idx) in range.enumerate() {
+ let r = &lines[idx];
+ let y = area.y + row as u16;
+ let line_range = r.start..r.end - 1;
+ // Draw base line with default style.
+ buf.set_string(area.x, y, &self.text[line_range.clone()], Style::default());
+
+ // Overlay styled segments for elements that intersect this line.
+ for elem in &self.elements {
+ // Compute overlap with displayed slice.
+ let overlap_start = elem.range.start.max(line_range.start);
+ let overlap_end = elem.range.end.min(line_range.end);
+ if overlap_start >= overlap_end {
+ continue;
+ }
+ let styled = &self.text[overlap_start..overlap_end];
+ let x_off = self.text[line_range.start..overlap_start].width() as u16;
+ let style = Style::default().fg(Color::Cyan);
+ buf.set_string(area.x + x_off, y, styled, style);
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ // crossterm types are intentionally not imported here to avoid unused warnings
+ use rand::prelude::*;
+
+ fn rand_grapheme(rng: &mut rand::rngs::StdRng) -> String {
+ let r: u8 = rng.random_range(0..100);
+ match r {
+ 0..=4 => "\n".to_string(),
+ 5..=12 => " ".to_string(),
+ 13..=35 => (rng.random_range(b'a'..=b'z') as char).to_string(),
+ 36..=45 => (rng.random_range(b'A'..=b'Z') as char).to_string(),
+ 46..=52 => (rng.random_range(b'0'..=b'9') as char).to_string(),
+ 53..=65 => {
+ // Some emoji (wide graphemes)
+ let choices = ["👍", "😊", "🐍", "🚀", "🧪", "🌟"];
+ choices[rng.random_range(0..choices.len())].to_string()
+ }
+ 66..=75 => {
+ // CJK wide characters
+ let choices = ["漢", "字", "測", "試", "你", "好", "界", "编", "码"];
+ choices[rng.random_range(0..choices.len())].to_string()
+ }
+ 76..=85 => {
+ // Combining mark sequences
+ let base = ["e", "a", "o", "n", "u"][rng.random_range(0..5)];
+ let marks = ["\u{0301}", "\u{0308}", "\u{0302}", "\u{0303}"];
+ format!("{base}{}", marks[rng.random_range(0..marks.len())])
+ }
+ 86..=92 => {
+ // Some non-latin single codepoints (Greek, Cyrillic, Hebrew)
+ let choices = ["Ω", "β", "Ж", "ю", "ש", "م", "ह"];
+ choices[rng.random_range(0..choices.len())].to_string()
+ }
+ _ => {
+ // ZWJ sequences (single graphemes but multi-codepoint)
+ let choices = [
+ "👩\u{200D}💻", // woman technologist
+ "👨\u{200D}💻", // man technologist
+ "🏳️\u{200D}🌈", // rainbow flag
+ ];
+ choices[rng.random_range(0..choices.len())].to_string()
+ }
+ }
+ }
+
+ fn ta_with(text: &str) -> TextArea {
+ let mut t = TextArea::new();
+ t.insert_str(text);
+ t
+ }
+
+ #[test]
+ fn insert_and_replace_update_cursor_and_text() {
+ // insert helpers
+ let mut t = ta_with("hello");
+ t.set_cursor(5);
+ t.insert_str("!");
+ assert_eq!(t.text(), "hello!");
+ assert_eq!(t.cursor(), 6);
+
+ t.insert_str_at(0, "X");
+ assert_eq!(t.text(), "Xhello!");
+ assert_eq!(t.cursor(), 7);
+
+ // Insert after the cursor should not move it
+ t.set_cursor(1);
+ let end = t.text().len();
+ t.insert_str_at(end, "Y");
+ assert_eq!(t.text(), "Xhello!Y");
+ assert_eq!(t.cursor(), 1);
+
+ // replace_range cases
+ // 1) cursor before range
+ let mut t = ta_with("abcd");
+ t.set_cursor(1);
+ t.replace_range(2..3, "Z");
+ assert_eq!(t.text(), "abZd");
+ assert_eq!(t.cursor(), 1);
+
+ // 2) cursor inside range
+ let mut t = ta_with("abcd");
+ t.set_cursor(2);
+ t.replace_range(1..3, "Q");
+ assert_eq!(t.text(), "aQd");
+ assert_eq!(t.cursor(), 2);
+
+ // 3) cursor after range with shifted by diff
+ let mut t = ta_with("abcd");
+ t.set_cursor(4);
+ t.replace_range(0..1, "AA");
+ assert_eq!(t.text(), "AAbcd");
+ assert_eq!(t.cursor(), 5);
+ }
+
+ #[test]
+ fn delete_backward_and_forward_edges() {
+ let mut t = ta_with("abc");
+ t.set_cursor(1);
+ t.delete_backward(1);
+ assert_eq!(t.text(), "bc");
+ assert_eq!(t.cursor(), 0);
+
+ // deleting backward at start is a no-op
+ t.set_cursor(0);
+ t.delete_backward(1);
+ assert_eq!(t.text(), "bc");
+ assert_eq!(t.cursor(), 0);
+
+ // forward delete removes next grapheme
+ t.set_cursor(1);
+ t.delete_forward(1);
+ assert_eq!(t.text(), "b");
+ assert_eq!(t.cursor(), 1);
+
+ // forward delete at end is a no-op
+ t.set_cursor(t.text().len());
+ t.delete_forward(1);
+ assert_eq!(t.text(), "b");
+ }
+
+ #[test]
+ fn delete_backward_word_and_kill_line_variants() {
+ // delete backward word at end removes the whole previous word
+ let mut t = ta_with("hello world ");
+ t.set_cursor(t.text().len());
+ t.delete_backward_word();
+ assert_eq!(t.text(), "hello ");
+ assert_eq!(t.cursor(), 8);
+
+ // From inside a word, delete from word start to cursor
+ let mut t = ta_with("foo bar");
+ t.set_cursor(6); // inside "bar" (after 'a')
+ t.delete_backward_word();
+ assert_eq!(t.text(), "foo r");
+ assert_eq!(t.cursor(), 4);
+
+ // From end, delete the last word only
+ let mut t = ta_with("foo bar");
+ t.set_cursor(t.text().len());
+ t.delete_backward_word();
+ assert_eq!(t.text(), "foo ");
+ assert_eq!(t.cursor(), 4);
+
+ // kill_to_end_of_line when not at EOL
+ let mut t = ta_with("abc\ndef");
+ t.set_cursor(1); // on first line, middle
+ t.kill_to_end_of_line();
+ assert_eq!(t.text(), "a\ndef");
+ assert_eq!(t.cursor(), 1);
+
+ // kill_to_end_of_line when at EOL deletes newline
+ let mut t = ta_with("abc\ndef");
+ t.set_cursor(3); // EOL of first line
+ t.kill_to_end_of_line();
+ assert_eq!(t.text(), "abcdef");
+ assert_eq!(t.cursor(), 3);
+
+ // kill_to_beginning_of_line from middle of line
+ let mut t = ta_with("abc\ndef");
+ t.set_cursor(5); // on second line, after 'e'
+ t.kill_to_beginning_of_line();
+ assert_eq!(t.text(), "abc\nef");
+
+ // kill_to_beginning_of_line at beginning of non-first line removes the previous newline
+ let mut t = ta_with("abc\ndef");
+ t.set_cursor(4); // beginning of second line
+ t.kill_to_beginning_of_line();
+ assert_eq!(t.text(), "abcdef");
+ assert_eq!(t.cursor(), 3);
+ }
+
+ #[test]
+ fn delete_forward_word_variants() {
+ let mut t = ta_with("hello world ");
+ t.set_cursor(0);
+ t.delete_forward_word();
+ assert_eq!(t.text(), " world ");
+ assert_eq!(t.cursor(), 0);
+
+ let mut t = ta_with("hello world ");
+ t.set_cursor(1);
+ t.delete_forward_word();
+ assert_eq!(t.text(), "h world ");
+ assert_eq!(t.cursor(), 1);
+
+ let mut t = ta_with("hello world");
+ t.set_cursor(t.text().len());
+ t.delete_forward_word();
+ assert_eq!(t.text(), "hello world");
+ assert_eq!(t.cursor(), t.text().len());
+
+ let mut t = ta_with("foo \nbar");
+ t.set_cursor(3);
+ t.delete_forward_word();
+ assert_eq!(t.text(), "foo");
+ assert_eq!(t.cursor(), 3);
+
+ let mut t = ta_with("foo\nbar");
+ t.set_cursor(3);
+ t.delete_forward_word();
+ assert_eq!(t.text(), "foo");
+ assert_eq!(t.cursor(), 3);
+
+ let mut t = ta_with("hello world ");
+ t.set_cursor(t.text().len() + 10);
+ t.delete_forward_word();
+ assert_eq!(t.text(), "hello world ");
+ assert_eq!(t.cursor(), t.text().len());
+ }
+
+ #[test]
+ fn delete_forward_word_handles_atomic_elements() {
+ let mut t = TextArea::new();
+ t.insert_element("<element>");
+ t.insert_str(" tail");
+
+ t.set_cursor(0);
+ t.delete_forward_word();
+ assert_eq!(t.text(), " tail");
+ assert_eq!(t.cursor(), 0);
+
+ let mut t = TextArea::new();
+ t.insert_str(" ");
+ t.insert_element("<element>");
+ t.insert_str(" tail");
+
+ t.set_cursor(0);
+ t.delete_forward_word();
+ assert_eq!(t.text(), " tail");
+ assert_eq!(t.cursor(), 0);
+
+ let mut t = TextArea::new();
+ t.insert_str("prefix ");
+ t.insert_element("<element>");
+ t.insert_str(" tail");
+
+ // cursor in the middle of the element, delete_forward_word deletes the element
+ let elem_range = t.elements[0].range.clone();
+ t.cursor_pos = elem_range.start + (elem_range.len() / 2);
+ t.delete_forward_word();
+ assert_eq!(t.text(), "prefix tail");
+ assert_eq!(t.cursor(), elem_range.start);
+ }
+
+ #[test]
+ fn delete_backward_word_respects_word_separators() {
+ let mut t = ta_with("path/to/file");
+ t.set_cursor(t.text().len());
+ t.delete_backward_word();
+ assert_eq!(t.text(), "path/to/");
+ assert_eq!(t.cursor(), t.text().len());
+
+ t.delete_backward_word();
+ assert_eq!(t.text(), "path/to");
+ assert_eq!(t.cursor(), t.text().len());
+
+ let mut t = ta_with("foo/ ");
+ t.set_cursor(t.text().len());
+ t.delete_backward_word();
+ assert_eq!(t.text(), "foo");
+ assert_eq!(t.cursor(), 3);
+
+ let mut t = ta_with("foo /");
+ t.set_cursor(t.text().len());
+ t.delete_backward_word();
+ assert_eq!(t.text(), "foo ");
+ assert_eq!(t.cursor(), 4);
+ }
+
+ #[test]
+ fn delete_forward_word_respects_word_separators() {
+ let mut t = ta_with("path/to/file");
+ t.set_cursor(0);
+ t.delete_forward_word();
+ assert_eq!(t.text(), "/to/file");
+ assert_eq!(t.cursor(), 0);
+
+ t.delete_forward_word();
+ assert_eq!(t.text(), "to/file");
+ assert_eq!(t.cursor(), 0);
+
+ let mut t = ta_with("/ foo");
+ t.set_cursor(0);
+ t.delete_forward_word();
+ assert_eq!(t.text(), " foo");
+ assert_eq!(t.cursor(), 0);
+
+ let mut t = ta_with(" /foo");
+ t.set_cursor(0);
+ t.delete_forward_word();
+ assert_eq!(t.text(), "foo");
+ assert_eq!(t.cursor(), 0);
+ }
+
+ #[test]
+ fn yank_restores_last_kill() {
+ let mut t = ta_with("hello");
+ t.set_cursor(0);
+ t.kill_to_end_of_line();
+ assert_eq!(t.text(), "");
+ assert_eq!(t.cursor(), 0);
+
+ t.yank();
+ assert_eq!(t.text(), "hello");
+ assert_eq!(t.cursor(), 5);
+
+ let mut t = ta_with("hello world");
+ t.set_cursor(t.text().len());
+ t.delete_backward_word();
+ assert_eq!(t.text(), "hello ");
+ assert_eq!(t.cursor(), 6);
+
+ t.yank();
+ assert_eq!(t.text(), "hello world");
+ assert_eq!(t.cursor(), 11);
+
+ let mut t = ta_with("hello");
+ t.set_cursor(5);
+ t.kill_to_beginning_of_line();
+ assert_eq!(t.text(), "");
+ assert_eq!(t.cursor(), 0);
+
+ t.yank();
+ assert_eq!(t.text(), "hello");
+ assert_eq!(t.cursor(), 5);
+ }
+
+ #[test]
+ fn cursor_left_and_right_handle_graphemes() {
+ let mut t = ta_with("a👍b");
+ t.set_cursor(t.text().len());
+
+ t.move_cursor_left(); // before 'b'
+ let after_first_left = t.cursor();
+ t.move_cursor_left(); // before '👍'
+ let after_second_left = t.cursor();
+ t.move_cursor_left(); // before 'a'
+ let after_third_left = t.cursor();
+
+ assert!(after_first_left < t.text().len());
+ assert!(after_second_left < after_first_left);
+ assert!(after_third_left < after_second_left);
+
+ // Move right back to end safely
+ t.move_cursor_right();
+ t.move_cursor_right();
+ t.move_cursor_right();
+ assert_eq!(t.cursor(), t.text().len());
+ }
+
+ #[test]
+ fn control_b_and_f_move_cursor() {
+ let mut t = ta_with("abcd");
+ t.set_cursor(1);
+
+ t.input(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::CONTROL));
+ assert_eq!(t.cursor(), 2);
+
+ t.input(KeyEvent::new(KeyCode::Char('b'), KeyModifiers::CONTROL));
+ assert_eq!(t.cursor(), 1);
+ }
+
+ #[test]
+ fn control_b_f_fallback_control_chars_move_cursor() {
+ let mut t = ta_with("abcd");
+ t.set_cursor(2);
+
+ // Simulate terminals that send C0 control chars without CONTROL modifier.
+ // ^B (U+0002) should move left
+ t.input(KeyEvent::new(KeyCode::Char('\u{0002}'), KeyModifiers::NONE));
+ assert_eq!(t.cursor(), 1);
+
+ // ^F (U+0006) should move right
+ t.input(KeyEvent::new(KeyCode::Char('\u{0006}'), KeyModifiers::NONE));
+ assert_eq!(t.cursor(), 2);
+ }
+
+ #[test]
+ fn delete_backward_word_alt_keys() {
+ // Test the custom Alt+Ctrl+h binding
+ let mut t = ta_with("hello world");
+ t.set_cursor(t.text().len()); // cursor at the end
+ t.input(KeyEvent::new(
+ KeyCode::Char('h'),
+ KeyModifiers::CONTROL | KeyModifiers::ALT,
+ ));
+ assert_eq!(t.text(), "hello ");
+ assert_eq!(t.cursor(), 6);
+
+ // Test the standard Alt+Backspace binding
+ let mut t = ta_with("hello world");
+ t.set_cursor(t.text().len()); // cursor at the end
+ t.input(KeyEvent::new(KeyCode::Backspace, KeyModifiers::ALT));
+ assert_eq!(t.text(), "hello ");
+ assert_eq!(t.cursor(), 6);
+ }
+
+ #[test]
+ fn delete_backward_word_handles_narrow_no_break_space() {
+ let mut t = ta_with("32\u{202F}AM");
+ t.set_cursor(t.text().len());
+ t.input(KeyEvent::new(KeyCode::Backspace, KeyModifiers::ALT));
+ pretty_assertions::assert_eq!(t.text(), "32\u{202F}");
+ pretty_assertions::assert_eq!(t.cursor(), t.text().len());
+ }
+
+ #[test]
+ fn delete_forward_word_with_without_alt_modifier() {
+ let mut t = ta_with("hello world");
+ t.set_cursor(0);
+ t.input(KeyEvent::new(KeyCode::Delete, KeyModifiers::ALT));
+ assert_eq!(t.text(), " world");
+ assert_eq!(t.cursor(), 0);
+
+ let mut t = ta_with("hello");
+ t.set_cursor(0);
+ t.input(KeyEvent::new(KeyCode::Delete, KeyModifiers::NONE));
+ assert_eq!(t.text(), "ello");
+ assert_eq!(t.cursor(), 0);
+ }
+
+ #[test]
+ fn control_h_backspace() {
+ // Test Ctrl+H as backspace
+ let mut t = ta_with("12345");
+ t.set_cursor(3); // cursor after '3'
+ t.input(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL));
+ assert_eq!(t.text(), "1245");
+ assert_eq!(t.cursor(), 2);
+
+ // Test Ctrl+H at beginning (should be no-op)
+ t.set_cursor(0);
+ t.input(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL));
+ assert_eq!(t.text(), "1245");
+ assert_eq!(t.cursor(), 0);
+
+ // Test Ctrl+H at end
+ t.set_cursor(t.text().len());
+ t.input(KeyEvent::new(KeyCode::Char('h'), KeyModifiers::CONTROL));
+ assert_eq!(t.text(), "124");
+ assert_eq!(t.cursor(), 3);
+ }
+
+ #[cfg_attr(not(windows), ignore = "AltGr modifier only applies on Windows")]
+ #[test]
+ fn altgr_ctrl_alt_char_inserts_literal() {
+ let mut t = ta_with("");
+ t.input(KeyEvent::new(
+ KeyCode::Char('c'),
+ KeyModifiers::CONTROL | KeyModifiers::ALT,
+ ));
+ assert_eq!(t.text(), "c");
+ assert_eq!(t.cursor(), 1);
+ }
+
+ #[test]
+ fn cursor_vertical_movement_across_lines_and_bounds() {
+ let mut t = ta_with("short\nloooooooooong\nmid");
+ // Place cursor on second line, column 5
+ let second_line_start = 6; // after first '\n'
+ t.set_cursor(second_line_start + 5);
+
+ // Move up: target column preserved, clamped by line length
+ t.move_cursor_up();
+ assert_eq!(t.cursor(), 5); // first line has len 5
+
+ // Move up again goes to start of text
+ t.move_cursor_up();
+ assert_eq!(t.cursor(), 0);
+
+ // Move down: from start to target col tracked
+ t.move_cursor_down();
+ // On first move down, we should land on second line, at col 0 (target col remembered as 0)
+ let pos_after_down = t.cursor();
+ assert!(pos_after_down >= second_line_start);
+
+ // Move down again to third line; clamp to its length
+ t.move_cursor_down();
+ let third_line_start = t.text().find("mid").unwrap();
+ let third_line_end = third_line_start + 3;
+ assert!(t.cursor() >= third_line_start && t.cursor() <= third_line_end);
+
+ // Moving down at last line jumps to end
+ t.move_cursor_down();
+ assert_eq!(t.cursor(), t.text().len());
+ }
+
+ #[test]
+ fn home_end_and_emacs_style_home_end() {
+ let mut t = ta_with("one\ntwo\nthree");
+ // Position at middle of second line
+ let second_line_start = t.text().find("two").unwrap();
+ t.set_cursor(second_line_start + 1);
+
+ t.move_cursor_to_beginning_of_line(false);
+ assert_eq!(t.cursor(), second_line_start);
+
+ // Ctrl-A behavior: if at BOL, go to beginning of previous line
+ t.move_cursor_to_beginning_of_line(true);
+ assert_eq!(t.cursor(), 0); // beginning of first line
+
+ // Move to EOL of first line
+ t.move_cursor_to_end_of_line(false);
+ assert_eq!(t.cursor(), 3);
+
+ // Ctrl-E: if at EOL, go to end of next line
+ t.move_cursor_to_end_of_line(true);
+ // end of second line ("two") is right before its '\n'
+ let end_second_nl = t.text().find("\nthree").unwrap();
+ assert_eq!(t.cursor(), end_second_nl);
+ }
+
+ #[test]
+ fn end_of_line_or_down_at_end_of_text() {
+ let mut t = ta_with("one\ntwo");
+ // Place cursor at absolute end of the text
+ t.set_cursor(t.text().len());
+ // Should remain at end without panicking
+ t.move_cursor_to_end_of_line(true);
+ assert_eq!(t.cursor(), t.text().len());
+
+ // Also verify behavior when at EOL of a non-final line:
+ let eol_first_line = 3; // index of '\n' in "one\ntwo"
+ t.set_cursor(eol_first_line);
+ t.move_cursor_to_end_of_line(true);
+ assert_eq!(t.cursor(), t.text().len()); // moves to end of next (last) line
+ }
+
+ #[test]
+ fn word_navigation_helpers() {
+ let t = ta_with(" alpha beta gamma");
+ let mut t = t; // make mutable for set_cursor
+ // Put cursor after "alpha"
+ let after_alpha = t.text().find("alpha").unwrap() + "alpha".len();
+ t.set_cursor(after_alpha);
+ assert_eq!(t.beginning_of_previous_word(), 2); // skip initial spaces
+
+ // Put cursor at start of beta
+ let beta_start = t.text().find("beta").unwrap();
+ t.set_cursor(beta_start);
+ assert_eq!(t.end_of_next_word(), beta_start + "beta".len());
+
+ // If at end, end_of_next_word returns len
+ t.set_cursor(t.text().len());
+ assert_eq!(t.end_of_next_word(), t.text().len());
+ }
+
+ #[test]
+ fn wrapping_and_cursor_positions() {
+ let mut t = ta_with("hello world here");
+ let area = Rect::new(0, 0, 6, 10); // width 6 -> wraps words
+ // desired height counts wrapped lines
+ assert!(t.desired_height(area.width) >= 3);
+
+ // Place cursor in "world"
+ let world_start = t.text().find("world").unwrap();
+ t.set_cursor(world_start + 3);
+ let (_x, y) = t.cursor_pos(area).unwrap();
+ assert_eq!(y, 1); // world should be on second wrapped line
+
+ // With state and small height, cursor is mapped onto visible row
+ let mut state = TextAreaState::default();
+ let small_area = Rect::new(0, 0, 6, 1);
+ // First call: cursor not visible -> effective scroll ensures it is
+ let (_x, y) = t.cursor_pos_with_state(small_area, state).unwrap();
+ assert_eq!(y, 0);
+
+ // Render with state to update actual scroll value
+ let mut buf = Buffer::empty(small_area);
+ ratatui::widgets::StatefulWidgetRef::render_ref(&(&t), small_area, &mut buf, &mut state);
+ // After render, state.scroll should be adjusted so cursor row fits
+ let effective_lines = t.desired_height(small_area.width);
+ assert!(state.scroll < effective_lines);
+ }
+
+ #[test]
+ fn cursor_pos_with_state_basic_and_scroll_behaviors() {
+ // Case 1: No wrapping needed, height fits — scroll ignored, y maps directly.
+ let mut t = ta_with("hello world");
+ t.set_cursor(3);
+ let area = Rect::new(2, 5, 20, 3);
+ // Even if an absurd scroll is provided, when content fits the area the
+ // effective scroll is 0 and the cursor position matches cursor_pos.
+ let bad_state = TextAreaState { scroll: 999 };
+ let (x1, y1) = t.cursor_pos(area).unwrap();
+ let (x2, y2) = t.cursor_pos_with_state(area, bad_state).unwrap();
+ assert_eq!((x2, y2), (x1, y1));
+
+ // Case 2: Cursor below the current window — y should be clamped to the
+ // bottom row (area.height - 1) after adjusting effective scroll.
+ let mut t = ta_with("one two three four five six");
+ // Force wrapping to many visual lines.
+ let wrap_width = 4;
+ let _ = t.desired_height(wrap_width);
+ // Put cursor somewhere near the end so it's definitely below the first window.
+ t.set_cursor(t.text().len().saturating_sub(2));
+ let small_area = Rect::new(0, 0, wrap_width, 2);
+ let state = TextAreaState { scroll: 0 };
+ let (_x, y) = t.cursor_pos_with_state(small_area, state).unwrap();
+ assert_eq!(y, small_area.y + small_area.height - 1);
+
+ // Case 3: Cursor above the current window — y should be top row (0)
+ // when the provided scroll is too large.
+ let mut t = ta_with("alpha beta gamma delta epsilon zeta");
+ let wrap_width = 5;
+ let lines = t.desired_height(wrap_width);
+ // Place cursor near start so an excessive scroll moves it to top row.
+ t.set_cursor(1);
+ let area = Rect::new(0, 0, wrap_width, 3);
+ let state = TextAreaState {
+ scroll: lines.saturating_mul(2),
+ };
+ let (_x, y) = t.cursor_pos_with_state(area, state).unwrap();
+ assert_eq!(y, area.y);
+ }
+
+ #[test]
+ fn wrapped_navigation_across_visual_lines() {
+ let mut t = ta_with("abcdefghij");
+ // Force wrapping at width 4: lines -> ["abcd", "efgh", "ij"]
+ let _ = t.desired_height(4);
+
+ // From the very start, moving down should go to the start of the next wrapped line (index 4)
+ t.set_cursor(0);
+ t.move_cursor_down();
+ assert_eq!(t.cursor(), 4);
+
+ // Cursor at boundary index 4 should be displayed at start of second wrapped line
+ t.set_cursor(4);
+ let area = Rect::new(0, 0, 4, 10);
+ let (x, y) = t.cursor_pos(area).unwrap();
+ assert_eq!((x, y), (0, 1));
+
+ // With state and small height, cursor should be visible at row 0, col 0
+ let small_area = Rect::new(0, 0, 4, 1);
+ let state = TextAreaState::default();
+ let (x, y) = t.cursor_pos_with_state(small_area, state).unwrap();
+ assert_eq!((x, y), (0, 0));
+
+ // Place cursor in the middle of the second wrapped line ("efgh"), at 'g'
+ t.set_cursor(6);
+ // Move up should go to same column on previous wrapped line -> index 2 ('c')
+ t.move_cursor_up();
+ assert_eq!(t.cursor(), 2);
+
+ // Move down should return to same position on the next wrapped line -> back to index 6 ('g')
+ t.move_cursor_down();
+ assert_eq!(t.cursor(), 6);
+
+ // Move down again should go to third wrapped line. Target col is 2, but the line has len 2 -> clamp to end
+ t.move_cursor_down();
+ assert_eq!(t.cursor(), t.text().len());
+ }
+
+ #[test]
+ fn cursor_pos_with_state_after_movements() {
+ let mut t = ta_with("abcdefghij");
+ // Wrap width 4 -> visual lines: abcd | efgh | ij
+ let _ = t.desired_height(4);
+ let area = Rect::new(0, 0, 4, 2);
+ let mut state = TextAreaState::default();
+ let mut buf = Buffer::empty(area);
+
+ // Start at beginning
+ t.set_cursor(0);
+ ratatui::widgets::StatefulWidgetRef::render_ref(&(&t), area, &mut buf, &mut state);
+ let (x, y) = t.cursor_pos_with_state(area, state).unwrap();
+ assert_eq!((x, y), (0, 0));
+
+ // Move down to second visual line; should be at bottom row (row 1) within 2-line viewport
+ t.move_cursor_down();
+ ratatui::widgets::StatefulWidgetRef::render_ref(&(&t), area, &mut buf, &mut state);
+ let (x, y) = t.cursor_pos_with_state(area, state).unwrap();
+ assert_eq!((x, y), (0, 1));
+
+ // Move down to third visual line; viewport scrolls and keeps cursor on bottom row
+ t.move_cursor_down();
+ ratatui::widgets::StatefulWidgetRef::render_ref(&(&t), area, &mut buf, &mut state);
+ let (x, y) = t.cursor_pos_with_state(area, state).unwrap();
+ assert_eq!((x, y), (0, 1));
+
+ // Move up to second visual line; with current scroll, it appears on top row
+ t.move_cursor_up();
+ ratatui::widgets::StatefulWidgetRef::render_ref(&(&t), area, &mut buf, &mut state);
+ let (x, y) = t.cursor_pos_with_state(area, state).unwrap();
+ assert_eq!((x, y), (0, 0));
+
+ // Column preservation across moves: set to col 2 on first line, move down
+ t.set_cursor(2);
+ ratatui::widgets::StatefulWidgetRef::render_ref(&(&t), area, &mut buf, &mut state);
+ let (x0, y0) = t.cursor_pos_with_state(area, state).unwrap();
+ assert_eq!((x0, y0), (2, 0));
+ t.move_cursor_down();
+ ratatui::widgets::StatefulWidgetRef::render_ref(&(&t), area, &mut buf, &mut state);
+ let (x1, y1) = t.cursor_pos_with_state(area, state).unwrap();
+ assert_eq!((x1, y1), (2, 1));
+ }
+
+ #[test]
+ fn wrapped_navigation_with_newlines_and_spaces() {
+ // Include spaces and an explicit newline to exercise boundaries
+ let mut t = ta_with("word1 word2\nword3");
+ // Width 6 will wrap "word1 " and then "word2" before the newline
+ let _ = t.desired_height(6);
+
+ // Put cursor on the second wrapped line before the newline, at column 1 of "word2"
+ let start_word2 = t.text().find("word2").unwrap();
+ t.set_cursor(start_word2 + 1);
+
+ // Up should go to first wrapped line, column 1 -> index 1
+ t.move_cursor_up();
+ assert_eq!(t.cursor(), 1);
+
+ // Down should return to the same visual column on "word2"
+ t.move_cursor_down();
+ assert_eq!(t.cursor(), start_word2 + 1);
+
+ // Down again should cross the logical newline to the next visual line ("word3"), clamped to its length if needed
+ t.move_cursor_down();
+ let start_word3 = t.text().find("word3").unwrap();
+ assert!(t.cursor() >= start_word3 && t.cursor() <= start_word3 + "word3".len());
+ }
+
+ #[test]
+ fn wrapped_navigation_with_wide_graphemes() {
+ // Four thumbs up, each of display width 2, with width 3 to force wrapping inside grapheme boundaries
+ let mut t = ta_with("👍👍👍👍");
+ let _ = t.desired_height(3);
+
+ // Put cursor after the second emoji (which should be on first wrapped line)
+ t.set_cursor("👍👍".len());
+
+ // Move down should go to the start of the next wrapped line (same column preserved but clamped)
+ t.move_cursor_down();
+ // We expect to land somewhere within the third emoji or at the start of it
+ let pos_after_down = t.cursor();
+ assert!(pos_after_down >= "👍👍".len());
+
+ // Moving up should take us back to the original position
+ t.move_cursor_up();
+ assert_eq!(t.cursor(), "👍👍".len());
+ }
+
+ #[test]
+ fn fuzz_textarea_randomized() {
+ // Deterministic seed for reproducibility
+ // Seed the RNG based on the current day in Pacific Time (PST/PDT). This
+ // keeps the fuzz test deterministic within a day while still varying
+ // day-to-day to improve coverage.
+ let pst_today_seed: u64 = (chrono::Utc::now() - chrono::Duration::hours(8))
+ .date_naive()
+ .and_hms_opt(0, 0, 0)
+ .unwrap()
+ .and_utc()
+ .timestamp() as u64;
+ let mut rng = rand::rngs::StdRng::seed_from_u64(pst_today_seed);
+
+ for _case in 0..500 {
+ let mut ta = TextArea::new();
+ let mut state = TextAreaState::default();
+ // Track element payloads we insert. Payloads use characters '[' and ']' which
+ // are not produced by rand_grapheme(), avoiding accidental collisions.
+ let mut elem_texts: Vec<String> = Vec::new();
+ let mut next_elem_id: usize = 0;
+ // Start with a random base string
+ let base_len = rng.random_range(0..30);
+ let mut base = String::new();
+ for _ in 0..base_len {
+ base.push_str(&rand_grapheme(&mut rng));
+ }
+ ta.set_text(&base);
+ // Choose a valid char boundary for initial cursor
+ let mut boundaries: Vec<usize> = vec![0];
+ boundaries.extend(ta.text().char_indices().map(|(i, _)| i).skip(1));
+ boundaries.push(ta.text().len());
+ let init = boundaries[rng.random_range(0..boundaries.len())];
+ ta.set_cursor(init);
+
+ let mut width: u16 = rng.random_range(1..=12);
+ let mut height: u16 = rng.random_range(1..=4);
+
+ for _step in 0..60 {
+ // Mostly stable width/height, occasionally change
+ if rng.random_bool(0.1) {
+ width = rng.random_range(1..=12);
+ }
+ if rng.random_bool(0.1) {
+ height = rng.random_range(1..=4);
+ }
+
+ // Pick an operation
+ match rng.random_range(0..18) {
+ 0 => {
+ // insert small random string at cursor
+ let len = rng.random_range(0..6);
+ let mut s = String::new();
+ for _ in 0..len {
+ s.push_str(&rand_grapheme(&mut rng));
+ }
+ ta.insert_str(&s);
+ }
+ 1 => {
+ // replace_range with small random slice
+ let mut b: Vec<usize> = vec![0];
+ b.extend(ta.text().char_indices().map(|(i, _)| i).skip(1));
+ b.push(ta.text().len());
+ let i1 = rng.random_range(0..b.len());
+ let i2 = rng.random_range(0..b.len());
+ let (start, end) = if b[i1] <= b[i2] {
+ (b[i1], b[i2])
+ } else {
+ (b[i2], b[i1])
+ };
+ let insert_len = rng.random_range(0..=4);
+ let mut s = String::new();
+ for _ in 0..insert_len {
+ s.push_str(&rand_grapheme(&mut rng));
+ }
+ let before = ta.text().len();
+ // If the chosen range intersects an element, replace_range will expand to
+ // element boundaries, so the naive size delta assertion does not hold.
+ let intersects_element = elem_texts.iter().any(|payload| {
+ if let Some(pstart) = ta.text().find(payload) {
+ let pend = pstart + payload.len();
+ pstart < end && pend > start
+ } else {
+ false
+ }
+ });
+ ta.replace_range(start..end, &s);
+ if !intersects_element {
+ let after = ta.text().len();
+ assert_eq!(
+ after as isize,
+ before as isize + (s.len() as isize) - ((end - start) as isize)
+ );
+ }
+ }
+ 2 => ta.delete_backward(rng.random_range(0..=3)),
+ 3 => ta.delete_forward(rng.random_range(0..=3)),
+ 4 => ta.delete_backward_word(),
+ 5 => ta.kill_to_beginning_of_line(),
+ 6 => ta.kill_to_end_of_line(),
+ 7 => ta.move_cursor_left(),
+ 8 => ta.move_cursor_right(),
+ 9 => ta.move_cursor_up(),
+ 10 => ta.move_cursor_down(),
+ 11 => ta.move_cursor_to_beginning_of_line(true),
+ 12 => ta.move_cursor_to_end_of_line(true),
+ 13 => {
+ // Insert an element with a unique sentinel payload
+ let payload =
+ format!("[[EL#{}:{}]]", next_elem_id, rng.random_range(1000..9999));
+ next_elem_id += 1;
+ ta.insert_element(&payload);
+ elem_texts.push(payload);
+ }
+ 14 => {
+ // Try inserting inside an existing element (should clamp to boundary)
+ if let Some(payload) = elem_texts.choose(&mut rng).cloned()
+ && let Some(start) = ta.text().find(&payload)
+ {
+ let end = start + payload.len();
+ if end - start > 2 {
+ let pos = rng.random_range(start + 1..end - 1);
+ let ins = rand_grapheme(&mut rng);
+ ta.insert_str_at(pos, &ins);
+ }
+ }
+ }
+ 15 => {
+ // Replace a range that intersects an element -> whole element should be replaced
+ if let Some(payload) = elem_texts.choose(&mut rng).cloned()
+ && let Some(start) = ta.text().find(&payload)
+ {
+ let end = start + payload.len();
+ // Create an intersecting range [start-δ, end-δ2)
+ let mut s = start.saturating_sub(rng.random_range(0..=2));
+ let mut e = (end + rng.random_range(0..=2)).min(ta.text().len());
+ // Align to char boundaries to satisfy String::replace_range contract
+ let txt = ta.text();
+ while s > 0 && !txt.is_char_boundary(s) {
+ s -= 1;
+ }
+ while e < txt.len() && !txt.is_char_boundary(e) {
+ e += 1;
+ }
+ if s < e {
+ // Small replacement text
+ let mut srep = String::new();
+ for _ in 0..rng.random_range(0..=2) {
+ srep.push_str(&rand_grapheme(&mut rng));
+ }
+ ta.replace_range(s..e, &srep);
+ }
+ }
+ }
+ 16 => {
+ // Try setting the cursor to a position inside an element; it should clamp out
+ if let Some(payload) = elem_texts.choose(&mut rng).cloned()
+ && let Some(start) = ta.text().find(&payload)
+ {
+ let end = start + payload.len();
+ if end - start > 2 {
+ let pos = rng.random_range(start + 1..end - 1);
+ ta.set_cursor(pos);
+ }
+ }
+ }
+ _ => {
+ // Jump to word boundaries
+ if rng.random_bool(0.5) {
+ let p = ta.beginning_of_previous_word();
+ ta.set_cursor(p);
+ } else {
+ let p = ta.end_of_next_word();
+ ta.set_cursor(p);
+ }
+ }
+ }
+
+ // Sanity invariants
+ assert!(ta.cursor() <= ta.text().len());
+
+ // Element invariants
+ for payload in &elem_texts {
+ if let Some(start) = ta.text().find(payload) {
+ let end = start + payload.len();
+ // 1) Text inside elements matches the initially set payload
+ assert_eq!(&ta.text()[start..end], payload);
+ // 2) Cursor is never strictly inside an element
+ let c = ta.cursor();
+ assert!(
+ c <= start || c >= end,
+ "cursor inside element: {start}..{end} at {c}"
+ );
+ }
+ }
+
+ // Render and compute cursor positions; ensure they are in-bounds and do not panic
+ let area = Rect::new(0, 0, width, height);
+ // Stateless render into an area tall enough for all wrapped lines
+ let total_lines = ta.desired_height(width);
+ let full_area = Rect::new(0, 0, width, total_lines.max(1));
+ let mut buf = Buffer::empty(full_area);
+ ratatui::widgets::WidgetRef::render_ref(&(&ta), full_area, &mut buf);
+
+ // cursor_pos: x must be within width when present
+ let _ = ta.cursor_pos(area);
+
+ // cursor_pos_with_state: always within viewport rows
+ let (_x, _y) = ta
+ .cursor_pos_with_state(area, state)
+ .unwrap_or((area.x, area.y));
+
+ // Stateful render should not panic, and updates scroll
+ let mut sbuf = Buffer::empty(area);
+ ratatui::widgets::StatefulWidgetRef::render_ref(
+ &(&ta),
+ area,
+ &mut sbuf,
+ &mut state,
+ );
+
+ // After wrapping, desired height equals the number of lines we would render without scroll
+ let total_lines = total_lines as usize;
+ // state.scroll must not exceed total_lines when content fits within area height
+ if (height as usize) >= total_lines {
+ assert_eq!(state.scroll, 0);
+ }
+ }
+ }
+ }
+}
diff --git a/codex-rs/tui2/src/chatwidget.rs b/codex-rs/tui2/src/chatwidget.rs
new file mode 100644
index 0000000000..ea29c00d93
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget.rs
@@ -0,0 +1,3463 @@
+use std::collections::HashMap;
+use std::collections::HashSet;
+use std::collections::VecDeque;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Duration;
+
+use codex_app_server_protocol::AuthMode;
+use codex_backend_client::Client as BackendClient;
+use codex_core::config::Config;
+use codex_core::config::types::Notifications;
+use codex_core::git_info::current_branch_name;
+use codex_core::git_info::local_git_branches;
+use codex_core::openai_models::model_family::ModelFamily;
+use codex_core::openai_models::models_manager::ModelsManager;
+use codex_core::project_doc::DEFAULT_PROJECT_DOC_FILENAME;
+use codex_core::protocol::AgentMessageDeltaEvent;
+use codex_core::protocol::AgentMessageEvent;
+use codex_core::protocol::AgentReasoningDeltaEvent;
+use codex_core::protocol::AgentReasoningEvent;
+use codex_core::protocol::AgentReasoningRawContentDeltaEvent;
+use codex_core::protocol::AgentReasoningRawContentEvent;
+use codex_core::protocol::ApplyPatchApprovalRequestEvent;
+use codex_core::protocol::BackgroundEventEvent;
+use codex_core::protocol::CreditsSnapshot;
+use codex_core::protocol::DeprecationNoticeEvent;
+use codex_core::protocol::ErrorEvent;
+use codex_core::protocol::Event;
+use codex_core::protocol::EventMsg;
+use codex_core::protocol::ExecApprovalRequestEvent;
+use codex_core::protocol::ExecCommandBeginEvent;
+use codex_core::protocol::ExecCommandEndEvent;
+use codex_core::protocol::ExecCommandSource;
+use codex_core::protocol::ExitedReviewModeEvent;
+use codex_core::protocol::ListCustomPromptsResponseEvent;
+use codex_core::protocol::McpListToolsResponseEvent;
+use codex_core::protocol::McpStartupCompleteEvent;
+use codex_core::protocol::McpStartupStatus;
+use codex_core::protocol::McpStartupUpdateEvent;
+use codex_core::protocol::McpToolCallBeginEvent;
+use codex_core::protocol::McpToolCallEndEvent;
+use codex_core::protocol::Op;
+use codex_core::protocol::PatchApplyBeginEvent;
+use codex_core::protocol::RateLimitSnapshot;
+use codex_core::protocol::ReviewRequest;
+use codex_core::protocol::ReviewTarget;
+use codex_core::protocol::StreamErrorEvent;
+use codex_core::protocol::TaskCompleteEvent;
+use codex_core::protocol::TerminalInteractionEvent;
+use codex_core::protocol::TokenUsage;
+use codex_core::protocol::TokenUsageInfo;
+use codex_core::protocol::TurnAbortReason;
+use codex_core::protocol::TurnDiffEvent;
+use codex_core::protocol::UndoCompletedEvent;
+use codex_core::protocol::UndoStartedEvent;
+use codex_core::protocol::UserMessageEvent;
+use codex_core::protocol::ViewImageToolCallEvent;
+use codex_core::protocol::WarningEvent;
+use codex_core::protocol::WebSearchBeginEvent;
+use codex_core::protocol::WebSearchEndEvent;
+use codex_core::skills::model::SkillMetadata;
+use codex_protocol::ConversationId;
+use codex_protocol::account::PlanType;
+use codex_protocol::approvals::ElicitationRequestEvent;
+use codex_protocol::parse_command::ParsedCommand;
+use codex_protocol::user_input::UserInput;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use crossterm::event::KeyModifiers;
+use rand::Rng;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::style::Color;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::Wrap;
+use tokio::sync::mpsc::UnboundedSender;
+use tokio::task::JoinHandle;
+use tracing::debug;
+
+use crate::app_event::AppEvent;
+use crate::app_event_sender::AppEventSender;
+use crate::bottom_pane::ApprovalRequest;
+use crate::bottom_pane::BottomPane;
+use crate::bottom_pane::BottomPaneParams;
+use crate::bottom_pane::CancellationEvent;
+use crate::bottom_pane::InputResult;
+use crate::bottom_pane::SelectionAction;
+use crate::bottom_pane::SelectionItem;
+use crate::bottom_pane::SelectionViewParams;
+use crate::bottom_pane::custom_prompt_view::CustomPromptView;
+use crate::bottom_pane::popup_consts::standard_popup_hint_line;
+use crate::clipboard_paste::paste_image_to_temp_png;
+use crate::diff_render::display_path_for;
+use crate::exec_cell::CommandOutput;
+use crate::exec_cell::ExecCell;
+use crate::exec_cell::new_active_exec_command;
+use crate::get_git_diff::get_git_diff;
+use crate::history_cell;
+use crate::history_cell::AgentMessageCell;
+use crate::history_cell::HistoryCell;
+use crate::history_cell::McpToolCallCell;
+use crate::history_cell::PlainHistoryCell;
+use crate::markdown::append_markdown;
+use crate::render::Insets;
+use crate::render::renderable::ColumnRenderable;
+use crate::render::renderable::FlexRenderable;
+use crate::render::renderable::Renderable;
+use crate::render::renderable::RenderableExt;
+use crate::render::renderable::RenderableItem;
+use crate::slash_command::SlashCommand;
+use crate::status::RateLimitSnapshotDisplay;
+use crate::text_formatting::truncate_text;
+use crate::tui::FrameRequester;
+mod interrupts;
+use self::interrupts::InterruptManager;
+mod agent;
+use self::agent::spawn_agent;
+use self::agent::spawn_agent_from_existing;
+mod session_header;
+use self::session_header::SessionHeader;
+use crate::streaming::controller::StreamController;
+use std::path::Path;
+
+use chrono::Local;
+use codex_common::approval_presets::ApprovalPreset;
+use codex_common::approval_presets::builtin_approval_presets;
+use codex_core::AuthManager;
+use codex_core::CodexAuth;
+use codex_core::ConversationManager;
+use codex_core::protocol::AskForApproval;
+use codex_core::protocol::SandboxPolicy;
+use codex_file_search::FileMatch;
+use codex_protocol::openai_models::ModelPreset;
+use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
+use codex_protocol::plan_tool::UpdatePlanArgs;
+use strum::IntoEnumIterator;
+
+const USER_SHELL_COMMAND_HELP_TITLE: &str = "Prefix a command with ! to run it locally";
+const USER_SHELL_COMMAND_HELP_HINT: &str = "Example: !ls";
+// Track information about an in-flight exec command.
+struct RunningCommand {
+ command: Vec<String>,
+ parsed_cmd: Vec<ParsedCommand>,
+ source: ExecCommandSource,
+}
+
+struct UnifiedExecWaitState {
+ command_display: String,
+}
+
+impl UnifiedExecWaitState {
+ fn new(command_display: String) -> Self {
+ Self { command_display }
+ }
+
+ fn is_duplicate(&self, command_display: &str) -> bool {
+ self.command_display == command_display
+ }
+}
+
+const RATE_LIMIT_WARNING_THRESHOLDS: [f64; 3] = [75.0, 90.0, 95.0];
+const NUDGE_MODEL_SLUG: &str = "gpt-5.1-codex-mini";
+const RATE_LIMIT_SWITCH_PROMPT_THRESHOLD: f64 = 90.0;
+
+#[derive(Default)]
+struct RateLimitWarningState {
+ secondary_index: usize,
+ primary_index: usize,
+}
+
+impl RateLimitWarningState {
+ fn take_warnings(
+ &mut self,
+ secondary_used_percent: Option<f64>,
+ secondary_window_minutes: Option<i64>,
+ primary_used_percent: Option<f64>,
+ primary_window_minutes: Option<i64>,
+ ) -> Vec<String> {
+ let reached_secondary_cap =
+ matches!(secondary_used_percent, Some(percent) if percent == 100.0);
+ let reached_primary_cap = matches!(primary_used_percent, Some(percent) if percent == 100.0);
+ if reached_secondary_cap || reached_primary_cap {
+ return Vec::new();
+ }
+
+ let mut warnings = Vec::new();
+
+ if let Some(secondary_used_percent) = secondary_used_percent {
+ let mut highest_secondary: Option<f64> = None;
+ while self.secondary_index < RATE_LIMIT_WARNING_THRESHOLDS.len()
+ && secondary_used_percent >= RATE_LIMIT_WARNING_THRESHOLDS[self.secondary_index]
+ {
+ highest_secondary = Some(RATE_LIMIT_WARNING_THRESHOLDS[self.secondary_index]);
+ self.secondary_index += 1;
+ }
+ if let Some(threshold) = highest_secondary {
+ let limit_label = secondary_window_minutes
+ .map(get_limits_duration)
+ .unwrap_or_else(|| "weekly".to_string());
+ let remaining_percent = 100.0 - threshold;
+ warnings.push(format!(
+ "Heads up, you have less than {remaining_percent:.0}% of your {limit_label} limit left. Run /status for a breakdown."
+ ));
+ }
+ }
+
+ if let Some(primary_used_percent) = primary_used_percent {
+ let mut highest_primary: Option<f64> = None;
+ while self.primary_index < RATE_LIMIT_WARNING_THRESHOLDS.len()
+ && primary_used_percent >= RATE_LIMIT_WARNING_THRESHOLDS[self.primary_index]
+ {
+ highest_primary = Some(RATE_LIMIT_WARNING_THRESHOLDS[self.primary_index]);
+ self.primary_index += 1;
+ }
+ if let Some(threshold) = highest_primary {
+ let limit_label = primary_window_minutes
+ .map(get_limits_duration)
+ .unwrap_or_else(|| "5h".to_string());
+ let remaining_percent = 100.0 - threshold;
+ warnings.push(format!(
+ "Heads up, you have less than {remaining_percent:.0}% of your {limit_label} limit left. Run /status for a breakdown."
+ ));
+ }
+ }
+
+ warnings
+ }
+}
+
+pub(crate) fn get_limits_duration(windows_minutes: i64) -> String {
+ const MINUTES_PER_HOUR: i64 = 60;
+ const MINUTES_PER_DAY: i64 = 24 * MINUTES_PER_HOUR;
+ const MINUTES_PER_WEEK: i64 = 7 * MINUTES_PER_DAY;
+ const MINUTES_PER_MONTH: i64 = 30 * MINUTES_PER_DAY;
+ const ROUNDING_BIAS_MINUTES: i64 = 3;
+
+ let windows_minutes = windows_minutes.max(0);
+
+ if windows_minutes <= MINUTES_PER_DAY.saturating_add(ROUNDING_BIAS_MINUTES) {
+ let adjusted = windows_minutes.saturating_add(ROUNDING_BIAS_MINUTES);
+ let hours = std::cmp::max(1, adjusted / MINUTES_PER_HOUR);
+ format!("{hours}h")
+ } else if windows_minutes <= MINUTES_PER_WEEK.saturating_add(ROUNDING_BIAS_MINUTES) {
+ "weekly".to_string()
+ } else if windows_minutes <= MINUTES_PER_MONTH.saturating_add(ROUNDING_BIAS_MINUTES) {
+ "monthly".to_string()
+ } else {
+ "annual".to_string()
+ }
+}
+
+/// Common initialization parameters shared by all `ChatWidget` constructors.
+pub(crate) struct ChatWidgetInit {
+ pub(crate) config: Config,
+ pub(crate) frame_requester: FrameRequester,
+ pub(crate) app_event_tx: AppEventSender,
+ pub(crate) initial_prompt: Option<String>,
+ pub(crate) initial_images: Vec<PathBuf>,
+ pub(crate) enhanced_keys_supported: bool,
+ pub(crate) auth_manager: Arc<AuthManager>,
+ pub(crate) models_manager: Arc<ModelsManager>,
+ pub(crate) feedback: codex_feedback::CodexFeedback,
+ pub(crate) skills: Option<Vec<SkillMetadata>>,
+ pub(crate) is_first_run: bool,
+ pub(crate) model_family: ModelFamily,
+}
+
+#[derive(Default)]
+enum RateLimitSwitchPromptState {
+ #[default]
+ Idle,
+ Pending,
+ Shown,
+}
+
+pub(crate) struct ChatWidget {
+ app_event_tx: AppEventSender,
+ codex_op_tx: UnboundedSender<Op>,
+ bottom_pane: BottomPane,
+ active_cell: Option<Box<dyn HistoryCell>>,
+ config: Config,
+ model_family: ModelFamily,
+ auth_manager: Arc<AuthManager>,
+ models_manager: Arc<ModelsManager>,
+ session_header: SessionHeader,
+ initial_user_message: Option<UserMessage>,
+ token_info: Option<TokenUsageInfo>,
+ rate_limit_snapshot: Option<RateLimitSnapshotDisplay>,
+ plan_type: Option<PlanType>,
+ rate_limit_warnings: RateLimitWarningState,
+ rate_limit_switch_prompt: RateLimitSwitchPromptState,
+ rate_limit_poller: Option<JoinHandle<()>>,
+ // Stream lifecycle controller
+ stream_controller: Option<StreamController>,
+ running_commands: HashMap<String, RunningCommand>,
+ suppressed_exec_calls: HashSet<String>,
+ last_unified_wait: Option<UnifiedExecWaitState>,
+ task_complete_pending: bool,
+ mcp_startup_status: Option<HashMap<String, McpStartupStatus>>,
+ // Queue of interruptive UI events deferred during an active write cycle
+ interrupts: InterruptManager,
+ // Accumulates the current reasoning block text to extract a header
+ reasoning_buffer: String,
+ // Accumulates full reasoning content for transcript-only recording
+ full_reasoning_buffer: String,
+ // Current status header shown in the status indicator.
+ current_status_header: String,
+ // Previous status header to restore after a transient stream retry.
+ retry_status_header: Option<String>,
+ conversation_id: Option<ConversationId>,
+ frame_requester: FrameRequester,
+ // Whether to include the initial welcome banner on session configured
+ show_welcome_banner: bool,
+ // When resuming an existing session (selected via resume picker), avoid an
+ // immediate redraw on SessionConfigured to prevent a gratuitous UI flicker.
+ suppress_session_configured_redraw: bool,
+ // User messages queued while a turn is in progress
+ queued_user_messages: VecDeque<UserMessage>,
+ // Pending notification to show when unfocused on next Draw
+ pending_notification: Option<Notification>,
+ // Simple review mode flag; used to adjust layout and banners.
+ is_review_mode: bool,
+ // Snapshot of token usage to restore after review mode exits.
+ pre_review_token_info: Option<Option<TokenUsageInfo>>,
+ // Whether to add a final message separator after the last message
+ needs_final_message_separator: bool,
+
+ last_rendered_width: std::cell::Cell<Option<usize>>,
+ // Feedback sink for /feedback
+ feedback: codex_feedback::CodexFeedback,
+ // Current session rollout path (if known)
+ current_rollout_path: Option<PathBuf>,
+}
+
+struct UserMessage {
+ text: String,
+ image_paths: Vec<PathBuf>,
+}
+
+impl From<String> for UserMessage {
+ fn from(text: String) -> Self {
+ Self {
+ text,
+ image_paths: Vec::new(),
+ }
+ }
+}
+
+impl From<&str> for UserMessage {
+ fn from(text: &str) -> Self {
+ Self {
+ text: text.to_string(),
+ image_paths: Vec::new(),
+ }
+ }
+}
+
+fn create_initial_user_message(text: String, image_paths: Vec<PathBuf>) -> Option<UserMessage> {
+ if text.is_empty() && image_paths.is_empty() {
+ None
+ } else {
+ Some(UserMessage { text, image_paths })
+ }
+}
+
+impl ChatWidget {
+ fn flush_answer_stream_with_separator(&mut self) {
+ if let Some(mut controller) = self.stream_controller.take()
+ && let Some(cell) = controller.finalize()
+ {
+ self.add_boxed_history(cell);
+ }
+ }
+
+ fn set_status_header(&mut self, header: String) {
+ self.current_status_header = header.clone();
+ self.bottom_pane.update_status_header(header);
+ }
+
+ fn restore_retry_status_header_if_present(&mut self) {
+ if let Some(header) = self.retry_status_header.take()
+ && self.current_status_header != header
+ {
+ self.set_status_header(header);
+ }
+ }
+
+ // --- Small event handlers ---
+ fn on_session_configured(&mut self, event: codex_core::protocol::SessionConfiguredEvent) {
+ self.bottom_pane
+ .set_history_metadata(event.history_log_id, event.history_entry_count);
+ self.conversation_id = Some(event.session_id);
+ self.current_rollout_path = Some(event.rollout_path.clone());
+ let initial_messages = event.initial_messages.clone();
+ let model_for_header = event.model.clone();
+ self.session_header.set_model(&model_for_header);
+ self.add_to_history(history_cell::new_session_info(
+ &self.config,
+ &model_for_header,
+ event,
+ self.show_welcome_banner,
+ ));
+ if let Some(messages) = initial_messages {
+ self.replay_initial_messages(messages);
+ }
+ // Ask codex-core to enumerate custom prompts for this session.
+ self.submit_op(Op::ListCustomPrompts);
+ if let Some(user_message) = self.initial_user_message.take() {
+ self.submit_user_message(user_message);
+ }
+ if !self.suppress_session_configured_redraw {
+ self.request_redraw();
+ }
+ }
+
+ pub(crate) fn open_feedback_note(
+ &mut self,
+ category: crate::app_event::FeedbackCategory,
+ include_logs: bool,
+ ) {
+ // Build a fresh snapshot at the time of opening the note overlay.
+ let snapshot = self.feedback.snapshot(self.conversation_id);
+ let rollout = if include_logs {
+ self.current_rollout_path.clone()
+ } else {
+ None
+ };
+ let view = crate::bottom_pane::FeedbackNoteView::new(
+ category,
+ snapshot,
+ rollout,
+ self.app_event_tx.clone(),
+ include_logs,
+ );
+ self.bottom_pane.show_view(Box::new(view));
+ self.request_redraw();
+ }
+
+ pub(crate) fn open_feedback_consent(&mut self, category: crate::app_event::FeedbackCategory) {
+ let params = crate::bottom_pane::feedback_upload_consent_params(
+ self.app_event_tx.clone(),
+ category,
+ self.current_rollout_path.clone(),
+ );
+ self.bottom_pane.show_selection_view(params);
+ self.request_redraw();
+ }
+
+ fn on_agent_message(&mut self, message: String) {
+ // If we have a stream_controller, then the final agent message is redundant and will be a
+ // duplicate of what has already been streamed.
+ if self.stream_controller.is_none() {
+ self.handle_streaming_delta(message);
+ }
+ self.flush_answer_stream_with_separator();
+ self.handle_stream_finished();
+ self.request_redraw();
+ }
+
+ fn on_agent_message_delta(&mut self, delta: String) {
+ self.handle_streaming_delta(delta);
+ }
+
+ fn on_agent_reasoning_delta(&mut self, delta: String) {
+ // For reasoning deltas, do not stream to history. Accumulate the
+ // current reasoning block and extract the first bold element
+ // (between **/**) as the chunk header. Show this header as status.
+ self.reasoning_buffer.push_str(&delta);
+
+ if let Some(header) = extract_first_bold(&self.reasoning_buffer) {
+ // Update the shimmer header to the extracted reasoning chunk header.
+ self.set_status_header(header);
+ } else {
+ // Fallback while we don't yet have a bold header: leave existing header as-is.
+ }
+ self.request_redraw();
+ }
+
+ fn on_agent_reasoning_final(&mut self) {
+ let reasoning_summary_format = self.get_model_family().reasoning_summary_format;
+ // At the end of a reasoning block, record transcript-only content.
+ self.full_reasoning_buffer.push_str(&self.reasoning_buffer);
+ if !self.full_reasoning_buffer.is_empty() {
+ let cell = history_cell::new_reasoning_summary_block(
+ self.full_reasoning_buffer.clone(),
+ reasoning_summary_format,
+ );
+ self.add_boxed_history(cell);
+ }
+ self.reasoning_buffer.clear();
+ self.full_reasoning_buffer.clear();
+ self.request_redraw();
+ }
+
+ fn on_reasoning_section_break(&mut self) {
+ // Start a new reasoning block for header extraction and accumulate transcript.
+ self.full_reasoning_buffer.push_str(&self.reasoning_buffer);
+ self.full_reasoning_buffer.push_str("\n\n");
+ self.reasoning_buffer.clear();
+ }
+
+ // Raw reasoning uses the same flow as summarized reasoning
+
+ fn on_task_started(&mut self) {
+ self.bottom_pane.clear_ctrl_c_quit_hint();
+ self.bottom_pane.set_task_running(true);
+ self.retry_status_header = None;
+ self.bottom_pane.set_interrupt_hint_visible(true);
+ self.set_status_header(String::from("Working"));
+ self.full_reasoning_buffer.clear();
+ self.reasoning_buffer.clear();
+ self.request_redraw();
+ }
+
+ fn on_task_complete(&mut self, last_agent_message: Option<String>) {
+ // If a stream is currently active, finalize it.
+ self.flush_answer_stream_with_separator();
+ // Mark task stopped and request redraw now that all content is in history.
+ self.bottom_pane.set_task_running(false);
+ self.running_commands.clear();
+ self.suppressed_exec_calls.clear();
+ self.last_unified_wait = None;
+ self.request_redraw();
+
+ // If there is a queued user message, send exactly one now to begin the next turn.
+ self.maybe_send_next_queued_input();
+ // Emit a notification when the turn completes (suppressed if focused).
+ self.notify(Notification::AgentTurnComplete {
+ response: last_agent_message.unwrap_or_default(),
+ });
+
+ self.maybe_show_pending_rate_limit_prompt();
+ }
+
+ pub(crate) fn set_token_info(&mut self, info: Option<TokenUsageInfo>) {
+ match info {
+ Some(info) => self.apply_token_info(info),
+ None => {
+ self.bottom_pane.set_context_window(None, None);
+ self.token_info = None;
+ }
+ }
+ }
+
+ fn apply_token_info(&mut self, info: TokenUsageInfo) {
+ let percent = self.context_remaining_percent(&info);
+ let used_tokens = self.context_used_tokens(&info, percent.is_some());
+ self.bottom_pane.set_context_window(percent, used_tokens);
+ self.token_info = Some(info);
+ }
+
+ fn context_remaining_percent(&self, info: &TokenUsageInfo) -> Option<i64> {
+ info.model_context_window
+ .or(self.model_family.context_window)
+ .map(|window| {
+ info.last_token_usage
+ .percent_of_context_window_remaining(window)
+ })
+ }
+
+ fn context_used_tokens(&self, info: &TokenUsageInfo, percent_known: bool) -> Option<i64> {
+ if percent_known {
+ return None;
+ }
+
+ Some(info.total_token_usage.tokens_in_context_window())
+ }
+
+ fn restore_pre_review_token_info(&mut self) {
+ if let Some(saved) = self.pre_review_token_info.take() {
+ match saved {
+ Some(info) => self.apply_token_info(info),
+ None => {
+ self.bottom_pane.set_context_window(None, None);
+ self.token_info = None;
+ }
+ }
+ }
+ }
+
+ pub(crate) fn on_rate_limit_snapshot(&mut self, snapshot: Option<RateLimitSnapshot>) {
+ if let Some(mut snapshot) = snapshot {
+ if snapshot.credits.is_none() {
+ snapshot.credits = self
+ .rate_limit_snapshot
+ .as_ref()
+ .and_then(|display| display.credits.as_ref())
+ .map(|credits| CreditsSnapshot {
+ has_credits: credits.has_credits,
+ unlimited: credits.unlimited,
+ balance: credits.balance.clone(),
+ });
+ }
+
+ self.plan_type = snapshot.plan_type.or(self.plan_type);
+
+ let warnings = self.rate_limit_warnings.take_warnings(
+ snapshot
+ .secondary
+ .as_ref()
+ .map(|window| window.used_percent),
+ snapshot
+ .secondary
+ .as_ref()
+ .and_then(|window| window.window_minutes),
+ snapshot.primary.as_ref().map(|window| window.used_percent),
+ snapshot
+ .primary
+ .as_ref()
+ .and_then(|window| window.window_minutes),
+ );
+
+ let high_usage = snapshot
+ .secondary
+ .as_ref()
+ .map(|w| w.used_percent >= RATE_LIMIT_SWITCH_PROMPT_THRESHOLD)
+ .unwrap_or(false)
+ || snapshot
+ .primary
+ .as_ref()
+ .map(|w| w.used_percent >= RATE_LIMIT_SWITCH_PROMPT_THRESHOLD)
+ .unwrap_or(false);
+
+ if high_usage
+ && !self.rate_limit_switch_prompt_hidden()
+ && self.model_family.get_model_slug() != NUDGE_MODEL_SLUG
+ && !matches!(
+ self.rate_limit_switch_prompt,
+ RateLimitSwitchPromptState::Shown
+ )
+ {
+ self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Pending;
+ }
+
+ let display = crate::status::rate_limit_snapshot_display(&snapshot, Local::now());
+ self.rate_limit_snapshot = Some(display);
+
+ if !warnings.is_empty() {
+ for warning in warnings {
+ self.add_to_history(history_cell::new_warning_event(warning));
+ }
+ self.request_redraw();
+ }
+ } else {
+ self.rate_limit_snapshot = None;
+ }
+ }
+ /// Finalize any active exec as failed and stop/clear running UI state.
+ fn finalize_turn(&mut self) {
+ // Ensure any spinner is replaced by a red ✗ and flushed into history.
+ self.finalize_active_cell_as_failed();
+ // Reset running state and clear streaming buffers.
+ self.bottom_pane.set_task_running(false);
+ self.running_commands.clear();
+ self.suppressed_exec_calls.clear();
+ self.last_unified_wait = None;
+ self.stream_controller = None;
+ self.maybe_show_pending_rate_limit_prompt();
+ }
+ pub(crate) fn get_model_family(&self) -> ModelFamily {
+ self.model_family.clone()
+ }
+
+ fn on_error(&mut self, message: String) {
+ self.finalize_turn();
+ self.add_to_history(history_cell::new_error_event(message));
+ self.request_redraw();
+
+ // After an error ends the turn, try sending the next queued input.
+ self.maybe_send_next_queued_input();
+ }
+
+ fn on_warning(&mut self, message: impl Into<String>) {
+ self.add_to_history(history_cell::new_warning_event(message.into()));
+ self.request_redraw();
+ }
+
+ fn on_mcp_startup_update(&mut self, ev: McpStartupUpdateEvent) {
+ let mut status = self.mcp_startup_status.take().unwrap_or_default();
+ if let McpStartupStatus::Failed { error } = &ev.status {
+ self.on_warning(error);
+ }
+ status.insert(ev.server, ev.status);
+ self.mcp_startup_status = Some(status);
+ self.bottom_pane.set_task_running(true);
+ if let Some(current) = &self.mcp_startup_status {
+ let total = current.len();
+ let mut starting: Vec<_> = current
+ .iter()
+ .filter_map(|(name, state)| {
+ if matches!(state, McpStartupStatus::Starting) {
+ Some(name)
+ } else {
+ None
+ }
+ })
+ .collect();
+ starting.sort();
+ if let Some(first) = starting.first() {
+ let completed = total.saturating_sub(starting.len());
+ let max_to_show = 3;
+ let mut to_show: Vec<String> = starting
+ .iter()
+ .take(max_to_show)
+ .map(ToString::to_string)
+ .collect();
+ if starting.len() > max_to_show {
+ to_show.push("…".to_string());
+ }
+ let header = if total > 1 {
+ format!(
+ "Starting MCP servers ({completed}/{total}): {}",
+ to_show.join(", ")
+ )
+ } else {
+ format!("Booting MCP server: {first}")
+ };
+ self.set_status_header(header);
+ }
+ }
+ self.request_redraw();
+ }
+
+ fn on_mcp_startup_complete(&mut self, ev: McpStartupCompleteEvent) {
+ let mut parts = Vec::new();
+ if !ev.failed.is_empty() {
+ let failed_servers: Vec<_> = ev.failed.iter().map(|f| f.server.clone()).collect();
+ parts.push(format!("failed: {}", failed_servers.join(", ")));
+ }
+ if !ev.cancelled.is_empty() {
+ self.on_warning(format!(
+ "MCP startup interrupted. The following servers were not initialized: {}",
+ ev.cancelled.join(", ")
+ ));
+ }
+ if !parts.is_empty() {
+ self.on_warning(format!("MCP startup incomplete ({})", parts.join("; ")));
+ }
+
+ self.mcp_startup_status = None;
+ self.bottom_pane.set_task_running(false);
+ self.maybe_send_next_queued_input();
+ self.request_redraw();
+ }
+
+ /// Handle a turn aborted due to user interrupt (Esc).
+ /// When there are queued user messages, restore them into the composer
+ /// separated by newlines rather than auto‑submitting the next one.
+ fn on_interrupted_turn(&mut self, reason: TurnAbortReason) {
+ // Finalize, log a gentle prompt, and clear running state.
+ self.finalize_turn();
+
+ if reason != TurnAbortReason::ReviewEnded {
+ self.add_to_history(history_cell::new_error_event(
+ "Conversation interrupted - tell the model what to do differently. Something went wrong? Hit `/feedback` to report the issue.".to_owned(),
+ ));
+ }
+
+ // If any messages were queued during the task, restore them into the composer.
+ if !self.queued_user_messages.is_empty() {
+ let queued_text = self
+ .queued_user_messages
+ .iter()
+ .map(|m| m.text.clone())
+ .collect::<Vec<_>>()
+ .join("\n");
+ let existing_text = self.bottom_pane.composer_text();
+ let combined = if existing_text.is_empty() {
+ queued_text
+ } else if queued_text.is_empty() {
+ existing_text
+ } else {
+ format!("{queued_text}\n{existing_text}")
+ };
+ self.bottom_pane.set_composer_text(combined);
+ // Clear the queue and update the status indicator list.
+ self.queued_user_messages.clear();
+ self.refresh_queued_user_messages();
+ }
+
+ self.request_redraw();
+ }
+
+ fn on_plan_update(&mut self, update: UpdatePlanArgs) {
+ self.add_to_history(history_cell::new_plan_update(update));
+ }
+
+ fn on_exec_approval_request(&mut self, id: String, ev: ExecApprovalRequestEvent) {
+ let id2 = id.clone();
+ let ev2 = ev.clone();
+ self.defer_or_handle(
+ |q| q.push_exec_approval(id, ev),
+ |s| s.handle_exec_approval_now(id2, ev2),
+ );
+ }
+
+ fn on_apply_patch_approval_request(&mut self, id: String, ev: ApplyPatchApprovalRequestEvent) {
+ let id2 = id.clone();
+ let ev2 = ev.clone();
+ self.defer_or_handle(
+ |q| q.push_apply_patch_approval(id, ev),
+ |s| s.handle_apply_patch_approval_now(id2, ev2),
+ );
+ }
+
+ fn on_elicitation_request(&mut self, ev: ElicitationRequestEvent) {
+ let ev2 = ev.clone();
+ self.defer_or_handle(
+ |q| q.push_elicitation(ev),
+ |s| s.handle_elicitation_request_now(ev2),
+ );
+ }
+
+ fn on_exec_command_begin(&mut self, ev: ExecCommandBeginEvent) {
+ self.flush_answer_stream_with_separator();
+ let ev2 = ev.clone();
+ self.defer_or_handle(|q| q.push_exec_begin(ev), |s| s.handle_exec_begin_now(ev2));
+ }
+
+ fn on_exec_command_output_delta(
+ &mut self,
+ _ev: codex_core::protocol::ExecCommandOutputDeltaEvent,
+ ) {
+ // TODO: Handle streaming exec output if/when implemented
+ }
+
+ fn on_terminal_interaction(&mut self, _ev: TerminalInteractionEvent) {
+ // TODO: Handle once design is ready
+ }
+
+ fn on_patch_apply_begin(&mut self, event: PatchApplyBeginEvent) {
+ self.add_to_history(history_cell::new_patch_event(
+ event.changes,
+ &self.config.cwd,
+ ));
+ }
+
+ fn on_view_image_tool_call(&mut self, event: ViewImageToolCallEvent) {
+ self.flush_answer_stream_with_separator();
+ self.add_to_history(history_cell::new_view_image_tool_call(
+ event.path,
+ &self.config.cwd,
+ ));
+ self.request_redraw();
+ }
+
+ fn on_patch_apply_end(&mut self, event: codex_core::protocol::PatchApplyEndEvent) {
+ let ev2 = event.clone();
+ self.defer_or_handle(
+ |q| q.push_patch_end(event),
+ |s| s.handle_patch_apply_end_now(ev2),
+ );
+ }
+
+ fn on_exec_command_end(&mut self, ev: ExecCommandEndEvent) {
+ let ev2 = ev.clone();
+ self.defer_or_handle(|q| q.push_exec_end(ev), |s| s.handle_exec_end_now(ev2));
+ }
+
+ fn on_mcp_tool_call_begin(&mut self, ev: McpToolCallBeginEvent) {
+ let ev2 = ev.clone();
+ self.defer_or_handle(|q| q.push_mcp_begin(ev), |s| s.handle_mcp_begin_now(ev2));
+ }
+
+ fn on_mcp_tool_call_end(&mut self, ev: McpToolCallEndEvent) {
+ let ev2 = ev.clone();
+ self.defer_or_handle(|q| q.push_mcp_end(ev), |s| s.handle_mcp_end_now(ev2));
+ }
+
+ fn on_web_search_begin(&mut self, _ev: WebSearchBeginEvent) {
+ self.flush_answer_stream_with_separator();
+ }
+
+ fn on_web_search_end(&mut self, ev: WebSearchEndEvent) {
+ self.flush_answer_stream_with_separator();
+ self.add_to_history(history_cell::new_web_search_call(format!(
+ "Searched: {}",
+ ev.query
+ )));
+ }
+
+ fn on_get_history_entry_response(
+ &mut self,
+ event: codex_core::protocol::GetHistoryEntryResponseEvent,
+ ) {
+ let codex_core::protocol::GetHistoryEntryResponseEvent {
+ offset,
+ log_id,
+ entry,
+ } = event;
+ self.bottom_pane
+ .on_history_entry_response(log_id, offset, entry.map(|e| e.text));
+ }
+
+ fn on_shutdown_complete(&mut self) {
+ self.request_exit();
+ }
+
+ fn on_turn_diff(&mut self, unified_diff: String) {
+ debug!("TurnDiffEvent: {unified_diff}");
+ }
+
+ fn on_deprecation_notice(&mut self, event: DeprecationNoticeEvent) {
+ let DeprecationNoticeEvent { summary, details } = event;
+ self.add_to_history(history_cell::new_deprecation_notice(summary, details));
+ self.request_redraw();
+ }
+
+ fn on_background_event(&mut self, message: String) {
+ debug!("BackgroundEvent: {message}");
+ self.bottom_pane.ensure_status_indicator();
+ self.bottom_pane.set_interrupt_hint_visible(true);
+ self.set_status_header(message);
+ }
+
+ fn on_undo_started(&mut self, event: UndoStartedEvent) {
+ self.bottom_pane.ensure_status_indicator();
+ self.bottom_pane.set_interrupt_hint_visible(false);
+ let message = event
+ .message
+ .unwrap_or_else(|| "Undo in progress...".to_string());
+ self.set_status_header(message);
+ }
+
+ fn on_undo_completed(&mut self, event: UndoCompletedEvent) {
+ let UndoCompletedEvent { success, message } = event;
+ self.bottom_pane.hide_status_indicator();
+ let message = message.unwrap_or_else(|| {
+ if success {
+ "Undo completed successfully.".to_string()
+ } else {
+ "Undo failed.".to_string()
+ }
+ });
+ if success {
+ self.add_info_message(message, None);
+ } else {
+ self.add_error_message(message);
+ }
+ }
+
+ fn on_stream_error(&mut self, message: String) {
+ if self.retry_status_header.is_none() {
+ self.retry_status_header = Some(self.current_status_header.clone());
+ }
+ self.set_status_header(message);
+ }
+
+ /// Periodic tick to commit at most one queued line to history with a small delay,
+ /// animating the output.
+ pub(crate) fn on_commit_tick(&mut self) {
+ if let Some(controller) = self.stream_controller.as_mut() {
+ let (cell, is_idle) = controller.on_commit_tick();
+ if let Some(cell) = cell {
+ self.bottom_pane.hide_status_indicator();
+ self.add_boxed_history(cell);
+ }
+ if is_idle {
+ self.app_event_tx.send(AppEvent::StopCommitAnimation);
+ }
+ }
+ }
+
+ fn flush_interrupt_queue(&mut self) {
+ let mut mgr = std::mem::take(&mut self.interrupts);
+ mgr.flush_all(self);
+ self.interrupts = mgr;
+ }
+
+ #[inline]
+ fn defer_or_handle(
+ &mut self,
+ push: impl FnOnce(&mut InterruptManager),
+ handle: impl FnOnce(&mut Self),
+ ) {
+ // Preserve deterministic FIFO across queued interrupts: once anything
+ // is queued due to an active write cycle, continue queueing until the
+ // queue is flushed to avoid reordering (e.g., ExecEnd before ExecBegin).
+ if self.stream_controller.is_some() || !self.interrupts.is_empty() {
+ push(&mut self.interrupts);
+ } else {
+ handle(self);
+ }
+ }
+
+ fn handle_stream_finished(&mut self) {
+ if self.task_complete_pending {
+ self.bottom_pane.hide_status_indicator();
+ self.task_complete_pending = false;
+ }
+ // A completed stream indicates non-exec content was just inserted.
+ self.flush_interrupt_queue();
+ }
+
+ #[inline]
+ fn handle_streaming_delta(&mut self, delta: String) {
+ // Before streaming agent content, flush any active exec cell group.
+ self.flush_active_cell();
+
+ if self.stream_controller.is_none() {
+ if self.needs_final_message_separator {
+ let elapsed_seconds = self
+ .bottom_pane
+ .status_widget()
+ .map(super::status_indicator_widget::StatusIndicatorWidget::elapsed_seconds);
+ self.add_to_history(history_cell::FinalMessageSeparator::new(elapsed_seconds));
+ self.needs_final_message_separator = false;
+ }
+ self.stream_controller = Some(StreamController::new(
+ self.last_rendered_width.get().map(|w| w.saturating_sub(2)),
+ ));
+ }
+ if let Some(controller) = self.stream_controller.as_mut()
+ && controller.push(&delta)
+ {
+ self.app_event_tx.send(AppEvent::StartCommitAnimation);
+ }
+ self.request_redraw();
+ }
+
+ pub(crate) fn handle_exec_end_now(&mut self, ev: ExecCommandEndEvent) {
+ let running = self.running_commands.remove(&ev.call_id);
+ if self.suppressed_exec_calls.remove(&ev.call_id) {
+ return;
+ }
+ let (command, parsed, source) = match running {
+ Some(rc) => (rc.command, rc.parsed_cmd, rc.source),
+ None => (ev.command.clone(), ev.parsed_cmd.clone(), ev.source),
+ };
+ let is_unified_exec_interaction =
+ matches!(source, ExecCommandSource::UnifiedExecInteraction);
+
+ let needs_new = self
+ .active_cell
+ .as_ref()
+ .map(|cell| cell.as_any().downcast_ref::<ExecCell>().is_none())
+ .unwrap_or(true);
+ if needs_new {
+ self.flush_active_cell();
+ self.active_cell = Some(Box::new(new_active_exec_command(
+ ev.call_id.clone(),
+ command,
+ parsed,
+ source,
+ ev.interaction_input.clone(),
+ self.config.animations,
+ )));
+ }
+
+ if let Some(cell) = self
+ .active_cell
+ .as_mut()
+ .and_then(|c| c.as_any_mut().downcast_mut::<ExecCell>())
+ {
+ let output = if is_unified_exec_interaction {
+ CommandOutput {
+ exit_code: ev.exit_code,
+ formatted_output: String::new(),
+ aggregated_output: String::new(),
+ }
+ } else {
+ CommandOutput {
+ exit_code: ev.exit_code,
+ formatted_output: ev.formatted_output.clone(),
+ aggregated_output: ev.aggregated_output.clone(),
+ }
+ };
+ cell.complete_call(&ev.call_id, output, ev.duration);
+ if cell.should_flush() {
+ self.flush_active_cell();
+ }
+ }
+ }
+
+ pub(crate) fn handle_patch_apply_end_now(
+ &mut self,
+ event: codex_core::protocol::PatchApplyEndEvent,
+ ) {
+ // If the patch was successful, just let the "Edited" block stand.
+ // Otherwise, add a failure block.
+ if !event.success {
+ self.add_to_history(history_cell::new_patch_apply_failure(event.stderr));
+ }
+ }
+
+ pub(crate) fn handle_exec_approval_now(&mut self, id: String, ev: ExecApprovalRequestEvent) {
+ self.flush_answer_stream_with_separator();
+ let command = shlex::try_join(ev.command.iter().map(String::as_str))
+ .unwrap_or_else(|_| ev.command.join(" "));
+ self.notify(Notification::ExecApprovalRequested { command });
+
+ let request = ApprovalRequest::Exec {
+ id,
+ command: ev.command,
+ reason: ev.reason,
+ proposed_execpolicy_amendment: ev.proposed_execpolicy_amendment,
+ };
+ self.bottom_pane
+ .push_approval_request(request, &self.config.features);
+ self.request_redraw();
+ }
+
+ pub(crate) fn handle_apply_patch_approval_now(
+ &mut self,
+ id: String,
+ ev: ApplyPatchApprovalRequestEvent,
+ ) {
+ self.flush_answer_stream_with_separator();
+
+ let request = ApprovalRequest::ApplyPatch {
+ id,
+ reason: ev.reason,
+ changes: ev.changes.clone(),
+ cwd: self.config.cwd.clone(),
+ };
+ self.bottom_pane
+ .push_approval_request(request, &self.config.features);
+ self.request_redraw();
+ self.notify(Notification::EditApprovalRequested {
+ cwd: self.config.cwd.clone(),
+ changes: ev.changes.keys().cloned().collect(),
+ });
+ }
+
+ pub(crate) fn handle_elicitation_request_now(&mut self, ev: ElicitationRequestEvent) {
+ self.flush_answer_stream_with_separator();
+
+ self.notify(Notification::ElicitationRequested {
+ server_name: ev.server_name.clone(),
+ });
+
+ let request = ApprovalRequest::McpElicitation {
+ server_name: ev.server_name,
+ request_id: ev.id,
+ message: ev.message,
+ };
+ self.bottom_pane
+ .push_approval_request(request, &self.config.features);
+ self.request_redraw();
+ }
+
+ pub(crate) fn handle_exec_begin_now(&mut self, ev: ExecCommandBeginEvent) {
+ // Ensure the status indicator is visible while the command runs.
+ self.running_commands.insert(
+ ev.call_id.clone(),
+ RunningCommand {
+ command: ev.command.clone(),
+ parsed_cmd: ev.parsed_cmd.clone(),
+ source: ev.source,
+ },
+ );
+ let is_wait_interaction = matches!(ev.source, ExecCommandSource::UnifiedExecInteraction)
+ && ev
+ .interaction_input
+ .as_deref()
+ .map(str::is_empty)
+ .unwrap_or(true);
+ let command_display = ev.command.join(" ");
+ let should_suppress_unified_wait = is_wait_interaction
+ && self
+ .last_unified_wait
+ .as_ref()
+ .is_some_and(|wait| wait.is_duplicate(&command_display));
+ if is_wait_interaction {
+ self.last_unified_wait = Some(UnifiedExecWaitState::new(command_display));
+ } else {
+ self.last_unified_wait = None;
+ }
+ if should_suppress_unified_wait {
+ self.suppressed_exec_calls.insert(ev.call_id);
+ return;
+ }
+ let interaction_input = ev.interaction_input.clone();
+ if let Some(cell) = self
+ .active_cell
+ .as_mut()
+ .and_then(|c| c.as_any_mut().downcast_mut::<ExecCell>())
+ && let Some(new_exec) = cell.with_added_call(
+ ev.call_id.clone(),
+ ev.command.clone(),
+ ev.parsed_cmd.clone(),
+ ev.source,
+ interaction_input.clone(),
+ )
+ {
+ *cell = new_exec;
+ } else {
+ self.flush_active_cell();
+
+ self.active_cell = Some(Box::new(new_active_exec_command(
+ ev.call_id.clone(),
+ ev.command.clone(),
+ ev.parsed_cmd,
+ ev.source,
+ interaction_input,
+ self.config.animations,
+ )));
+ }
+
+ self.request_redraw();
+ }
+
+ pub(crate) fn handle_mcp_begin_now(&mut self, ev: McpToolCallBeginEvent) {
+ self.flush_answer_stream_with_separator();
+ self.flush_active_cell();
+ self.active_cell = Some(Box::new(history_cell::new_active_mcp_tool_call(
+ ev.call_id,
+ ev.invocation,
+ self.config.animations,
+ )));
+ self.request_redraw();
+ }
+ pub(crate) fn handle_mcp_end_now(&mut self, ev: McpToolCallEndEvent) {
+ self.flush_answer_stream_with_separator();
+
+ let McpToolCallEndEvent {
+ call_id,
+ invocation,
+ duration,
+ result,
+ } = ev;
+
+ let extra_cell = match self
+ .active_cell
+ .as_mut()
+ .and_then(|cell| cell.as_any_mut().downcast_mut::<McpToolCallCell>())
+ {
+ Some(cell) if cell.call_id() == call_id => cell.complete(duration, result),
+ _ => {
+ self.flush_active_cell();
+ let mut cell = history_cell::new_active_mcp_tool_call(
+ call_id,
+ invocation,
+ self.config.animations,
+ );
+ let extra_cell = cell.complete(duration, result);
+ self.active_cell = Some(Box::new(cell));
+ extra_cell
+ }
+ };
+
+ self.flush_active_cell();
+ if let Some(extra) = extra_cell {
+ self.add_boxed_history(extra);
+ }
+ }
+
+ pub(crate) fn new(
+ common: ChatWidgetInit,
+ conversation_manager: Arc<ConversationManager>,
+ ) -> Self {
+ let ChatWidgetInit {
+ config,
+ frame_requester,
+ app_event_tx,
+ initial_prompt,
+ initial_images,
+ enhanced_keys_supported,
+ auth_manager,
+ models_manager,
+ feedback,
+ skills,
+ is_first_run,
+ model_family,
+ } = common;
+ let model_slug = model_family.get_model_slug().to_string();
+ let mut config = config;
+ config.model = Some(model_slug.clone());
+ let mut rng = rand::rng();
+ let placeholder = EXAMPLE_PROMPTS[rng.random_range(0..EXAMPLE_PROMPTS.len())].to_string();
+ let codex_op_tx = spawn_agent(config.clone(), app_event_tx.clone(), conversation_manager);
+
+ let mut widget = Self {
+ app_event_tx: app_event_tx.clone(),
+ frame_requester: frame_requester.clone(),
+ codex_op_tx,
+ bottom_pane: BottomPane::new(BottomPaneParams {
+ frame_requester,
+ app_event_tx,
+ has_input_focus: true,
+ enhanced_keys_supported,
+ placeholder_text: placeholder,
+ disable_paste_burst: config.disable_paste_burst,
+ animations_enabled: config.animations,
+ skills,
+ }),
+ active_cell: None,
+ config,
+ model_family,
+ auth_manager,
+ models_manager,
+ session_header: SessionHeader::new(model_slug),
+ initial_user_message: create_initial_user_message(
+ initial_prompt.unwrap_or_default(),
+ initial_images,
+ ),
+ token_info: None,
+ rate_limit_snapshot: None,
+ plan_type: None,
+ rate_limit_warnings: RateLimitWarningState::default(),
+ rate_limit_switch_prompt: RateLimitSwitchPromptState::default(),
+ rate_limit_poller: None,
+ stream_controller: None,
+ running_commands: HashMap::new(),
+ suppressed_exec_calls: HashSet::new(),
+ last_unified_wait: None,
+ task_complete_pending: false,
+ mcp_startup_status: None,
+ interrupts: InterruptManager::new(),
+ reasoning_buffer: String::new(),
+ full_reasoning_buffer: String::new(),
+ current_status_header: String::from("Working"),
+ retry_status_header: None,
+ conversation_id: None,
+ queued_user_messages: VecDeque::new(),
+ show_welcome_banner: is_first_run,
+ suppress_session_configured_redraw: false,
+ pending_notification: None,
+ is_review_mode: false,
+ pre_review_token_info: None,
+ needs_final_message_separator: false,
+ last_rendered_width: std::cell::Cell::new(None),
+ feedback,
+ current_rollout_path: None,
+ };
+
+ widget.prefetch_rate_limits();
+
+ widget
+ }
+
+ /// Create a ChatWidget attached to an existing conversation (e.g., a fork).
+ pub(crate) fn new_from_existing(
+ common: ChatWidgetInit,
+ conversation: std::sync::Arc<codex_core::CodexConversation>,
+ session_configured: codex_core::protocol::SessionConfiguredEvent,
+ ) -> Self {
+ let ChatWidgetInit {
+ config,
+ frame_requester,
+ app_event_tx,
+ initial_prompt,
+ initial_images,
+ enhanced_keys_supported,
+ auth_manager,
+ models_manager,
+ feedback,
+ skills,
+ model_family,
+ ..
+ } = common;
+ let model_slug = model_family.get_model_slug().to_string();
+ let mut rng = rand::rng();
+ let placeholder = EXAMPLE_PROMPTS[rng.random_range(0..EXAMPLE_PROMPTS.len())].to_string();
+
+ let codex_op_tx =
+ spawn_agent_from_existing(conversation, session_configured, app_event_tx.clone());
+
+ let mut widget = Self {
+ app_event_tx: app_event_tx.clone(),
+ frame_requester: frame_requester.clone(),
+ codex_op_tx,
+ bottom_pane: BottomPane::new(BottomPaneParams {
+ frame_requester,
+ app_event_tx,
+ has_input_focus: true,
+ enhanced_keys_supported,
+ placeholder_text: placeholder,
+ disable_paste_burst: config.disable_paste_burst,
+ animations_enabled: config.animations,
+ skills,
+ }),
+ active_cell: None,
+ config,
+ model_family,
+ auth_manager,
+ models_manager,
+ session_header: SessionHeader::new(model_slug),
+ initial_user_message: create_initial_user_message(
+ initial_prompt.unwrap_or_default(),
+ initial_images,
+ ),
+ token_info: None,
+ rate_limit_snapshot: None,
+ plan_type: None,
+ rate_limit_warnings: RateLimitWarningState::default(),
+ rate_limit_switch_prompt: RateLimitSwitchPromptState::default(),
+ rate_limit_poller: None,
+ stream_controller: None,
+ running_commands: HashMap::new(),
+ suppressed_exec_calls: HashSet::new(),
+ last_unified_wait: None,
+ task_complete_pending: false,
+ mcp_startup_status: None,
+ interrupts: InterruptManager::new(),
+ reasoning_buffer: String::new(),
+ full_reasoning_buffer: String::new(),
+ current_status_header: String::from("Working"),
+ retry_status_header: None,
+ conversation_id: None,
+ queued_user_messages: VecDeque::new(),
+ show_welcome_banner: false,
+ suppress_session_configured_redraw: true,
+ pending_notification: None,
+ is_review_mode: false,
+ pre_review_token_info: None,
+ needs_final_message_separator: false,
+ last_rendered_width: std::cell::Cell::new(None),
+ feedback,
+ current_rollout_path: None,
+ };
+
+ widget.prefetch_rate_limits();
+
+ widget
+ }
+
+ pub(crate) fn handle_key_event(&mut self, key_event: KeyEvent) {
+ match key_event {
+ KeyEvent {
+ code: KeyCode::Char(c),
+ modifiers,
+ kind: KeyEventKind::Press,
+ ..
+ } if modifiers.contains(KeyModifiers::CONTROL) && c.eq_ignore_ascii_case(&'c') => {
+ self.on_ctrl_c();
+ return;
+ }
+ KeyEvent {
+ code: KeyCode::Char(c),
+ modifiers,
+ kind: KeyEventKind::Press,
+ ..
+ } if modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
+ && c.eq_ignore_ascii_case(&'v') =>
+ {
+ match paste_image_to_temp_png() {
+ Ok((path, info)) => {
+ self.attach_image(
+ path,
+ info.width,
+ info.height,
+ info.encoded_format.label(),
+ );
+ }
+ Err(err) => {
+ tracing::warn!("failed to paste image: {err}");
+ self.add_to_history(history_cell::new_error_event(format!(
+ "Failed to paste image: {err}",
+ )));
+ }
+ }
+ return;
+ }
+ other if other.kind == KeyEventKind::Press => {
+ self.bottom_pane.clear_ctrl_c_quit_hint();
+ }
+ _ => {}
+ }
+
+ match key_event {
+ KeyEvent {
+ code: KeyCode::Up,
+ modifiers: KeyModifiers::ALT,
+ kind: KeyEventKind::Press,
+ ..
+ } if !self.queued_user_messages.is_empty() => {
+ // Prefer the most recently queued item.
+ if let Some(user_message) = self.queued_user_messages.pop_back() {
+ self.bottom_pane.set_composer_text(user_message.text);
+ self.refresh_queued_user_messages();
+ self.request_redraw();
+ }
+ }
+ _ => {
+ match self.bottom_pane.handle_key_event(key_event) {
+ InputResult::Submitted(text) => {
+ // If a task is running, queue the user input to be sent after the turn completes.
+ let user_message = UserMessage {
+ text,
+ image_paths: self.bottom_pane.take_recent_submission_images(),
+ };
+ self.queue_user_message(user_message);
+ }
+ InputResult::Command(cmd) => {
+ self.dispatch_command(cmd);
+ }
+ InputResult::None => {}
+ }
+ }
+ }
+ }
+
+ pub(crate) fn attach_image(
+ &mut self,
+ path: PathBuf,
+ width: u32,
+ height: u32,
+ format_label: &str,
+ ) {
+ tracing::info!(
+ "attach_image path={path:?} width={width} height={height} format={format_label}",
+ );
+ self.bottom_pane
+ .attach_image(path, width, height, format_label);
+ self.request_redraw();
+ }
+
+ fn dispatch_command(&mut self, cmd: SlashCommand) {
+ if !cmd.available_during_task() && self.bottom_pane.is_task_running() {
+ let message = format!(
+ "'/{}' is disabled while a task is in progress.",
+ cmd.command()
+ );
+ self.add_to_history(history_cell::new_error_event(message));
+ self.request_redraw();
+ return;
+ }
+ match cmd {
+ SlashCommand::Feedback => {
+ // Step 1: pick a category (UI built in feedback_view)
+ let params =
+ crate::bottom_pane::feedback_selection_params(self.app_event_tx.clone());
+ self.bottom_pane.show_selection_view(params);
+ self.request_redraw();
+ }
+ SlashCommand::New => {
+ self.app_event_tx.send(AppEvent::NewSession);
+ }
+ SlashCommand::Resume => {
+ self.app_event_tx.send(AppEvent::OpenResumePicker);
+ }
+ SlashCommand::Init => {
+ let init_target = self.config.cwd.join(DEFAULT_PROJECT_DOC_FILENAME);
+ if init_target.exists() {
+ let message = format!(
+ "{DEFAULT_PROJECT_DOC_FILENAME} already exists here. Skipping /init to avoid overwriting it."
+ );
+ self.add_info_message(message, None);
+ return;
+ }
+ const INIT_PROMPT: &str = include_str!("../prompt_for_init_command.md");
+ self.submit_user_message(INIT_PROMPT.to_string().into());
+ }
+ SlashCommand::Compact => {
+ self.clear_token_usage();
+ self.app_event_tx.send(AppEvent::CodexOp(Op::Compact));
+ }
+ SlashCommand::Review => {
+ self.open_review_popup();
+ }
+ SlashCommand::Model => {
+ self.open_model_popup();
+ }
+ SlashCommand::Approvals => {
+ self.open_approvals_popup();
+ }
+ SlashCommand::Quit | SlashCommand::Exit => {
+ self.request_exit();
+ }
+ SlashCommand::Logout => {
+ if let Err(e) = codex_core::auth::logout(
+ &self.config.codex_home,
+ self.config.cli_auth_credentials_store_mode,
+ ) {
+ tracing::error!("failed to logout: {e}");
+ }
+ self.request_exit();
+ }
+ SlashCommand::Undo => {
+ self.app_event_tx.send(AppEvent::CodexOp(Op::Undo));
+ }
+ SlashCommand::Diff => {
+ self.add_diff_in_progress();
+ let tx = self.app_event_tx.clone();
+ tokio::spawn(async move {
+ let text = match get_git_diff().await {
+ Ok((is_git_repo, diff_text)) => {
+ if is_git_repo {
+ diff_text
+ } else {
+ "`/diff` — _not inside a git repository_".to_string()
+ }
+ }
+ Err(e) => format!("Failed to compute diff: {e}"),
+ };
+ tx.send(AppEvent::DiffResult(text));
+ });
+ }
+ SlashCommand::Mention => {
+ self.insert_str("@");
+ }
+ SlashCommand::Skills => {
+ self.insert_str("$");
+ }
+ SlashCommand::Status => {
+ self.add_status_output();
+ }
+ SlashCommand::Mcp => {
+ self.add_mcp_output();
+ }
+ SlashCommand::Rollout => {
+ if let Some(path) = self.rollout_path() {
+ self.add_info_message(
+ format!("Current rollout path: {}", path.display()),
+ None,
+ );
+ } else {
+ self.add_info_message("Rollout path is not available yet.".to_string(), None);
+ }
+ }
+ SlashCommand::TestApproval => {
+ use codex_core::protocol::EventMsg;
+ use std::collections::HashMap;
+
+ use codex_core::protocol::ApplyPatchApprovalRequestEvent;
+ use codex_core::protocol::FileChange;
+
+ self.app_event_tx.send(AppEvent::CodexEvent(Event {
+ id: "1".to_string(),
+ // msg: EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent {
+ // call_id: "1".to_string(),
+ // command: vec!["git".into(), "apply".into()],
+ // cwd: self.config.cwd.clone(),
+ // reason: Some("test".to_string()),
+ // }),
+ msg: EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent {
+ call_id: "1".to_string(),
+ turn_id: "turn-1".to_string(),
+ changes: HashMap::from([
+ (
+ PathBuf::from("/tmp/test.txt"),
+ FileChange::Add {
+ content: "test".to_string(),
+ },
+ ),
+ (
+ PathBuf::from("/tmp/test2.txt"),
+ FileChange::Update {
+ unified_diff: "+test\n-test2".to_string(),
+ move_path: None,
+ },
+ ),
+ ]),
+ reason: None,
+ grant_root: Some(PathBuf::from("/tmp")),
+ }),
+ }));
+ }
+ }
+ }
+
+ pub(crate) fn handle_paste(&mut self, text: String) {
+ self.bottom_pane.handle_paste(text);
+ }
+
+ // Returns true if caller should skip rendering this frame (a future frame is scheduled).
+ pub(crate) fn handle_paste_burst_tick(&mut self, frame_requester: FrameRequester) -> bool {
+ if self.bottom_pane.flush_paste_burst_if_due() {
+ // A paste just flushed; request an immediate redraw and skip this frame.
+ self.request_redraw();
+ true
+ } else if self.bottom_pane.is_in_paste_burst() {
+ // While capturing a burst, schedule a follow-up tick and skip this frame
+ // to avoid redundant renders between ticks.
+ frame_requester.schedule_frame_in(
+ crate::bottom_pane::ChatComposer::recommended_paste_flush_delay(),
+ );
+ true
+ } else {
+ false
+ }
+ }
+
+ fn flush_active_cell(&mut self) {
+ if let Some(active) = self.active_cell.take() {
+ self.needs_final_message_separator = true;
+ self.app_event_tx.send(AppEvent::InsertHistoryCell(active));
+ }
+ }
+
+ fn add_to_history(&mut self, cell: impl HistoryCell + 'static) {
+ self.add_boxed_history(Box::new(cell));
+ }
+
+ fn add_boxed_history(&mut self, cell: Box<dyn HistoryCell>) {
+ if !cell.display_lines(u16::MAX).is_empty() {
+ // Only break exec grouping if the cell renders visible lines.
+ self.flush_active_cell();
+ self.needs_final_message_separator = true;
+ }
+ self.app_event_tx.send(AppEvent::InsertHistoryCell(cell));
+ }
+
+ fn queue_user_message(&mut self, user_message: UserMessage) {
+ if self.bottom_pane.is_task_running() {
+ self.queued_user_messages.push_back(user_message);
+ self.refresh_queued_user_messages();
+ } else {
+ self.submit_user_message(user_message);
+ }
+ }
+
+ fn submit_user_message(&mut self, user_message: UserMessage) {
+ let UserMessage { text, image_paths } = user_message;
+ if text.is_empty() && image_paths.is_empty() {
+ return;
+ }
+
+ let mut items: Vec<UserInput> = Vec::new();
+
+ // Special-case: "!cmd" executes a local shell command instead of sending to the model.
+ if let Some(stripped) = text.strip_prefix('!') {
+ let cmd = stripped.trim();
+ if cmd.is_empty() {
+ self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
+ history_cell::new_info_event(
+ USER_SHELL_COMMAND_HELP_TITLE.to_string(),
+ Some(USER_SHELL_COMMAND_HELP_HINT.to_string()),
+ ),
+ )));
+ return;
+ }
+ self.submit_op(Op::RunUserShellCommand {
+ command: cmd.to_string(),
+ });
+ return;
+ }
+
+ if !text.is_empty() {
+ items.push(UserInput::Text { text: text.clone() });
+ }
+
+ for path in image_paths {
+ items.push(UserInput::LocalImage { path });
+ }
+
+ self.codex_op_tx
+ .send(Op::UserInput { items })
+ .unwrap_or_else(|e| {
+ tracing::error!("failed to send message: {e}");
+ });
+
+ // Persist the text to cross-session message history.
+ if !text.is_empty() {
+ self.codex_op_tx
+ .send(Op::AddToHistory { text: text.clone() })
+ .unwrap_or_else(|e| {
+ tracing::error!("failed to send AddHistory op: {e}");
+ });
+ }
+
+ // Only show the text portion in conversation history.
+ if !text.is_empty() {
+ self.add_to_history(history_cell::new_user_prompt(text));
+ }
+ self.needs_final_message_separator = false;
+ }
+
+ /// Replay a subset of initial events into the UI to seed the transcript when
+ /// resuming an existing session. This approximates the live event flow and
+ /// is intentionally conservative: only safe-to-replay items are rendered to
+ /// avoid triggering side effects. Event ids are passed as `None` to
+ /// distinguish replayed events from live ones.
+ fn replay_initial_messages(&mut self, events: Vec<EventMsg>) {
+ for msg in events {
+ if matches!(msg, EventMsg::SessionConfigured(_)) {
+ continue;
+ }
+ // `id: None` indicates a synthetic/fake id coming from replay.
+ self.dispatch_event_msg(None, msg, true);
+ }
+ }
+
+ pub(crate) fn handle_codex_event(&mut self, event: Event) {
+ let Event { id, msg } = event;
+ self.dispatch_event_msg(Some(id), msg, false);
+ }
+
+ /// Dispatch a protocol `EventMsg` to the appropriate handler.
+ ///
+ /// `id` is `Some` for live events and `None` for replayed events from
+ /// `replay_initial_messages()`. Callers should treat `None` as a "fake" id
+ /// that must not be used to correlate follow-up actions.
+ fn dispatch_event_msg(&mut self, id: Option<String>, msg: EventMsg, from_replay: bool) {
+ let is_stream_error = matches!(&msg, EventMsg::StreamError(_));
+ if !is_stream_error {
+ self.restore_retry_status_header_if_present();
+ }
+
+ match msg {
+ EventMsg::AgentMessageDelta(_)
+ | EventMsg::AgentReasoningDelta(_)
+ | EventMsg::TerminalInteraction(_)
+ | EventMsg::ExecCommandOutputDelta(_) => {}
+ _ => {
+ tracing::trace!("handle_codex_event: {:?}", msg);
+ }
+ }
+
+ match msg {
+ EventMsg::SessionConfigured(e) => self.on_session_configured(e),
+ EventMsg::AgentMessage(AgentMessageEvent { message }) => self.on_agent_message(message),
+ EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { delta }) => {
+ self.on_agent_message_delta(delta)
+ }
+ EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent { delta })
+ | EventMsg::AgentReasoningRawContentDelta(AgentReasoningRawContentDeltaEvent {
+ delta,
+ }) => self.on_agent_reasoning_delta(delta),
+ EventMsg::AgentReasoning(AgentReasoningEvent { .. }) => self.on_agent_reasoning_final(),
+ EventMsg::AgentReasoningRawContent(AgentReasoningRawContentEvent { text }) => {
+ self.on_agent_reasoning_delta(text);
+ self.on_agent_reasoning_final();
+ }
+ EventMsg::AgentReasoningSectionBreak(_) => self.on_reasoning_section_break(),
+ EventMsg::TaskStarted(_) => self.on_task_started(),
+ EventMsg::TaskComplete(TaskCompleteEvent { last_agent_message }) => {
+ self.on_task_complete(last_agent_message)
+ }
+ EventMsg::TokenCount(ev) => {
+ self.set_token_info(ev.info);
+ self.on_rate_limit_snapshot(ev.rate_limits);
+ }
+ EventMsg::Warning(WarningEvent { message }) => self.on_warning(message),
+ EventMsg::Error(ErrorEvent { message, .. }) => self.on_error(message),
+ EventMsg::McpStartupUpdate(ev) => self.on_mcp_startup_update(ev),
+ EventMsg::McpStartupComplete(ev) => self.on_mcp_startup_complete(ev),
+ EventMsg::TurnAborted(ev) => match ev.reason {
+ TurnAbortReason::Interrupted => {
+ self.on_interrupted_turn(ev.reason);
+ }
+ TurnAbortReason::Replaced => {
+ self.on_error("Turn aborted: replaced by a new task".to_owned())
+ }
+ TurnAbortReason::ReviewEnded => {
+ self.on_interrupted_turn(ev.reason);
+ }
+ },
+ EventMsg::PlanUpdate(update) => self.on_plan_update(update),
+ EventMsg::ExecApprovalRequest(ev) => {
+ // For replayed events, synthesize an empty id (these should not occur).
+ self.on_exec_approval_request(id.unwrap_or_default(), ev)
+ }
+ EventMsg::ApplyPatchApprovalRequest(ev) => {
+ self.on_apply_patch_approval_request(id.unwrap_or_default(), ev)
+ }
+ EventMsg::ElicitationRequest(ev) => {
+ self.on_elicitation_request(ev);
+ }
+ EventMsg::ExecCommandBegin(ev) => self.on_exec_command_begin(ev),
+ EventMsg::TerminalInteraction(delta) => self.on_terminal_interaction(delta),
+ EventMsg::ExecCommandOutputDelta(delta) => self.on_exec_command_output_delta(delta),
+ EventMsg::PatchApplyBegin(ev) => self.on_patch_apply_begin(ev),
+ EventMsg::PatchApplyEnd(ev) => self.on_patch_apply_end(ev),
+ EventMsg::ExecCommandEnd(ev) => self.on_exec_command_end(ev),
+ EventMsg::ViewImageToolCall(ev) => self.on_view_image_tool_call(ev),
+ EventMsg::McpToolCallBegin(ev) => self.on_mcp_tool_call_begin(ev),
+ EventMsg::McpToolCallEnd(ev) => self.on_mcp_tool_call_end(ev),
+ EventMsg::WebSearchBegin(ev) => self.on_web_search_begin(ev),
+ EventMsg::WebSearchEnd(ev) => self.on_web_search_end(ev),
+ EventMsg::GetHistoryEntryResponse(ev) => self.on_get_history_entry_response(ev),
+ EventMsg::McpListToolsResponse(ev) => self.on_list_mcp_tools(ev),
+ EventMsg::ListCustomPromptsResponse(ev) => self.on_list_custom_prompts(ev),
+ EventMsg::ShutdownComplete => self.on_shutdown_complete(),
+ EventMsg::TurnDiff(TurnDiffEvent { unified_diff }) => self.on_turn_diff(unified_diff),
+ EventMsg::DeprecationNotice(ev) => self.on_deprecation_notice(ev),
+ EventMsg::BackgroundEvent(BackgroundEventEvent { message }) => {
+ self.on_background_event(message)
+ }
+ EventMsg::UndoStarted(ev) => self.on_undo_started(ev),
+ EventMsg::UndoCompleted(ev) => self.on_undo_completed(ev),
+ EventMsg::StreamError(StreamErrorEvent { message, .. }) => {
+ self.on_stream_error(message)
+ }
+ EventMsg::UserMessage(ev) => {
+ if from_replay {
+ self.on_user_message_event(ev);
+ }
+ }
+ EventMsg::EnteredReviewMode(review_request) => {
+ self.on_entered_review_mode(review_request)
+ }
+ EventMsg::ExitedReviewMode(review) => self.on_exited_review_mode(review),
+ EventMsg::ContextCompacted(_) => self.on_agent_message("Context compacted".to_owned()),
+ EventMsg::RawResponseItem(_)
+ | EventMsg::ItemStarted(_)
+ | EventMsg::ItemCompleted(_)
+ | EventMsg::AgentMessageContentDelta(_)
+ | EventMsg::ReasoningContentDelta(_)
+ | EventMsg::ReasoningRawContentDelta(_) => {}
+ }
+ }
+
+ fn on_entered_review_mode(&mut self, review: ReviewRequest) {
+ // Enter review mode and emit a concise banner
+ if self.pre_review_token_info.is_none() {
+ self.pre_review_token_info = Some(self.token_info.clone());
+ }
+ self.is_review_mode = true;
+ let hint = review
+ .user_facing_hint
+ .unwrap_or_else(|| codex_core::review_prompts::user_facing_hint(&review.target));
+ let banner = format!(">> Code review started: {hint} <<");
+ self.add_to_history(history_cell::new_review_status_line(banner));
+ self.request_redraw();
+ }
+
+ fn on_exited_review_mode(&mut self, review: ExitedReviewModeEvent) {
+ // Leave review mode; if output is present, flush pending stream + show results.
+ if let Some(output) = review.review_output {
+ self.flush_answer_stream_with_separator();
+ self.flush_interrupt_queue();
+ self.flush_active_cell();
+
+ if output.findings.is_empty() {
+ let explanation = output.overall_explanation.trim().to_string();
+ if explanation.is_empty() {
+ tracing::error!("Reviewer failed to output a response.");
+ self.add_to_history(history_cell::new_error_event(
+ "Reviewer failed to output a response.".to_owned(),
+ ));
+ } else {
+ // Show explanation when there are no structured findings.
+ let mut rendered: Vec<ratatui::text::Line<'static>> = vec!["".into()];
+ append_markdown(&explanation, None, &mut rendered);
+ let body_cell = AgentMessageCell::new(rendered, false);
+ self.app_event_tx
+ .send(AppEvent::InsertHistoryCell(Box::new(body_cell)));
+ }
+ } else {
+ let message_text =
+ codex_core::review_format::format_review_findings_block(&output.findings, None);
+ let mut message_lines: Vec<ratatui::text::Line<'static>> = Vec::new();
+ append_markdown(&message_text, None, &mut message_lines);
+ let body_cell = AgentMessageCell::new(message_lines, true);
+ self.app_event_tx
+ .send(AppEvent::InsertHistoryCell(Box::new(body_cell)));
+ }
+ }
+
+ self.is_review_mode = false;
+ self.restore_pre_review_token_info();
+ // Append a finishing banner at the end of this turn.
+ self.add_to_history(history_cell::new_review_status_line(
+ "<< Code review finished >>".to_string(),
+ ));
+ self.request_redraw();
+ }
+
+ fn on_user_message_event(&mut self, event: UserMessageEvent) {
+ let message = event.message.trim();
+ if !message.is_empty() {
+ self.add_to_history(history_cell::new_user_prompt(message.to_string()));
+ }
+ }
+
+ fn request_exit(&self) {
+ self.app_event_tx.send(AppEvent::ExitRequest);
+ }
+
+ fn request_redraw(&mut self) {
+ self.frame_requester.schedule_frame();
+ }
+
+ fn notify(&mut self, notification: Notification) {
+ if !notification.allowed_for(&self.config.tui_notifications) {
+ return;
+ }
+ self.pending_notification = Some(notification);
+ self.request_redraw();
+ }
+
+ pub(crate) fn maybe_post_pending_notification(&mut self, tui: &mut crate::tui::Tui) {
+ if let Some(notif) = self.pending_notification.take() {
+ tui.notify(notif.display());
+ }
+ }
+
+ /// Mark the active cell as failed (✗) and flush it into history.
+ fn finalize_active_cell_as_failed(&mut self) {
+ if let Some(mut cell) = self.active_cell.take() {
+ // Insert finalized cell into history and keep grouping consistent.
+ if let Some(exec) = cell.as_any_mut().downcast_mut::<ExecCell>() {
+ exec.mark_failed();
+ } else if let Some(tool) = cell.as_any_mut().downcast_mut::<McpToolCallCell>() {
+ tool.mark_failed();
+ }
+ self.add_boxed_history(cell);
+ }
+ }
+
+ // If idle and there are queued inputs, submit exactly one to start the next turn.
+ fn maybe_send_next_queued_input(&mut self) {
+ if self.bottom_pane.is_task_running() {
+ return;
+ }
+ if let Some(user_message) = self.queued_user_messages.pop_front() {
+ self.submit_user_message(user_message);
+ }
+ // Update the list to reflect the remaining queued messages (if any).
+ self.refresh_queued_user_messages();
+ }
+
+ /// Rebuild and update the queued user messages from the current queue.
+ fn refresh_queued_user_messages(&mut self) {
+ let messages: Vec<String> = self
+ .queued_user_messages
+ .iter()
+ .map(|m| m.text.clone())
+ .collect();
+ self.bottom_pane.set_queued_user_messages(messages);
+ }
+
+ pub(crate) fn add_diff_in_progress(&mut self) {
+ self.request_redraw();
+ }
+
+ pub(crate) fn on_diff_complete(&mut self) {
+ self.request_redraw();
+ }
+
+ pub(crate) fn add_status_output(&mut self) {
+ let default_usage = TokenUsage::default();
+ let (total_usage, context_usage) = if let Some(ti) = &self.token_info {
+ (&ti.total_token_usage, Some(&ti.last_token_usage))
+ } else {
+ (&default_usage, Some(&default_usage))
+ };
+ self.add_to_history(crate::status::new_status_output(
+ &self.config,
+ self.auth_manager.as_ref(),
+ &self.model_family,
+ total_usage,
+ context_usage,
+ &self.conversation_id,
+ self.rate_limit_snapshot.as_ref(),
+ self.plan_type,
+ Local::now(),
+ self.model_family.get_model_slug(),
+ ));
+ }
+ fn stop_rate_limit_poller(&mut self) {
+ if let Some(handle) = self.rate_limit_poller.take() {
+ handle.abort();
+ }
+ }
+
+ fn prefetch_rate_limits(&mut self) {
+ self.stop_rate_limit_poller();
+
+ let Some(auth) = self.auth_manager.auth() else {
+ return;
+ };
+ if auth.mode != AuthMode::ChatGPT {
+ return;
+ }
+
+ let base_url = self.config.chatgpt_base_url.clone();
+ let app_event_tx = self.app_event_tx.clone();
+
+ let handle = tokio::spawn(async move {
+ let mut interval = tokio::time::interval(Duration::from_secs(60));
+
+ loop {
+ if let Some(snapshot) = fetch_rate_limits(base_url.clone(), auth.clone()).await {
+ app_event_tx.send(AppEvent::RateLimitSnapshotFetched(snapshot));
+ }
+ interval.tick().await;
+ }
+ });
+
+ self.rate_limit_poller = Some(handle);
+ }
+
+ fn lower_cost_preset(&self) -> Option<ModelPreset> {
+ let models = self.models_manager.try_list_models().ok()?;
+ models
+ .iter()
+ .find(|preset| preset.model == NUDGE_MODEL_SLUG)
+ .cloned()
+ }
+
+ fn rate_limit_switch_prompt_hidden(&self) -> bool {
+ self.config
+ .notices
+ .hide_rate_limit_model_nudge
+ .unwrap_or(false)
+ }
+
+ fn maybe_show_pending_rate_limit_prompt(&mut self) {
+ if self.rate_limit_switch_prompt_hidden() {
+ self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Idle;
+ return;
+ }
+ if !matches!(
+ self.rate_limit_switch_prompt,
+ RateLimitSwitchPromptState::Pending
+ ) {
+ return;
+ }
+ if let Some(preset) = self.lower_cost_preset() {
+ self.open_rate_limit_switch_prompt(preset);
+ self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Shown;
+ } else {
+ self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Idle;
+ }
+ }
+
+ fn open_rate_limit_switch_prompt(&mut self, preset: ModelPreset) {
+ let switch_model = preset.model.to_string();
+ let display_name = preset.display_name.to_string();
+ let default_effort: ReasoningEffortConfig = preset.default_reasoning_effort;
+
+ let switch_actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
+ tx.send(AppEvent::CodexOp(Op::OverrideTurnContext {
+ cwd: None,
+ approval_policy: None,
+ sandbox_policy: None,
+ model: Some(switch_model.clone()),
+ effort: Some(Some(default_effort)),
+ summary: None,
+ }));
+ tx.send(AppEvent::UpdateModel(switch_model.clone()));
+ tx.send(AppEvent::UpdateReasoningEffort(Some(default_effort)));
+ })];
+
+ let keep_actions: Vec<SelectionAction> = Vec::new();
+ let never_actions: Vec<SelectionAction> = vec![Box::new(|tx| {
+ tx.send(AppEvent::UpdateRateLimitSwitchPromptHidden(true));
+ tx.send(AppEvent::PersistRateLimitSwitchPromptHidden);
+ })];
+ let description = if preset.description.is_empty() {
+ Some("Uses fewer credits for upcoming turns.".to_string())
+ } else {
+ Some(preset.description)
+ };
+
+ let items = vec![
+ SelectionItem {
+ name: format!("Switch to {display_name}"),
+ description,
+ selected_description: None,
+ is_current: false,
+ actions: switch_actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "Keep current model".to_string(),
+ description: None,
+ selected_description: None,
+ is_current: false,
+ actions: keep_actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "Keep current model (never show again)".to_string(),
+ description: Some(
+ "Hide future rate limit reminders about switching models.".to_string(),
+ ),
+ selected_description: None,
+ is_current: false,
+ actions: never_actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ ];
+
+ self.bottom_pane.show_selection_view(SelectionViewParams {
+ title: Some("Approaching rate limits".to_string()),
+ subtitle: Some(format!("Switch to {display_name} for lower credit usage?")),
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ ..Default::default()
+ });
+ }
+
+ /// Open a popup to choose a quick auto model. Selecting "All models"
+ /// opens the full picker with every available preset.
+ pub(crate) fn open_model_popup(&mut self) {
+ let current_model = self.model_family.get_model_slug().to_string();
+ let presets: Vec<ModelPreset> =
+ // todo(aibrahim): make this async function
+ match self.models_manager.try_list_models() {
+ Ok(models) => models,
+ Err(_) => {
+ self.add_info_message(
+ "Models are being updated; please try /model again in a moment."
+ .to_string(),
+ None,
+ );
+ return;
+ }
+ };
+
+ let current_label = presets
+ .iter()
+ .find(|preset| preset.model == current_model)
+ .map(|preset| preset.display_name.to_string())
+ .unwrap_or_else(|| current_model.clone());
+
+ let (mut auto_presets, other_presets): (Vec<ModelPreset>, Vec<ModelPreset>) = presets
+ .into_iter()
+ .partition(|preset| Self::is_auto_model(&preset.model));
+
+ if auto_presets.is_empty() {
+ self.open_all_models_popup(other_presets);
+ return;
+ }
+
+ auto_presets.sort_by_key(|preset| Self::auto_model_order(&preset.model));
+
+ let mut items: Vec<SelectionItem> = auto_presets
+ .into_iter()
+ .map(|preset| {
+ let description =
+ (!preset.description.is_empty()).then_some(preset.description.clone());
+ let model = preset.model.clone();
+ let actions = Self::model_selection_actions(
+ model.clone(),
+ Some(preset.default_reasoning_effort),
+ );
+ SelectionItem {
+ name: preset.display_name,
+ description,
+ is_current: model == current_model,
+ actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ }
+ })
+ .collect();
+
+ if !other_presets.is_empty() {
+ let all_models = other_presets;
+ let actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
+ tx.send(AppEvent::OpenAllModelsPopup {
+ models: all_models.clone(),
+ });
+ })];
+
+ let is_current = !items.iter().any(|item| item.is_current);
+ let description = Some(format!(
+ "Choose a specific model and reasoning level (current: {current_label})"
+ ));
+
+ items.push(SelectionItem {
+ name: "All models".to_string(),
+ description,
+ is_current,
+ actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ });
+ }
+
+ self.bottom_pane.show_selection_view(SelectionViewParams {
+ title: Some("Select Model".to_string()),
+ subtitle: Some("Pick a quick auto mode or browse all models.".to_string()),
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ ..Default::default()
+ });
+ }
+
+ fn is_auto_model(model: &str) -> bool {
+ model.starts_with("codex-auto-")
+ }
+
+ fn auto_model_order(model: &str) -> usize {
+ match model {
+ "codex-auto-fast" => 0,
+ "codex-auto-balanced" => 1,
+ "codex-auto-thorough" => 2,
+ _ => 3,
+ }
+ }
+
+ pub(crate) fn open_all_models_popup(&mut self, presets: Vec<ModelPreset>) {
+ if presets.is_empty() {
+ self.add_info_message(
+ "No additional models are available right now.".to_string(),
+ None,
+ );
+ return;
+ }
+
+ let current_model = self.model_family.get_model_slug().to_string();
+ let mut items: Vec<SelectionItem> = Vec::new();
+ for preset in presets.into_iter() {
+ let description =
+ (!preset.description.is_empty()).then_some(preset.description.to_string());
+ let is_current = preset.model == current_model;
+ let single_supported_effort = preset.supported_reasoning_efforts.len() == 1;
+ let preset_for_action = preset.clone();
+ let actions: Vec<SelectionAction> = vec![Box::new(move |tx| {
+ let preset_for_event = preset_for_action.clone();
+ tx.send(AppEvent::OpenReasoningPopup {
+ model: preset_for_event,
+ });
+ })];
+ items.push(SelectionItem {
+ name: preset.display_name.to_string(),
+ description,
+ is_current,
+ actions,
+ dismiss_on_select: single_supported_effort,
+ ..Default::default()
+ });
+ }
+
+ self.bottom_pane.show_selection_view(SelectionViewParams {
+ title: Some("Select Model and Effort".to_string()),
+ subtitle: Some(
+ "Access legacy models by running codex -m <model_name> or in your config.toml"
+ .to_string(),
+ ),
+ footer_hint: Some("Press enter to select reasoning effort, or esc to dismiss.".into()),
+ items,
+ ..Default::default()
+ });
+ }
+
+ fn model_selection_actions(
+ model_for_action: String,
+ effort_for_action: Option<ReasoningEffortConfig>,
+ ) -> Vec<SelectionAction> {
+ vec![Box::new(move |tx| {
+ let effort_label = effort_for_action
+ .map(|effort| effort.to_string())
+ .unwrap_or_else(|| "default".to_string());
+ tx.send(AppEvent::CodexOp(Op::OverrideTurnContext {
+ cwd: None,
+ approval_policy: None,
+ sandbox_policy: None,
+ model: Some(model_for_action.clone()),
+ effort: Some(effort_for_action),
+ summary: None,
+ }));
+ tx.send(AppEvent::UpdateModel(model_for_action.clone()));
+ tx.send(AppEvent::UpdateReasoningEffort(effort_for_action));
+ tx.send(AppEvent::PersistModelSelection {
+ model: model_for_action.clone(),
+ effort: effort_for_action,
+ });
+ tracing::info!(
+ "Selected model: {}, Selected effort: {}",
+ model_for_action,
+ effort_label
+ );
+ })]
+ }
+
+ /// Open a popup to choose the reasoning effort (stage 2) for the given model.
+ pub(crate) fn open_reasoning_popup(&mut self, preset: ModelPreset) {
+ let default_effort: ReasoningEffortConfig = preset.default_reasoning_effort;
+ let supported = preset.supported_reasoning_efforts;
+
+ let warn_effort = if supported
+ .iter()
+ .any(|option| option.effort == ReasoningEffortConfig::XHigh)
+ {
+ Some(ReasoningEffortConfig::XHigh)
+ } else if supported
+ .iter()
+ .any(|option| option.effort == ReasoningEffortConfig::High)
+ {
+ Some(ReasoningEffortConfig::High)
+ } else {
+ None
+ };
+ let warning_text = warn_effort.map(|effort| {
+ let effort_label = Self::reasoning_effort_label(effort);
+ format!("⚠ {effort_label} reasoning effort can quickly consume Plus plan rate limits.")
+ });
+ let warn_for_model = preset.model.starts_with("gpt-5.1-codex")
+ || preset.model.starts_with("gpt-5.1-codex-max");
+
+ struct EffortChoice {
+ stored: Option<ReasoningEffortConfig>,
+ display: ReasoningEffortConfig,
+ }
+ let mut choices: Vec<EffortChoice> = Vec::new();
+ for effort in ReasoningEffortConfig::iter() {
+ if supported.iter().any(|option| option.effort == effort) {
+ choices.push(EffortChoice {
+ stored: Some(effort),
+ display: effort,
+ });
+ }
+ }
+ if choices.is_empty() {
+ choices.push(EffortChoice {
+ stored: Some(default_effort),
+ display: default_effort,
+ });
+ }
+
+ if choices.len() == 1 {
+ if let Some(effort) = choices.first().and_then(|c| c.stored) {
+ self.apply_model_and_effort(preset.model, Some(effort));
+ } else {
+ self.apply_model_and_effort(preset.model, None);
+ }
+ return;
+ }
+
+ let default_choice: Option<ReasoningEffortConfig> = choices
+ .iter()
+ .any(|choice| choice.stored == Some(default_effort))
+ .then_some(Some(default_effort))
+ .flatten()
+ .or_else(|| choices.iter().find_map(|choice| choice.stored))
+ .or(Some(default_effort));
+
+ let model_slug = preset.model.to_string();
+ let is_current_model = self.model_family.get_model_slug() == preset.model;
+ let highlight_choice = if is_current_model {
+ self.config.model_reasoning_effort
+ } else {
+ default_choice
+ };
+ let selection_choice = highlight_choice.or(default_choice);
+ let initial_selected_idx = choices
+ .iter()
+ .position(|choice| choice.stored == selection_choice)
+ .or_else(|| {
+ selection_choice
+ .and_then(|effort| choices.iter().position(|choice| choice.display == effort))
+ });
+ let mut items: Vec<SelectionItem> = Vec::new();
+ for choice in choices.iter() {
+ let effort = choice.display;
+ let mut effort_label = Self::reasoning_effort_label(effort).to_string();
+ if choice.stored == default_choice {
+ effort_label.push_str(" (default)");
+ }
+
+ let description = choice
+ .stored
+ .and_then(|effort| {
+ supported
+ .iter()
+ .find(|option| option.effort == effort)
+ .map(|option| option.description.to_string())
+ })
+ .filter(|text| !text.is_empty());
+
+ let show_warning = warn_for_model && warn_effort == Some(effort);
+ let selected_description = if show_warning {
+ warning_text.as_ref().map(|warning_message| {
+ description.as_ref().map_or_else(
+ || warning_message.clone(),
+ |d| format!("{d}\n{warning_message}"),
+ )
+ })
+ } else {
+ None
+ };
+
+ let model_for_action = model_slug.clone();
+ let actions = Self::model_selection_actions(model_for_action, choice.stored);
+
+ items.push(SelectionItem {
+ name: effort_label,
+ description,
+ selected_description,
+ is_current: is_current_model && choice.stored == highlight_choice,
+ actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ });
+ }
+
+ let mut header = ColumnRenderable::new();
+ header.push(Line::from(
+ format!("Select Reasoning Level for {model_slug}").bold(),
+ ));
+
+ self.bottom_pane.show_selection_view(SelectionViewParams {
+ header: Box::new(header),
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ initial_selected_idx,
+ ..Default::default()
+ });
+ }
+
+ fn reasoning_effort_label(effort: ReasoningEffortConfig) -> &'static str {
+ match effort {
+ ReasoningEffortConfig::None => "None",
+ ReasoningEffortConfig::Minimal => "Minimal",
+ ReasoningEffortConfig::Low => "Low",
+ ReasoningEffortConfig::Medium => "Medium",
+ ReasoningEffortConfig::High => "High",
+ ReasoningEffortConfig::XHigh => "Extra high",
+ }
+ }
+
+ fn apply_model_and_effort(&self, model: String, effort: Option<ReasoningEffortConfig>) {
+ self.app_event_tx
+ .send(AppEvent::CodexOp(Op::OverrideTurnContext {
+ cwd: None,
+ approval_policy: None,
+ sandbox_policy: None,
+ model: Some(model.clone()),
+ effort: Some(effort),
+ summary: None,
+ }));
+ self.app_event_tx.send(AppEvent::UpdateModel(model.clone()));
+ self.app_event_tx
+ .send(AppEvent::UpdateReasoningEffort(effort));
+ self.app_event_tx.send(AppEvent::PersistModelSelection {
+ model: model.clone(),
+ effort,
+ });
+ tracing::info!(
+ "Selected model: {}, Selected effort: {}",
+ model,
+ effort
+ .map(|e| e.to_string())
+ .unwrap_or_else(|| "default".to_string())
+ );
+ }
+
+ /// Open a popup to choose the approvals mode (ask for approval policy + sandbox policy).
+ pub(crate) fn open_approvals_popup(&mut self) {
+ let current_approval = self.config.approval_policy;
+ let current_sandbox = self.config.sandbox_policy.clone();
+ let mut items: Vec<SelectionItem> = Vec::new();
+ let presets: Vec<ApprovalPreset> = builtin_approval_presets();
+ for preset in presets.into_iter() {
+ let is_current =
+ Self::preset_matches_current(current_approval, &current_sandbox, &preset);
+ let name = preset.label.to_string();
+ let description_text = preset.description;
+ let description = Some(description_text.to_string());
+ let requires_confirmation = preset.id == "full-access"
+ && !self
+ .config
+ .notices
+ .hide_full_access_warning
+ .unwrap_or(false);
+ let actions: Vec<SelectionAction> = if requires_confirmation {
+ let preset_clone = preset.clone();
+ vec![Box::new(move |tx| {
+ tx.send(AppEvent::OpenFullAccessConfirmation {
+ preset: preset_clone.clone(),
+ });
+ })]
+ } else if preset.id == "auto" {
+ #[cfg(target_os = "windows")]
+ {
+ if codex_core::get_platform_sandbox().is_none() {
+ let preset_clone = preset.clone();
+ vec![Box::new(move |tx| {
+ tx.send(AppEvent::OpenWindowsSandboxEnablePrompt {
+ preset: preset_clone.clone(),
+ });
+ })]
+ } else if let Some((sample_paths, extra_count, failed_scan)) =
+ self.world_writable_warning_details()
+ {
+ let preset_clone = preset.clone();
+ vec![Box::new(move |tx| {
+ tx.send(AppEvent::OpenWorldWritableWarningConfirmation {
+ preset: Some(preset_clone.clone()),
+ sample_paths: sample_paths.clone(),
+ extra_count,
+ failed_scan,
+ });
+ })]
+ } else {
+ Self::approval_preset_actions(preset.approval, preset.sandbox.clone())
+ }
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ Self::approval_preset_actions(preset.approval, preset.sandbox.clone())
+ }
+ } else {
+ Self::approval_preset_actions(preset.approval, preset.sandbox.clone())
+ };
+ items.push(SelectionItem {
+ name,
+ description,
+ is_current,
+ actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ });
+ }
+
+ self.bottom_pane.show_selection_view(SelectionViewParams {
+ title: Some("Select Approval Mode".to_string()),
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ header: Box::new(()),
+ ..Default::default()
+ });
+ }
+
+ fn approval_preset_actions(
+ approval: AskForApproval,
+ sandbox: SandboxPolicy,
+ ) -> Vec<SelectionAction> {
+ vec![Box::new(move |tx| {
+ let sandbox_clone = sandbox.clone();
+ tx.send(AppEvent::CodexOp(Op::OverrideTurnContext {
+ cwd: None,
+ approval_policy: Some(approval),
+ sandbox_policy: Some(sandbox_clone.clone()),
+ model: None,
+ effort: None,
+ summary: None,
+ }));
+ tx.send(AppEvent::UpdateAskForApprovalPolicy(approval));
+ tx.send(AppEvent::UpdateSandboxPolicy(sandbox_clone));
+ })]
+ }
+
+ fn preset_matches_current(
+ current_approval: AskForApproval,
+ current_sandbox: &SandboxPolicy,
+ preset: &ApprovalPreset,
+ ) -> bool {
+ if current_approval != preset.approval {
+ return false;
+ }
+ matches!(
+ (&preset.sandbox, current_sandbox),
+ (SandboxPolicy::ReadOnly, SandboxPolicy::ReadOnly)
+ | (
+ SandboxPolicy::DangerFullAccess,
+ SandboxPolicy::DangerFullAccess
+ )
+ | (
+ SandboxPolicy::WorkspaceWrite { .. },
+ SandboxPolicy::WorkspaceWrite { .. }
+ )
+ )
+ }
+
+ #[cfg(target_os = "windows")]
+ pub(crate) fn world_writable_warning_details(&self) -> Option<(Vec<String>, usize, bool)> {
+ if self
+ .config
+ .notices
+ .hide_world_writable_warning
+ .unwrap_or(false)
+ {
+ return None;
+ }
+ let cwd = self.config.cwd.clone();
+ let env_map: std::collections::HashMap<String, String> = std::env::vars().collect();
+ match codex_windows_sandbox::apply_world_writable_scan_and_denies(
+ self.config.codex_home.as_path(),
+ cwd.as_path(),
+ &env_map,
+ &self.config.sandbox_policy,
+ Some(self.config.codex_home.as_path()),
+ ) {
+ Ok(_) => None,
+ Err(_) => Some((Vec::new(), 0, true)),
+ }
+ }
+
+ #[cfg(not(target_os = "windows"))]
+ #[allow(dead_code)]
+ pub(crate) fn world_writable_warning_details(&self) -> Option<(Vec<String>, usize, bool)> {
+ None
+ }
+
+ pub(crate) fn open_full_access_confirmation(&mut self, preset: ApprovalPreset) {
+ let approval = preset.approval;
+ let sandbox = preset.sandbox;
+ let mut header_children: Vec<Box<dyn Renderable>> = Vec::new();
+ let title_line = Line::from("Enable full access?").bold();
+ let info_line = Line::from(vec![
+ "When Codex runs with full access, it can edit any file on your computer and run commands with network, without your approval. "
+ .into(),
+ "Exercise caution when enabling full access. This significantly increases the risk of data loss, leaks, or unexpected behavior."
+ .fg(Color::Red),
+ ]);
+ header_children.push(Box::new(title_line));
+ header_children.push(Box::new(
+ Paragraph::new(vec![info_line]).wrap(Wrap { trim: false }),
+ ));
+ let header = ColumnRenderable::with(header_children);
+
+ let mut accept_actions = Self::approval_preset_actions(approval, sandbox.clone());
+ accept_actions.push(Box::new(|tx| {
+ tx.send(AppEvent::UpdateFullAccessWarningAcknowledged(true));
+ }));
+
+ let mut accept_and_remember_actions = Self::approval_preset_actions(approval, sandbox);
+ accept_and_remember_actions.push(Box::new(|tx| {
+ tx.send(AppEvent::UpdateFullAccessWarningAcknowledged(true));
+ tx.send(AppEvent::PersistFullAccessWarningAcknowledged);
+ }));
+
+ let deny_actions: Vec<SelectionAction> = vec![Box::new(|tx| {
+ tx.send(AppEvent::OpenApprovalsPopup);
+ })];
+
+ let items = vec![
+ SelectionItem {
+ name: "Yes, continue anyway".to_string(),
+ description: Some("Apply full access for this session".to_string()),
+ actions: accept_actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "Yes, and don't ask again".to_string(),
+ description: Some("Enable full access and remember this choice".to_string()),
+ actions: accept_and_remember_actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "Cancel".to_string(),
+ description: Some("Go back without enabling full access".to_string()),
+ actions: deny_actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ ];
+
+ self.bottom_pane.show_selection_view(SelectionViewParams {
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ header: Box::new(header),
+ ..Default::default()
+ });
+ }
+
+ #[cfg(target_os = "windows")]
+ pub(crate) fn open_world_writable_warning_confirmation(
+ &mut self,
+ preset: Option<ApprovalPreset>,
+ sample_paths: Vec<String>,
+ extra_count: usize,
+ failed_scan: bool,
+ ) {
+ let (approval, sandbox) = match &preset {
+ Some(p) => (Some(p.approval), Some(p.sandbox.clone())),
+ None => (None, None),
+ };
+ let mut header_children: Vec<Box<dyn Renderable>> = Vec::new();
+ let describe_policy = |policy: &SandboxPolicy| match policy {
+ SandboxPolicy::WorkspaceWrite { .. } => "Agent mode",
+ SandboxPolicy::ReadOnly => "Read-Only mode",
+ _ => "Agent mode",
+ };
+ let mode_label = preset
+ .as_ref()
+ .map(|p| describe_policy(&p.sandbox))
+ .unwrap_or_else(|| describe_policy(&self.config.sandbox_policy));
+ let info_line = if failed_scan {
+ Line::from(vec![
+ "We couldn't complete the world-writable scan, so protections cannot be verified. "
+ .into(),
+ format!("The Windows sandbox cannot guarantee protection in {mode_label}.")
+ .fg(Color::Red),
+ ])
+ } else {
+ Line::from(vec![
+ "The Windows sandbox cannot protect writes to folders that are writable by Everyone.".into(),
+ " Consider removing write access for Everyone from the following folders:".into(),
+ ])
+ };
+ header_children.push(Box::new(
+ Paragraph::new(vec![info_line]).wrap(Wrap { trim: false }),
+ ));
+
+ if !sample_paths.is_empty() {
+ // Show up to three examples and optionally an "and X more" line.
+ let mut lines: Vec<Line> = Vec::new();
+ lines.push(Line::from(""));
+ for p in &sample_paths {
+ lines.push(Line::from(format!(" - {p}")));
+ }
+ if extra_count > 0 {
+ lines.push(Line::from(format!("and {extra_count} more")));
+ }
+ header_children.push(Box::new(Paragraph::new(lines).wrap(Wrap { trim: false })));
+ }
+ let header = ColumnRenderable::with(header_children);
+
+ // Build actions ensuring acknowledgement happens before applying the new sandbox policy,
+ // so downstream policy-change hooks don't re-trigger the warning.
+ let mut accept_actions: Vec<SelectionAction> = Vec::new();
+ // Suppress the immediate re-scan only when a preset will be applied (i.e., via /approvals),
+ // to avoid duplicate warnings from the ensuing policy change.
+ if preset.is_some() {
+ accept_actions.push(Box::new(|tx| {
+ tx.send(AppEvent::SkipNextWorldWritableScan);
+ }));
+ }
+ if let (Some(approval), Some(sandbox)) = (approval, sandbox.clone()) {
+ accept_actions.extend(Self::approval_preset_actions(approval, sandbox));
+ }
+
+ let mut accept_and_remember_actions: Vec<SelectionAction> = Vec::new();
+ accept_and_remember_actions.push(Box::new(|tx| {
+ tx.send(AppEvent::UpdateWorldWritableWarningAcknowledged(true));
+ tx.send(AppEvent::PersistWorldWritableWarningAcknowledged);
+ }));
+ if let (Some(approval), Some(sandbox)) = (approval, sandbox) {
+ accept_and_remember_actions.extend(Self::approval_preset_actions(approval, sandbox));
+ }
+
+ let items = vec![
+ SelectionItem {
+ name: "Continue".to_string(),
+ description: Some(format!("Apply {mode_label} for this session")),
+ actions: accept_actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "Continue and don't warn again".to_string(),
+ description: Some(format!("Enable {mode_label} and remember this choice")),
+ actions: accept_and_remember_actions,
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ ];
+
+ self.bottom_pane.show_selection_view(SelectionViewParams {
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ header: Box::new(header),
+ ..Default::default()
+ });
+ }
+
+ #[cfg(not(target_os = "windows"))]
+ pub(crate) fn open_world_writable_warning_confirmation(
+ &mut self,
+ _preset: Option<ApprovalPreset>,
+ _sample_paths: Vec<String>,
+ _extra_count: usize,
+ _failed_scan: bool,
+ ) {
+ }
+
+ #[cfg(target_os = "windows")]
+ pub(crate) fn open_windows_sandbox_enable_prompt(&mut self, preset: ApprovalPreset) {
+ use ratatui_macros::line;
+
+ let mut header = ColumnRenderable::new();
+ header.push(*Box::new(
+ Paragraph::new(vec![
+ line!["Agent mode on Windows uses an experimental sandbox to limit network and filesystem access.".bold()],
+ line![
+ "Learn more: https://developers.openai.com/codex/windows"
+ ],
+ ])
+ .wrap(Wrap { trim: false }),
+ ));
+
+ let preset_clone = preset;
+ let items = vec![
+ SelectionItem {
+ name: "Enable experimental sandbox".to_string(),
+ description: None,
+ actions: vec![Box::new(move |tx| {
+ tx.send(AppEvent::EnableWindowsSandboxForAgentMode {
+ preset: preset_clone.clone(),
+ });
+ })],
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ SelectionItem {
+ name: "Go back".to_string(),
+ description: None,
+ actions: vec![Box::new(|tx| {
+ tx.send(AppEvent::OpenApprovalsPopup);
+ })],
+ dismiss_on_select: true,
+ ..Default::default()
+ },
+ ];
+
+ self.bottom_pane.show_selection_view(SelectionViewParams {
+ title: None,
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ header: Box::new(header),
+ ..Default::default()
+ });
+ }
+
+ #[cfg(not(target_os = "windows"))]
+ pub(crate) fn open_windows_sandbox_enable_prompt(&mut self, _preset: ApprovalPreset) {}
+
+ #[cfg(target_os = "windows")]
+ pub(crate) fn maybe_prompt_windows_sandbox_enable(&mut self) {
+ if self.config.forced_auto_mode_downgraded_on_windows
+ && codex_core::get_platform_sandbox().is_none()
+ && let Some(preset) = builtin_approval_presets()
+ .into_iter()
+ .find(|preset| preset.id == "auto")
+ {
+ self.open_windows_sandbox_enable_prompt(preset);
+ }
+ }
+
+ #[cfg(not(target_os = "windows"))]
+ pub(crate) fn maybe_prompt_windows_sandbox_enable(&mut self) {}
+
+ #[cfg(target_os = "windows")]
+ pub(crate) fn clear_forced_auto_mode_downgrade(&mut self) {
+ self.config.forced_auto_mode_downgraded_on_windows = false;
+ }
+
+ #[cfg(not(target_os = "windows"))]
+ #[allow(dead_code)]
+ pub(crate) fn clear_forced_auto_mode_downgrade(&mut self) {}
+
+ /// Set the approval policy in the widget's config copy.
+ pub(crate) fn set_approval_policy(&mut self, policy: AskForApproval) {
+ self.config.approval_policy = policy;
+ }
+
+ /// Set the sandbox policy in the widget's config copy.
+ pub(crate) fn set_sandbox_policy(&mut self, policy: SandboxPolicy) {
+ #[cfg(target_os = "windows")]
+ let should_clear_downgrade = !matches!(policy, SandboxPolicy::ReadOnly)
+ || codex_core::get_platform_sandbox().is_some();
+
+ self.config.sandbox_policy = policy;
+
+ #[cfg(target_os = "windows")]
+ if should_clear_downgrade {
+ self.config.forced_auto_mode_downgraded_on_windows = false;
+ }
+ }
+
+ pub(crate) fn set_full_access_warning_acknowledged(&mut self, acknowledged: bool) {
+ self.config.notices.hide_full_access_warning = Some(acknowledged);
+ }
+
+ pub(crate) fn set_world_writable_warning_acknowledged(&mut self, acknowledged: bool) {
+ self.config.notices.hide_world_writable_warning = Some(acknowledged);
+ }
+
+ pub(crate) fn set_rate_limit_switch_prompt_hidden(&mut self, hidden: bool) {
+ self.config.notices.hide_rate_limit_model_nudge = Some(hidden);
+ if hidden {
+ self.rate_limit_switch_prompt = RateLimitSwitchPromptState::Idle;
+ }
+ }
+
+ #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
+ pub(crate) fn world_writable_warning_hidden(&self) -> bool {
+ self.config
+ .notices
+ .hide_world_writable_warning
+ .unwrap_or(false)
+ }
+
+ /// Set the reasoning effort in the widget's config copy.
+ pub(crate) fn set_reasoning_effort(&mut self, effort: Option<ReasoningEffortConfig>) {
+ self.config.model_reasoning_effort = effort;
+ }
+
+ /// Set the model in the widget's config copy.
+ pub(crate) fn set_model(&mut self, model: &str, model_family: ModelFamily) {
+ self.session_header.set_model(model);
+ self.model_family = model_family;
+ }
+
+ pub(crate) fn add_info_message(&mut self, message: String, hint: Option<String>) {
+ self.add_to_history(history_cell::new_info_event(message, hint));
+ self.request_redraw();
+ }
+
+ pub(crate) fn add_plain_history_lines(&mut self, lines: Vec<Line<'static>>) {
+ self.add_boxed_history(Box::new(PlainHistoryCell::new(lines)));
+ self.request_redraw();
+ }
+
+ pub(crate) fn add_error_message(&mut self, message: String) {
+ self.add_to_history(history_cell::new_error_event(message));
+ self.request_redraw();
+ }
+
+ pub(crate) fn add_mcp_output(&mut self) {
+ if self.config.mcp_servers.is_empty() {
+ self.add_to_history(history_cell::empty_mcp_output());
+ } else {
+ self.submit_op(Op::ListMcpTools);
+ }
+ }
+
+ /// Forward file-search results to the bottom pane.
+ pub(crate) fn apply_file_search_result(&mut self, query: String, matches: Vec<FileMatch>) {
+ self.bottom_pane.on_file_search_result(query, matches);
+ }
+
+ /// Handle Ctrl-C key press.
+ fn on_ctrl_c(&mut self) {
+ if self.bottom_pane.on_ctrl_c() == CancellationEvent::Handled {
+ return;
+ }
+
+ if self.bottom_pane.is_task_running() {
+ self.bottom_pane.show_ctrl_c_quit_hint();
+ self.submit_op(Op::Interrupt);
+ return;
+ }
+
+ self.submit_op(Op::Shutdown);
+ }
+
+ pub(crate) fn composer_is_empty(&self) -> bool {
+ self.bottom_pane.composer_is_empty()
+ }
+
+ /// True when the UI is in the regular composer state with no running task,
+ /// no modal overlay (e.g. approvals or status indicator), and no composer popups.
+ /// In this state Esc-Esc backtracking is enabled.
+ pub(crate) fn is_normal_backtrack_mode(&self) -> bool {
+ self.bottom_pane.is_normal_backtrack_mode()
+ }
+
+ pub(crate) fn insert_str(&mut self, text: &str) {
+ self.bottom_pane.insert_str(text);
+ }
+
+ /// Replace the composer content with the provided text and reset cursor.
+ pub(crate) fn set_composer_text(&mut self, text: String) {
+ self.bottom_pane.set_composer_text(text);
+ }
+
+ pub(crate) fn show_esc_backtrack_hint(&mut self) {
+ self.bottom_pane.show_esc_backtrack_hint();
+ }
+
+ pub(crate) fn clear_esc_backtrack_hint(&mut self) {
+ self.bottom_pane.clear_esc_backtrack_hint();
+ }
+ /// Forward an `Op` directly to codex.
+ pub(crate) fn submit_op(&self, op: Op) {
+ // Record outbound operation for session replay fidelity.
+ crate::session_log::log_outbound_op(&op);
+ if let Err(e) = self.codex_op_tx.send(op) {
+ tracing::error!("failed to submit op: {e}");
+ }
+ }
+
+ fn on_list_mcp_tools(&mut self, ev: McpListToolsResponseEvent) {
+ self.add_to_history(history_cell::new_mcp_tools_output(
+ &self.config,
+ ev.tools,
+ ev.resources,
+ ev.resource_templates,
+ &ev.auth_statuses,
+ ));
+ }
+
+ fn on_list_custom_prompts(&mut self, ev: ListCustomPromptsResponseEvent) {
+ let len = ev.custom_prompts.len();
+ debug!("received {len} custom prompts");
+ // Forward to bottom pane so the slash popup can show them now.
+ self.bottom_pane.set_custom_prompts(ev.custom_prompts);
+ }
+
+ pub(crate) fn open_review_popup(&mut self) {
+ let mut items: Vec<SelectionItem> = Vec::new();
+
+ items.push(SelectionItem {
+ name: "Review against a base branch".to_string(),
+ description: Some("(PR Style)".into()),
+ actions: vec![Box::new({
+ let cwd = self.config.cwd.clone();
+ move |tx| {
+ tx.send(AppEvent::OpenReviewBranchPicker(cwd.clone()));
+ }
+ })],
+ dismiss_on_select: false,
+ ..Default::default()
+ });
+
+ items.push(SelectionItem {
+ name: "Review uncommitted changes".to_string(),
+ actions: vec![Box::new(move |tx: &AppEventSender| {
+ tx.send(AppEvent::CodexOp(Op::Review {
+ review_request: ReviewRequest {
+ target: ReviewTarget::UncommittedChanges,
+ user_facing_hint: None,
+ },
+ }));
+ })],
+ dismiss_on_select: true,
+ ..Default::default()
+ });
+
+ // New: Review a specific commit (opens commit picker)
+ items.push(SelectionItem {
+ name: "Review a commit".to_string(),
+ actions: vec![Box::new({
+ let cwd = self.config.cwd.clone();
+ move |tx| {
+ tx.send(AppEvent::OpenReviewCommitPicker(cwd.clone()));
+ }
+ })],
+ dismiss_on_select: false,
+ ..Default::default()
+ });
+
+ items.push(SelectionItem {
+ name: "Custom review instructions".to_string(),
+ actions: vec![Box::new(move |tx| {
+ tx.send(AppEvent::OpenReviewCustomPrompt);
+ })],
+ dismiss_on_select: false,
+ ..Default::default()
+ });
+
+ self.bottom_pane.show_selection_view(SelectionViewParams {
+ title: Some("Select a review preset".into()),
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ ..Default::default()
+ });
+ }
+
+ pub(crate) async fn show_review_branch_picker(&mut self, cwd: &Path) {
+ let branches = local_git_branches(cwd).await;
+ let current_branch = current_branch_name(cwd)
+ .await
+ .unwrap_or_else(|| "(detached HEAD)".to_string());
+ let mut items: Vec<SelectionItem> = Vec::with_capacity(branches.len());
+
+ for option in branches {
+ let branch = option.clone();
+ items.push(SelectionItem {
+ name: format!("{current_branch} -> {branch}"),
+ actions: vec![Box::new(move |tx3: &AppEventSender| {
+ tx3.send(AppEvent::CodexOp(Op::Review {
+ review_request: ReviewRequest {
+ target: ReviewTarget::BaseBranch {
+ branch: branch.clone(),
+ },
+ user_facing_hint: None,
+ },
+ }));
+ })],
+ dismiss_on_select: true,
+ search_value: Some(option),
+ ..Default::default()
+ });
+ }
+
+ self.bottom_pane.show_selection_view(SelectionViewParams {
+ title: Some("Select a base branch".to_string()),
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ is_searchable: true,
+ search_placeholder: Some("Type to search branches".to_string()),
+ ..Default::default()
+ });
+ }
+
+ pub(crate) async fn show_review_commit_picker(&mut self, cwd: &Path) {
+ let commits = codex_core::git_info::recent_commits(cwd, 100).await;
+
+ let mut items: Vec<SelectionItem> = Vec::with_capacity(commits.len());
+ for entry in commits {
+ let subject = entry.subject.clone();
+ let sha = entry.sha.clone();
+ let search_val = format!("{subject} {sha}");
+
+ items.push(SelectionItem {
+ name: subject.clone(),
+ actions: vec![Box::new(move |tx3: &AppEventSender| {
+ tx3.send(AppEvent::CodexOp(Op::Review {
+ review_request: ReviewRequest {
+ target: ReviewTarget::Commit {
+ sha: sha.clone(),
+ title: Some(subject.clone()),
+ },
+ user_facing_hint: None,
+ },
+ }));
+ })],
+ dismiss_on_select: true,
+ search_value: Some(search_val),
+ ..Default::default()
+ });
+ }
+
+ self.bottom_pane.show_selection_view(SelectionViewParams {
+ title: Some("Select a commit to review".to_string()),
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ is_searchable: true,
+ search_placeholder: Some("Type to search commits".to_string()),
+ ..Default::default()
+ });
+ }
+
+ pub(crate) fn show_review_custom_prompt(&mut self) {
+ let tx = self.app_event_tx.clone();
+ let view = CustomPromptView::new(
+ "Custom review instructions".to_string(),
+ "Type instructions and press Enter".to_string(),
+ None,
+ Box::new(move |prompt: String| {
+ let trimmed = prompt.trim().to_string();
+ if trimmed.is_empty() {
+ return;
+ }
+ tx.send(AppEvent::CodexOp(Op::Review {
+ review_request: ReviewRequest {
+ target: ReviewTarget::Custom {
+ instructions: trimmed,
+ },
+ user_facing_hint: None,
+ },
+ }));
+ }),
+ );
+ self.bottom_pane.show_view(Box::new(view));
+ }
+
+ pub(crate) fn token_usage(&self) -> TokenUsage {
+ self.token_info
+ .as_ref()
+ .map(|ti| ti.total_token_usage.clone())
+ .unwrap_or_default()
+ }
+
+ pub(crate) fn conversation_id(&self) -> Option<ConversationId> {
+ self.conversation_id
+ }
+
+ pub(crate) fn rollout_path(&self) -> Option<PathBuf> {
+ self.current_rollout_path.clone()
+ }
+
+ /// Return a reference to the widget's current config (includes any
+ /// runtime overrides applied via TUI, e.g., model or approval policy).
+ pub(crate) fn config_ref(&self) -> &Config {
+ &self.config
+ }
+
+ pub(crate) fn clear_token_usage(&mut self) {
+ self.token_info = None;
+ }
+
+ fn as_renderable(&self) -> RenderableItem<'_> {
+ let active_cell_renderable = match &self.active_cell {
+ Some(cell) => RenderableItem::Borrowed(cell).inset(Insets::tlbr(1, 0, 0, 0)),
+ None => RenderableItem::Owned(Box::new(())),
+ };
+ let mut flex = FlexRenderable::new();
+ flex.push(1, active_cell_renderable);
+ flex.push(
+ 0,
+ RenderableItem::Borrowed(&self.bottom_pane).inset(Insets::tlbr(1, 0, 0, 0)),
+ );
+ RenderableItem::Owned(Box::new(flex))
+ }
+}
+
+impl Drop for ChatWidget {
+ fn drop(&mut self) {
+ self.stop_rate_limit_poller();
+ }
+}
+
+impl Renderable for ChatWidget {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ self.as_renderable().render(area, buf);
+ self.last_rendered_width.set(Some(area.width as usize));
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ self.as_renderable().desired_height(width)
+ }
+
+ fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ self.as_renderable().cursor_pos(area)
+ }
+}
+
+enum Notification {
+ AgentTurnComplete { response: String },
+ ExecApprovalRequested { command: String },
+ EditApprovalRequested { cwd: PathBuf, changes: Vec<PathBuf> },
+ ElicitationRequested { server_name: String },
+}
+
+impl Notification {
+ fn display(&self) -> String {
+ match self {
+ Notification::AgentTurnComplete { response } => {
+ Notification::agent_turn_preview(response)
+ .unwrap_or_else(|| "Agent turn complete".to_string())
+ }
+ Notification::ExecApprovalRequested { command } => {
+ format!("Approval requested: {}", truncate_text(command, 30))
+ }
+ Notification::EditApprovalRequested { cwd, changes } => {
+ format!(
+ "Codex wants to edit {}",
+ if changes.len() == 1 {
+ #[allow(clippy::unwrap_used)]
+ display_path_for(changes.first().unwrap(), cwd)
+ } else {
+ format!("{} files", changes.len())
+ }
+ )
+ }
+ Notification::ElicitationRequested { server_name } => {
+ format!("Approval requested by {server_name}")
+ }
+ }
+ }
+
+ fn type_name(&self) -> &str {
+ match self {
+ Notification::AgentTurnComplete { .. } => "agent-turn-complete",
+ Notification::ExecApprovalRequested { .. }
+ | Notification::EditApprovalRequested { .. }
+ | Notification::ElicitationRequested { .. } => "approval-requested",
+ }
+ }
+
+ fn allowed_for(&self, settings: &Notifications) -> bool {
+ match settings {
+ Notifications::Enabled(enabled) => *enabled,
+ Notifications::Custom(allowed) => allowed.iter().any(|a| a == self.type_name()),
+ }
+ }
+
+ fn agent_turn_preview(response: &str) -> Option<String> {
+ let mut normalized = String::new();
+ for part in response.split_whitespace() {
+ if !normalized.is_empty() {
+ normalized.push(' ');
+ }
+ normalized.push_str(part);
+ }
+ let trimmed = normalized.trim();
+ if trimmed.is_empty() {
+ None
+ } else {
+ Some(truncate_text(trimmed, AGENT_NOTIFICATION_PREVIEW_GRAPHEMES))
+ }
+ }
+}
+
+const AGENT_NOTIFICATION_PREVIEW_GRAPHEMES: usize = 200;
+
+const EXAMPLE_PROMPTS: [&str; 6] = [
+ "Explain this codebase",
+ "Summarize recent commits",
+ "Implement {feature}",
+ "Find and fix a bug in @filename",
+ "Write tests for @filename",
+ "Improve documentation in @filename",
+];
+
+// Extract the first bold (Markdown) element in the form **...** from `s`.
+// Returns the inner text if found; otherwise `None`.
+fn extract_first_bold(s: &str) -> Option<String> {
+ let bytes = s.as_bytes();
+ let mut i = 0usize;
+ while i + 1 < bytes.len() {
+ if bytes[i] == b'*' && bytes[i + 1] == b'*' {
+ let start = i + 2;
+ let mut j = start;
+ while j + 1 < bytes.len() {
+ if bytes[j] == b'*' && bytes[j + 1] == b'*' {
+ // Found closing **
+ let inner = &s[start..j];
+ let trimmed = inner.trim();
+ if !trimmed.is_empty() {
+ return Some(trimmed.to_string());
+ } else {
+ return None;
+ }
+ }
+ j += 1;
+ }
+ // No closing; stop searching (wait for more deltas)
+ return None;
+ }
+ i += 1;
+ }
+ None
+}
+
+async fn fetch_rate_limits(base_url: String, auth: CodexAuth) -> Option<RateLimitSnapshot> {
+ match BackendClient::from_auth(base_url, &auth).await {
+ Ok(client) => match client.get_rate_limits().await {
+ Ok(snapshot) => Some(snapshot),
+ Err(err) => {
+ debug!(error = ?err, "failed to fetch rate limits from /usage");
+ None
+ }
+ },
+ Err(err) => {
+ debug!(error = ?err, "failed to construct backend client for rate limits");
+ None
+ }
+ }
+}
+
+#[cfg(test)]
+pub(crate) fn show_review_commit_picker_with_entries(
+ chat: &mut ChatWidget,
+ entries: Vec<codex_core::git_info::CommitLogEntry>,
+) {
+ let mut items: Vec<SelectionItem> = Vec::with_capacity(entries.len());
+ for entry in entries {
+ let subject = entry.subject.clone();
+ let sha = entry.sha.clone();
+ let search_val = format!("{subject} {sha}");
+
+ items.push(SelectionItem {
+ name: subject.clone(),
+ actions: vec![Box::new(move |tx3: &AppEventSender| {
+ tx3.send(AppEvent::CodexOp(Op::Review {
+ review_request: ReviewRequest {
+ target: ReviewTarget::Commit {
+ sha: sha.clone(),
+ title: Some(subject.clone()),
+ },
+ user_facing_hint: None,
+ },
+ }));
+ })],
+ dismiss_on_select: true,
+ search_value: Some(search_val),
+ ..Default::default()
+ });
+ }
+
+ chat.bottom_pane.show_selection_view(SelectionViewParams {
+ title: Some("Select a commit to review".to_string()),
+ footer_hint: Some(standard_popup_hint_line()),
+ items,
+ is_searchable: true,
+ search_placeholder: Some("Type to search commits".to_string()),
+ ..Default::default()
+ });
+}
+
+#[cfg(test)]
+pub(crate) mod tests;
diff --git a/codex-rs/tui2/src/chatwidget/agent.rs b/codex-rs/tui2/src/chatwidget/agent.rs
new file mode 100644
index 0000000000..240972347f
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/agent.rs
@@ -0,0 +1,108 @@
+use std::sync::Arc;
+
+use codex_core::CodexConversation;
+use codex_core::ConversationManager;
+use codex_core::NewConversation;
+use codex_core::config::Config;
+use codex_core::protocol::Event;
+use codex_core::protocol::EventMsg;
+use codex_core::protocol::Op;
+use tokio::sync::mpsc::UnboundedSender;
+use tokio::sync::mpsc::unbounded_channel;
+
+use crate::app_event::AppEvent;
+use crate::app_event_sender::AppEventSender;
+
+/// Spawn the agent bootstrapper and op forwarding loop, returning the
+/// `UnboundedSender<Op>` used by the UI to submit operations.
+pub(crate) fn spawn_agent(
+ config: Config,
+ app_event_tx: AppEventSender,
+ server: Arc<ConversationManager>,
+) -> UnboundedSender<Op> {
+ let (codex_op_tx, mut codex_op_rx) = unbounded_channel::<Op>();
+
+ let app_event_tx_clone = app_event_tx;
+ tokio::spawn(async move {
+ let NewConversation {
+ conversation_id: _,
+ conversation,
+ session_configured,
+ } = match server.new_conversation(config).await {
+ Ok(v) => v,
+ #[allow(clippy::print_stderr)]
+ Err(err) => {
+ let message = err.to_string();
+ eprintln!("{message}");
+ app_event_tx_clone.send(AppEvent::CodexEvent(Event {
+ id: "".to_string(),
+ msg: EventMsg::Error(err.to_error_event(None)),
+ }));
+ app_event_tx_clone.send(AppEvent::ExitRequest);
+ tracing::error!("failed to initialize codex: {err}");
+ return;
+ }
+ };
+
+ // Forward the captured `SessionConfigured` event so it can be rendered in the UI.
+ let ev = codex_core::protocol::Event {
+ // The `id` does not matter for rendering, so we can use a fake value.
+ id: "".to_string(),
+ msg: codex_core::protocol::EventMsg::SessionConfigured(session_configured),
+ };
+ app_event_tx_clone.send(AppEvent::CodexEvent(ev));
+
+ let conversation_clone = conversation.clone();
+ tokio::spawn(async move {
+ while let Some(op) = codex_op_rx.recv().await {
+ let id = conversation_clone.submit(op).await;
+ if let Err(e) = id {
+ tracing::error!("failed to submit op: {e}");
+ }
+ }
+ });
+
+ while let Ok(event) = conversation.next_event().await {
+ app_event_tx_clone.send(AppEvent::CodexEvent(event));
+ }
+ });
+
+ codex_op_tx
+}
+
+/// Spawn agent loops for an existing conversation (e.g., a forked conversation).
+/// Sends the provided `SessionConfiguredEvent` immediately, then forwards subsequent
+/// events and accepts Ops for submission.
+pub(crate) fn spawn_agent_from_existing(
+ conversation: std::sync::Arc<CodexConversation>,
+ session_configured: codex_core::protocol::SessionConfiguredEvent,
+ app_event_tx: AppEventSender,
+) -> UnboundedSender<Op> {
+ let (codex_op_tx, mut codex_op_rx) = unbounded_channel::<Op>();
+
+ let app_event_tx_clone = app_event_tx;
+ tokio::spawn(async move {
+ // Forward the captured `SessionConfigured` event so it can be rendered in the UI.
+ let ev = codex_core::protocol::Event {
+ id: "".to_string(),
+ msg: codex_core::protocol::EventMsg::SessionConfigured(session_configured),
+ };
+ app_event_tx_clone.send(AppEvent::CodexEvent(ev));
+
+ let conversation_clone = conversation.clone();
+ tokio::spawn(async move {
+ while let Some(op) = codex_op_rx.recv().await {
+ let id = conversation_clone.submit(op).await;
+ if let Err(e) = id {
+ tracing::error!("failed to submit op: {e}");
+ }
+ }
+ });
+
+ while let Ok(event) = conversation.next_event().await {
+ app_event_tx_clone.send(AppEvent::CodexEvent(event));
+ }
+ });
+
+ codex_op_tx
+}
diff --git a/codex-rs/tui2/src/chatwidget/interrupts.rs b/codex-rs/tui2/src/chatwidget/interrupts.rs
new file mode 100644
index 0000000000..dc1e683ea5
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/interrupts.rs
@@ -0,0 +1,96 @@
+use std::collections::VecDeque;
+
+use codex_core::protocol::ApplyPatchApprovalRequestEvent;
+use codex_core::protocol::ExecApprovalRequestEvent;
+use codex_core::protocol::ExecCommandBeginEvent;
+use codex_core::protocol::ExecCommandEndEvent;
+use codex_core::protocol::McpToolCallBeginEvent;
+use codex_core::protocol::McpToolCallEndEvent;
+use codex_core::protocol::PatchApplyEndEvent;
+use codex_protocol::approvals::ElicitationRequestEvent;
+
+use super::ChatWidget;
+
+#[derive(Debug)]
+pub(crate) enum QueuedInterrupt {
+ ExecApproval(String, ExecApprovalRequestEvent),
+ ApplyPatchApproval(String, ApplyPatchApprovalRequestEvent),
+ Elicitation(ElicitationRequestEvent),
+ ExecBegin(ExecCommandBeginEvent),
+ ExecEnd(ExecCommandEndEvent),
+ McpBegin(McpToolCallBeginEvent),
+ McpEnd(McpToolCallEndEvent),
+ PatchEnd(PatchApplyEndEvent),
+}
+
+#[derive(Default)]
+pub(crate) struct InterruptManager {
+ queue: VecDeque<QueuedInterrupt>,
+}
+
+impl InterruptManager {
+ pub(crate) fn new() -> Self {
+ Self {
+ queue: VecDeque::new(),
+ }
+ }
+
+ #[inline]
+ pub(crate) fn is_empty(&self) -> bool {
+ self.queue.is_empty()
+ }
+
+ pub(crate) fn push_exec_approval(&mut self, id: String, ev: ExecApprovalRequestEvent) {
+ self.queue.push_back(QueuedInterrupt::ExecApproval(id, ev));
+ }
+
+ pub(crate) fn push_apply_patch_approval(
+ &mut self,
+ id: String,
+ ev: ApplyPatchApprovalRequestEvent,
+ ) {
+ self.queue
+ .push_back(QueuedInterrupt::ApplyPatchApproval(id, ev));
+ }
+
+ pub(crate) fn push_elicitation(&mut self, ev: ElicitationRequestEvent) {
+ self.queue.push_back(QueuedInterrupt::Elicitation(ev));
+ }
+
+ pub(crate) fn push_exec_begin(&mut self, ev: ExecCommandBeginEvent) {
+ self.queue.push_back(QueuedInterrupt::ExecBegin(ev));
+ }
+
+ pub(crate) fn push_exec_end(&mut self, ev: ExecCommandEndEvent) {
+ self.queue.push_back(QueuedInterrupt::ExecEnd(ev));
+ }
+
+ pub(crate) fn push_mcp_begin(&mut self, ev: McpToolCallBeginEvent) {
+ self.queue.push_back(QueuedInterrupt::McpBegin(ev));
+ }
+
+ pub(crate) fn push_mcp_end(&mut self, ev: McpToolCallEndEvent) {
+ self.queue.push_back(QueuedInterrupt::McpEnd(ev));
+ }
+
+ pub(crate) fn push_patch_end(&mut self, ev: PatchApplyEndEvent) {
+ self.queue.push_back(QueuedInterrupt::PatchEnd(ev));
+ }
+
+ pub(crate) fn flush_all(&mut self, chat: &mut ChatWidget) {
+ while let Some(q) = self.queue.pop_front() {
+ match q {
+ QueuedInterrupt::ExecApproval(id, ev) => chat.handle_exec_approval_now(id, ev),
+ QueuedInterrupt::ApplyPatchApproval(id, ev) => {
+ chat.handle_apply_patch_approval_now(id, ev)
+ }
+ QueuedInterrupt::Elicitation(ev) => chat.handle_elicitation_request_now(ev),
+ QueuedInterrupt::ExecBegin(ev) => chat.handle_exec_begin_now(ev),
+ QueuedInterrupt::ExecEnd(ev) => chat.handle_exec_end_now(ev),
+ QueuedInterrupt::McpBegin(ev) => chat.handle_mcp_begin_now(ev),
+ QueuedInterrupt::McpEnd(ev) => chat.handle_mcp_end_now(ev),
+ QueuedInterrupt::PatchEnd(ev) => chat.handle_patch_apply_end_now(ev),
+ }
+ }
+ }
+}
diff --git a/codex-rs/tui2/src/chatwidget/session_header.rs b/codex-rs/tui2/src/chatwidget/session_header.rs
new file mode 100644
index 0000000000..32e31b6682
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/session_header.rs
@@ -0,0 +1,16 @@
+pub(crate) struct SessionHeader {
+ model: String,
+}
+
+impl SessionHeader {
+ pub(crate) fn new(model: String) -> Self {
+ Self { model }
+ }
+
+ /// Updates the header's model text.
+ pub(crate) fn set_model(&mut self, model: &str) {
+ if self.model != model {
+ self.model = model.to_string();
+ }
+ }
+}
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__apply_patch_manual_flow_history_approved.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__apply_patch_manual_flow_history_approved.snap
new file mode 100644
index 0000000000..26c7f58709
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__apply_patch_manual_flow_history_approved.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: lines_to_single_string(&approved_lines)
+---
+• Added foo.txt (+1 -0)
+ 1 +hello
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approval_modal_exec.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approval_modal_exec.snap
new file mode 100644
index 0000000000..c69730b483
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approval_modal_exec.snap
@@ -0,0 +1,15 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: terminal.backend().vt100().screen().contents()
+---
+ 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)
+
+ Press enter to confirm or esc to cancel
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approval_modal_exec_no_reason.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approval_modal_exec_no_reason.snap
new file mode 100644
index 0000000000..ab469f34b6
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approval_modal_exec_no_reason.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: terminal.backend().vt100().screen().contents()
+---
+ Would you like to run the following command?
+
+ $ 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)
+
+ Press enter to confirm or esc to cancel
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approval_modal_patch.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approval_modal_patch.snap
new file mode 100644
index 0000000000..a5bfd136b7
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approval_modal_patch.snap
@@ -0,0 +1,17 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: terminal.backend().vt100().screen().contents()
+---
+ Would you like to make the following edits?
+
+ Reason: The model wants to apply changes
+
+ README.md (+2 -0)
+
+ 1 +hello
+ 2 +world
+
+› 1. Yes, proceed (y)
+ 2. No, and tell Codex what to do differently (esc)
+
+ Press enter to confirm or esc to cancel
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approvals_selection_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approvals_selection_popup.snap
new file mode 100644
index 0000000000..46ec74d117
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approvals_selection_popup.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: popup
+---
+ Select Approval Mode
+
+› 1. Read Only (current) Requires approval to edit files and run commands.
+ 2. Agent Read and edit files, and run commands.
+ 3. Agent (full access) Codex can edit files outside this workspace and run
+ commands with network access. Exercise caution when
+ using.
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approvals_selection_popup@windows.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approvals_selection_popup@windows.snap
new file mode 100644
index 0000000000..5024b90a62
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__approvals_selection_popup@windows.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: popup
+---
+ Select Approval Mode
+
+› 1. Read Only (current) Requires approval to edit files and run commands.
+ 2. Agent Read and edit files, and run commands.
+ 3. Agent (full access) Codex can edit files outside this workspace and run
+ commands with network access. Exercise caution when
+ using.
+
+ Press enter to confirm or esc to go back
+
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_idle_h1.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_idle_h1.snap
new file mode 100644
index 0000000000..8900e83d9a
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_idle_h1.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_idle_h2.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_idle_h2.snap
new file mode 100644
index 0000000000..a2afe14dfa
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_idle_h2.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_idle_h3.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_idle_h3.snap
new file mode 100644
index 0000000000..1b285fb810
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_idle_h3.snap
@@ -0,0 +1,7 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_running_h1.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_running_h1.snap
new file mode 100644
index 0000000000..8900e83d9a
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_running_h1.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_running_h2.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_running_h2.snap
new file mode 100644
index 0000000000..a2afe14dfa
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_running_h2.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_running_h3.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_running_h3.snap
new file mode 100644
index 0000000000..1b285fb810
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chat_small_running_h3.snap
@@ -0,0 +1,7 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap
new file mode 100644
index 0000000000..a447b748bb
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap
@@ -0,0 +1,17 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: term.backend().vt100().screen().contents()
+---
+• I’m going to search the repo for where “Change Approved” is rendered to update
+ that view.
+
+• Explored
+ └ Search Change Approved
+ Read diff_render.rs
+
+• Investigating rendering code (0s • esc to interrupt)
+
+
+› Summarize recent commits
+
+ 100% context left
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chatwidget_markdown_code_blocks_vt100_snapshot.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chatwidget_markdown_code_blocks_vt100_snapshot.snap
new file mode 100644
index 0000000000..9ab9b03380
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chatwidget_markdown_code_blocks_vt100_snapshot.snap
@@ -0,0 +1,18 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: term.backend().vt100().screen().contents()
+---
+• -- Indented code block (4 spaces)
+ SELECT *
+ FROM "users"
+ WHERE "email" LIKE '%@example.com';
+
+ ```sh
+ printf 'fenced within fenced\n'
+ ```
+
+ {
+ // comment allowed in jsonc
+ "path": "C:\\Program Files\\App",
+ "regex": "^foo.*(bar)?$"
+ }
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chatwidget_tall.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chatwidget_tall.snap
new file mode 100644
index 0000000000..3cc0b593d4
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__chatwidget_tall.snap
@@ -0,0 +1,27 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: term.backend().vt100().screen().contents()
+---
+• Working (0s • esc to interrupt)
+ ↳ Hello, world! 0
+ ↳ Hello, world! 1
+ ↳ Hello, world! 2
+ ↳ Hello, world! 3
+ ↳ Hello, world! 4
+ ↳ Hello, world! 5
+ ↳ Hello, world! 6
+ ↳ Hello, world! 7
+ ↳ Hello, world! 8
+ ↳ Hello, world! 9
+ ↳ Hello, world! 10
+ ↳ Hello, world! 11
+ ↳ Hello, world! 12
+ ↳ Hello, world! 13
+ ↳ Hello, world! 14
+ ↳ Hello, world! 15
+ ↳ Hello, world! 16
+
+
+› Ask Codex to do anything
+
+ 100% context left · ? for shortcuts
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap
new file mode 100644
index 0000000000..3d83bdb0f5
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: combined
+---
+• Here is the result.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__disabled_slash_command_while_task_running_snapshot.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__disabled_slash_command_while_task_running_snapshot.snap
new file mode 100644
index 0000000000..6d252a0d3e
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__disabled_slash_command_while_task_running_snapshot.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: blob
+---
+■ '/model' is disabled while a task is in progress.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_history_decision_aborted_long.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_history_decision_aborted_long.snap
new file mode 100644
index 0000000000..50c0828773
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_history_decision_aborted_long.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: lines_to_single_string(&aborted_long)
+---
+✗ You canceled the request to run echo
+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_history_decision_aborted_multiline.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_history_decision_aborted_multiline.snap
new file mode 100644
index 0000000000..d7e1e2ac3a
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_history_decision_aborted_multiline.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: lines_to_single_string(&aborted_multi)
+---
+✗ You canceled the request to run echo line1 ...
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_history_decision_approved_short.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_history_decision_approved_short.snap
new file mode 100644
index 0000000000..2d3767dffb
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_history_decision_approved_short.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: lines_to_single_string(&decision)
+---
+✔ You approved codex to run echo hello world this time
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_modal_exec.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_modal_exec.snap
new file mode 100644
index 0000000000..93451be714
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exec_approval_modal_exec.snap
@@ -0,0 +1,36 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 80, height: 13 },
+ content: [
+ " ",
+ " ",
+ " 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. No, and tell Codex what to do differently (esc) ",
+ " ",
+ " Press enter to confirm or esc to cancel ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 2, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
+ x: 46, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 10, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: ITALIC,
+ x: 73, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 2, y: 5, fg: Reset, bg: Reset, underline: Reset, modifier: ITALIC,
+ x: 7, y: 5, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 9, fg: Cyan, bg: Reset, underline: Reset, modifier: BOLD,
+ x: 21, y: 9, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 48, y: 10, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 51, y: 10, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 2, y: 12, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ ]
+}
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step1_start_ls.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step1_start_ls.snap
new file mode 100644
index 0000000000..7a20304601
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step1_start_ls.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: active_blob(&chat)
+---
+• Exploring
+ └ List ls -la
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step2_finish_ls.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step2_finish_ls.snap
new file mode 100644
index 0000000000..b13ce510e0
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step2_finish_ls.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: active_blob(&chat)
+---
+• Explored
+ └ List ls -la
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step3_start_cat_foo.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step3_start_cat_foo.snap
new file mode 100644
index 0000000000..ab15a80ff3
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step3_start_cat_foo.snap
@@ -0,0 +1,7 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: active_blob(&chat)
+---
+• Exploring
+ └ List ls -la
+ Read foo.txt
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step4_finish_cat_foo.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step4_finish_cat_foo.snap
new file mode 100644
index 0000000000..21b41860fc
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step4_finish_cat_foo.snap
@@ -0,0 +1,7 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: active_blob(&chat)
+---
+• Explored
+ └ List ls -la
+ Read foo.txt
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step5_finish_sed_range.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step5_finish_sed_range.snap
new file mode 100644
index 0000000000..21b41860fc
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step5_finish_sed_range.snap
@@ -0,0 +1,7 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: active_blob(&chat)
+---
+• Explored
+ └ List ls -la
+ Read foo.txt
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step6_finish_cat_bar.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step6_finish_cat_bar.snap
new file mode 100644
index 0000000000..a38d4c7fd2
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__exploring_step6_finish_cat_bar.snap
@@ -0,0 +1,7 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: active_blob(&chat)
+---
+• Explored
+ └ List ls -la
+ Read foo.txt, bar.txt
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__feedback_selection_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__feedback_selection_popup.snap
new file mode 100644
index 0000000000..52ce03bbea
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__feedback_selection_popup.snap
@@ -0,0 +1,11 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: popup
+---
+ How was this?
+
+› 1. bug Crash, error message, hang, or broken UI/behavior.
+ 2. bad result Output was off-target, incorrect, incomplete, or unhelpful.
+ 3. good result Helpful, correct, high‑quality, or delightful result worth
+ celebrating.
+ 4. other Slowness, feature suggestion, UX feedback, or anything else.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__feedback_upload_consent_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__feedback_upload_consent_popup.snap
new file mode 100644
index 0000000000..21d031df6c
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__feedback_upload_consent_popup.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: popup
+---
+ Upload logs?
+
+ The following files will be sent:
+ • codex-logs.log
+
+› 1. Yes Share the current Codex session logs with the team for
+ troubleshooting.
+ 2. No
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__final_reasoning_then_message_without_deltas_are_rendered.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__final_reasoning_then_message_without_deltas_are_rendered.snap
new file mode 100644
index 0000000000..3d83bdb0f5
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__final_reasoning_then_message_without_deltas_are_rendered.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: combined
+---
+• Here is the result.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__full_access_confirmation_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__full_access_confirmation_popup.snap
new file mode 100644
index 0000000000..f7a2b3dcb6
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__full_access_confirmation_popup.snap
@@ -0,0 +1,15 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: popup
+---
+ Enable full access?
+ When Codex runs with full access, it can edit any file on your computer and
+ run commands with network, without your approval. Exercise caution when
+ enabling full access. This significantly increases the risk of data loss,
+ leaks, or unexpected behavior.
+
+› 1. Yes, continue anyway Apply full access for this session
+ 2. Yes, and don't ask again Enable full access and remember this choice
+ 3. Cancel Go back without enabling full access
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__interrupt_exec_marks_failed.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__interrupt_exec_marks_failed.snap
new file mode 100644
index 0000000000..3863f9a8d5
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__interrupt_exec_marks_failed.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: exec_blob
+---
+• Ran sleep 1
+ └ (no output)
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__interrupted_turn_error_message.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__interrupted_turn_error_message.snap
new file mode 100644
index 0000000000..943fe34440
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__interrupted_turn_error_message.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: last
+---
+■ Conversation interrupted - tell the model what to do differently. Something went wrong? Hit `/feedback` to report the issue.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__local_image_attachment_history_snapshot.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__local_image_attachment_history_snapshot.snap
new file mode 100644
index 0000000000..31c5e74b0a
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__local_image_attachment_history_snapshot.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: combined
+---
+• Viewed Image
+ └ example.png
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup.snap
new file mode 100644
index 0000000000..cbf5f0fb52
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup.snap
@@ -0,0 +1,12 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: popup
+---
+ Select Reasoning Level for gpt-5.1-codex-max
+
+ 1. Low Fast responses with lighter reasoning
+ 2. Medium (default) Balances speed and reasoning depth for everyday tasks
+› 3. High (current) Maximizes reasoning depth for complex problems
+ 4. Extra high Extra high reasoning depth for complex problems
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap
new file mode 100644
index 0000000000..ed6c6fee19
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap
@@ -0,0 +1,15 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: popup
+---
+ Select Reasoning Level for gpt-5.1-codex-max
+
+ 1. Low Fast responses with lighter reasoning
+ 2. Medium (default) Balances speed and reasoning depth for everyday
+ tasks
+ 3. High Maximizes reasoning depth for complex problems
+› 4. Extra high (current) Extra high reasoning depth for complex problems
+ ⚠ Extra high reasoning effort can quickly consume
+ Plus plan rate limits.
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_selection_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_selection_popup.snap
new file mode 100644
index 0000000000..3937194a1f
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__model_selection_popup.snap
@@ -0,0 +1,15 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: popup
+---
+ Select Model and Effort
+ Access legacy models by running codex -m <model_name> or in your config.toml
+
+› 1. gpt-5.1-codex-max Latest Codex-optimized flagship for deep and fast
+ reasoning.
+ 2. gpt-5.1-codex Optimized for codex.
+ 3. gpt-5.1-codex-mini Optimized for codex. Cheaper, faster, but less
+ capable.
+ 4. gpt-5.1 Broad world knowledge with strong general reasoning.
+
+ Press enter to select reasoning effort, or esc to dismiss.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__rate_limit_switch_prompt_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__rate_limit_switch_prompt_popup.snap
new file mode 100644
index 0000000000..d553957350
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__rate_limit_switch_prompt_popup.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: popup
+---
+ Approaching rate limits
+ Switch to gpt-5.1-codex-mini for lower credit usage?
+
+› 1. Switch to gpt-5.1-codex-mini Optimized for codex. Cheaper,
+ faster, but less capable.
+ 2. Keep current model
+ 3. Keep current model (never show again) Hide future rate limit reminders
+ about switching models.
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__status_widget_active.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__status_widget_active.snap
new file mode 100644
index 0000000000..f761e5730b
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__status_widget_active.snap
@@ -0,0 +1,11 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
+"• Analyzing (0s • esc to interrupt) "
+" "
+" "
+"› Ask Codex to do anything "
+" "
+" 100% context left · ? for shortcuts "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__status_widget_and_approval_modal.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__status_widget_and_approval_modal.snap
new file mode 100644
index 0000000000..567794cea6
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__status_widget_and_approval_modal.snap
@@ -0,0 +1,17 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
+" "
+" 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) "
+" "
+" Press enter to confirm or esc to cancel "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__user_shell_ls_output.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__user_shell_ls_output.snap
new file mode 100644
index 0000000000..3a9f08ab94
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui2__chatwidget__tests__user_shell_ls_output.snap
@@ -0,0 +1,7 @@
+---
+source: tui2/src/chatwidget/tests.rs
+expression: blob
+---
+• You ran ls
+ └ file1
+ file2
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__apply_patch_manual_flow_history_approved.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__apply_patch_manual_flow_history_approved.snap
new file mode 100644
index 0000000000..e139b51088
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__apply_patch_manual_flow_history_approved.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: lines_to_single_string(&approved_lines)
+---
+• Added foo.txt (+1 -0)
+ 1 +hello
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec.snap
new file mode 100644
index 0000000000..15511611a1
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec.snap
@@ -0,0 +1,17 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: terminal.backend().vt100().screen().contents()
+---
+
+
+ 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)
+
+ Press enter to confirm or esc to cancel
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec_no_reason.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec_no_reason.snap
new file mode 100644
index 0000000000..2bbe9aefcd
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_exec_no_reason.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: terminal.backend().vt100().screen().contents()
+---
+ Would you like to run the following command?
+
+ $ 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)
+
+ Press enter to confirm or esc to cancel
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_patch.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_patch.snap
new file mode 100644
index 0000000000..ed18675ac3
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approval_modal_patch.snap
@@ -0,0 +1,17 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: terminal.backend().vt100().screen().contents()
+---
+ Would you like to make the following edits?
+
+ Reason: The model wants to apply changes
+
+ README.md (+2 -0)
+
+ 1 +hello
+ 2 +world
+
+› 1. Yes, proceed (y)
+ 2. No, and tell Codex what to do differently (esc)
+
+ Press enter to confirm or esc to cancel
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup.snap
new file mode 100644
index 0000000000..6758ec62c5
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: popup
+---
+ Select Approval Mode
+
+› 1. Read Only (current) Requires approval to edit files and run commands.
+ 2. Agent Read and edit files, and run commands.
+ 3. Agent (full access) Codex can edit files outside this workspace and run
+ commands with network access. Exercise caution when
+ using.
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup@windows.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup@windows.snap
new file mode 100644
index 0000000000..6758ec62c5
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__approvals_selection_popup@windows.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: popup
+---
+ Select Approval Mode
+
+› 1. Read Only (current) Requires approval to edit files and run commands.
+ 2. Agent Read and edit files, and run commands.
+ 3. Agent (full access) Codex can edit files outside this workspace and run
+ commands with network access. Exercise caution when
+ using.
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap
new file mode 100644
index 0000000000..77738439a1
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap
@@ -0,0 +1,153 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: "lines[start_idx..].join(\"\\n\")"
+---
+• I need to check the codex-rs repository to explain why the project's binaries
+ are large. The user is likely seeking specifics about the setup: are Rust
+ builds static, what features are enabled, and is debug information included?
+ It could be due to static linking, included OpenSSL, or how panic handling
+ is set up. I should look into the Cargo.toml file to confirm features and
+ profiles without needing to edit any code. Let's get started on this!
+
+─ Worked for 0s ────────────────────────────────────────────────────────────────
+
+• I’m going to scan the workspace and Cargo manifests to see build profiles and
+ dependencies that impact binary size. Then I’ll summarize the main causes.
+
+• Explored
+ └ List ls -la
+ Read Cargo.toml
+
+• I'm reviewing the workspace's release profile, which has settings like
+ lto=fat, strip=symbols, and codegen-units=1 to reduce binary size. However, it
+ seems that "strip = symbols" only removes symbols, not debug information. In
+ Rust 1.73+, both "symbols" and "debuginfo" stripping options are available. I
+ should check whether using these results in a smaller binary. I’ll also skim
+ through crates for heavy dependencies in Cargo.toml, including cli, core,
+ exec, linux-sandbox, tui, login, ollama, and mcp.
+
+• Ran for d in ansi-escape apply-patch arg0 cli common core exec execpolicy
+ │ file-search linux-sandbox login mcp-client mcp-server mcp-types ollama
+ │ tui; do echo "--- $d/Cargo.toml"; sed -n '1,200p' $d/Cargo.toml; echo;
+ │ … +1 lines
+ └ --- ansi-escape/Cargo.toml
+ [package]
+ … +243 lines
+ ] }
+ tracing = { version
+
+• Explored
+ └ Read Cargo.toml
+
+• I’m evaluating how binary size is influenced by various factors. There are
+ many binaries, such as codex and codex-exec, which include dependencies by
+ default, pulling in features like Tokio and hyper. For instance, reqwest
+ includes default features like TLS through rustls. If default features remain
+ enabled, it inflates the size with many additional components. I notice
+ that for musl targets, using vendored builds of OpenSSL could significantly
+ increase binary size. This is quite the intricate web of dependencies!
+
+ Analyzing musl and binary size
+
+ I’m considering the implications of building for musl with static linking.
+ In this case, OpenSSL might come into play through some crates, but reqwest
+ defaults to using rustls, although openssl-sys vendored could increase
+ binary size. It’s interesting to think about whether they’re targeting musl,
+ especially since it seems they might often be building for Mac and Linux with
+ dynamic linking instead.
+
+ I also realize there’s a difference between debug and release builds — release
+ should be smaller due to optimizations, but if they’re defaulting to debug
+ builds, that could lead to much larger binaries.
+
+ Assessing crate impacts on size
+
+ I need to be precise when analyzing binary sizes from various crates. Some
+ crates, like ratatui-image, include heavy features such as libjpeg decoders,
+ which can really bulk things up. Then there are the tree-sitter crates that
+ contain large static grammar tables, adding significant size. The starlark
+ crate and tracing-subscriber also contribute to size increases.
+
+ With static linking per binary being standard in Rust, it leads to multiple
+ copies of the same dependencies unless cdylibs are used. That makes the
+ compile times longer, but using LTO helps reduce bloat somewhat through
+ deduplication.
+
+ Evaluating binary size factors
+
+ Having multiple binaries indeed increases the overall size significantly.
+ I'm considering options like upgrading to "opt-level = 'z'" or using
+ "strip=debuginfo" for reducing size. It's interesting that while the profile
+ only sets symbols for stripping, not debuginfo, this could inflate sizes if
+ retained in release builds.
+
+ The distinction between "symbols" and "debuginfo" is critical; "symbols"
+ keeps debug information which may not align with the goal of minimizing
+ size. I’d like to verify with the Rust documentation, but my network access
+ is restricted.
+
+ Explaining large binary sizes
+
+ I’m analyzing why binaries in this project are so large. The primary reasons
+ include monolithic static linking, where each binary includes the full
+ dependency graph without shared libraries. Heavy dependencies such as reqwest,
+ hyper, and TLS components also contribute significantly to size, along with
+ image decoders and other libraries.
+
+ Using MUSL targets means vendored OpenSSL can drastically increase the
+ size due to static linking. Furthermore, if the release profile keeps debug
+ information due to using "strip = symbols," that can lead to larger binaries
+ as well. It’s a mix of several factors, including panic strategies and
+ platform-specific linking behavior.
+
+ Identifying binary size contributors
+
+ I’m considering why binaries are still large even without static linking. The
+ tracing-subscriber crate potentially adds weight because it includes regex,
+ though it can sometimes use a lighter version. References from files like
+ "core/Cargo.toml" show dependencies like reqwest and tokio, while the tui uses
+ the image crate.
+
+ To present this clearly, I’ll format the final answer with two main sections:
+ "Main Causes" and "Build-Mode Notes." I can also include brief suggestions for
+ reducing size, but I want to stay focused on answering the user's question.
+
+─ Worked for 0s ────────────────────────────────────────────────────────────────
+
+• Here’s what’s driving size in this workspace’s binaries.
+
+ Main Causes
+
+ - Static linking style: Each bin (codex, codex-tui, codex-exec, codex-mcp-
+ server, etc.) statically links its full dependency graph, so common code isn’t
+ shared at runtime across executables.
+ - Heavy deps (HTTP/TLS): reqwest brings in Hyper, HTTP/2, compressors,
+ and a TLS stack (rustls by default; OpenSSL on musl). In core, login, tui,
+ and ollama you enable reqwest with json/stream, which still pulls a large
+ transitive set.
+ - Image/terminal stack: codex-tui includes image (with jpeg), ratatui,
+ crossterm, and ratatui-image, which together contribute significant code size
+ (decoders, pixel ops, terminal backends).
+ - Parsers/VMs: tree-sitter + tree-sitter-bash (in core and apply-patch) and
+ starlark (in execpolicy) include sizeable parser/VM tables and runtimes.
+ - Tokio runtime: Broad tokio features (rt-multi-thread, macros, process,
+ signal) across many crates inflate code size even if only subsets are used
+ per bin.
+ - Panic + backtraces: Default panic = unwind and backtrace support keep
+ unwinding tables and symbols that add weight.
+ - Per-target OpenSSL (musl): For *-unknown-linux-musl, core enables openssl-
+ sys with vendored, compiling OpenSSL into the binary—this adds multiple
+ megabytes per executable.
+
+ Build-Mode Notes
+
+ - Release settings: You use lto = "fat" and codegen-units = 1 (good for size),
+ but strip = "symbols" keeps debuginfo. Debuginfo is often the largest single
+ contributor; if you build in release with that setting, binaries can still
+ be large.
+ - Debug builds: cargo build (dev profile) includes full debuginfo, no LTO, and
+ assertions—outputs are much larger than cargo build --release.
+
+ If you want, I can outline targeted trims (e.g., strip = "debuginfo", opt-
+ level = "z", panic abort, tighter tokio/reqwest features) and estimate impact
+ per binary.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_idle_h1.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_idle_h1.snap
new file mode 100644
index 0000000000..1e73a237eb
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_idle_h1.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_idle_h2.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_idle_h2.snap
new file mode 100644
index 0000000000..7a04b0ef19
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_idle_h2.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_idle_h3.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_idle_h3.snap
new file mode 100644
index 0000000000..4487d0652e
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_idle_h3.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h1.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h1.snap
new file mode 100644
index 0000000000..1e73a237eb
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h1.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h2.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h2.snap
new file mode 100644
index 0000000000..7a04b0ef19
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h2.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h3.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h3.snap
new file mode 100644
index 0000000000..4487d0652e
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chat_small_running_h3.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap
new file mode 100644
index 0000000000..c3bdf60bd2
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_exec_and_status_layout_vt100_snapshot.snap
@@ -0,0 +1,17 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: term.backend().vt100().screen().contents()
+---
+• I’m going to search the repo for where “Change Approved” is rendered to update
+ that view.
+
+• Explored
+ └ Search Change Approved
+ Read diff_render.rs
+
+• Investigating rendering code (0s • esc to interrupt)
+
+
+› Summarize recent commits
+
+ 100% context left
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_markdown_code_blocks_vt100_snapshot.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_markdown_code_blocks_vt100_snapshot.snap
new file mode 100644
index 0000000000..1ed73b5fa5
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_markdown_code_blocks_vt100_snapshot.snap
@@ -0,0 +1,18 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: visual
+---
+• -- Indented code block (4 spaces)
+ SELECT *
+ FROM "users"
+ WHERE "email" LIKE '%@example.com';
+
+ ```sh
+ printf 'fenced within fenced\n'
+ ```
+
+ {
+ // comment allowed in jsonc
+ "path": "C:\\Program Files\\App",
+ "regex": "^foo.*(bar)?$"
+ }
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_tall.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_tall.snap
new file mode 100644
index 0000000000..6d9aa515b1
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__chatwidget_tall.snap
@@ -0,0 +1,27 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: term.backend().vt100().screen().contents()
+---
+• Working (0s • esc to interrupt)
+ ↳ Hello, world! 0
+ ↳ Hello, world! 1
+ ↳ Hello, world! 2
+ ↳ Hello, world! 3
+ ↳ Hello, world! 4
+ ↳ Hello, world! 5
+ ↳ Hello, world! 6
+ ↳ Hello, world! 7
+ ↳ Hello, world! 8
+ ↳ Hello, world! 9
+ ↳ Hello, world! 10
+ ↳ Hello, world! 11
+ ↳ Hello, world! 12
+ ↳ Hello, world! 13
+ ↳ Hello, world! 14
+ ↳ Hello, world! 15
+ ↳ Hello, world! 16
+
+
+› Ask Codex to do anything
+
+ 100% context left · ? for shortcuts
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap
new file mode 100644
index 0000000000..6062087181
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: combined
+---
+• Here is the result.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__disabled_slash_command_while_task_running_snapshot.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__disabled_slash_command_while_task_running_snapshot.snap
new file mode 100644
index 0000000000..e8f08a437a
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__disabled_slash_command_while_task_running_snapshot.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: blob
+---
+■ '/model' is disabled while a task is in progress.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_aborted_long.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_aborted_long.snap
new file mode 100644
index 0000000000..f04e1f078a
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_aborted_long.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/chatwidget/tests.rs
+assertion_line: 495
+expression: lines_to_single_string(&aborted_long)
+---
+✗ You canceled the request to run echo
+ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_aborted_multiline.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_aborted_multiline.snap
new file mode 100644
index 0000000000..d35cb17597
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_aborted_multiline.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: lines_to_single_string(&aborted_multi)
+---
+✗ You canceled the request to run echo line1 ...
+
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_approved_short.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_approved_short.snap
new file mode 100644
index 0000000000..2f0f1412a1
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_history_decision_approved_short.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: lines_to_single_string(&decision)
+---
+✔ You approved codex to run echo hello world this time
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap
new file mode 100644
index 0000000000..1c6a3ef136
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exec_approval_modal_exec.snap
@@ -0,0 +1,36 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: "format!(\"{buf:?}\")"
+---
+Buffer {
+ area: Rect { x: 0, y: 0, width: 80, height: 13 },
+ content: [
+ " ",
+ " ",
+ " 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. No, and tell Codex what to do differently (esc) ",
+ " ",
+ " Press enter to confirm or esc to cancel ",
+ ],
+ styles: [
+ x: 0, y: 0, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 2, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: BOLD,
+ x: 46, y: 2, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 10, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: ITALIC,
+ x: 73, y: 4, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 2, y: 5, fg: Reset, bg: Reset, underline: Reset, modifier: ITALIC,
+ x: 7, y: 5, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 0, y: 9, fg: Cyan, bg: Reset, underline: Reset, modifier: BOLD,
+ x: 21, y: 9, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 48, y: 10, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ x: 51, y: 10, fg: Reset, bg: Reset, underline: Reset, modifier: NONE,
+ x: 2, y: 12, fg: Reset, bg: Reset, underline: Reset, modifier: DIM,
+ ]
+}
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step1_start_ls.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step1_start_ls.snap
new file mode 100644
index 0000000000..588a9503eb
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step1_start_ls.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: blob1
+---
+• Exploring
+ └ List ls -la
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step2_finish_ls.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step2_finish_ls.snap
new file mode 100644
index 0000000000..492e8b7708
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step2_finish_ls.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: blob2
+---
+• Explored
+ └ List ls -la
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step3_start_cat_foo.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step3_start_cat_foo.snap
new file mode 100644
index 0000000000..2ce4170929
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step3_start_cat_foo.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: blob3
+---
+• Exploring
+ └ List ls -la
+ Read foo.txt
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step4_finish_cat_foo.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step4_finish_cat_foo.snap
new file mode 100644
index 0000000000..9e29785f71
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step4_finish_cat_foo.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: blob4
+---
+• Explored
+ └ List ls -la
+ Read foo.txt
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step5_finish_sed_range.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step5_finish_sed_range.snap
new file mode 100644
index 0000000000..296b00f905
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step5_finish_sed_range.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: blob5
+---
+• Explored
+ └ List ls -la
+ Read foo.txt
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step6_finish_cat_bar.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step6_finish_cat_bar.snap
new file mode 100644
index 0000000000..55fa979123
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__exploring_step6_finish_cat_bar.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: blob6
+---
+• Explored
+ └ List ls -la
+ Read foo.txt, bar.txt
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_selection_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_selection_popup.snap
new file mode 100644
index 0000000000..4a98242027
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_selection_popup.snap
@@ -0,0 +1,11 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: popup
+---
+ How was this?
+
+› 1. bug Crash, error message, hang, or broken UI/behavior.
+ 2. bad result Output was off-target, incorrect, incomplete, or unhelpful.
+ 3. good result Helpful, correct, high‑quality, or delightful result worth
+ celebrating.
+ 4. other Slowness, feature suggestion, UX feedback, or anything else.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap
new file mode 100644
index 0000000000..cc3d8e3755
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: popup
+---
+ Upload logs?
+
+ The following files will be sent:
+ • codex-logs.log
+
+› 1. Yes Share the current Codex session logs with the team for
+ troubleshooting.
+ 2. No
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__final_reasoning_then_message_without_deltas_are_rendered.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__final_reasoning_then_message_without_deltas_are_rendered.snap
new file mode 100644
index 0000000000..6062087181
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__final_reasoning_then_message_without_deltas_are_rendered.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: combined
+---
+• Here is the result.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__full_access_confirmation_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__full_access_confirmation_popup.snap
new file mode 100644
index 0000000000..71dac5f590
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__full_access_confirmation_popup.snap
@@ -0,0 +1,15 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: popup
+---
+ Enable full access?
+ When Codex runs with full access, it can edit any file on your computer and
+ run commands with network, without your approval. Exercise caution when
+ enabling full access. This significantly increases the risk of data loss,
+ leaks, or unexpected behavior.
+
+› 1. Yes, continue anyway Apply full access for this session
+ 2. Yes, and don't ask again Enable full access and remember this choice
+ 3. Cancel Go back without enabling full access
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__interrupt_exec_marks_failed.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__interrupt_exec_marks_failed.snap
new file mode 100644
index 0000000000..59eff20ace
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__interrupt_exec_marks_failed.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: exec_blob
+---
+• Ran sleep 1
+ └ (no output)
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__interrupted_turn_error_message.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__interrupted_turn_error_message.snap
new file mode 100644
index 0000000000..60715e581e
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__interrupted_turn_error_message.snap
@@ -0,0 +1,5 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: last
+---
+■ Conversation interrupted - tell the model what to do differently. Something went wrong? Hit `/feedback` to report the issue.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__local_image_attachment_history_snapshot.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__local_image_attachment_history_snapshot.snap
new file mode 100644
index 0000000000..cf4c6943fd
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__local_image_attachment_history_snapshot.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: combined
+---
+• Viewed Image
+ └ example.png
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap
new file mode 100644
index 0000000000..b4b89736a9
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup.snap
@@ -0,0 +1,12 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: popup
+---
+ Select Reasoning Level for gpt-5.1-codex-max
+
+ 1. Low Fast responses with lighter reasoning
+ 2. Medium (default) Balances speed and reasoning depth for everyday tasks
+› 3. High (current) Maximizes reasoning depth for complex problems
+ 4. Extra high Extra high reasoning depth for complex problems
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap
new file mode 100644
index 0000000000..c5332ff590
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_reasoning_selection_popup_extra_high_warning.snap
@@ -0,0 +1,16 @@
+---
+source: tui/src/chatwidget/tests.rs
+assertion_line: 1548
+expression: popup
+---
+ Select Reasoning Level for gpt-5.1-codex-max
+
+ 1. Low Fast responses with lighter reasoning
+ 2. Medium (default) Balances speed and reasoning depth for everyday
+ tasks
+ 3. High Maximizes reasoning depth for complex problems
+› 4. Extra high (current) Extra high reasoning depth for complex problems
+ ⚠ Extra high reasoning effort can quickly consume
+ Plus plan rate limits.
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap
new file mode 100644
index 0000000000..56a209ef73
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__model_selection_popup.snap
@@ -0,0 +1,15 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: popup
+---
+ Select Model and Effort
+ Access legacy models by running codex -m <model_name> or in your config.toml
+
+› 1. gpt-5.1-codex-max Latest Codex-optimized flagship for deep and fast
+ reasoning.
+ 2. gpt-5.1-codex Optimized for codex.
+ 3. gpt-5.1-codex-mini Optimized for codex. Cheaper, faster, but less
+ capable.
+ 4. gpt-5.1 Broad world knowledge with strong general reasoning.
+
+ Press enter to select reasoning effort, or esc to dismiss.
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_switch_prompt_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_switch_prompt_popup.snap
new file mode 100644
index 0000000000..e210d1f0a3
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__rate_limit_switch_prompt_popup.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: popup
+---
+ Approaching rate limits
+ Switch to gpt-5.1-codex-mini for lower credit usage?
+
+› 1. Switch to gpt-5.1-codex-mini Optimized for codex. Cheaper,
+ faster, but less capable.
+ 2. Keep current model
+ 3. Keep current model (never show again) Hide future rate limit reminders
+ about switching models.
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap
new file mode 100644
index 0000000000..9fbebfb500
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_active.snap
@@ -0,0 +1,12 @@
+---
+source: tui/src/chatwidget/tests.rs
+assertion_line: 1577
+expression: terminal.backend()
+---
+" "
+"• Analyzing (0s • esc to interrupt) "
+" "
+" "
+"› Ask Codex to do anything "
+" "
+" 100% context left · ? for shortcuts "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_and_approval_modal.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_and_approval_modal.snap
new file mode 100644
index 0000000000..5e6e33dece
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__status_widget_and_approval_modal.snap
@@ -0,0 +1,17 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: terminal.backend()
+---
+" "
+" "
+" 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) "
+" "
+" Press enter to confirm or esc to cancel "
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__update_popup.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__update_popup.snap
new file mode 100644
index 0000000000..6a49cb253c
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__update_popup.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: terminal.backend().vt100().screen().contents()
+---
+ ✨ New version available! Would you like to update?
+
+ Full release notes: https://github.com/openai/codex/releases/latest
+
+
+› 1. Yes, update now
+ 2. No, not now
+ 3. Don't remind me
+
+ Press enter to confirm or esc to go back
diff --git a/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__user_shell_ls_output.snap b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__user_shell_ls_output.snap
new file mode 100644
index 0000000000..c67cd637d7
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/snapshots/codex_tui__chatwidget__tests__user_shell_ls_output.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/chatwidget/tests.rs
+expression: blob
+---
+• You ran ls
+ └ file1
+ file2
diff --git a/codex-rs/tui2/src/chatwidget/tests.rs b/codex-rs/tui2/src/chatwidget/tests.rs
new file mode 100644
index 0000000000..d9e242674b
--- /dev/null
+++ b/codex-rs/tui2/src/chatwidget/tests.rs
@@ -0,0 +1,3329 @@
+use super::*;
+use crate::app_event::AppEvent;
+use crate::app_event_sender::AppEventSender;
+use crate::test_backend::VT100Backend;
+use crate::tui::FrameRequester;
+use assert_matches::assert_matches;
+use codex_common::approval_presets::builtin_approval_presets;
+use codex_core::AuthManager;
+use codex_core::CodexAuth;
+use codex_core::config::Config;
+use codex_core::config::ConfigOverrides;
+use codex_core::config::ConfigToml;
+use codex_core::openai_models::models_manager::ModelsManager;
+use codex_core::protocol::AgentMessageDeltaEvent;
+use codex_core::protocol::AgentMessageEvent;
+use codex_core::protocol::AgentReasoningDeltaEvent;
+use codex_core::protocol::AgentReasoningEvent;
+use codex_core::protocol::ApplyPatchApprovalRequestEvent;
+use codex_core::protocol::BackgroundEventEvent;
+use codex_core::protocol::CreditsSnapshot;
+use codex_core::protocol::Event;
+use codex_core::protocol::EventMsg;
+use codex_core::protocol::ExecApprovalRequestEvent;
+use codex_core::protocol::ExecCommandBeginEvent;
+use codex_core::protocol::ExecCommandEndEvent;
+use codex_core::protocol::ExecCommandSource;
+use codex_core::protocol::ExecPolicyAmendment;
+use codex_core::protocol::ExitedReviewModeEvent;
+use codex_core::protocol::FileChange;
+use codex_core::protocol::Op;
+use codex_core::protocol::PatchApplyBeginEvent;
+use codex_core::protocol::PatchApplyEndEvent;
+use codex_core::protocol::RateLimitWindow;
+use codex_core::protocol::ReviewCodeLocation;
+use codex_core::protocol::ReviewFinding;
+use codex_core::protocol::ReviewLineRange;
+use codex_core::protocol::ReviewOutputEvent;
+use codex_core::protocol::ReviewRequest;
+use codex_core::protocol::ReviewTarget;
+use codex_core::protocol::StreamErrorEvent;
+use codex_core::protocol::TaskCompleteEvent;
+use codex_core::protocol::TaskStartedEvent;
+use codex_core::protocol::TokenCountEvent;
+use codex_core::protocol::TokenUsage;
+use codex_core::protocol::TokenUsageInfo;
+use codex_core::protocol::UndoCompletedEvent;
+use codex_core::protocol::UndoStartedEvent;
+use codex_core::protocol::ViewImageToolCallEvent;
+use codex_core::protocol::WarningEvent;
+use codex_protocol::ConversationId;
+use codex_protocol::account::PlanType;
+use codex_protocol::openai_models::ModelPreset;
+use codex_protocol::openai_models::ReasoningEffortPreset;
+use codex_protocol::parse_command::ParsedCommand;
+use codex_protocol::plan_tool::PlanItemArg;
+use codex_protocol::plan_tool::StepStatus;
+use codex_protocol::plan_tool::UpdatePlanArgs;
+use codex_protocol::protocol::CodexErrorInfo;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyModifiers;
+use insta::assert_snapshot;
+use pretty_assertions::assert_eq;
+use std::collections::HashSet;
+use std::path::PathBuf;
+use tempfile::NamedTempFile;
+use tempfile::tempdir;
+use tokio::sync::mpsc::error::TryRecvError;
+use tokio::sync::mpsc::unbounded_channel;
+
+#[cfg(target_os = "windows")]
+fn set_windows_sandbox_enabled(enabled: bool) {
+ codex_core::set_windows_sandbox_enabled(enabled);
+}
+
+fn test_config() -> Config {
+ // Use base defaults to avoid depending on host state.
+
+ Config::load_from_base_config_with_overrides(
+ ConfigToml::default(),
+ ConfigOverrides::default(),
+ std::env::temp_dir(),
+ )
+ .expect("config")
+}
+
+fn snapshot(percent: f64) -> RateLimitSnapshot {
+ RateLimitSnapshot {
+ primary: Some(RateLimitWindow {
+ used_percent: percent,
+ window_minutes: Some(60),
+ resets_at: None,
+ }),
+ secondary: None,
+ credits: None,
+ plan_type: None,
+ }
+}
+
+#[test]
+fn resumed_initial_messages_render_history() {
+ let (mut chat, mut rx, _ops) = make_chatwidget_manual(None);
+
+ let conversation_id = ConversationId::new();
+ let rollout_file = NamedTempFile::new().unwrap();
+ let configured = codex_core::protocol::SessionConfiguredEvent {
+ session_id: conversation_id,
+ model: "test-model".to_string(),
+ model_provider_id: "test-provider".to_string(),
+ approval_policy: AskForApproval::Never,
+ sandbox_policy: SandboxPolicy::ReadOnly,
+ cwd: PathBuf::from("/home/user/project"),
+ reasoning_effort: Some(ReasoningEffortConfig::default()),
+ history_log_id: 0,
+ history_entry_count: 0,
+ initial_messages: Some(vec![
+ EventMsg::UserMessage(UserMessageEvent {
+ message: "hello from user".to_string(),
+ images: None,
+ }),
+ EventMsg::AgentMessage(AgentMessageEvent {
+ message: "assistant reply".to_string(),
+ }),
+ ]),
+ skill_load_outcome: None,
+ rollout_path: rollout_file.path().to_path_buf(),
+ };
+
+ chat.handle_codex_event(Event {
+ id: "initial".into(),
+ msg: EventMsg::SessionConfigured(configured),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ let mut merged_lines = Vec::new();
+ for lines in cells {
+ let text = lines
+ .iter()
+ .flat_map(|line| line.spans.iter())
+ .map(|span| span.content.clone())
+ .collect::<String>();
+ merged_lines.push(text);
+ }
+
+ let text_blob = merged_lines.join("\n");
+ assert!(
+ text_blob.contains("hello from user"),
+ "expected replayed user message",
+ );
+ assert!(
+ text_blob.contains("assistant reply"),
+ "expected replayed agent message",
+ );
+}
+
+/// Entering review mode uses the hint provided by the review request.
+#[test]
+fn entered_review_mode_uses_request_hint() {
+ let (mut chat, mut rx, _ops) = make_chatwidget_manual(None);
+
+ chat.handle_codex_event(Event {
+ id: "review-start".into(),
+ msg: EventMsg::EnteredReviewMode(ReviewRequest {
+ target: ReviewTarget::BaseBranch {
+ branch: "feature".to_string(),
+ },
+ user_facing_hint: Some("feature branch".to_string()),
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ let banner = lines_to_single_string(cells.last().expect("review banner"));
+ assert_eq!(banner, ">> Code review started: feature branch <<\n");
+ assert!(chat.is_review_mode);
+}
+
+/// Entering review mode renders the current changes banner when requested.
+#[test]
+fn entered_review_mode_defaults_to_current_changes_banner() {
+ let (mut chat, mut rx, _ops) = make_chatwidget_manual(None);
+
+ chat.handle_codex_event(Event {
+ id: "review-start".into(),
+ msg: EventMsg::EnteredReviewMode(ReviewRequest {
+ target: ReviewTarget::UncommittedChanges,
+ user_facing_hint: None,
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ let banner = lines_to_single_string(cells.last().expect("review banner"));
+ assert_eq!(banner, ">> Code review started: current changes <<\n");
+ assert!(chat.is_review_mode);
+}
+
+/// Completing review with findings shows the selection popup and finishes with
+/// the closing banner while clearing review mode state.
+#[test]
+fn exited_review_mode_emits_results_and_finishes() {
+ let (mut chat, mut rx, _ops) = make_chatwidget_manual(None);
+
+ let review = ReviewOutputEvent {
+ findings: vec![ReviewFinding {
+ title: "[P1] Fix bug".to_string(),
+ body: "Something went wrong".to_string(),
+ confidence_score: 0.9,
+ priority: 1,
+ code_location: ReviewCodeLocation {
+ absolute_file_path: PathBuf::from("src/lib.rs"),
+ line_range: ReviewLineRange { start: 10, end: 12 },
+ },
+ }],
+ overall_correctness: "needs work".to_string(),
+ overall_explanation: "Investigate the failure".to_string(),
+ overall_confidence_score: 0.5,
+ };
+
+ chat.handle_codex_event(Event {
+ id: "review-end".into(),
+ msg: EventMsg::ExitedReviewMode(ExitedReviewModeEvent {
+ review_output: Some(review),
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ let banner = lines_to_single_string(cells.last().expect("finished banner"));
+ assert_eq!(banner, "\n<< Code review finished >>\n");
+ assert!(!chat.is_review_mode);
+}
+
+/// Exiting review restores the pre-review context window indicator.
+#[test]
+fn review_restores_context_window_indicator() {
+ let (mut chat, mut rx, _ops) = make_chatwidget_manual(None);
+
+ let context_window = 13_000;
+ let pre_review_tokens = 12_700; // ~30% remaining after subtracting baseline.
+ let review_tokens = 12_030; // ~97% remaining after subtracting baseline.
+
+ chat.handle_codex_event(Event {
+ id: "token-before".into(),
+ msg: EventMsg::TokenCount(TokenCountEvent {
+ info: Some(make_token_info(pre_review_tokens, context_window)),
+ rate_limits: None,
+ }),
+ });
+ assert_eq!(chat.bottom_pane.context_window_percent(), Some(30));
+
+ chat.handle_codex_event(Event {
+ id: "review-start".into(),
+ msg: EventMsg::EnteredReviewMode(ReviewRequest {
+ target: ReviewTarget::BaseBranch {
+ branch: "feature".to_string(),
+ },
+ user_facing_hint: Some("feature branch".to_string()),
+ }),
+ });
+
+ chat.handle_codex_event(Event {
+ id: "token-review".into(),
+ msg: EventMsg::TokenCount(TokenCountEvent {
+ info: Some(make_token_info(review_tokens, context_window)),
+ rate_limits: None,
+ }),
+ });
+ assert_eq!(chat.bottom_pane.context_window_percent(), Some(97));
+
+ chat.handle_codex_event(Event {
+ id: "review-end".into(),
+ msg: EventMsg::ExitedReviewMode(ExitedReviewModeEvent {
+ review_output: None,
+ }),
+ });
+ let _ = drain_insert_history(&mut rx);
+
+ assert_eq!(chat.bottom_pane.context_window_percent(), Some(30));
+ assert!(!chat.is_review_mode);
+}
+
+/// Receiving a TokenCount event without usage clears the context indicator.
+#[test]
+fn token_count_none_resets_context_indicator() {
+ let (mut chat, _rx, _ops) = make_chatwidget_manual(None);
+
+ let context_window = 13_000;
+ let pre_compact_tokens = 12_700;
+
+ chat.handle_codex_event(Event {
+ id: "token-before".into(),
+ msg: EventMsg::TokenCount(TokenCountEvent {
+ info: Some(make_token_info(pre_compact_tokens, context_window)),
+ rate_limits: None,
+ }),
+ });
+ assert_eq!(chat.bottom_pane.context_window_percent(), Some(30));
+
+ chat.handle_codex_event(Event {
+ id: "token-cleared".into(),
+ msg: EventMsg::TokenCount(TokenCountEvent {
+ info: None,
+ rate_limits: None,
+ }),
+ });
+ assert_eq!(chat.bottom_pane.context_window_percent(), None);
+}
+
+#[test]
+fn context_indicator_shows_used_tokens_when_window_unknown() {
+ let (mut chat, _rx, _ops) = make_chatwidget_manual(Some("unknown-model"));
+
+ chat.config.model_context_window = None;
+ let auto_compact_limit = 200_000;
+ chat.config.model_auto_compact_token_limit = Some(auto_compact_limit);
+
+ // No model window, so the indicator should fall back to showing tokens used.
+ let total_tokens = 106_000;
+ let token_usage = TokenUsage {
+ total_tokens,
+ ..TokenUsage::default()
+ };
+ let token_info = TokenUsageInfo {
+ total_token_usage: token_usage.clone(),
+ last_token_usage: token_usage,
+ model_context_window: None,
+ };
+
+ chat.handle_codex_event(Event {
+ id: "token-usage".into(),
+ msg: EventMsg::TokenCount(TokenCountEvent {
+ info: Some(token_info),
+ rate_limits: None,
+ }),
+ });
+
+ assert_eq!(chat.bottom_pane.context_window_percent(), None);
+ assert_eq!(
+ chat.bottom_pane.context_window_used_tokens(),
+ Some(total_tokens)
+ );
+}
+
+#[cfg_attr(
+ target_os = "macos",
+ ignore = "system configuration APIs are blocked under macOS seatbelt"
+)]
+#[tokio::test]
+async fn helpers_are_available_and_do_not_panic() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let cfg = test_config();
+ let resolved_model = ModelsManager::get_model_offline(cfg.model.as_deref());
+ let model_family = ModelsManager::construct_model_family_offline(&resolved_model, &cfg);
+ let conversation_manager = Arc::new(ConversationManager::with_models_provider(
+ CodexAuth::from_api_key("test"),
+ cfg.model_provider.clone(),
+ ));
+ let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test"));
+ let init = ChatWidgetInit {
+ config: cfg,
+ frame_requester: FrameRequester::test_dummy(),
+ app_event_tx: tx,
+ initial_prompt: None,
+ initial_images: Vec::new(),
+ enhanced_keys_supported: false,
+ auth_manager,
+ models_manager: conversation_manager.get_models_manager(),
+ feedback: codex_feedback::CodexFeedback::new(),
+ skills: None,
+ is_first_run: true,
+ model_family,
+ };
+ let mut w = ChatWidget::new(init, conversation_manager);
+ // Basic construction sanity.
+ let _ = &mut w;
+}
+
+// --- Helpers for tests that need direct construction and event draining ---
+fn make_chatwidget_manual(
+ model_override: Option<&str>,
+) -> (
+ ChatWidget,
+ tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
+ tokio::sync::mpsc::UnboundedReceiver<Op>,
+) {
+ let (tx_raw, rx) = unbounded_channel::<AppEvent>();
+ let app_event_tx = AppEventSender::new(tx_raw);
+ let (op_tx, op_rx) = unbounded_channel::<Op>();
+ let mut cfg = test_config();
+ let resolved_model = model_override
+ .map(str::to_owned)
+ .unwrap_or_else(|| ModelsManager::get_model_offline(cfg.model.as_deref()));
+ if let Some(model) = model_override {
+ cfg.model = Some(model.to_string());
+ }
+ let bottom = BottomPane::new(BottomPaneParams {
+ app_event_tx: app_event_tx.clone(),
+ frame_requester: FrameRequester::test_dummy(),
+ has_input_focus: true,
+ enhanced_keys_supported: false,
+ placeholder_text: "Ask Codex to do anything".to_string(),
+ disable_paste_burst: false,
+ animations_enabled: cfg.animations,
+ skills: None,
+ });
+ let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("test"));
+ let widget = ChatWidget {
+ app_event_tx,
+ codex_op_tx: op_tx,
+ bottom_pane: bottom,
+ active_cell: None,
+ config: cfg.clone(),
+ model_family: ModelsManager::construct_model_family_offline(&resolved_model, &cfg),
+ auth_manager: auth_manager.clone(),
+ models_manager: Arc::new(ModelsManager::new(auth_manager)),
+ session_header: SessionHeader::new(resolved_model.clone()),
+ initial_user_message: None,
+ token_info: None,
+ rate_limit_snapshot: None,
+ plan_type: None,
+ rate_limit_warnings: RateLimitWarningState::default(),
+ rate_limit_switch_prompt: RateLimitSwitchPromptState::default(),
+ rate_limit_poller: None,
+ stream_controller: None,
+ running_commands: HashMap::new(),
+ suppressed_exec_calls: HashSet::new(),
+ last_unified_wait: None,
+ task_complete_pending: false,
+ mcp_startup_status: None,
+ interrupts: InterruptManager::new(),
+ reasoning_buffer: String::new(),
+ full_reasoning_buffer: String::new(),
+ current_status_header: String::from("Working"),
+ retry_status_header: None,
+ conversation_id: None,
+ frame_requester: FrameRequester::test_dummy(),
+ show_welcome_banner: true,
+ queued_user_messages: VecDeque::new(),
+ suppress_session_configured_redraw: false,
+ pending_notification: None,
+ is_review_mode: false,
+ pre_review_token_info: None,
+ needs_final_message_separator: false,
+ last_rendered_width: std::cell::Cell::new(None),
+ feedback: codex_feedback::CodexFeedback::new(),
+ current_rollout_path: None,
+ };
+ (widget, rx, op_rx)
+}
+
+fn set_chatgpt_auth(chat: &mut ChatWidget) {
+ chat.auth_manager =
+ AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
+ chat.models_manager = Arc::new(ModelsManager::new(chat.auth_manager.clone()));
+}
+
+pub(crate) fn make_chatwidget_manual_with_sender() -> (
+ ChatWidget,
+ AppEventSender,
+ tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
+ tokio::sync::mpsc::UnboundedReceiver<Op>,
+) {
+ let (widget, rx, op_rx) = make_chatwidget_manual(None);
+ let app_event_tx = widget.app_event_tx.clone();
+ (widget, app_event_tx, rx, op_rx)
+}
+
+fn drain_insert_history(
+ rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
+) -> Vec<Vec<ratatui::text::Line<'static>>> {
+ let mut out = Vec::new();
+ while let Ok(ev) = rx.try_recv() {
+ if let AppEvent::InsertHistoryCell(cell) = ev {
+ let mut lines = cell.display_lines(80);
+ if !cell.is_stream_continuation() && !out.is_empty() && !lines.is_empty() {
+ lines.insert(0, "".into());
+ }
+ out.push(lines)
+ }
+ }
+ out
+}
+
+fn lines_to_single_string(lines: &[ratatui::text::Line<'static>]) -> String {
+ let mut s = String::new();
+ for line in lines {
+ for span in &line.spans {
+ s.push_str(&span.content);
+ }
+ s.push('\n');
+ }
+ s
+}
+
+fn make_token_info(total_tokens: i64, context_window: i64) -> TokenUsageInfo {
+ fn usage(total_tokens: i64) -> TokenUsage {
+ TokenUsage {
+ total_tokens,
+ ..TokenUsage::default()
+ }
+ }
+
+ TokenUsageInfo {
+ total_token_usage: usage(total_tokens),
+ last_token_usage: usage(total_tokens),
+ model_context_window: Some(context_window),
+ }
+}
+
+#[test]
+fn rate_limit_warnings_emit_thresholds() {
+ let mut state = RateLimitWarningState::default();
+ let mut warnings: Vec<String> = Vec::new();
+
+ warnings.extend(state.take_warnings(Some(10.0), Some(10079), Some(55.0), Some(299)));
+ warnings.extend(state.take_warnings(Some(55.0), Some(10081), Some(10.0), Some(299)));
+ warnings.extend(state.take_warnings(Some(10.0), Some(10081), Some(80.0), Some(299)));
+ warnings.extend(state.take_warnings(Some(80.0), Some(10081), Some(10.0), Some(299)));
+ warnings.extend(state.take_warnings(Some(10.0), Some(10081), Some(95.0), Some(299)));
+ warnings.extend(state.take_warnings(Some(95.0), Some(10079), Some(10.0), Some(299)));
+
+ assert_eq!(
+ warnings,
+ vec![
+ String::from(
+ "Heads up, you have less than 25% of your 5h limit left. Run /status for a breakdown."
+ ),
+ String::from(
+ "Heads up, you have less than 25% of your weekly limit left. Run /status for a breakdown.",
+ ),
+ String::from(
+ "Heads up, you have less than 5% of your 5h limit left. Run /status for a breakdown."
+ ),
+ String::from(
+ "Heads up, you have less than 5% of your weekly limit left. Run /status for a breakdown.",
+ ),
+ ],
+ "expected one warning per limit for the highest crossed threshold"
+ );
+}
+
+#[test]
+fn test_rate_limit_warnings_monthly() {
+ let mut state = RateLimitWarningState::default();
+ let mut warnings: Vec<String> = Vec::new();
+
+ warnings.extend(state.take_warnings(Some(75.0), Some(43199), None, None));
+ assert_eq!(
+ warnings,
+ vec![String::from(
+ "Heads up, you have less than 25% of your monthly limit left. Run /status for a breakdown.",
+ ),],
+ "expected one warning per limit for the highest crossed threshold"
+ );
+}
+
+#[test]
+fn rate_limit_snapshot_keeps_prior_credits_when_missing_from_headers() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
+ primary: None,
+ secondary: None,
+ credits: Some(CreditsSnapshot {
+ has_credits: true,
+ unlimited: false,
+ balance: Some("17.5".to_string()),
+ }),
+ plan_type: None,
+ }));
+ let initial_balance = chat
+ .rate_limit_snapshot
+ .as_ref()
+ .and_then(|snapshot| snapshot.credits.as_ref())
+ .and_then(|credits| credits.balance.as_deref());
+ assert_eq!(initial_balance, Some("17.5"));
+
+ chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
+ primary: Some(RateLimitWindow {
+ used_percent: 80.0,
+ window_minutes: Some(60),
+ resets_at: Some(123),
+ }),
+ secondary: None,
+ credits: None,
+ plan_type: None,
+ }));
+
+ let display = chat
+ .rate_limit_snapshot
+ .as_ref()
+ .expect("rate limits should be cached");
+ let credits = display
+ .credits
+ .as_ref()
+ .expect("credits should persist when headers omit them");
+
+ assert_eq!(credits.balance.as_deref(), Some("17.5"));
+ assert!(!credits.unlimited);
+ assert_eq!(
+ display.primary.as_ref().map(|window| window.used_percent),
+ Some(80.0)
+ );
+}
+
+#[test]
+fn rate_limit_snapshot_updates_and_retains_plan_type() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
+ primary: Some(RateLimitWindow {
+ used_percent: 10.0,
+ window_minutes: Some(60),
+ resets_at: None,
+ }),
+ secondary: Some(RateLimitWindow {
+ used_percent: 5.0,
+ window_minutes: Some(300),
+ resets_at: None,
+ }),
+ credits: None,
+ plan_type: Some(PlanType::Plus),
+ }));
+ assert_eq!(chat.plan_type, Some(PlanType::Plus));
+
+ chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
+ primary: Some(RateLimitWindow {
+ used_percent: 25.0,
+ window_minutes: Some(30),
+ resets_at: Some(123),
+ }),
+ secondary: Some(RateLimitWindow {
+ used_percent: 15.0,
+ window_minutes: Some(300),
+ resets_at: Some(234),
+ }),
+ credits: None,
+ plan_type: Some(PlanType::Pro),
+ }));
+ assert_eq!(chat.plan_type, Some(PlanType::Pro));
+
+ chat.on_rate_limit_snapshot(Some(RateLimitSnapshot {
+ primary: Some(RateLimitWindow {
+ used_percent: 30.0,
+ window_minutes: Some(60),
+ resets_at: Some(456),
+ }),
+ secondary: Some(RateLimitWindow {
+ used_percent: 18.0,
+ window_minutes: Some(300),
+ resets_at: Some(567),
+ }),
+ credits: None,
+ plan_type: None,
+ }));
+ assert_eq!(chat.plan_type, Some(PlanType::Pro));
+}
+
+#[test]
+fn rate_limit_switch_prompt_skips_when_on_lower_cost_model() {
+ let (mut chat, _, _) = make_chatwidget_manual(Some(NUDGE_MODEL_SLUG));
+ chat.auth_manager =
+ AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
+
+ chat.on_rate_limit_snapshot(Some(snapshot(95.0)));
+
+ assert!(matches!(
+ chat.rate_limit_switch_prompt,
+ RateLimitSwitchPromptState::Idle
+ ));
+}
+
+#[test]
+fn rate_limit_switch_prompt_shows_once_per_session() {
+ let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
+ let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5"));
+ chat.auth_manager = AuthManager::from_auth_for_testing(auth);
+
+ chat.on_rate_limit_snapshot(Some(snapshot(90.0)));
+ assert!(
+ chat.rate_limit_warnings.primary_index >= 1,
+ "warnings not emitted"
+ );
+ chat.maybe_show_pending_rate_limit_prompt();
+ assert!(matches!(
+ chat.rate_limit_switch_prompt,
+ RateLimitSwitchPromptState::Shown
+ ));
+
+ chat.on_rate_limit_snapshot(Some(snapshot(95.0)));
+ assert!(matches!(
+ chat.rate_limit_switch_prompt,
+ RateLimitSwitchPromptState::Shown
+ ));
+}
+
+#[test]
+fn rate_limit_switch_prompt_respects_hidden_notice() {
+ let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
+ let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5"));
+ chat.auth_manager = AuthManager::from_auth_for_testing(auth);
+ chat.config.notices.hide_rate_limit_model_nudge = Some(true);
+
+ chat.on_rate_limit_snapshot(Some(snapshot(95.0)));
+
+ assert!(matches!(
+ chat.rate_limit_switch_prompt,
+ RateLimitSwitchPromptState::Idle
+ ));
+}
+
+#[test]
+fn rate_limit_switch_prompt_defers_until_task_complete() {
+ let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
+ let (mut chat, _, _) = make_chatwidget_manual(Some("gpt-5"));
+ chat.auth_manager = AuthManager::from_auth_for_testing(auth);
+
+ chat.bottom_pane.set_task_running(true);
+ chat.on_rate_limit_snapshot(Some(snapshot(90.0)));
+ assert!(matches!(
+ chat.rate_limit_switch_prompt,
+ RateLimitSwitchPromptState::Pending
+ ));
+
+ chat.bottom_pane.set_task_running(false);
+ chat.maybe_show_pending_rate_limit_prompt();
+ assert!(matches!(
+ chat.rate_limit_switch_prompt,
+ RateLimitSwitchPromptState::Shown
+ ));
+}
+
+#[test]
+fn rate_limit_switch_prompt_popup_snapshot() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5"));
+ chat.auth_manager =
+ AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
+
+ chat.on_rate_limit_snapshot(Some(snapshot(92.0)));
+ chat.maybe_show_pending_rate_limit_prompt();
+
+ let popup = render_bottom_popup(&chat, 80);
+ assert_snapshot!("rate_limit_switch_prompt_popup", popup);
+}
+
+// (removed experimental resize snapshot test)
+
+#[test]
+fn exec_approval_emits_proposed_command_and_decision_history() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Trigger an exec approval request with a short, single-line command
+ let ev = ExecApprovalRequestEvent {
+ call_id: "call-short".into(),
+ turn_id: "turn-short".into(),
+ command: vec!["bash".into(), "-lc".into(), "echo hello world".into()],
+ cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
+ reason: Some(
+ "this is a test reason such as one that would be produced by the model".into(),
+ ),
+ proposed_execpolicy_amendment: None,
+ parsed_cmd: vec![],
+ };
+ chat.handle_codex_event(Event {
+ id: "sub-short".into(),
+ msg: EventMsg::ExecApprovalRequest(ev),
+ });
+
+ let proposed_cells = drain_insert_history(&mut rx);
+ assert!(
+ proposed_cells.is_empty(),
+ "expected approval request to render via modal without emitting history cells"
+ );
+
+ // The approval modal should display the command snippet for user confirmation.
+ let area = Rect::new(0, 0, 80, chat.desired_height(80));
+ let mut buf = ratatui::buffer::Buffer::empty(area);
+ chat.render(area, &mut buf);
+ assert_snapshot!("exec_approval_modal_exec", format!("{buf:?}"));
+
+ // Approve via keyboard and verify a concise decision history line is added
+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
+ let decision = drain_insert_history(&mut rx)
+ .pop()
+ .expect("expected decision cell in history");
+ assert_snapshot!(
+ "exec_approval_history_decision_approved_short",
+ lines_to_single_string(&decision)
+ );
+}
+
+#[test]
+fn exec_approval_decision_truncates_multiline_and_long_commands() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Multiline command: modal should show full command, history records decision only
+ let ev_multi = ExecApprovalRequestEvent {
+ call_id: "call-multi".into(),
+ turn_id: "turn-multi".into(),
+ command: vec!["bash".into(), "-lc".into(), "echo line1\necho line2".into()],
+ cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
+ reason: Some(
+ "this is a test reason such as one that would be produced by the model".into(),
+ ),
+ proposed_execpolicy_amendment: None,
+ parsed_cmd: vec![],
+ };
+ chat.handle_codex_event(Event {
+ id: "sub-multi".into(),
+ msg: EventMsg::ExecApprovalRequest(ev_multi),
+ });
+ let proposed_multi = drain_insert_history(&mut rx);
+ assert!(
+ proposed_multi.is_empty(),
+ "expected multiline approval request to render via modal without emitting history cells"
+ );
+
+ let area = Rect::new(0, 0, 80, chat.desired_height(80));
+ let mut buf = ratatui::buffer::Buffer::empty(area);
+ chat.render(area, &mut buf);
+ let mut saw_first_line = false;
+ for y in 0..area.height {
+ let mut row = String::new();
+ for x in 0..area.width {
+ row.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
+ }
+ if row.contains("echo line1") {
+ saw_first_line = true;
+ break;
+ }
+ }
+ assert!(
+ saw_first_line,
+ "expected modal to show first line of multiline snippet"
+ );
+
+ // Deny via keyboard; decision snippet should be single-line and elided with " ..."
+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE));
+ let aborted_multi = drain_insert_history(&mut rx)
+ .pop()
+ .expect("expected aborted decision cell (multiline)");
+ assert_snapshot!(
+ "exec_approval_history_decision_aborted_multiline",
+ lines_to_single_string(&aborted_multi)
+ );
+
+ // Very long single-line command: decision snippet should be truncated <= 80 chars with trailing ...
+ let long = format!("echo {}", "a".repeat(200));
+ let ev_long = ExecApprovalRequestEvent {
+ call_id: "call-long".into(),
+ turn_id: "turn-long".into(),
+ command: vec!["bash".into(), "-lc".into(), long],
+ cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
+ reason: None,
+ proposed_execpolicy_amendment: None,
+ parsed_cmd: vec![],
+ };
+ chat.handle_codex_event(Event {
+ id: "sub-long".into(),
+ msg: EventMsg::ExecApprovalRequest(ev_long),
+ });
+ let proposed_long = drain_insert_history(&mut rx);
+ assert!(
+ proposed_long.is_empty(),
+ "expected long approval request to avoid emitting history cells before decision"
+ );
+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE));
+ let aborted_long = drain_insert_history(&mut rx)
+ .pop()
+ .expect("expected aborted decision cell (long)");
+ assert_snapshot!(
+ "exec_approval_history_decision_aborted_long",
+ lines_to_single_string(&aborted_long)
+ );
+}
+
+// --- Small helpers to tersely drive exec begin/end and snapshot active cell ---
+fn begin_exec_with_source(
+ chat: &mut ChatWidget,
+ call_id: &str,
+ raw_cmd: &str,
+ source: ExecCommandSource,
+) -> ExecCommandBeginEvent {
+ // Build the full command vec and parse it using core's parser,
+ // then convert to protocol variants for the event payload.
+ let command = vec!["bash".to_string(), "-lc".to_string(), raw_cmd.to_string()];
+ let parsed_cmd: Vec<ParsedCommand> = codex_core::parse_command::parse_command(&command);
+ let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
+ let interaction_input = None;
+ let event = ExecCommandBeginEvent {
+ call_id: call_id.to_string(),
+ process_id: None,
+ turn_id: "turn-1".to_string(),
+ command,
+ cwd,
+ parsed_cmd,
+ source,
+ interaction_input,
+ };
+ chat.handle_codex_event(Event {
+ id: call_id.to_string(),
+ msg: EventMsg::ExecCommandBegin(event.clone()),
+ });
+ event
+}
+
+fn begin_exec(chat: &mut ChatWidget, call_id: &str, raw_cmd: &str) -> ExecCommandBeginEvent {
+ begin_exec_with_source(chat, call_id, raw_cmd, ExecCommandSource::Agent)
+}
+
+fn end_exec(
+ chat: &mut ChatWidget,
+ begin_event: ExecCommandBeginEvent,
+ stdout: &str,
+ stderr: &str,
+ exit_code: i32,
+) {
+ let aggregated = if stderr.is_empty() {
+ stdout.to_string()
+ } else {
+ format!("{stdout}{stderr}")
+ };
+ let ExecCommandBeginEvent {
+ call_id,
+ turn_id,
+ command,
+ cwd,
+ parsed_cmd,
+ source,
+ interaction_input,
+ process_id,
+ } = begin_event;
+ chat.handle_codex_event(Event {
+ id: call_id.clone(),
+ msg: EventMsg::ExecCommandEnd(ExecCommandEndEvent {
+ call_id,
+ process_id,
+ turn_id,
+ command,
+ cwd,
+ parsed_cmd,
+ source,
+ interaction_input,
+ stdout: stdout.to_string(),
+ stderr: stderr.to_string(),
+ aggregated_output: aggregated.clone(),
+ exit_code,
+ duration: std::time::Duration::from_millis(5),
+ formatted_output: aggregated,
+ }),
+ });
+}
+
+fn active_blob(chat: &ChatWidget) -> String {
+ let lines = chat
+ .active_cell
+ .as_ref()
+ .expect("active cell present")
+ .display_lines(80);
+ lines_to_single_string(&lines)
+}
+
+fn get_available_model(chat: &ChatWidget, model: &str) -> ModelPreset {
+ let models = chat
+ .models_manager
+ .try_list_models()
+ .expect("models lock available");
+ models
+ .iter()
+ .find(|&preset| preset.model == model)
+ .cloned()
+ .unwrap_or_else(|| panic!("{model} preset not found"))
+}
+
+#[test]
+fn empty_enter_during_task_does_not_queue() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Simulate running task so submissions would normally be queued.
+ chat.bottom_pane.set_task_running(true);
+
+ // Press Enter with an empty composer.
+ chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ // Ensure nothing was queued.
+ assert!(chat.queued_user_messages.is_empty());
+}
+
+#[test]
+fn alt_up_edits_most_recent_queued_message() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Simulate a running task so messages would normally be queued.
+ chat.bottom_pane.set_task_running(true);
+
+ // Seed two queued messages.
+ chat.queued_user_messages
+ .push_back(UserMessage::from("first queued".to_string()));
+ chat.queued_user_messages
+ .push_back(UserMessage::from("second queued".to_string()));
+ chat.refresh_queued_user_messages();
+
+ // Press Alt+Up to edit the most recent (last) queued message.
+ chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::ALT));
+
+ // Composer should now contain the last queued message.
+ assert_eq!(
+ chat.bottom_pane.composer_text(),
+ "second queued".to_string()
+ );
+ // And the queue should now contain only the remaining (older) item.
+ assert_eq!(chat.queued_user_messages.len(), 1);
+ assert_eq!(
+ chat.queued_user_messages.front().unwrap().text,
+ "first queued"
+ );
+}
+
+/// Pressing Up to recall the most recent history entry and immediately queuing
+/// it while a task is running should always enqueue the same text, even when it
+/// is queued repeatedly.
+#[test]
+fn enqueueing_history_prompt_multiple_times_is_stable() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Submit an initial prompt to seed history.
+ chat.bottom_pane.set_composer_text("repeat me".to_string());
+ chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ // Simulate an active task so further submissions are queued.
+ chat.bottom_pane.set_task_running(true);
+
+ for _ in 0..3 {
+ // Recall the prompt from history and ensure it is what we expect.
+ chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
+ assert_eq!(chat.bottom_pane.composer_text(), "repeat me");
+
+ // Queue the prompt while the task is running.
+ chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ }
+
+ assert_eq!(chat.queued_user_messages.len(), 3);
+ for message in chat.queued_user_messages.iter() {
+ assert_eq!(message.text, "repeat me");
+ }
+}
+
+#[test]
+fn streaming_final_answer_keeps_task_running_state() {
+ let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None);
+
+ chat.on_task_started();
+ chat.on_agent_message_delta("Final answer line\n".to_string());
+ chat.on_commit_tick();
+
+ assert!(chat.bottom_pane.is_task_running());
+ assert!(chat.bottom_pane.status_widget().is_none());
+
+ chat.bottom_pane
+ .set_composer_text("queued submission".to_string());
+ chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ assert_eq!(chat.queued_user_messages.len(), 1);
+ assert_eq!(
+ chat.queued_user_messages.front().unwrap().text,
+ "queued submission"
+ );
+ assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty));
+
+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
+ match op_rx.try_recv() {
+ Ok(Op::Interrupt) => {}
+ other => panic!("expected Op::Interrupt, got {other:?}"),
+ }
+ assert!(chat.bottom_pane.ctrl_c_quit_hint_visible());
+}
+
+#[test]
+fn ctrl_c_shutdown_ignores_caps_lock() {
+ let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None);
+
+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('C'), KeyModifiers::CONTROL));
+
+ match op_rx.try_recv() {
+ Ok(Op::Shutdown) => {}
+ other => panic!("expected Op::Shutdown, got {other:?}"),
+ }
+}
+
+#[test]
+fn ctrl_c_cleared_prompt_is_recoverable_via_history() {
+ let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None);
+
+ chat.bottom_pane.insert_str("draft message ");
+ chat.bottom_pane
+ .attach_image(PathBuf::from("/tmp/preview.png"), 24, 42, "png");
+ let placeholder = "[preview.png 24x42]";
+ assert!(
+ chat.bottom_pane.composer_text().ends_with(placeholder),
+ "expected placeholder {placeholder:?} in composer text"
+ );
+
+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
+ assert!(chat.bottom_pane.composer_text().is_empty());
+ assert_matches!(op_rx.try_recv(), Err(TryRecvError::Empty));
+ assert!(chat.bottom_pane.ctrl_c_quit_hint_visible());
+
+ chat.handle_key_event(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
+ let restored_text = chat.bottom_pane.composer_text();
+ assert!(
+ restored_text.ends_with(placeholder),
+ "expected placeholder {placeholder:?} after history recall"
+ );
+ assert!(restored_text.starts_with("draft message "));
+ assert!(!chat.bottom_pane.ctrl_c_quit_hint_visible());
+
+ let images = chat.bottom_pane.take_recent_submission_images();
+ assert!(
+ images.is_empty(),
+ "attachments are not preserved in history recall"
+ );
+}
+
+#[test]
+fn exec_history_cell_shows_working_then_completed() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Begin command
+ let begin = begin_exec(&mut chat, "call-1", "echo done");
+
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(cells.len(), 0, "no exec cell should have been flushed yet");
+
+ // End command successfully
+ end_exec(&mut chat, begin, "done", "", 0);
+
+ let cells = drain_insert_history(&mut rx);
+ // Exec end now finalizes and flushes the exec cell immediately.
+ assert_eq!(cells.len(), 1, "expected finalized exec cell to flush");
+ // Inspect the flushed exec cell rendering.
+ let lines = &cells[0];
+ let blob = lines_to_single_string(lines);
+ // New behavior: no glyph markers; ensure command is shown and no panic.
+ assert!(
+ blob.contains("• Ran"),
+ "expected summary header present: {blob:?}"
+ );
+ assert!(
+ blob.contains("echo done"),
+ "expected command text to be present: {blob:?}"
+ );
+}
+
+#[test]
+fn exec_history_cell_shows_working_then_failed() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Begin command
+ let begin = begin_exec(&mut chat, "call-2", "false");
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(cells.len(), 0, "no exec cell should have been flushed yet");
+
+ // End command with failure
+ end_exec(&mut chat, begin, "", "Bloop", 2);
+
+ let cells = drain_insert_history(&mut rx);
+ // Exec end with failure should also flush immediately.
+ assert_eq!(cells.len(), 1, "expected finalized exec cell to flush");
+ let lines = &cells[0];
+ let blob = lines_to_single_string(lines);
+ assert!(
+ blob.contains("• Ran false"),
+ "expected command and header text present: {blob:?}"
+ );
+ assert!(blob.to_lowercase().contains("bloop"), "expected error text");
+}
+
+#[test]
+fn exec_end_without_begin_uses_event_command() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+ let command = vec![
+ "bash".to_string(),
+ "-lc".to_string(),
+ "echo orphaned".to_string(),
+ ];
+ let parsed_cmd = codex_core::parse_command::parse_command(&command);
+ let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
+ chat.handle_codex_event(Event {
+ id: "call-orphan".to_string(),
+ msg: EventMsg::ExecCommandEnd(ExecCommandEndEvent {
+ call_id: "call-orphan".to_string(),
+ process_id: None,
+ turn_id: "turn-1".to_string(),
+ command,
+ cwd,
+ parsed_cmd,
+ source: ExecCommandSource::Agent,
+ interaction_input: None,
+ stdout: "done".to_string(),
+ stderr: String::new(),
+ aggregated_output: "done".to_string(),
+ exit_code: 0,
+ duration: std::time::Duration::from_millis(5),
+ formatted_output: "done".to_string(),
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(cells.len(), 1, "expected finalized exec cell to flush");
+ let blob = lines_to_single_string(&cells[0]);
+ assert!(
+ blob.contains("• Ran echo orphaned"),
+ "expected command text to come from event: {blob:?}"
+ );
+ assert!(
+ !blob.contains("call-orphan"),
+ "call id should not be rendered when event has the command: {blob:?}"
+ );
+}
+
+#[test]
+fn exec_history_shows_unified_exec_startup_commands() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ let begin = begin_exec_with_source(
+ &mut chat,
+ "call-startup",
+ "echo unified exec startup",
+ ExecCommandSource::UnifiedExecStartup,
+ );
+ assert!(
+ drain_insert_history(&mut rx).is_empty(),
+ "exec begin should not flush until completion"
+ );
+
+ end_exec(&mut chat, begin, "echo unified exec startup\n", "", 0);
+
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(cells.len(), 1, "expected finalized exec cell to flush");
+ let blob = lines_to_single_string(&cells[0]);
+ assert!(
+ blob.contains("• Ran echo unified exec startup"),
+ "expected startup command to render: {blob:?}"
+ );
+}
+
+/// Selecting the custom prompt option from the review popup sends
+/// OpenReviewCustomPrompt to the app event channel.
+#[test]
+fn review_popup_custom_prompt_action_sends_event() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Open the preset selection popup
+ chat.open_review_popup();
+
+ // Move selection down to the fourth item: "Custom review instructions"
+ chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
+ chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
+ chat.handle_key_event(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
+ // Activate
+ chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ // Drain events and ensure we saw the OpenReviewCustomPrompt request
+ let mut found = false;
+ while let Ok(ev) = rx.try_recv() {
+ if let AppEvent::OpenReviewCustomPrompt = ev {
+ found = true;
+ break;
+ }
+ }
+ assert!(found, "expected OpenReviewCustomPrompt event to be sent");
+}
+
+#[test]
+fn slash_init_skips_when_project_doc_exists() {
+ let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None);
+ let tempdir = tempdir().unwrap();
+ let existing_path = tempdir.path().join(DEFAULT_PROJECT_DOC_FILENAME);
+ std::fs::write(&existing_path, "existing instructions").unwrap();
+ chat.config.cwd = tempdir.path().to_path_buf();
+
+ chat.dispatch_command(SlashCommand::Init);
+
+ match op_rx.try_recv() {
+ Err(TryRecvError::Empty) => {}
+ other => panic!("expected no Codex op to be sent, got {other:?}"),
+ }
+
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(cells.len(), 1, "expected one info message");
+ let rendered = lines_to_single_string(&cells[0]);
+ assert!(
+ rendered.contains(DEFAULT_PROJECT_DOC_FILENAME),
+ "info message should mention the existing file: {rendered:?}"
+ );
+ assert!(
+ rendered.contains("Skipping /init"),
+ "info message should explain why /init was skipped: {rendered:?}"
+ );
+ assert_eq!(
+ std::fs::read_to_string(existing_path).unwrap(),
+ "existing instructions"
+ );
+}
+
+#[test]
+fn slash_quit_requests_exit() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.dispatch_command(SlashCommand::Quit);
+
+ assert_matches!(rx.try_recv(), Ok(AppEvent::ExitRequest));
+}
+
+#[test]
+fn slash_exit_requests_exit() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.dispatch_command(SlashCommand::Exit);
+
+ assert_matches!(rx.try_recv(), Ok(AppEvent::ExitRequest));
+}
+
+#[test]
+fn slash_resume_opens_picker() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.dispatch_command(SlashCommand::Resume);
+
+ assert_matches!(rx.try_recv(), Ok(AppEvent::OpenResumePicker));
+}
+
+#[test]
+fn slash_undo_sends_op() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.dispatch_command(SlashCommand::Undo);
+
+ match rx.try_recv() {
+ Ok(AppEvent::CodexOp(Op::Undo)) => {}
+ other => panic!("expected AppEvent::CodexOp(Op::Undo), got {other:?}"),
+ }
+}
+
+#[test]
+fn slash_rollout_displays_current_path() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+ let rollout_path = PathBuf::from("/tmp/codex-test-rollout.jsonl");
+ chat.current_rollout_path = Some(rollout_path.clone());
+
+ chat.dispatch_command(SlashCommand::Rollout);
+
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(cells.len(), 1, "expected info message for rollout path");
+ let rendered = lines_to_single_string(&cells[0]);
+ assert!(
+ rendered.contains(&rollout_path.display().to_string()),
+ "expected rollout path to be shown: {rendered}"
+ );
+}
+
+#[test]
+fn slash_rollout_handles_missing_path() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.dispatch_command(SlashCommand::Rollout);
+
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(
+ cells.len(),
+ 1,
+ "expected info message explaining missing path"
+ );
+ let rendered = lines_to_single_string(&cells[0]);
+ assert!(
+ rendered.contains("not available"),
+ "expected missing rollout path message: {rendered}"
+ );
+}
+
+#[test]
+fn undo_success_events_render_info_messages() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.handle_codex_event(Event {
+ id: "turn-1".to_string(),
+ msg: EventMsg::UndoStarted(UndoStartedEvent {
+ message: Some("Undo requested for the last turn...".to_string()),
+ }),
+ });
+ assert!(
+ chat.bottom_pane.status_indicator_visible(),
+ "status indicator should be visible during undo"
+ );
+
+ chat.handle_codex_event(Event {
+ id: "turn-1".to_string(),
+ msg: EventMsg::UndoCompleted(UndoCompletedEvent {
+ success: true,
+ message: None,
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(cells.len(), 1, "expected final status only");
+ assert!(
+ !chat.bottom_pane.status_indicator_visible(),
+ "status indicator should be hidden after successful undo"
+ );
+
+ let completed = lines_to_single_string(&cells[0]);
+ assert!(
+ completed.contains("Undo completed successfully."),
+ "expected default success message, got {completed:?}"
+ );
+}
+
+#[test]
+fn undo_failure_events_render_error_message() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.handle_codex_event(Event {
+ id: "turn-2".to_string(),
+ msg: EventMsg::UndoStarted(UndoStartedEvent { message: None }),
+ });
+ assert!(
+ chat.bottom_pane.status_indicator_visible(),
+ "status indicator should be visible during undo"
+ );
+
+ chat.handle_codex_event(Event {
+ id: "turn-2".to_string(),
+ msg: EventMsg::UndoCompleted(UndoCompletedEvent {
+ success: false,
+ message: Some("Failed to restore workspace state.".to_string()),
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(cells.len(), 1, "expected final status only");
+ assert!(
+ !chat.bottom_pane.status_indicator_visible(),
+ "status indicator should be hidden after failed undo"
+ );
+
+ let completed = lines_to_single_string(&cells[0]);
+ assert!(
+ completed.contains("Failed to restore workspace state."),
+ "expected failure message, got {completed:?}"
+ );
+}
+
+#[test]
+fn undo_started_hides_interrupt_hint() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.handle_codex_event(Event {
+ id: "turn-hint".to_string(),
+ msg: EventMsg::UndoStarted(UndoStartedEvent { message: None }),
+ });
+
+ let status = chat
+ .bottom_pane
+ .status_widget()
+ .expect("status indicator should be active");
+ assert!(
+ !status.interrupt_hint_visible(),
+ "undo should hide the interrupt hint because the operation cannot be cancelled"
+ );
+}
+
+/// The commit picker shows only commit subjects (no timestamps).
+#[test]
+fn review_commit_picker_shows_subjects_without_timestamps() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Open the Review presets parent popup.
+ chat.open_review_popup();
+
+ // Show commit picker with synthetic entries.
+ let entries = vec![
+ codex_core::git_info::CommitLogEntry {
+ sha: "1111111deadbeef".to_string(),
+ timestamp: 0,
+ subject: "Add new feature X".to_string(),
+ },
+ codex_core::git_info::CommitLogEntry {
+ sha: "2222222cafebabe".to_string(),
+ timestamp: 0,
+ subject: "Fix bug Y".to_string(),
+ },
+ ];
+ super::show_review_commit_picker_with_entries(&mut chat, entries);
+
+ // Render the bottom pane and inspect the lines for subjects and absence of time words.
+ let width = 72;
+ let height = chat.desired_height(width);
+ let area = ratatui::layout::Rect::new(0, 0, width, height);
+ let mut buf = ratatui::buffer::Buffer::empty(area);
+ chat.render(area, &mut buf);
+
+ let mut blob = String::new();
+ for y in 0..area.height {
+ for x in 0..area.width {
+ let s = buf[(x, y)].symbol();
+ if s.is_empty() {
+ blob.push(' ');
+ } else {
+ blob.push_str(s);
+ }
+ }
+ blob.push('\n');
+ }
+
+ assert!(
+ blob.contains("Add new feature X"),
+ "expected subject in output"
+ );
+ assert!(blob.contains("Fix bug Y"), "expected subject in output");
+
+ // Ensure no relative-time phrasing is present.
+ let lowered = blob.to_lowercase();
+ assert!(
+ !lowered.contains("ago")
+ && !lowered.contains(" second")
+ && !lowered.contains(" minute")
+ && !lowered.contains(" hour")
+ && !lowered.contains(" day"),
+ "expected no relative time in commit picker output: {blob:?}"
+ );
+}
+
+/// Submitting the custom prompt view sends Op::Review with the typed prompt
+/// and uses the same text for the user-facing hint.
+#[test]
+fn custom_prompt_submit_sends_review_op() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.show_review_custom_prompt();
+ // Paste prompt text via ChatWidget handler, then submit
+ chat.handle_paste(" please audit dependencies ".to_string());
+ chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ // Expect AppEvent::CodexOp(Op::Review { .. }) with trimmed prompt
+ let evt = rx.try_recv().expect("expected one app event");
+ match evt {
+ AppEvent::CodexOp(Op::Review { review_request }) => {
+ assert_eq!(
+ review_request,
+ ReviewRequest {
+ target: ReviewTarget::Custom {
+ instructions: "please audit dependencies".to_string(),
+ },
+ user_facing_hint: None,
+ }
+ );
+ }
+ other => panic!("unexpected app event: {other:?}"),
+ }
+}
+
+/// Hitting Enter on an empty custom prompt view does not submit.
+#[test]
+fn custom_prompt_enter_empty_does_not_send() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.show_review_custom_prompt();
+ // Enter without any text
+ chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+
+ // No AppEvent::CodexOp should be sent
+ assert!(rx.try_recv().is_err(), "no app event should be sent");
+}
+
+#[test]
+fn view_image_tool_call_adds_history_cell() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+ let image_path = chat.config.cwd.join("example.png");
+
+ chat.handle_codex_event(Event {
+ id: "sub-image".into(),
+ msg: EventMsg::ViewImageToolCall(ViewImageToolCallEvent {
+ call_id: "call-image".into(),
+ path: image_path,
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(cells.len(), 1, "expected a single history cell");
+ let combined = lines_to_single_string(&cells[0]);
+ assert_snapshot!("local_image_attachment_history_snapshot", combined);
+}
+
+// Snapshot test: interrupting a running exec finalizes the active cell with a red ✗
+// marker (replacing the spinner) and flushes it into history.
+#[test]
+fn interrupt_exec_marks_failed_snapshot() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Begin a long-running command so we have an active exec cell with a spinner.
+ begin_exec(&mut chat, "call-int", "sleep 1");
+
+ // Simulate the task being aborted (as if ESC was pressed), which should
+ // cause the active exec cell to be finalized as failed and flushed.
+ chat.handle_codex_event(Event {
+ id: "call-int".into(),
+ msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent {
+ reason: TurnAbortReason::Interrupted,
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ assert!(
+ !cells.is_empty(),
+ "expected finalized exec cell to be inserted into history"
+ );
+
+ // The first inserted cell should be the finalized exec; snapshot its text.
+ let exec_blob = lines_to_single_string(&cells[0]);
+ assert_snapshot!("interrupt_exec_marks_failed", exec_blob);
+}
+
+// Snapshot test: after an interrupted turn, a gentle error message is inserted
+// suggesting the user to tell the model what to do differently and to use /feedback.
+#[test]
+fn interrupted_turn_error_message_snapshot() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Simulate an in-progress task so the widget is in a running state.
+ chat.handle_codex_event(Event {
+ id: "task-1".into(),
+ msg: EventMsg::TaskStarted(TaskStartedEvent {
+ model_context_window: None,
+ }),
+ });
+
+ // Abort the turn (like pressing Esc) and drain inserted history.
+ chat.handle_codex_event(Event {
+ id: "task-1".into(),
+ msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent {
+ reason: TurnAbortReason::Interrupted,
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ assert!(
+ !cells.is_empty(),
+ "expected error message to be inserted after interruption"
+ );
+ let last = lines_to_single_string(cells.last().unwrap());
+ assert_snapshot!("interrupted_turn_error_message", last);
+}
+
+/// Opening custom prompt from the review popup, pressing Esc returns to the
+/// parent popup, pressing Esc again dismisses all panels (back to normal mode).
+#[test]
+fn review_custom_prompt_escape_navigates_back_then_dismisses() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Open the Review presets parent popup.
+ chat.open_review_popup();
+
+ // Open the custom prompt submenu (child view) directly.
+ chat.show_review_custom_prompt();
+
+ // Verify child view is on top.
+ let header = render_bottom_first_row(&chat, 60);
+ assert!(
+ header.contains("Custom review instructions"),
+ "expected custom prompt view header: {header:?}"
+ );
+
+ // Esc once: child view closes, parent (review presets) remains.
+ chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+ let header = render_bottom_first_row(&chat, 60);
+ assert!(
+ header.contains("Select a review preset"),
+ "expected to return to parent review popup: {header:?}"
+ );
+
+ // Esc again: parent closes; back to normal composer state.
+ chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+ assert!(
+ chat.is_normal_backtrack_mode(),
+ "expected to be back in normal composer mode"
+ );
+}
+
+/// Opening base-branch picker from the review popup, pressing Esc returns to the
+/// parent popup, pressing Esc again dismisses all panels (back to normal mode).
+#[tokio::test]
+async fn review_branch_picker_escape_navigates_back_then_dismisses() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Open the Review presets parent popup.
+ chat.open_review_popup();
+
+ // Open the branch picker submenu (child view). Using a temp cwd with no git repo is fine.
+ let cwd = std::env::temp_dir();
+ chat.show_review_branch_picker(&cwd).await;
+
+ // Verify child view header.
+ let header = render_bottom_first_row(&chat, 60);
+ assert!(
+ header.contains("Select a base branch"),
+ "expected branch picker header: {header:?}"
+ );
+
+ // Esc once: child view closes, parent remains.
+ chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+ let header = render_bottom_first_row(&chat, 60);
+ assert!(
+ header.contains("Select a review preset"),
+ "expected to return to parent review popup: {header:?}"
+ );
+
+ // Esc again: parent closes; back to normal composer state.
+ chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+ assert!(
+ chat.is_normal_backtrack_mode(),
+ "expected to be back in normal composer mode"
+ );
+}
+
+fn render_bottom_first_row(chat: &ChatWidget, width: u16) -> String {
+ let height = chat.desired_height(width);
+ let area = Rect::new(0, 0, width, height);
+ let mut buf = Buffer::empty(area);
+ chat.render(area, &mut buf);
+ for y in 0..area.height {
+ let mut row = String::new();
+ for x in 0..area.width {
+ let s = buf[(x, y)].symbol();
+ if s.is_empty() {
+ row.push(' ');
+ } else {
+ row.push_str(s);
+ }
+ }
+ if !row.trim().is_empty() {
+ return row;
+ }
+ }
+ String::new()
+}
+
+fn render_bottom_popup(chat: &ChatWidget, width: u16) -> String {
+ let height = chat.desired_height(width);
+ let area = Rect::new(0, 0, width, height);
+ let mut buf = Buffer::empty(area);
+ chat.render(area, &mut buf);
+
+ let mut lines: Vec<String> = (0..area.height)
+ .map(|row| {
+ let mut line = String::new();
+ for col in 0..area.width {
+ let symbol = buf[(area.x + col, area.y + row)].symbol();
+ if symbol.is_empty() {
+ line.push(' ');
+ } else {
+ line.push_str(symbol);
+ }
+ }
+ line.trim_end().to_string()
+ })
+ .collect();
+
+ while lines.first().is_some_and(|line| line.trim().is_empty()) {
+ lines.remove(0);
+ }
+ while lines.last().is_some_and(|line| line.trim().is_empty()) {
+ lines.pop();
+ }
+
+ lines.join("\n")
+}
+
+#[test]
+fn model_selection_popup_snapshot() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5-codex"));
+ chat.open_model_popup();
+
+ let popup = render_bottom_popup(&chat, 80);
+ assert_snapshot!("model_selection_popup", popup);
+}
+
+#[test]
+fn approvals_selection_popup_snapshot() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.config.notices.hide_full_access_warning = None;
+ chat.open_approvals_popup();
+
+ let popup = render_bottom_popup(&chat, 80);
+ #[cfg(target_os = "windows")]
+ insta::with_settings!({ snapshot_suffix => "windows" }, {
+ assert_snapshot!("approvals_selection_popup", popup);
+ });
+ #[cfg(not(target_os = "windows"))]
+ assert_snapshot!("approvals_selection_popup", popup);
+}
+
+#[test]
+fn preset_matching_ignores_extra_writable_roots() {
+ let preset = builtin_approval_presets()
+ .into_iter()
+ .find(|p| p.id == "auto")
+ .expect("auto preset exists");
+ let current_sandbox = SandboxPolicy::WorkspaceWrite {
+ writable_roots: vec![PathBuf::from("C:\\extra")],
+ network_access: false,
+ exclude_tmpdir_env_var: false,
+ exclude_slash_tmp: false,
+ };
+
+ assert!(
+ ChatWidget::preset_matches_current(AskForApproval::OnRequest, &current_sandbox, &preset),
+ "WorkspaceWrite with extra roots should still match the Agent preset"
+ );
+ assert!(
+ !ChatWidget::preset_matches_current(AskForApproval::Never, &current_sandbox, &preset),
+ "approval mismatch should prevent matching the preset"
+ );
+}
+
+#[test]
+fn full_access_confirmation_popup_snapshot() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ let preset = builtin_approval_presets()
+ .into_iter()
+ .find(|preset| preset.id == "full-access")
+ .expect("full access preset");
+ chat.open_full_access_confirmation(preset);
+
+ let popup = render_bottom_popup(&chat, 80);
+ assert_snapshot!("full_access_confirmation_popup", popup);
+}
+
+#[cfg(target_os = "windows")]
+#[test]
+fn windows_auto_mode_prompt_requests_enabling_sandbox_feature() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ let preset = builtin_approval_presets()
+ .into_iter()
+ .find(|preset| preset.id == "auto")
+ .expect("auto preset");
+ chat.open_windows_sandbox_enable_prompt(preset);
+
+ let popup = render_bottom_popup(&chat, 120);
+ assert!(
+ popup.contains("Agent mode on Windows uses an experimental sandbox"),
+ "expected auto mode prompt to mention enabling the sandbox feature, popup: {popup}"
+ );
+}
+
+#[cfg(target_os = "windows")]
+#[test]
+fn startup_prompts_for_windows_sandbox_when_agent_requested() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ set_windows_sandbox_enabled(false);
+ chat.config.forced_auto_mode_downgraded_on_windows = true;
+
+ chat.maybe_prompt_windows_sandbox_enable();
+
+ let popup = render_bottom_popup(&chat, 120);
+ assert!(
+ popup.contains("Agent mode on Windows uses an experimental sandbox"),
+ "expected startup prompt to explain sandbox: {popup}"
+ );
+ assert!(
+ popup.contains("Enable experimental sandbox"),
+ "expected startup prompt to offer enabling the sandbox: {popup}"
+ );
+
+ set_windows_sandbox_enabled(true);
+}
+
+#[test]
+fn model_reasoning_selection_popup_snapshot() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max"));
+
+ set_chatgpt_auth(&mut chat);
+ chat.config.model_reasoning_effort = Some(ReasoningEffortConfig::High);
+
+ let preset = get_available_model(&chat, "gpt-5.1-codex-max");
+ chat.open_reasoning_popup(preset);
+
+ let popup = render_bottom_popup(&chat, 80);
+ assert_snapshot!("model_reasoning_selection_popup", popup);
+}
+
+#[test]
+fn model_reasoning_selection_popup_extra_high_warning_snapshot() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max"));
+
+ set_chatgpt_auth(&mut chat);
+ chat.config.model_reasoning_effort = Some(ReasoningEffortConfig::XHigh);
+
+ let preset = get_available_model(&chat, "gpt-5.1-codex-max");
+ chat.open_reasoning_popup(preset);
+
+ let popup = render_bottom_popup(&chat, 80);
+ assert_snapshot!("model_reasoning_selection_popup_extra_high_warning", popup);
+}
+
+#[test]
+fn reasoning_popup_shows_extra_high_with_space() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max"));
+
+ set_chatgpt_auth(&mut chat);
+
+ let preset = get_available_model(&chat, "gpt-5.1-codex-max");
+ chat.open_reasoning_popup(preset);
+
+ let popup = render_bottom_popup(&chat, 120);
+ assert!(
+ popup.contains("Extra high"),
+ "expected popup to include 'Extra high'; popup: {popup}"
+ );
+ assert!(
+ !popup.contains("Extrahigh"),
+ "expected popup not to include 'Extrahigh'; popup: {popup}"
+ );
+}
+
+#[test]
+fn single_reasoning_option_skips_selection() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ let single_effort = vec![ReasoningEffortPreset {
+ effort: ReasoningEffortConfig::High,
+ description: "Maximizes reasoning depth for complex or ambiguous problems".to_string(),
+ }];
+ let preset = ModelPreset {
+ id: "model-with-single-reasoning".to_string(),
+ model: "model-with-single-reasoning".to_string(),
+ display_name: "model-with-single-reasoning".to_string(),
+ description: "".to_string(),
+ default_reasoning_effort: ReasoningEffortConfig::High,
+ supported_reasoning_efforts: single_effort,
+ is_default: false,
+ upgrade: None,
+ show_in_picker: true,
+ };
+ chat.open_reasoning_popup(preset);
+
+ let popup = render_bottom_popup(&chat, 80);
+ assert!(
+ !popup.contains("Select Reasoning Level"),
+ "expected reasoning selection popup to be skipped"
+ );
+
+ let mut events = Vec::new();
+ while let Ok(ev) = rx.try_recv() {
+ events.push(ev);
+ }
+
+ assert!(
+ events
+ .iter()
+ .any(|ev| matches!(ev, AppEvent::UpdateReasoningEffort(Some(effort)) if *effort == ReasoningEffortConfig::High)),
+ "expected reasoning effort to be applied automatically; events: {events:?}"
+ );
+}
+
+#[test]
+fn feedback_selection_popup_snapshot() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Open the feedback category selection popup via slash command.
+ chat.dispatch_command(SlashCommand::Feedback);
+
+ let popup = render_bottom_popup(&chat, 80);
+ assert_snapshot!("feedback_selection_popup", popup);
+}
+
+#[test]
+fn feedback_upload_consent_popup_snapshot() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Open the consent popup directly for a chosen category.
+ chat.open_feedback_consent(crate::app_event::FeedbackCategory::Bug);
+
+ let popup = render_bottom_popup(&chat, 80);
+ assert_snapshot!("feedback_upload_consent_popup", popup);
+}
+
+#[test]
+fn reasoning_popup_escape_returns_to_model_popup() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1"));
+ chat.open_model_popup();
+
+ let preset = get_available_model(&chat, "gpt-5.1-codex");
+ chat.open_reasoning_popup(preset);
+
+ let before_escape = render_bottom_popup(&chat, 80);
+ assert!(before_escape.contains("Select Reasoning Level"));
+
+ chat.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+
+ let after_escape = render_bottom_popup(&chat, 80);
+ assert!(after_escape.contains("Select Model"));
+ assert!(!after_escape.contains("Select Reasoning Level"));
+}
+
+#[test]
+fn exec_history_extends_previous_when_consecutive() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+
+ // 1) Start "ls -la" (List)
+ let begin_ls = begin_exec(&mut chat, "call-ls", "ls -la");
+ assert_snapshot!("exploring_step1_start_ls", active_blob(&chat));
+
+ // 2) Finish "ls -la"
+ end_exec(&mut chat, begin_ls, "", "", 0);
+ assert_snapshot!("exploring_step2_finish_ls", active_blob(&chat));
+
+ // 3) Start "cat foo.txt" (Read)
+ let begin_cat_foo = begin_exec(&mut chat, "call-cat-foo", "cat foo.txt");
+ assert_snapshot!("exploring_step3_start_cat_foo", active_blob(&chat));
+
+ // 4) Complete "cat foo.txt"
+ end_exec(&mut chat, begin_cat_foo, "hello from foo", "", 0);
+ assert_snapshot!("exploring_step4_finish_cat_foo", active_blob(&chat));
+
+ // 5) Start & complete "sed -n 100,200p foo.txt" (treated as Read of foo.txt)
+ let begin_sed_range = begin_exec(&mut chat, "call-sed-range", "sed -n 100,200p foo.txt");
+ end_exec(&mut chat, begin_sed_range, "chunk", "", 0);
+ assert_snapshot!("exploring_step5_finish_sed_range", active_blob(&chat));
+
+ // 6) Start & complete "cat bar.txt"
+ let begin_cat_bar = begin_exec(&mut chat, "call-cat-bar", "cat bar.txt");
+ end_exec(&mut chat, begin_cat_bar, "hello from bar", "", 0);
+ assert_snapshot!("exploring_step6_finish_cat_bar", active_blob(&chat));
+}
+
+#[test]
+fn user_shell_command_renders_output_not_exploring() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ let begin_ls = begin_exec_with_source(
+ &mut chat,
+ "user-shell-ls",
+ "ls",
+ ExecCommandSource::UserShell,
+ );
+ end_exec(&mut chat, begin_ls, "file1\nfile2\n", "", 0);
+
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(
+ cells.len(),
+ 1,
+ "expected a single history cell for the user command"
+ );
+ let blob = lines_to_single_string(cells.first().unwrap());
+ assert_snapshot!("user_shell_ls_output", blob);
+}
+
+#[test]
+fn disabled_slash_command_while_task_running_snapshot() {
+ // Build a chat widget and simulate an active task
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+ chat.bottom_pane.set_task_running(true);
+
+ // Dispatch a command that is unavailable while a task runs (e.g., /model)
+ chat.dispatch_command(SlashCommand::Model);
+
+ // Drain history and snapshot the rendered error line(s)
+ let cells = drain_insert_history(&mut rx);
+ assert!(
+ !cells.is_empty(),
+ "expected an error message history cell to be emitted",
+ );
+ let blob = lines_to_single_string(cells.last().unwrap());
+ assert_snapshot!(blob);
+}
+
+//
+// Snapshot test: command approval modal
+//
+// Synthesizes a Codex ExecApprovalRequest event to trigger the approval modal
+// and snapshots the visual output using the ratatui TestBackend.
+#[test]
+fn approval_modal_exec_snapshot() {
+ // Build a chat widget with manual channels to avoid spawning the agent.
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+ // Ensure policy allows surfacing approvals explicitly (not strictly required for direct event).
+ chat.config.approval_policy = AskForApproval::OnRequest;
+ // Inject an exec approval request to display the approval modal.
+ let ev = ExecApprovalRequestEvent {
+ call_id: "call-approve-cmd".into(),
+ turn_id: "turn-approve-cmd".into(),
+ command: vec!["bash".into(), "-lc".into(), "echo hello world".into()],
+ cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
+ reason: Some(
+ "this is a test reason such as one that would be produced by the model".into(),
+ ),
+ proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![
+ "echo".into(),
+ "hello".into(),
+ "world".into(),
+ ])),
+ parsed_cmd: vec![],
+ };
+ chat.handle_codex_event(Event {
+ id: "sub-approve".into(),
+ msg: EventMsg::ExecApprovalRequest(ev),
+ });
+ // Render to a fixed-size test terminal and snapshot.
+ // Call desired_height first and use that exact height for rendering.
+ let width = 100;
+ let height = chat.desired_height(width);
+ let mut terminal =
+ crate::custom_terminal::Terminal::with_options(VT100Backend::new(width, height))
+ .expect("create terminal");
+ let viewport = Rect::new(0, 0, width, height);
+ terminal.set_viewport_area(viewport);
+
+ terminal
+ .draw(|f| chat.render(f.area(), f.buffer_mut()))
+ .expect("draw approval modal");
+ assert!(
+ terminal
+ .backend()
+ .vt100()
+ .screen()
+ .contents()
+ .contains("echo hello world")
+ );
+ assert_snapshot!(
+ "approval_modal_exec",
+ terminal.backend().vt100().screen().contents()
+ );
+}
+
+// Snapshot test: command approval modal without a reason
+// Ensures spacing looks correct when no reason text is provided.
+#[test]
+fn approval_modal_exec_without_reason_snapshot() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+ chat.config.approval_policy = AskForApproval::OnRequest;
+
+ let ev = ExecApprovalRequestEvent {
+ call_id: "call-approve-cmd-noreason".into(),
+ turn_id: "turn-approve-cmd-noreason".into(),
+ command: vec!["bash".into(), "-lc".into(), "echo hello world".into()],
+ cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
+ reason: None,
+ proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![
+ "echo".into(),
+ "hello".into(),
+ "world".into(),
+ ])),
+ parsed_cmd: vec![],
+ };
+ chat.handle_codex_event(Event {
+ id: "sub-approve-noreason".into(),
+ msg: EventMsg::ExecApprovalRequest(ev),
+ });
+
+ let width = 100;
+ let height = chat.desired_height(width);
+ let mut terminal =
+ ratatui::Terminal::new(VT100Backend::new(width, height)).expect("create terminal");
+ terminal.set_viewport_area(Rect::new(0, 0, width, height));
+ terminal
+ .draw(|f| chat.render(f.area(), f.buffer_mut()))
+ .expect("draw approval modal (no reason)");
+ assert_snapshot!(
+ "approval_modal_exec_no_reason",
+ terminal.backend().vt100().screen().contents()
+ );
+}
+
+// Snapshot test: patch approval modal
+#[test]
+fn approval_modal_patch_snapshot() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+ chat.config.approval_policy = AskForApproval::OnRequest;
+
+ // Build a small changeset and a reason/grant_root to exercise the prompt text.
+ let mut changes = HashMap::new();
+ changes.insert(
+ PathBuf::from("README.md"),
+ FileChange::Add {
+ content: "hello\nworld\n".into(),
+ },
+ );
+ let ev = ApplyPatchApprovalRequestEvent {
+ call_id: "call-approve-patch".into(),
+ turn_id: "turn-approve-patch".into(),
+ changes,
+ reason: Some("The model wants to apply changes".into()),
+ grant_root: Some(PathBuf::from("/tmp")),
+ };
+ chat.handle_codex_event(Event {
+ id: "sub-approve-patch".into(),
+ msg: EventMsg::ApplyPatchApprovalRequest(ev),
+ });
+
+ // Render at the widget's desired height and snapshot.
+ let height = chat.desired_height(80);
+ let mut terminal =
+ ratatui::Terminal::new(VT100Backend::new(80, height)).expect("create terminal");
+ terminal.set_viewport_area(Rect::new(0, 0, 80, height));
+ terminal
+ .draw(|f| chat.render(f.area(), f.buffer_mut()))
+ .expect("draw patch approval modal");
+ assert_snapshot!(
+ "approval_modal_patch",
+ terminal.backend().vt100().screen().contents()
+ );
+}
+
+#[test]
+fn interrupt_restores_queued_messages_into_composer() {
+ let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None);
+
+ // Simulate a running task to enable queuing of user inputs.
+ chat.bottom_pane.set_task_running(true);
+
+ // Queue two user messages while the task is running.
+ chat.queued_user_messages
+ .push_back(UserMessage::from("first queued".to_string()));
+ chat.queued_user_messages
+ .push_back(UserMessage::from("second queued".to_string()));
+ chat.refresh_queued_user_messages();
+
+ // Deliver a TurnAborted event with Interrupted reason (as if Esc was pressed).
+ chat.handle_codex_event(Event {
+ id: "turn-1".into(),
+ msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent {
+ reason: TurnAbortReason::Interrupted,
+ }),
+ });
+
+ // Composer should now contain the queued messages joined by newlines, in order.
+ assert_eq!(
+ chat.bottom_pane.composer_text(),
+ "first queued\nsecond queued"
+ );
+
+ // Queue should be cleared and no new user input should have been auto-submitted.
+ assert!(chat.queued_user_messages.is_empty());
+ assert!(
+ op_rx.try_recv().is_err(),
+ "unexpected outbound op after interrupt"
+ );
+
+ // Drain rx to avoid unused warnings.
+ let _ = drain_insert_history(&mut rx);
+}
+
+#[test]
+fn interrupt_prepends_queued_messages_before_existing_composer_text() {
+ let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None);
+
+ chat.bottom_pane.set_task_running(true);
+ chat.bottom_pane
+ .set_composer_text("current draft".to_string());
+
+ chat.queued_user_messages
+ .push_back(UserMessage::from("first queued".to_string()));
+ chat.queued_user_messages
+ .push_back(UserMessage::from("second queued".to_string()));
+ chat.refresh_queued_user_messages();
+
+ chat.handle_codex_event(Event {
+ id: "turn-1".into(),
+ msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent {
+ reason: TurnAbortReason::Interrupted,
+ }),
+ });
+
+ assert_eq!(
+ chat.bottom_pane.composer_text(),
+ "first queued\nsecond queued\ncurrent draft"
+ );
+ assert!(chat.queued_user_messages.is_empty());
+ assert!(
+ op_rx.try_recv().is_err(),
+ "unexpected outbound op after interrupt"
+ );
+
+ let _ = drain_insert_history(&mut rx);
+}
+
+// Snapshot test: ChatWidget at very small heights (idle)
+// Ensures overall layout behaves when terminal height is extremely constrained.
+#[test]
+fn ui_snapshots_small_heights_idle() {
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+ let (chat, _rx, _op_rx) = make_chatwidget_manual(None);
+ for h in [1u16, 2, 3] {
+ let name = format!("chat_small_idle_h{h}");
+ let mut terminal = Terminal::new(TestBackend::new(40, h)).expect("create terminal");
+ terminal
+ .draw(|f| chat.render(f.area(), f.buffer_mut()))
+ .expect("draw chat idle");
+ assert_snapshot!(name, terminal.backend());
+ }
+}
+
+// Snapshot test: ChatWidget at very small heights (task running)
+// Validates how status + composer are presented within tight space.
+#[test]
+fn ui_snapshots_small_heights_task_running() {
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+ // Activate status line
+ chat.handle_codex_event(Event {
+ id: "task-1".into(),
+ msg: EventMsg::TaskStarted(TaskStartedEvent {
+ model_context_window: None,
+ }),
+ });
+ chat.handle_codex_event(Event {
+ id: "task-1".into(),
+ msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent {
+ delta: "**Thinking**".into(),
+ }),
+ });
+ for h in [1u16, 2, 3] {
+ let name = format!("chat_small_running_h{h}");
+ let mut terminal = Terminal::new(TestBackend::new(40, h)).expect("create terminal");
+ terminal
+ .draw(|f| chat.render(f.area(), f.buffer_mut()))
+ .expect("draw chat running");
+ assert_snapshot!(name, terminal.backend());
+ }
+}
+
+// Snapshot test: status widget + approval modal active together
+// The modal takes precedence visually; this captures the layout with a running
+// task (status indicator active) while an approval request is shown.
+#[test]
+fn status_widget_and_approval_modal_snapshot() {
+ use codex_core::protocol::ExecApprovalRequestEvent;
+
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+ // Begin a running task so the status indicator would be active.
+ chat.handle_codex_event(Event {
+ id: "task-1".into(),
+ msg: EventMsg::TaskStarted(TaskStartedEvent {
+ model_context_window: None,
+ }),
+ });
+ // Provide a deterministic header for the status line.
+ chat.handle_codex_event(Event {
+ id: "task-1".into(),
+ msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent {
+ delta: "**Analyzing**".into(),
+ }),
+ });
+
+ // Now show an approval modal (e.g. exec approval).
+ let ev = ExecApprovalRequestEvent {
+ call_id: "call-approve-exec".into(),
+ turn_id: "turn-approve-exec".into(),
+ command: vec!["echo".into(), "hello world".into()],
+ cwd: PathBuf::from("/tmp"),
+ reason: Some(
+ "this is a test reason such as one that would be produced by the model".into(),
+ ),
+ proposed_execpolicy_amendment: Some(ExecPolicyAmendment::new(vec![
+ "echo".into(),
+ "hello world".into(),
+ ])),
+ parsed_cmd: vec![],
+ };
+ chat.handle_codex_event(Event {
+ id: "sub-approve-exec".into(),
+ msg: EventMsg::ExecApprovalRequest(ev),
+ });
+
+ // Render at the widget's desired height and snapshot.
+ let width: u16 = 100;
+ let height = chat.desired_height(width);
+ let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height))
+ .expect("create terminal");
+ terminal.set_viewport_area(Rect::new(0, 0, width, height));
+ terminal
+ .draw(|f| chat.render(f.area(), f.buffer_mut()))
+ .expect("draw status + approval modal");
+ assert_snapshot!("status_widget_and_approval_modal", terminal.backend());
+}
+
+// Snapshot test: status widget active (StatusIndicatorView)
+// Ensures the VT100 rendering of the status indicator is stable when active.
+#[test]
+fn status_widget_active_snapshot() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+ // Activate the status indicator by simulating a task start.
+ chat.handle_codex_event(Event {
+ id: "task-1".into(),
+ msg: EventMsg::TaskStarted(TaskStartedEvent {
+ model_context_window: None,
+ }),
+ });
+ // Provide a deterministic header via a bold reasoning chunk.
+ chat.handle_codex_event(Event {
+ id: "task-1".into(),
+ msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent {
+ delta: "**Analyzing**".into(),
+ }),
+ });
+ // Render and snapshot.
+ let height = chat.desired_height(80);
+ let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, height))
+ .expect("create terminal");
+ terminal
+ .draw(|f| chat.render(f.area(), f.buffer_mut()))
+ .expect("draw status widget");
+ assert_snapshot!("status_widget_active", terminal.backend());
+}
+
+#[test]
+fn background_event_updates_status_header() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ chat.handle_codex_event(Event {
+ id: "bg-1".into(),
+ msg: EventMsg::BackgroundEvent(BackgroundEventEvent {
+ message: "Waiting for `vim`".to_string(),
+ }),
+ });
+
+ assert!(chat.bottom_pane.status_indicator_visible());
+ assert_eq!(chat.current_status_header, "Waiting for `vim`");
+ assert!(drain_insert_history(&mut rx).is_empty());
+}
+
+#[test]
+fn apply_patch_events_emit_history_cells() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // 1) Approval request -> proposed patch summary cell
+ let mut changes = HashMap::new();
+ changes.insert(
+ PathBuf::from("foo.txt"),
+ FileChange::Add {
+ content: "hello\n".to_string(),
+ },
+ );
+ let ev = ApplyPatchApprovalRequestEvent {
+ call_id: "c1".into(),
+ turn_id: "turn-c1".into(),
+ changes,
+ reason: None,
+ grant_root: None,
+ };
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::ApplyPatchApprovalRequest(ev),
+ });
+ let cells = drain_insert_history(&mut rx);
+ assert!(
+ cells.is_empty(),
+ "expected approval request to surface via modal without emitting history cells"
+ );
+
+ let area = Rect::new(0, 0, 80, chat.desired_height(80));
+ let mut buf = ratatui::buffer::Buffer::empty(area);
+ chat.render(area, &mut buf);
+ let mut saw_summary = false;
+ for y in 0..area.height {
+ let mut row = String::new();
+ for x in 0..area.width {
+ row.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
+ }
+ if row.contains("foo.txt (+1 -0)") {
+ saw_summary = true;
+ break;
+ }
+ }
+ assert!(saw_summary, "expected approval modal to show diff summary");
+
+ // 2) Begin apply -> per-file apply block cell (no global header)
+ let mut changes2 = HashMap::new();
+ changes2.insert(
+ PathBuf::from("foo.txt"),
+ FileChange::Add {
+ content: "hello\n".to_string(),
+ },
+ );
+ let begin = PatchApplyBeginEvent {
+ call_id: "c1".into(),
+ turn_id: "turn-c1".into(),
+ auto_approved: true,
+ changes: changes2,
+ };
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::PatchApplyBegin(begin),
+ });
+ let cells = drain_insert_history(&mut rx);
+ assert!(!cells.is_empty(), "expected apply block cell to be sent");
+ let blob = lines_to_single_string(cells.last().unwrap());
+ assert!(
+ blob.contains("Added foo.txt") || blob.contains("Edited foo.txt"),
+ "expected single-file header with filename (Added/Edited): {blob:?}"
+ );
+
+ // 3) End apply success -> success cell
+ let mut end_changes = HashMap::new();
+ end_changes.insert(
+ PathBuf::from("foo.txt"),
+ FileChange::Add {
+ content: "hello\n".to_string(),
+ },
+ );
+ let end = PatchApplyEndEvent {
+ call_id: "c1".into(),
+ turn_id: "turn-c1".into(),
+ stdout: "ok\n".into(),
+ stderr: String::new(),
+ success: true,
+ changes: end_changes,
+ };
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::PatchApplyEnd(end),
+ });
+ let cells = drain_insert_history(&mut rx);
+ assert!(
+ cells.is_empty(),
+ "no success cell should be emitted anymore"
+ );
+}
+
+#[test]
+fn apply_patch_manual_approval_adjusts_header() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ let mut proposed_changes = HashMap::new();
+ proposed_changes.insert(
+ PathBuf::from("foo.txt"),
+ FileChange::Add {
+ content: "hello\n".to_string(),
+ },
+ );
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent {
+ call_id: "c1".into(),
+ turn_id: "turn-c1".into(),
+ changes: proposed_changes,
+ reason: None,
+ grant_root: None,
+ }),
+ });
+ drain_insert_history(&mut rx);
+
+ let mut apply_changes = HashMap::new();
+ apply_changes.insert(
+ PathBuf::from("foo.txt"),
+ FileChange::Add {
+ content: "hello\n".to_string(),
+ },
+ );
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::PatchApplyBegin(PatchApplyBeginEvent {
+ call_id: "c1".into(),
+ turn_id: "turn-c1".into(),
+ auto_approved: false,
+ changes: apply_changes,
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ assert!(!cells.is_empty(), "expected apply block cell to be sent");
+ let blob = lines_to_single_string(cells.last().unwrap());
+ assert!(
+ blob.contains("Added foo.txt") || blob.contains("Edited foo.txt"),
+ "expected apply summary header for foo.txt: {blob:?}"
+ );
+}
+
+#[test]
+fn apply_patch_manual_flow_snapshot() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ let mut proposed_changes = HashMap::new();
+ proposed_changes.insert(
+ PathBuf::from("foo.txt"),
+ FileChange::Add {
+ content: "hello\n".to_string(),
+ },
+ );
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent {
+ call_id: "c1".into(),
+ turn_id: "turn-c1".into(),
+ changes: proposed_changes,
+ reason: Some("Manual review required".into()),
+ grant_root: None,
+ }),
+ });
+ let history_before_apply = drain_insert_history(&mut rx);
+ assert!(
+ history_before_apply.is_empty(),
+ "expected approval modal to defer history emission"
+ );
+
+ let mut apply_changes = HashMap::new();
+ apply_changes.insert(
+ PathBuf::from("foo.txt"),
+ FileChange::Add {
+ content: "hello\n".to_string(),
+ },
+ );
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::PatchApplyBegin(PatchApplyBeginEvent {
+ call_id: "c1".into(),
+ turn_id: "turn-c1".into(),
+ auto_approved: false,
+ changes: apply_changes,
+ }),
+ });
+ let approved_lines = drain_insert_history(&mut rx)
+ .pop()
+ .expect("approved patch cell");
+
+ assert_snapshot!(
+ "apply_patch_manual_flow_history_approved",
+ lines_to_single_string(&approved_lines)
+ );
+}
+
+#[test]
+fn apply_patch_approval_sends_op_with_submission_id() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+ // Simulate receiving an approval request with a distinct submission id and call id
+ let mut changes = HashMap::new();
+ changes.insert(
+ PathBuf::from("file.rs"),
+ FileChange::Add {
+ content: "fn main(){}\n".into(),
+ },
+ );
+ let ev = ApplyPatchApprovalRequestEvent {
+ call_id: "call-999".into(),
+ turn_id: "turn-999".into(),
+ changes,
+ reason: None,
+ grant_root: None,
+ };
+ chat.handle_codex_event(Event {
+ id: "sub-123".into(),
+ msg: EventMsg::ApplyPatchApprovalRequest(ev),
+ });
+
+ // Approve via key press 'y'
+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
+
+ // Expect a CodexOp with PatchApproval carrying the submission id, not call id
+ let mut found = false;
+ while let Ok(app_ev) = rx.try_recv() {
+ if let AppEvent::CodexOp(Op::PatchApproval { id, decision }) = app_ev {
+ assert_eq!(id, "sub-123");
+ assert_matches!(decision, codex_core::protocol::ReviewDecision::Approved);
+ found = true;
+ break;
+ }
+ }
+ assert!(found, "expected PatchApproval op to be sent");
+}
+
+#[test]
+fn apply_patch_full_flow_integration_like() {
+ let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None);
+
+ // 1) Backend requests approval
+ let mut changes = HashMap::new();
+ changes.insert(
+ PathBuf::from("pkg.rs"),
+ FileChange::Add { content: "".into() },
+ );
+ chat.handle_codex_event(Event {
+ id: "sub-xyz".into(),
+ msg: EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent {
+ call_id: "call-1".into(),
+ turn_id: "turn-call-1".into(),
+ changes,
+ reason: None,
+ grant_root: None,
+ }),
+ });
+
+ // 2) User approves via 'y' and App receives a CodexOp
+ chat.handle_key_event(KeyEvent::new(KeyCode::Char('y'), KeyModifiers::NONE));
+ let mut maybe_op: Option<Op> = None;
+ while let Ok(app_ev) = rx.try_recv() {
+ if let AppEvent::CodexOp(op) = app_ev {
+ maybe_op = Some(op);
+ break;
+ }
+ }
+ let op = maybe_op.expect("expected CodexOp after key press");
+
+ // 3) App forwards to widget.submit_op, which pushes onto codex_op_tx
+ chat.submit_op(op);
+ let forwarded = op_rx
+ .try_recv()
+ .expect("expected op forwarded to codex channel");
+ match forwarded {
+ Op::PatchApproval { id, decision } => {
+ assert_eq!(id, "sub-xyz");
+ assert_matches!(decision, codex_core::protocol::ReviewDecision::Approved);
+ }
+ other => panic!("unexpected op forwarded: {other:?}"),
+ }
+
+ // 4) Simulate patch begin/end events from backend; ensure history cells are emitted
+ let mut changes2 = HashMap::new();
+ changes2.insert(
+ PathBuf::from("pkg.rs"),
+ FileChange::Add { content: "".into() },
+ );
+ chat.handle_codex_event(Event {
+ id: "sub-xyz".into(),
+ msg: EventMsg::PatchApplyBegin(PatchApplyBeginEvent {
+ call_id: "call-1".into(),
+ turn_id: "turn-call-1".into(),
+ auto_approved: false,
+ changes: changes2,
+ }),
+ });
+ let mut end_changes = HashMap::new();
+ end_changes.insert(
+ PathBuf::from("pkg.rs"),
+ FileChange::Add { content: "".into() },
+ );
+ chat.handle_codex_event(Event {
+ id: "sub-xyz".into(),
+ msg: EventMsg::PatchApplyEnd(PatchApplyEndEvent {
+ call_id: "call-1".into(),
+ turn_id: "turn-call-1".into(),
+ stdout: String::from("ok"),
+ stderr: String::new(),
+ success: true,
+ changes: end_changes,
+ }),
+ });
+}
+
+#[test]
+fn apply_patch_untrusted_shows_approval_modal() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+ // Ensure approval policy is untrusted (OnRequest)
+ chat.config.approval_policy = AskForApproval::OnRequest;
+
+ // Simulate a patch approval request from backend
+ let mut changes = HashMap::new();
+ changes.insert(
+ PathBuf::from("a.rs"),
+ FileChange::Add { content: "".into() },
+ );
+ chat.handle_codex_event(Event {
+ id: "sub-1".into(),
+ msg: EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent {
+ call_id: "call-1".into(),
+ turn_id: "turn-call-1".into(),
+ changes,
+ reason: None,
+ grant_root: None,
+ }),
+ });
+
+ // Render and ensure the approval modal title is present
+ let area = Rect::new(0, 0, 80, 12);
+ let mut buf = Buffer::empty(area);
+ chat.render(area, &mut buf);
+
+ let mut contains_title = false;
+ for y in 0..area.height {
+ let mut row = String::new();
+ for x in 0..area.width {
+ row.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
+ }
+ if row.contains("Would you like to make the following edits?") {
+ contains_title = true;
+ break;
+ }
+ }
+ assert!(
+ contains_title,
+ "expected approval modal to be visible with title 'Would you like to make the following edits?'"
+ );
+}
+
+#[test]
+fn apply_patch_request_shows_diff_summary() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Ensure we are in OnRequest so an approval is surfaced
+ chat.config.approval_policy = AskForApproval::OnRequest;
+
+ // Simulate backend asking to apply a patch adding two lines to README.md
+ let mut changes = HashMap::new();
+ changes.insert(
+ PathBuf::from("README.md"),
+ FileChange::Add {
+ // Two lines (no trailing empty line counted)
+ content: "line one\nline two\n".into(),
+ },
+ );
+ chat.handle_codex_event(Event {
+ id: "sub-apply".into(),
+ msg: EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent {
+ call_id: "call-apply".into(),
+ turn_id: "turn-apply".into(),
+ changes,
+ reason: None,
+ grant_root: None,
+ }),
+ });
+
+ // No history entries yet; the modal should contain the diff summary
+ let cells = drain_insert_history(&mut rx);
+ assert!(
+ cells.is_empty(),
+ "expected approval request to render via modal instead of history"
+ );
+
+ let area = Rect::new(0, 0, 80, chat.desired_height(80));
+ let mut buf = ratatui::buffer::Buffer::empty(area);
+ chat.render(area, &mut buf);
+
+ let mut saw_header = false;
+ let mut saw_line1 = false;
+ let mut saw_line2 = false;
+ for y in 0..area.height {
+ let mut row = String::new();
+ for x in 0..area.width {
+ row.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
+ }
+ if row.contains("README.md (+2 -0)") {
+ saw_header = true;
+ }
+ if row.contains("+line one") {
+ saw_line1 = true;
+ }
+ if row.contains("+line two") {
+ saw_line2 = true;
+ }
+ if saw_header && saw_line1 && saw_line2 {
+ break;
+ }
+ }
+ assert!(saw_header, "expected modal to show diff header with totals");
+ assert!(
+ saw_line1 && saw_line2,
+ "expected modal to show per-line diff summary"
+ );
+}
+
+#[test]
+fn plan_update_renders_history_cell() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+ let update = UpdatePlanArgs {
+ explanation: Some("Adapting plan".to_string()),
+ plan: vec![
+ PlanItemArg {
+ step: "Explore codebase".into(),
+ status: StepStatus::Completed,
+ },
+ PlanItemArg {
+ step: "Implement feature".into(),
+ status: StepStatus::InProgress,
+ },
+ PlanItemArg {
+ step: "Write tests".into(),
+ status: StepStatus::Pending,
+ },
+ ],
+ };
+ chat.handle_codex_event(Event {
+ id: "sub-1".into(),
+ msg: EventMsg::PlanUpdate(update),
+ });
+ let cells = drain_insert_history(&mut rx);
+ assert!(!cells.is_empty(), "expected plan update cell to be sent");
+ let blob = lines_to_single_string(cells.last().unwrap());
+ assert!(
+ blob.contains("Updated Plan"),
+ "missing plan header: {blob:?}"
+ );
+ assert!(blob.contains("Explore codebase"));
+ assert!(blob.contains("Implement feature"));
+ assert!(blob.contains("Write tests"));
+}
+
+#[test]
+fn stream_error_updates_status_indicator() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+ chat.bottom_pane.set_task_running(true);
+ let msg = "Reconnecting... 2/5";
+ chat.handle_codex_event(Event {
+ id: "sub-1".into(),
+ msg: EventMsg::StreamError(StreamErrorEvent {
+ message: msg.to_string(),
+ codex_error_info: Some(CodexErrorInfo::Other),
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ assert!(
+ cells.is_empty(),
+ "expected no history cell for StreamError event"
+ );
+ let status = chat
+ .bottom_pane
+ .status_widget()
+ .expect("status indicator should be visible");
+ assert_eq!(status.header(), msg);
+}
+
+#[test]
+fn warning_event_adds_warning_history_cell() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+ chat.handle_codex_event(Event {
+ id: "sub-1".into(),
+ msg: EventMsg::Warning(WarningEvent {
+ message: "test warning message".to_string(),
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ assert_eq!(cells.len(), 1, "expected one warning history cell");
+ let rendered = lines_to_single_string(&cells[0]);
+ assert!(
+ rendered.contains("test warning message"),
+ "warning cell missing content: {rendered}"
+ );
+}
+
+#[test]
+fn stream_recovery_restores_previous_status_header() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+ chat.handle_codex_event(Event {
+ id: "task".into(),
+ msg: EventMsg::TaskStarted(TaskStartedEvent {
+ model_context_window: None,
+ }),
+ });
+ drain_insert_history(&mut rx);
+ chat.handle_codex_event(Event {
+ id: "retry".into(),
+ msg: EventMsg::StreamError(StreamErrorEvent {
+ message: "Reconnecting... 1/5".to_string(),
+ codex_error_info: Some(CodexErrorInfo::Other),
+ }),
+ });
+ drain_insert_history(&mut rx);
+ chat.handle_codex_event(Event {
+ id: "delta".into(),
+ msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent {
+ delta: "hello".to_string(),
+ }),
+ });
+
+ let status = chat
+ .bottom_pane
+ .status_widget()
+ .expect("status indicator should be visible");
+ assert_eq!(status.header(), "Working");
+ assert!(chat.retry_status_header.is_none());
+}
+
+#[test]
+fn multiple_agent_messages_in_single_turn_emit_multiple_headers() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Begin turn
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::TaskStarted(TaskStartedEvent {
+ model_context_window: None,
+ }),
+ });
+
+ // First finalized assistant message
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::AgentMessage(AgentMessageEvent {
+ message: "First message".into(),
+ }),
+ });
+
+ // Second finalized assistant message in the same turn
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::AgentMessage(AgentMessageEvent {
+ message: "Second message".into(),
+ }),
+ });
+
+ // End turn
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::TaskComplete(TaskCompleteEvent {
+ last_agent_message: None,
+ }),
+ });
+
+ let cells = drain_insert_history(&mut rx);
+ let combined: String = cells
+ .iter()
+ .map(|lines| lines_to_single_string(lines))
+ .collect();
+ assert!(
+ combined.contains("First message"),
+ "missing first message: {combined}"
+ );
+ assert!(
+ combined.contains("Second message"),
+ "missing second message: {combined}"
+ );
+ let first_idx = combined.find("First message").unwrap();
+ let second_idx = combined.find("Second message").unwrap();
+ assert!(first_idx < second_idx, "messages out of order: {combined}");
+}
+
+#[test]
+fn final_reasoning_then_message_without_deltas_are_rendered() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // No deltas; only final reasoning followed by final message.
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::AgentReasoning(AgentReasoningEvent {
+ text: "I will first analyze the request.".into(),
+ }),
+ });
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::AgentMessage(AgentMessageEvent {
+ message: "Here is the result.".into(),
+ }),
+ });
+
+ // Drain history and snapshot the combined visible content.
+ let cells = drain_insert_history(&mut rx);
+ let combined = cells
+ .iter()
+ .map(|lines| lines_to_single_string(lines))
+ .collect::<String>();
+ assert_snapshot!(combined);
+}
+
+#[test]
+fn deltas_then_same_final_message_are_rendered_snapshot() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Stream some reasoning deltas first.
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent {
+ delta: "I will ".into(),
+ }),
+ });
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent {
+ delta: "first analyze the ".into(),
+ }),
+ });
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent {
+ delta: "request.".into(),
+ }),
+ });
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::AgentReasoning(AgentReasoningEvent {
+ text: "request.".into(),
+ }),
+ });
+
+ // Then stream answer deltas, followed by the exact same final message.
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent {
+ delta: "Here is the ".into(),
+ }),
+ });
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent {
+ delta: "result.".into(),
+ }),
+ });
+
+ chat.handle_codex_event(Event {
+ id: "s1".into(),
+ msg: EventMsg::AgentMessage(AgentMessageEvent {
+ message: "Here is the result.".into(),
+ }),
+ });
+
+ // Snapshot the combined visible content to ensure we render as expected
+ // when deltas are followed by the identical final message.
+ let cells = drain_insert_history(&mut rx);
+ let combined = cells
+ .iter()
+ .map(|lines| lines_to_single_string(lines))
+ .collect::<String>();
+ assert_snapshot!(combined);
+}
+
+// Combined visual snapshot using vt100 for history + direct buffer overlay for UI.
+// This renders the final visual as seen in a terminal: history above, then a blank line,
+// then the exec block, another blank line, the status line, a blank line, and the composer.
+#[test]
+fn chatwidget_exec_and_status_layout_vt100_snapshot() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+ chat.handle_codex_event(Event {
+ id: "t1".into(),
+ msg: EventMsg::AgentMessage(AgentMessageEvent { message: "I’m going to search the repo for where “Change Approved” is rendered to update that view.".into() }),
+ });
+
+ let command = vec!["bash".into(), "-lc".into(), "rg \"Change Approved\"".into()];
+ let parsed_cmd = vec![
+ ParsedCommand::Search {
+ query: Some("Change Approved".into()),
+ path: None,
+ cmd: "rg \"Change Approved\"".into(),
+ },
+ ParsedCommand::Read {
+ name: "diff_render.rs".into(),
+ cmd: "cat diff_render.rs".into(),
+ path: "diff_render.rs".into(),
+ },
+ ];
+ let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
+ chat.handle_codex_event(Event {
+ id: "c1".into(),
+ msg: EventMsg::ExecCommandBegin(ExecCommandBeginEvent {
+ call_id: "c1".into(),
+ process_id: None,
+ turn_id: "turn-1".into(),
+ command: command.clone(),
+ cwd: cwd.clone(),
+ parsed_cmd: parsed_cmd.clone(),
+ source: ExecCommandSource::Agent,
+ interaction_input: None,
+ }),
+ });
+ chat.handle_codex_event(Event {
+ id: "c1".into(),
+ msg: EventMsg::ExecCommandEnd(ExecCommandEndEvent {
+ call_id: "c1".into(),
+ process_id: None,
+ turn_id: "turn-1".into(),
+ command,
+ cwd,
+ parsed_cmd,
+ source: ExecCommandSource::Agent,
+ interaction_input: None,
+ stdout: String::new(),
+ stderr: String::new(),
+ aggregated_output: String::new(),
+ exit_code: 0,
+ duration: std::time::Duration::from_millis(16000),
+ formatted_output: String::new(),
+ }),
+ });
+ chat.handle_codex_event(Event {
+ id: "t1".into(),
+ msg: EventMsg::TaskStarted(TaskStartedEvent {
+ model_context_window: None,
+ }),
+ });
+ chat.handle_codex_event(Event {
+ id: "t1".into(),
+ msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent {
+ delta: "**Investigating rendering code**".into(),
+ }),
+ });
+ chat.bottom_pane
+ .set_composer_text("Summarize recent commits".to_string());
+
+ let width: u16 = 80;
+ let ui_height: u16 = chat.desired_height(width);
+ let vt_height: u16 = 40;
+ let viewport = Rect::new(0, vt_height - ui_height - 1, width, ui_height);
+
+ let backend = VT100Backend::new(width, vt_height);
+ let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal");
+ term.set_viewport_area(viewport);
+
+ for lines in drain_insert_history(&mut rx) {
+ crate::insert_history::insert_history_lines(&mut term, lines)
+ .expect("Failed to insert history lines in test");
+ }
+
+ term.draw(|f| {
+ chat.render(f.area(), f.buffer_mut());
+ })
+ .unwrap();
+
+ assert_snapshot!(term.backend().vt100().screen().contents());
+}
+
+// E2E vt100 snapshot for complex markdown with indented and nested fenced code blocks
+#[test]
+fn chatwidget_markdown_code_blocks_vt100_snapshot() {
+ let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None);
+
+ // Simulate a final agent message via streaming deltas instead of a single message
+
+ chat.handle_codex_event(Event {
+ id: "t1".into(),
+ msg: EventMsg::TaskStarted(TaskStartedEvent {
+ model_context_window: None,
+ }),
+ });
+ // Build a vt100 visual from the history insertions only (no UI overlay)
+ let width: u16 = 80;
+ let height: u16 = 50;
+ let backend = VT100Backend::new(width, height);
+ let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal");
+ // Place viewport at the last line so that history lines insert above it
+ term.set_viewport_area(Rect::new(0, height - 1, width, 1));
+
+ // Simulate streaming via AgentMessageDelta in 2-character chunks (no final AgentMessage).
+ let source: &str = r#"
+
+ -- Indented code block (4 spaces)
+ SELECT *
+ FROM "users"
+ WHERE "email" LIKE '%@example.com';
+
+````markdown
+```sh
+printf 'fenced within fenced\n'
+```
+````
+
+```jsonc
+{
+ // comment allowed in jsonc
+ "path": "C:\\Program Files\\App",
+ "regex": "^foo.*(bar)?$"
+}
+```
+"#;
+
+ let mut it = source.chars();
+ loop {
+ let mut delta = String::new();
+ match it.next() {
+ Some(c) => delta.push(c),
+ None => break,
+ }
+ if let Some(c2) = it.next() {
+ delta.push(c2);
+ }
+
+ chat.handle_codex_event(Event {
+ id: "t1".into(),
+ msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { delta }),
+ });
+ // Drive commit ticks and drain emitted history lines into the vt100 buffer.
+ loop {
+ chat.on_commit_tick();
+ let mut inserted_any = false;
+ while let Ok(app_ev) = rx.try_recv() {
+ if let AppEvent::InsertHistoryCell(cell) = app_ev {
+ let lines = cell.display_lines(width);
+ crate::insert_history::insert_history_lines(&mut term, lines)
+ .expect("Failed to insert history lines in test");
+ inserted_any = true;
+ }
+ }
+ if !inserted_any {
+ break;
+ }
+ }
+ }
+
+ // Finalize the stream without sending a final AgentMessage, to flush any tail.
+ chat.handle_codex_event(Event {
+ id: "t1".into(),
+ msg: EventMsg::TaskComplete(TaskCompleteEvent {
+ last_agent_message: None,
+ }),
+ });
+ for lines in drain_insert_history(&mut rx) {
+ crate::insert_history::insert_history_lines(&mut term, lines)
+ .expect("Failed to insert history lines in test");
+ }
+
+ assert_snapshot!(term.backend().vt100().screen().contents());
+}
+
+#[test]
+fn chatwidget_tall() {
+ let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None);
+ chat.handle_codex_event(Event {
+ id: "t1".into(),
+ msg: EventMsg::TaskStarted(TaskStartedEvent {
+ model_context_window: None,
+ }),
+ });
+ for i in 0..30 {
+ chat.queue_user_message(format!("Hello, world! {i}").into());
+ }
+ let width: u16 = 80;
+ let height: u16 = 24;
+ let backend = VT100Backend::new(width, height);
+ let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal");
+ let desired_height = chat.desired_height(width).min(height);
+ term.set_viewport_area(Rect::new(0, height - desired_height, width, desired_height));
+ term.draw(|f| {
+ chat.render(f.area(), f.buffer_mut());
+ })
+ .unwrap();
+ assert_snapshot!(term.backend().vt100().screen().contents());
+}
diff --git a/codex-rs/tui2/src/cli.rs b/codex-rs/tui2/src/cli.rs
new file mode 100644
index 0000000000..b0daa44770
--- /dev/null
+++ b/codex-rs/tui2/src/cli.rs
@@ -0,0 +1,115 @@
+use clap::Parser;
+use clap::ValueHint;
+use codex_common::ApprovalModeCliArg;
+use codex_common::CliConfigOverrides;
+use std::path::PathBuf;
+
+#[derive(Parser, Debug)]
+#[command(version)]
+pub struct Cli {
+ /// Optional user prompt to start the session.
+ #[arg(value_name = "PROMPT", value_hint = clap::ValueHint::Other)]
+ pub prompt: Option<String>,
+
+ /// Optional image(s) to attach to the initial prompt.
+ #[arg(long = "image", short = 'i', value_name = "FILE", value_delimiter = ',', num_args = 1..)]
+ pub images: Vec<PathBuf>,
+
+ // Internal controls set by the top-level `codex resume` subcommand.
+ // These are not exposed as user flags on the base `codex` command.
+ #[clap(skip)]
+ pub resume_picker: bool,
+
+ #[clap(skip)]
+ pub resume_last: bool,
+
+ /// Internal: resume a specific recorded session by id (UUID). Set by the
+ /// top-level `codex resume <SESSION_ID>` wrapper; not exposed as a public flag.
+ #[clap(skip)]
+ pub resume_session_id: Option<String>,
+
+ /// Internal: show all sessions (disables cwd filtering and shows CWD column).
+ #[clap(skip)]
+ pub resume_show_all: bool,
+
+ /// Model the agent should use.
+ #[arg(long, short = 'm')]
+ pub model: Option<String>,
+
+ /// Convenience flag to select the local open source model provider. Equivalent to -c
+ /// model_provider=oss; verifies a local LM Studio or Ollama server is running.
+ #[arg(long = "oss", default_value_t = false)]
+ pub oss: bool,
+
+ /// Specify which local provider to use (lmstudio or ollama).
+ /// If not specified with --oss, will use config default or show selection.
+ #[arg(long = "local-provider")]
+ pub oss_provider: Option<String>,
+
+ /// Configuration profile from config.toml to specify default options.
+ #[arg(long = "profile", short = 'p')]
+ pub config_profile: Option<String>,
+
+ /// Select the sandbox policy to use when executing model-generated shell
+ /// commands.
+ #[arg(long = "sandbox", short = 's')]
+ pub sandbox_mode: Option<codex_common::SandboxModeCliArg>,
+
+ /// Configure when the model requires human approval before executing a command.
+ #[arg(long = "ask-for-approval", short = 'a')]
+ pub approval_policy: Option<ApprovalModeCliArg>,
+
+ /// Convenience alias for low-friction sandboxed automatic execution (-a on-request, --sandbox workspace-write).
+ #[arg(long = "full-auto", default_value_t = false)]
+ pub full_auto: bool,
+
+ /// Skip all confirmation prompts and execute commands without sandboxing.
+ /// EXTREMELY DANGEROUS. Intended solely for running in environments that are externally sandboxed.
+ #[arg(
+ long = "dangerously-bypass-approvals-and-sandbox",
+ alias = "yolo",
+ default_value_t = false,
+ conflicts_with_all = ["approval_policy", "full_auto"]
+ )]
+ pub dangerously_bypass_approvals_and_sandbox: bool,
+
+ /// Tell the agent to use the specified directory as its working root.
+ #[clap(long = "cd", short = 'C', value_name = "DIR")]
+ pub cwd: Option<PathBuf>,
+
+ /// Enable web search (off by default). When enabled, the native Responses `web_search` tool is available to the model (no per‑call approval).
+ #[arg(long = "search", default_value_t = false)]
+ pub web_search: bool,
+
+ /// Additional directories that should be writable alongside the primary workspace.
+ #[arg(long = "add-dir", value_name = "DIR", value_hint = ValueHint::DirPath)]
+ pub add_dir: Vec<PathBuf>,
+
+ #[clap(skip)]
+ pub config_overrides: CliConfigOverrides,
+}
+
+impl From<codex_tui::Cli> for Cli {
+ fn from(cli: codex_tui::Cli) -> Self {
+ Self {
+ prompt: cli.prompt,
+ images: cli.images,
+ resume_picker: cli.resume_picker,
+ resume_last: cli.resume_last,
+ resume_session_id: cli.resume_session_id,
+ resume_show_all: cli.resume_show_all,
+ model: cli.model,
+ oss: cli.oss,
+ oss_provider: cli.oss_provider,
+ config_profile: cli.config_profile,
+ sandbox_mode: cli.sandbox_mode,
+ approval_policy: cli.approval_policy,
+ full_auto: cli.full_auto,
+ dangerously_bypass_approvals_and_sandbox: cli.dangerously_bypass_approvals_and_sandbox,
+ cwd: cli.cwd,
+ web_search: cli.web_search,
+ add_dir: cli.add_dir,
+ config_overrides: cli.config_overrides,
+ }
+ }
+}
diff --git a/codex-rs/tui2/src/clipboard_paste.rs b/codex-rs/tui2/src/clipboard_paste.rs
new file mode 100644
index 0000000000..5863c728b0
--- /dev/null
+++ b/codex-rs/tui2/src/clipboard_paste.rs
@@ -0,0 +1,504 @@
+use std::path::Path;
+use std::path::PathBuf;
+use tempfile::Builder;
+
+#[derive(Debug, Clone)]
+pub enum PasteImageError {
+ ClipboardUnavailable(String),
+ NoImage(String),
+ EncodeFailed(String),
+ IoError(String),
+}
+
+impl std::fmt::Display for PasteImageError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ PasteImageError::ClipboardUnavailable(msg) => write!(f, "clipboard unavailable: {msg}"),
+ PasteImageError::NoImage(msg) => write!(f, "no image on clipboard: {msg}"),
+ PasteImageError::EncodeFailed(msg) => write!(f, "could not encode image: {msg}"),
+ PasteImageError::IoError(msg) => write!(f, "io error: {msg}"),
+ }
+ }
+}
+impl std::error::Error for PasteImageError {}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum EncodedImageFormat {
+ Png,
+ Jpeg,
+ Other,
+}
+
+impl EncodedImageFormat {
+ pub fn label(self) -> &'static str {
+ match self {
+ EncodedImageFormat::Png => "PNG",
+ EncodedImageFormat::Jpeg => "JPEG",
+ EncodedImageFormat::Other => "IMG",
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct PastedImageInfo {
+ pub width: u32,
+ pub height: u32,
+ pub encoded_format: EncodedImageFormat, // Always PNG for now.
+}
+
+/// Capture image from system clipboard, encode to PNG, and return bytes + info.
+#[cfg(not(target_os = "android"))]
+pub fn paste_image_as_png() -> Result<(Vec<u8>, PastedImageInfo), PasteImageError> {
+ let _span = tracing::debug_span!("paste_image_as_png").entered();
+ tracing::debug!("attempting clipboard image read");
+ let mut cb = arboard::Clipboard::new()
+ .map_err(|e| PasteImageError::ClipboardUnavailable(e.to_string()))?;
+ // Sometimes images on the clipboard come as files (e.g. when copy/pasting from
+ // Finder), sometimes they come as image data (e.g. when pasting from Chrome).
+ // Accept both, and prefer files if both are present.
+ let files = cb
+ .get()
+ .file_list()
+ .map_err(|e| PasteImageError::ClipboardUnavailable(e.to_string()));
+ let dyn_img = if let Some(img) = files
+ .unwrap_or_default()
+ .into_iter()
+ .find_map(|f| image::open(f).ok())
+ {
+ tracing::debug!(
+ "clipboard image opened from file: {}x{}",
+ img.width(),
+ img.height()
+ );
+ img
+ } else {
+ let _span = tracing::debug_span!("get_image").entered();
+ let img = cb
+ .get_image()
+ .map_err(|e| PasteImageError::NoImage(e.to_string()))?;
+ let w = img.width as u32;
+ let h = img.height as u32;
+ tracing::debug!("clipboard image opened from image: {}x{}", w, h);
+
+ let Some(rgba_img) = image::RgbaImage::from_raw(w, h, img.bytes.into_owned()) else {
+ return Err(PasteImageError::EncodeFailed("invalid RGBA buffer".into()));
+ };
+
+ image::DynamicImage::ImageRgba8(rgba_img)
+ };
+
+ let mut png: Vec<u8> = Vec::new();
+ {
+ let span =
+ tracing::debug_span!("encode_image", byte_length = tracing::field::Empty).entered();
+ let mut cursor = std::io::Cursor::new(&mut png);
+ dyn_img
+ .write_to(&mut cursor, image::ImageFormat::Png)
+ .map_err(|e| PasteImageError::EncodeFailed(e.to_string()))?;
+ span.record("byte_length", png.len());
+ }
+
+ Ok((
+ png,
+ PastedImageInfo {
+ width: dyn_img.width(),
+ height: dyn_img.height(),
+ encoded_format: EncodedImageFormat::Png,
+ },
+ ))
+}
+
+/// Android/Termux does not support arboard; return a clear error.
+#[cfg(target_os = "android")]
+pub fn paste_image_as_png() -> Result<(Vec<u8>, PastedImageInfo), PasteImageError> {
+ Err(PasteImageError::ClipboardUnavailable(
+ "clipboard image paste is unsupported on Android".into(),
+ ))
+}
+
+/// Convenience: write to a temp file and return its path + info.
+#[cfg(not(target_os = "android"))]
+pub fn paste_image_to_temp_png() -> Result<(PathBuf, PastedImageInfo), PasteImageError> {
+ // First attempt: read image from system clipboard via arboard (native paths or image data).
+ match paste_image_as_png() {
+ Ok((png, info)) => {
+ // Create a unique temporary file with a .png suffix to avoid collisions.
+ let tmp = Builder::new()
+ .prefix("codex-clipboard-")
+ .suffix(".png")
+ .tempfile()
+ .map_err(|e| PasteImageError::IoError(e.to_string()))?;
+ std::fs::write(tmp.path(), &png)
+ .map_err(|e| PasteImageError::IoError(e.to_string()))?;
+ // Persist the file (so it remains after the handle is dropped) and return its PathBuf.
+ let (_file, path) = tmp
+ .keep()
+ .map_err(|e| PasteImageError::IoError(e.error.to_string()))?;
+ Ok((path, info))
+ }
+ Err(e) => {
+ #[cfg(target_os = "linux")]
+ {
+ try_wsl_clipboard_fallback(&e).or(Err(e))
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ Err(e)
+ }
+ }
+ }
+}
+
+/// Attempt WSL fallback for clipboard image paste.
+///
+/// If clipboard is unavailable (common under WSL because arboard cannot access
+/// the Windows clipboard), attempt a WSL fallback that calls PowerShell on the
+/// Windows side to write the clipboard image to a temporary file, then return
+/// the corresponding WSL path.
+#[cfg(target_os = "linux")]
+fn try_wsl_clipboard_fallback(
+ error: &PasteImageError,
+) -> Result<(PathBuf, PastedImageInfo), PasteImageError> {
+ use PasteImageError::ClipboardUnavailable;
+ use PasteImageError::NoImage;
+
+ if !is_probably_wsl() || !matches!(error, ClipboardUnavailable(_) | NoImage(_)) {
+ return Err(error.clone());
+ }
+
+ tracing::debug!("attempting Windows PowerShell clipboard fallback");
+ let Some(win_path) = try_dump_windows_clipboard_image() else {
+ return Err(error.clone());
+ };
+
+ tracing::debug!("powershell produced path: {}", win_path);
+ let Some(mapped_path) = convert_windows_path_to_wsl(&win_path) else {
+ return Err(error.clone());
+ };
+
+ let Ok((w, h)) = image::image_dimensions(&mapped_path) else {
+ return Err(error.clone());
+ };
+
+ // Return the mapped path directly without copying.
+ // The file will be read and base64-encoded during serialization.
+ Ok((
+ mapped_path,
+ PastedImageInfo {
+ width: w,
+ height: h,
+ encoded_format: EncodedImageFormat::Png,
+ },
+ ))
+}
+
+/// Try to call a Windows PowerShell command (several common names) to save the
+/// clipboard image to a temporary PNG and return the Windows path to that file.
+/// Returns None if no command succeeded or no image was present.
+#[cfg(target_os = "linux")]
+fn try_dump_windows_clipboard_image() -> Option<String> {
+ // Powershell script: save image from clipboard to a temp png and print the path.
+ // Force UTF-8 output to avoid encoding issues between powershell.exe (UTF-16LE default)
+ // and pwsh (UTF-8 default).
+ let script = r#"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $img = Get-Clipboard -Format Image; if ($img -ne $null) { $p=[System.IO.Path]::GetTempFileName(); $p = [System.IO.Path]::ChangeExtension($p,'png'); $img.Save($p,[System.Drawing.Imaging.ImageFormat]::Png); Write-Output $p } else { exit 1 }"#;
+
+ for cmd in ["powershell.exe", "pwsh", "powershell"] {
+ match std::process::Command::new(cmd)
+ .args(["-NoProfile", "-Command", script])
+ .output()
+ {
+ // Executing PowerShell command
+ Ok(output) => {
+ if output.status.success() {
+ // Decode as UTF-8 (forced by the script above).
+ let win_path = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ if !win_path.is_empty() {
+ tracing::debug!("{} saved clipboard image to {}", cmd, win_path);
+ return Some(win_path);
+ }
+ } else {
+ tracing::debug!("{} returned non-zero status", cmd);
+ }
+ }
+ Err(err) => {
+ tracing::debug!("{} not executable: {}", cmd, err);
+ }
+ }
+ }
+ None
+}
+
+#[cfg(target_os = "android")]
+pub fn paste_image_to_temp_png() -> Result<(PathBuf, PastedImageInfo), PasteImageError> {
+ // Keep error consistent with paste_image_as_png.
+ Err(PasteImageError::ClipboardUnavailable(
+ "clipboard image paste is unsupported on Android".into(),
+ ))
+}
+
+/// Normalize pasted text that may represent a filesystem path.
+///
+/// Supports:
+/// - `file://` URLs (converted to local paths)
+/// - Windows/UNC paths
+/// - shell-escaped single paths (via `shlex`)
+pub fn normalize_pasted_path(pasted: &str) -> Option<PathBuf> {
+ let pasted = pasted.trim();
+
+ // file:// URL → filesystem path
+ if let Ok(url) = url::Url::parse(pasted)
+ && url.scheme() == "file"
+ {
+ return url.to_file_path().ok();
+ }
+
+ // TODO: We'll improve the implementation/unit tests over time, as appropriate.
+ // Possibly use typed-path: https://github.com/openai/codex/pull/2567/commits/3cc92b78e0a1f94e857cf4674d3a9db918ed352e
+ //
+ // Detect unquoted Windows paths and bypass POSIX shlex which
+ // treats backslashes as escapes (e.g., C:\Users\Alice\file.png).
+ // Also handles UNC paths (\\server\share\path).
+ let looks_like_windows_path = {
+ // Drive letter path: C:\ or C:/
+ let drive = pasted
+ .chars()
+ .next()
+ .map(|c| c.is_ascii_alphabetic())
+ .unwrap_or(false)
+ && pasted.get(1..2) == Some(":")
+ && pasted
+ .get(2..3)
+ .map(|s| s == "\\" || s == "/")
+ .unwrap_or(false);
+ // UNC path: \\server\share
+ let unc = pasted.starts_with("\\\\");
+ drive || unc
+ };
+ if looks_like_windows_path {
+ #[cfg(target_os = "linux")]
+ {
+ if is_probably_wsl()
+ && let Some(converted) = convert_windows_path_to_wsl(pasted)
+ {
+ return Some(converted);
+ }
+ }
+ return Some(PathBuf::from(pasted));
+ }
+
+ // shell-escaped single path → unescaped
+ let parts: Vec<String> = shlex::Shlex::new(pasted).collect();
+ if parts.len() == 1 {
+ return parts.into_iter().next().map(PathBuf::from);
+ }
+
+ None
+}
+
+#[cfg(target_os = "linux")]
+pub(crate) fn is_probably_wsl() -> bool {
+ // Primary: Check /proc/version for "microsoft" or "WSL" (most reliable for standard WSL).
+ if let Ok(version) = std::fs::read_to_string("/proc/version") {
+ let version_lower = version.to_lowercase();
+ if version_lower.contains("microsoft") || version_lower.contains("wsl") {
+ return true;
+ }
+ }
+
+ // Fallback: Check WSL environment variables. This handles edge cases like
+ // custom Linux kernels installed in WSL where /proc/version may not contain
+ // "microsoft" or "WSL".
+ std::env::var_os("WSL_DISTRO_NAME").is_some() || std::env::var_os("WSL_INTEROP").is_some()
+}
+
+#[cfg(target_os = "linux")]
+fn convert_windows_path_to_wsl(input: &str) -> Option<PathBuf> {
+ if input.starts_with("\\\\") {
+ return None;
+ }
+
+ let drive_letter = input.chars().next()?.to_ascii_lowercase();
+ if !drive_letter.is_ascii_lowercase() {
+ return None;
+ }
+
+ if input.get(1..2) != Some(":") {
+ return None;
+ }
+
+ let mut result = PathBuf::from(format!("/mnt/{drive_letter}"));
+ for component in input
+ .get(2..)?
+ .trim_start_matches(['\\', '/'])
+ .split(['\\', '/'])
+ .filter(|component| !component.is_empty())
+ {
+ result.push(component);
+ }
+
+ Some(result)
+}
+
+/// Infer an image format for the provided path based on its extension.
+pub fn pasted_image_format(path: &Path) -> EncodedImageFormat {
+ match path
+ .extension()
+ .and_then(|e| e.to_str())
+ .map(str::to_ascii_lowercase)
+ .as_deref()
+ {
+ Some("png") => EncodedImageFormat::Png,
+ Some("jpg") | Some("jpeg") => EncodedImageFormat::Jpeg,
+ _ => EncodedImageFormat::Other,
+ }
+}
+
+#[cfg(test)]
+mod pasted_paths_tests {
+ use super::*;
+
+ #[cfg(not(windows))]
+ #[test]
+ fn normalize_file_url() {
+ let input = "file:///tmp/example.png";
+ let result = normalize_pasted_path(input).expect("should parse file URL");
+ assert_eq!(result, PathBuf::from("/tmp/example.png"));
+ }
+
+ #[test]
+ fn normalize_file_url_windows() {
+ let input = r"C:\Temp\example.png";
+ let result = normalize_pasted_path(input).expect("should parse file URL");
+ #[cfg(target_os = "linux")]
+ let expected = if is_probably_wsl()
+ && let Some(converted) = convert_windows_path_to_wsl(input)
+ {
+ converted
+ } else {
+ PathBuf::from(r"C:\Temp\example.png")
+ };
+ #[cfg(not(target_os = "linux"))]
+ let expected = PathBuf::from(r"C:\Temp\example.png");
+ assert_eq!(result, expected);
+ }
+
+ #[test]
+ fn normalize_shell_escaped_single_path() {
+ let input = "/home/user/My\\ File.png";
+ let result = normalize_pasted_path(input).expect("should unescape shell-escaped path");
+ assert_eq!(result, PathBuf::from("/home/user/My File.png"));
+ }
+
+ #[test]
+ fn normalize_simple_quoted_path_fallback() {
+ let input = "\"/home/user/My File.png\"";
+ let result = normalize_pasted_path(input).expect("should trim simple quotes");
+ assert_eq!(result, PathBuf::from("/home/user/My File.png"));
+ }
+
+ #[test]
+ fn normalize_single_quoted_unix_path() {
+ let input = "'/home/user/My File.png'";
+ let result = normalize_pasted_path(input).expect("should trim single quotes via shlex");
+ assert_eq!(result, PathBuf::from("/home/user/My File.png"));
+ }
+
+ #[test]
+ fn normalize_multiple_tokens_returns_none() {
+ // Two tokens after shell splitting → not a single path
+ let input = "/home/user/a\\ b.png /home/user/c.png";
+ let result = normalize_pasted_path(input);
+ assert!(result.is_none());
+ }
+
+ #[test]
+ fn pasted_image_format_png_jpeg_unknown() {
+ assert_eq!(
+ pasted_image_format(Path::new("/a/b/c.PNG")),
+ EncodedImageFormat::Png
+ );
+ assert_eq!(
+ pasted_image_format(Path::new("/a/b/c.jpg")),
+ EncodedImageFormat::Jpeg
+ );
+ assert_eq!(
+ pasted_image_format(Path::new("/a/b/c.JPEG")),
+ EncodedImageFormat::Jpeg
+ );
+ assert_eq!(
+ pasted_image_format(Path::new("/a/b/c")),
+ EncodedImageFormat::Other
+ );
+ assert_eq!(
+ pasted_image_format(Path::new("/a/b/c.webp")),
+ EncodedImageFormat::Other
+ );
+ }
+
+ #[test]
+ fn normalize_single_quoted_windows_path() {
+ let input = r"'C:\\Users\\Alice\\My File.jpeg'";
+ let result =
+ normalize_pasted_path(input).expect("should trim single quotes on windows path");
+ assert_eq!(result, PathBuf::from(r"C:\\Users\\Alice\\My File.jpeg"));
+ }
+
+ #[test]
+ fn normalize_unquoted_windows_path_with_spaces() {
+ let input = r"C:\\Users\\Alice\\My Pictures\\example image.png";
+ let result = normalize_pasted_path(input).expect("should accept unquoted windows path");
+ #[cfg(target_os = "linux")]
+ let expected = if is_probably_wsl()
+ && let Some(converted) = convert_windows_path_to_wsl(input)
+ {
+ converted
+ } else {
+ PathBuf::from(r"C:\\Users\\Alice\\My Pictures\\example image.png")
+ };
+ #[cfg(not(target_os = "linux"))]
+ let expected = PathBuf::from(r"C:\\Users\\Alice\\My Pictures\\example image.png");
+ assert_eq!(result, expected);
+ }
+
+ #[test]
+ fn normalize_unc_windows_path() {
+ let input = r"\\\\server\\share\\folder\\file.jpg";
+ let result = normalize_pasted_path(input).expect("should accept UNC windows path");
+ assert_eq!(
+ result,
+ PathBuf::from(r"\\\\server\\share\\folder\\file.jpg")
+ );
+ }
+
+ #[test]
+ fn pasted_image_format_with_windows_style_paths() {
+ assert_eq!(
+ pasted_image_format(Path::new(r"C:\\a\\b\\c.PNG")),
+ EncodedImageFormat::Png
+ );
+ assert_eq!(
+ pasted_image_format(Path::new(r"C:\\a\\b\\c.jpeg")),
+ EncodedImageFormat::Jpeg
+ );
+ assert_eq!(
+ pasted_image_format(Path::new(r"C:\\a\\b\\noext")),
+ EncodedImageFormat::Other
+ );
+ }
+
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn normalize_windows_path_in_wsl() {
+ // This test only runs on actual WSL systems
+ if !is_probably_wsl() {
+ // Skip test if not on WSL
+ return;
+ }
+ let input = r"C:\\Users\\Alice\\Pictures\\example image.png";
+ let result = normalize_pasted_path(input).expect("should convert windows path on wsl");
+ assert_eq!(
+ result,
+ PathBuf::from("/mnt/c/Users/Alice/Pictures/example image.png")
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/color.rs b/codex-rs/tui2/src/color.rs
new file mode 100644
index 0000000000..f5121a1f6c
--- /dev/null
+++ b/codex-rs/tui2/src/color.rs
@@ -0,0 +1,75 @@
+pub(crate) fn is_light(bg: (u8, u8, u8)) -> bool {
+ let (r, g, b) = bg;
+ let y = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
+ y > 128.0
+}
+
+pub(crate) fn blend(fg: (u8, u8, u8), bg: (u8, u8, u8), alpha: f32) -> (u8, u8, u8) {
+ let r = (fg.0 as f32 * alpha + bg.0 as f32 * (1.0 - alpha)) as u8;
+ let g = (fg.1 as f32 * alpha + bg.1 as f32 * (1.0 - alpha)) as u8;
+ let b = (fg.2 as f32 * alpha + bg.2 as f32 * (1.0 - alpha)) as u8;
+ (r, g, b)
+}
+
+/// Returns the perceptual color distance between two RGB colors.
+/// Uses the CIE76 formula (Euclidean distance in Lab space approximation).
+pub(crate) fn perceptual_distance(a: (u8, u8, u8), b: (u8, u8, u8)) -> f32 {
+ // Convert sRGB to linear RGB
+ fn srgb_to_linear(c: u8) -> f32 {
+ let c = c as f32 / 255.0;
+ if c <= 0.04045 {
+ c / 12.92
+ } else {
+ ((c + 0.055) / 1.055).powf(2.4)
+ }
+ }
+
+ // Convert RGB to XYZ
+ fn rgb_to_xyz(r: u8, g: u8, b: u8) -> (f32, f32, f32) {
+ let r = srgb_to_linear(r);
+ let g = srgb_to_linear(g);
+ let b = srgb_to_linear(b);
+
+ let x = r * 0.4124 + g * 0.3576 + b * 0.1805;
+ let y = r * 0.2126 + g * 0.7152 + b * 0.0722;
+ let z = r * 0.0193 + g * 0.1192 + b * 0.9505;
+ (x, y, z)
+ }
+
+ // Convert XYZ to Lab
+ fn xyz_to_lab(x: f32, y: f32, z: f32) -> (f32, f32, f32) {
+ // D65 reference white
+ let xr = x / 0.95047;
+ let yr = y / 1.00000;
+ let zr = z / 1.08883;
+
+ fn f(t: f32) -> f32 {
+ if t > 0.008856 {
+ t.powf(1.0 / 3.0)
+ } else {
+ 7.787 * t + 16.0 / 116.0
+ }
+ }
+
+ let fx = f(xr);
+ let fy = f(yr);
+ let fz = f(zr);
+
+ let l = 116.0 * fy - 16.0;
+ let a = 500.0 * (fx - fy);
+ let b = 200.0 * (fy - fz);
+ (l, a, b)
+ }
+
+ let (x1, y1, z1) = rgb_to_xyz(a.0, a.1, a.2);
+ let (x2, y2, z2) = rgb_to_xyz(b.0, b.1, b.2);
+
+ let (l1, a1, b1) = xyz_to_lab(x1, y1, z1);
+ let (l2, a2, b2) = xyz_to_lab(x2, y2, z2);
+
+ let dl = l1 - l2;
+ let da = a1 - a2;
+ let db = b1 - b2;
+
+ (dl * dl + da * da + db * db).sqrt()
+}
diff --git a/codex-rs/tui2/src/custom_terminal.rs b/codex-rs/tui2/src/custom_terminal.rs
new file mode 100644
index 0000000000..46d16a83f0
--- /dev/null
+++ b/codex-rs/tui2/src/custom_terminal.rs
@@ -0,0 +1,645 @@
+// This is derived from `ratatui::Terminal`, which is licensed under the following terms:
+//
+// The MIT License (MIT)
+// Copyright (c) 2016-2022 Florian Dehau
+// Copyright (c) 2023-2025 The Ratatui Developers
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in all
+// copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+// SOFTWARE.
+use std::io;
+use std::io::Write;
+
+use crossterm::cursor::MoveTo;
+use crossterm::queue;
+use crossterm::style::Colors;
+use crossterm::style::Print;
+use crossterm::style::SetAttribute;
+use crossterm::style::SetBackgroundColor;
+use crossterm::style::SetColors;
+use crossterm::style::SetForegroundColor;
+use crossterm::terminal::Clear;
+use derive_more::IsVariant;
+use ratatui::backend::Backend;
+use ratatui::backend::ClearType;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Position;
+use ratatui::layout::Rect;
+use ratatui::layout::Size;
+use ratatui::style::Color;
+use ratatui::style::Modifier;
+use ratatui::widgets::WidgetRef;
+
+#[derive(Debug, Hash)]
+pub struct Frame<'a> {
+ /// Where should the cursor be after drawing this frame?
+ ///
+ /// If `None`, the cursor is hidden and its position is controlled by the backend. If `Some((x,
+ /// y))`, the cursor is shown and placed at `(x, y)` after the call to `Terminal::draw()`.
+ pub(crate) cursor_position: Option<Position>,
+
+ /// The area of the viewport
+ pub(crate) viewport_area: Rect,
+
+ /// The buffer that is used to draw the current frame
+ pub(crate) buffer: &'a mut Buffer,
+}
+
+impl Frame<'_> {
+ /// The area of the current frame
+ ///
+ /// This is guaranteed not to change during rendering, so may be called multiple times.
+ ///
+ /// If your app listens for a resize event from the backend, it should ignore the values from
+ /// the event for any calculations that are used to render the current frame and use this value
+ /// instead as this is the area of the buffer that is used to render the current frame.
+ pub const fn area(&self) -> Rect {
+ self.viewport_area
+ }
+
+ /// Render a [`WidgetRef`] to the current buffer using [`WidgetRef::render_ref`].
+ ///
+ /// Usually the area argument is the size of the current frame or a sub-area of the current
+ /// frame (which can be obtained using [`Layout`] to split the total area).
+ #[allow(clippy::needless_pass_by_value)]
+ pub fn render_widget_ref<W: WidgetRef>(&mut self, widget: W, area: Rect) {
+ widget.render_ref(area, self.buffer);
+ }
+
+ /// After drawing this frame, make the cursor visible and put it at the specified (x, y)
+ /// coordinates. If this method is not called, the cursor will be hidden.
+ ///
+ /// Note that this will interfere with calls to [`Terminal::hide_cursor`],
+ /// [`Terminal::show_cursor`], and [`Terminal::set_cursor_position`]. Pick one of the APIs and
+ /// stick with it.
+ ///
+ /// [`Terminal::hide_cursor`]: crate::Terminal::hide_cursor
+ /// [`Terminal::show_cursor`]: crate::Terminal::show_cursor
+ /// [`Terminal::set_cursor_position`]: crate::Terminal::set_cursor_position
+ pub fn set_cursor_position<P: Into<Position>>(&mut self, position: P) {
+ self.cursor_position = Some(position.into());
+ }
+
+ /// Gets the buffer that this `Frame` draws into as a mutable reference.
+ pub fn buffer_mut(&mut self) -> &mut Buffer {
+ self.buffer
+ }
+}
+
+#[derive(Debug, Default, Clone, Eq, PartialEq, Hash)]
+pub struct Terminal<B>
+where
+ B: Backend + Write,
+{
+ /// The backend used to interface with the terminal
+ backend: B,
+ /// Holds the results of the current and previous draw calls. The two are compared at the end
+ /// of each draw pass to output the necessary updates to the terminal
+ buffers: [Buffer; 2],
+ /// Index of the current buffer in the previous array
+ current: usize,
+ /// Whether the cursor is currently hidden
+ pub hidden_cursor: bool,
+ /// Area of the viewport
+ pub viewport_area: Rect,
+ /// Last known size of the terminal. Used to detect if the internal buffers have to be resized.
+ pub last_known_screen_size: Size,
+ /// Last known position of the cursor. Used to find the new area when the viewport is inlined
+ /// and the terminal resized.
+ pub last_known_cursor_pos: Position,
+}
+
+impl<B> Drop for Terminal<B>
+where
+ B: Backend,
+ B: Write,
+{
+ #[allow(clippy::print_stderr)]
+ fn drop(&mut self) {
+ // Attempt to restore the cursor state
+ if self.hidden_cursor
+ && let Err(err) = self.show_cursor()
+ {
+ eprintln!("Failed to show the cursor: {err}");
+ }
+ }
+}
+
+impl<B> Terminal<B>
+where
+ B: Backend,
+ B: Write,
+{
+ /// Creates a new [`Terminal`] with the given [`Backend`] and [`TerminalOptions`].
+ pub fn with_options(mut backend: B) -> io::Result<Self> {
+ let screen_size = backend.size()?;
+ let cursor_pos = backend.get_cursor_position()?;
+ Ok(Self {
+ backend,
+ buffers: [Buffer::empty(Rect::ZERO), Buffer::empty(Rect::ZERO)],
+ current: 0,
+ hidden_cursor: false,
+ viewport_area: Rect::new(0, cursor_pos.y, 0, 0),
+ last_known_screen_size: screen_size,
+ last_known_cursor_pos: cursor_pos,
+ })
+ }
+
+ /// Get a Frame object which provides a consistent view into the terminal state for rendering.
+ pub fn get_frame(&mut self) -> Frame<'_> {
+ Frame {
+ cursor_position: None,
+ viewport_area: self.viewport_area,
+ buffer: self.current_buffer_mut(),
+ }
+ }
+
+ /// Gets the current buffer as a reference.
+ fn current_buffer(&self) -> &Buffer {
+ &self.buffers[self.current]
+ }
+
+ /// Gets the current buffer as a mutable reference.
+ fn current_buffer_mut(&mut self) -> &mut Buffer {
+ &mut self.buffers[self.current]
+ }
+
+ /// Gets the previous buffer as a reference.
+ fn previous_buffer(&self) -> &Buffer {
+ &self.buffers[1 - self.current]
+ }
+
+ /// Gets the previous buffer as a mutable reference.
+ fn previous_buffer_mut(&mut self) -> &mut Buffer {
+ &mut self.buffers[1 - self.current]
+ }
+
+ /// Gets the backend
+ pub const fn backend(&self) -> &B {
+ &self.backend
+ }
+
+ /// Gets the backend as a mutable reference
+ pub fn backend_mut(&mut self) -> &mut B {
+ &mut self.backend
+ }
+
+ /// Obtains a difference between the previous and the current buffer and passes it to the
+ /// current backend for drawing.
+ pub fn flush(&mut self) -> io::Result<()> {
+ let updates = diff_buffers(self.previous_buffer(), self.current_buffer());
+ let last_put_command = updates.iter().rfind(|command| command.is_put());
+ if let Some(&DrawCommand::Put { x, y, .. }) = last_put_command {
+ self.last_known_cursor_pos = Position { x, y };
+ }
+ draw(&mut self.backend, updates.into_iter())
+ }
+
+ /// Updates the Terminal so that internal buffers match the requested area.
+ ///
+ /// Requested area will be saved to remain consistent when rendering. This leads to a full clear
+ /// of the screen.
+ pub fn resize(&mut self, screen_size: Size) -> io::Result<()> {
+ self.last_known_screen_size = screen_size;
+ Ok(())
+ }
+
+ /// Sets the viewport area.
+ pub fn set_viewport_area(&mut self, area: Rect) {
+ self.current_buffer_mut().resize(area);
+ self.previous_buffer_mut().resize(area);
+ self.viewport_area = area;
+ }
+
+ /// Queries the backend for size and resizes if it doesn't match the previous size.
+ pub fn autoresize(&mut self) -> io::Result<()> {
+ let screen_size = self.size()?;
+ if screen_size != self.last_known_screen_size {
+ self.resize(screen_size)?;
+ }
+ Ok(())
+ }
+
+ /// Draws a single frame to the terminal.
+ ///
+ /// Returns a [`CompletedFrame`] if successful, otherwise a [`std::io::Error`].
+ ///
+ /// If the render callback passed to this method can fail, use [`try_draw`] instead.
+ ///
+ /// Applications should call `draw` or [`try_draw`] in a loop to continuously render the
+ /// terminal. These methods are the main entry points for drawing to the terminal.
+ ///
+ /// [`try_draw`]: Terminal::try_draw
+ ///
+ /// This method will:
+ ///
+ /// - autoresize the terminal if necessary
+ /// - call the render callback, passing it a [`Frame`] reference to render to
+ /// - flush the current internal state by copying the current buffer to the backend
+ /// - move the cursor to the last known position if it was set during the rendering closure
+ ///
+ /// The render callback should fully render the entire frame when called, including areas that
+ /// are unchanged from the previous frame. This is because each frame is compared to the
+ /// previous frame to determine what has changed, and only the changes are written to the
+ /// terminal. If the render callback does not fully render the frame, the terminal will not be
+ /// in a consistent state.
+ pub fn draw<F>(&mut self, render_callback: F) -> io::Result<()>
+ where
+ F: FnOnce(&mut Frame),
+ {
+ self.try_draw(|frame| {
+ render_callback(frame);
+ io::Result::Ok(())
+ })
+ }
+
+ /// Tries to draw a single frame to the terminal.
+ ///
+ /// Returns [`Result::Ok`] containing a [`CompletedFrame`] if successful, otherwise
+ /// [`Result::Err`] containing the [`std::io::Error`] that caused the failure.
+ ///
+ /// This is the equivalent of [`Terminal::draw`] but the render callback is a function or
+ /// closure that returns a `Result` instead of nothing.
+ ///
+ /// Applications should call `try_draw` or [`draw`] in a loop to continuously render the
+ /// terminal. These methods are the main entry points for drawing to the terminal.
+ ///
+ /// [`draw`]: Terminal::draw
+ ///
+ /// This method will:
+ ///
+ /// - autoresize the terminal if necessary
+ /// - call the render callback, passing it a [`Frame`] reference to render to
+ /// - flush the current internal state by copying the current buffer to the backend
+ /// - move the cursor to the last known position if it was set during the rendering closure
+ /// - return a [`CompletedFrame`] with the current buffer and the area of the terminal
+ ///
+ /// The render callback passed to `try_draw` can return any [`Result`] with an error type that
+ /// can be converted into an [`std::io::Error`] using the [`Into`] trait. This makes it possible
+ /// to use the `?` operator to propagate errors that occur during rendering. If the render
+ /// callback returns an error, the error will be returned from `try_draw` as an
+ /// [`std::io::Error`] and the terminal will not be updated.
+ ///
+ /// The [`CompletedFrame`] returned by this method can be useful for debugging or testing
+ /// purposes, but it is often not used in regular applicationss.
+ ///
+ /// The render callback should fully render the entire frame when called, including areas that
+ /// are unchanged from the previous frame. This is because each frame is compared to the
+ /// previous frame to determine what has changed, and only the changes are written to the
+ /// terminal. If the render function does not fully render the frame, the terminal will not be
+ /// in a consistent state.
+ pub fn try_draw<F, E>(&mut self, render_callback: F) -> io::Result<()>
+ where
+ F: FnOnce(&mut Frame) -> Result<(), E>,
+ E: Into<io::Error>,
+ {
+ // Autoresize - otherwise we get glitches if shrinking or potential desync between widgets
+ // and the terminal (if growing), which may OOB.
+ self.autoresize()?;
+
+ let mut frame = self.get_frame();
+
+ render_callback(&mut frame).map_err(Into::into)?;
+
+ // We can't change the cursor position right away because we have to flush the frame to
+ // stdout first. But we also can't keep the frame around, since it holds a &mut to
+ // Buffer. Thus, we're taking the important data out of the Frame and dropping it.
+ let cursor_position = frame.cursor_position;
+
+ // Draw to stdout
+ self.flush()?;
+
+ match cursor_position {
+ None => self.hide_cursor()?,
+ Some(position) => {
+ self.show_cursor()?;
+ self.set_cursor_position(position)?;
+ }
+ }
+
+ self.swap_buffers();
+
+ Backend::flush(&mut self.backend)?;
+
+ Ok(())
+ }
+
+ /// Hides the cursor.
+ pub fn hide_cursor(&mut self) -> io::Result<()> {
+ self.backend.hide_cursor()?;
+ self.hidden_cursor = true;
+ Ok(())
+ }
+
+ /// Shows the cursor.
+ pub fn show_cursor(&mut self) -> io::Result<()> {
+ self.backend.show_cursor()?;
+ self.hidden_cursor = false;
+ Ok(())
+ }
+
+ /// Gets the current cursor position.
+ ///
+ /// This is the position of the cursor after the last draw call.
+ #[allow(dead_code)]
+ pub fn get_cursor_position(&mut self) -> io::Result<Position> {
+ self.backend.get_cursor_position()
+ }
+
+ /// Sets the cursor position.
+ pub fn set_cursor_position<P: Into<Position>>(&mut self, position: P) -> io::Result<()> {
+ let position = position.into();
+ self.backend.set_cursor_position(position)?;
+ self.last_known_cursor_pos = position;
+ Ok(())
+ }
+
+ /// Clear the terminal and force a full redraw on the next draw call.
+ pub fn clear(&mut self) -> io::Result<()> {
+ if self.viewport_area.is_empty() {
+ return Ok(());
+ }
+ self.backend
+ .set_cursor_position(self.viewport_area.as_position())?;
+ self.backend.clear_region(ClearType::AfterCursor)?;
+ // Reset the back buffer to make sure the next update will redraw everything.
+ self.previous_buffer_mut().reset();
+ Ok(())
+ }
+
+ /// Clears the inactive buffer and swaps it with the current buffer
+ pub fn swap_buffers(&mut self) {
+ self.previous_buffer_mut().reset();
+ self.current = 1 - self.current;
+ }
+
+ /// Queries the real size of the backend.
+ pub fn size(&self) -> io::Result<Size> {
+ self.backend.size()
+ }
+}
+
+use ratatui::buffer::Cell;
+use unicode_width::UnicodeWidthStr;
+
+#[derive(Debug, IsVariant)]
+enum DrawCommand {
+ Put { x: u16, y: u16, cell: Cell },
+ ClearToEnd { x: u16, y: u16, bg: Color },
+}
+
+fn diff_buffers(a: &Buffer, b: &Buffer) -> Vec<DrawCommand> {
+ let previous_buffer = &a.content;
+ let next_buffer = &b.content;
+
+ let mut updates = vec![];
+ let mut last_nonblank_columns = vec![0; a.area.height as usize];
+ for y in 0..a.area.height {
+ let row_start = y as usize * a.area.width as usize;
+ let row_end = row_start + a.area.width as usize;
+ let row = &next_buffer[row_start..row_end];
+ let bg = row.last().map(|cell| cell.bg).unwrap_or(Color::Reset);
+
+ // Scan the row to find the rightmost column that still matters: any non-space glyph,
+ // any cell whose bg differs from the row’s trailing bg, or any cell with modifiers.
+ // Multi-width glyphs extend that region through their full displayed width.
+ // After that point the rest of the row can be cleared with a single ClearToEnd, a perf win
+ // versus emitting multiple space Put commands.
+ let mut last_nonblank_column = 0usize;
+ let mut column = 0usize;
+ while column < row.len() {
+ let cell = &row[column];
+ let width = cell.symbol().width();
+ if cell.symbol() != " " || cell.bg != bg || cell.modifier != Modifier::empty() {
+ last_nonblank_column = column + (width.saturating_sub(1));
+ }
+ column += width.max(1); // treat zero-width symbols as width 1
+ }
+
+ if last_nonblank_column + 1 < row.len() {
+ let (x, y) = a.pos_of(row_start + last_nonblank_column + 1);
+ updates.push(DrawCommand::ClearToEnd { x, y, bg });
+ }
+
+ last_nonblank_columns[y as usize] = last_nonblank_column as u16;
+ }
+
+ // Cells invalidated by drawing/replacing preceding multi-width characters:
+ let mut invalidated: usize = 0;
+ // Cells from the current buffer to skip due to preceding multi-width characters taking
+ // their place (the skipped cells should be blank anyway), or due to per-cell-skipping:
+ let mut to_skip: usize = 0;
+ for (i, (current, previous)) in next_buffer.iter().zip(previous_buffer.iter()).enumerate() {
+ if !current.skip && (current != previous || invalidated > 0) && to_skip == 0 {
+ let (x, y) = a.pos_of(i);
+ let row = i / a.area.width as usize;
+ if x <= last_nonblank_columns[row] {
+ updates.push(DrawCommand::Put {
+ x,
+ y,
+ cell: next_buffer[i].clone(),
+ });
+ }
+ }
+
+ to_skip = current.symbol().width().saturating_sub(1);
+
+ let affected_width = std::cmp::max(current.symbol().width(), previous.symbol().width());
+ invalidated = std::cmp::max(affected_width, invalidated).saturating_sub(1);
+ }
+ updates
+}
+
+fn draw<I>(writer: &mut impl Write, commands: I) -> io::Result<()>
+where
+ I: Iterator<Item = DrawCommand>,
+{
+ let mut fg = Color::Reset;
+ let mut bg = Color::Reset;
+ let mut modifier = Modifier::empty();
+ let mut last_pos: Option<Position> = None;
+ for command in commands {
+ let (x, y) = match command {
+ DrawCommand::Put { x, y, .. } => (x, y),
+ DrawCommand::ClearToEnd { x, y, .. } => (x, y),
+ };
+ // Move the cursor if the previous location was not (x - 1, y)
+ if !matches!(last_pos, Some(p) if x == p.x + 1 && y == p.y) {
+ queue!(writer, MoveTo(x, y))?;
+ }
+ last_pos = Some(Position { x, y });
+ match command {
+ DrawCommand::Put { cell, .. } => {
+ if cell.modifier != modifier {
+ let diff = ModifierDiff {
+ from: modifier,
+ to: cell.modifier,
+ };
+ diff.queue(writer)?;
+ modifier = cell.modifier;
+ }
+ if cell.fg != fg || cell.bg != bg {
+ queue!(
+ writer,
+ SetColors(Colors::new(cell.fg.into(), cell.bg.into()))
+ )?;
+ fg = cell.fg;
+ bg = cell.bg;
+ }
+
+ queue!(writer, Print(cell.symbol()))?;
+ }
+ DrawCommand::ClearToEnd { bg: clear_bg, .. } => {
+ queue!(writer, SetAttribute(crossterm::style::Attribute::Reset))?;
+ modifier = Modifier::empty();
+ queue!(writer, SetBackgroundColor(clear_bg.into()))?;
+ bg = clear_bg;
+ queue!(writer, Clear(crossterm::terminal::ClearType::UntilNewLine))?;
+ }
+ }
+ }
+
+ queue!(
+ writer,
+ SetForegroundColor(crossterm::style::Color::Reset),
+ SetBackgroundColor(crossterm::style::Color::Reset),
+ SetAttribute(crossterm::style::Attribute::Reset),
+ )?;
+
+ Ok(())
+}
+
+/// The `ModifierDiff` struct is used to calculate the difference between two `Modifier`
+/// values. This is useful when updating the terminal display, as it allows for more
+/// efficient updates by only sending the necessary changes.
+struct ModifierDiff {
+ pub from: Modifier,
+ pub to: Modifier,
+}
+
+impl ModifierDiff {
+ fn queue<W: io::Write>(self, w: &mut W) -> io::Result<()> {
+ use crossterm::style::Attribute as CAttribute;
+ let removed = self.from - self.to;
+ if removed.contains(Modifier::REVERSED) {
+ queue!(w, SetAttribute(CAttribute::NoReverse))?;
+ }
+ if removed.contains(Modifier::BOLD) {
+ queue!(w, SetAttribute(CAttribute::NormalIntensity))?;
+ if self.to.contains(Modifier::DIM) {
+ queue!(w, SetAttribute(CAttribute::Dim))?;
+ }
+ }
+ if removed.contains(Modifier::ITALIC) {
+ queue!(w, SetAttribute(CAttribute::NoItalic))?;
+ }
+ if removed.contains(Modifier::UNDERLINED) {
+ queue!(w, SetAttribute(CAttribute::NoUnderline))?;
+ }
+ if removed.contains(Modifier::DIM) {
+ queue!(w, SetAttribute(CAttribute::NormalIntensity))?;
+ }
+ if removed.contains(Modifier::CROSSED_OUT) {
+ queue!(w, SetAttribute(CAttribute::NotCrossedOut))?;
+ }
+ if removed.contains(Modifier::SLOW_BLINK) || removed.contains(Modifier::RAPID_BLINK) {
+ queue!(w, SetAttribute(CAttribute::NoBlink))?;
+ }
+
+ let added = self.to - self.from;
+ if added.contains(Modifier::REVERSED) {
+ queue!(w, SetAttribute(CAttribute::Reverse))?;
+ }
+ if added.contains(Modifier::BOLD) {
+ queue!(w, SetAttribute(CAttribute::Bold))?;
+ }
+ if added.contains(Modifier::ITALIC) {
+ queue!(w, SetAttribute(CAttribute::Italic))?;
+ }
+ if added.contains(Modifier::UNDERLINED) {
+ queue!(w, SetAttribute(CAttribute::Underlined))?;
+ }
+ if added.contains(Modifier::DIM) {
+ queue!(w, SetAttribute(CAttribute::Dim))?;
+ }
+ if added.contains(Modifier::CROSSED_OUT) {
+ queue!(w, SetAttribute(CAttribute::CrossedOut))?;
+ }
+ if added.contains(Modifier::SLOW_BLINK) {
+ queue!(w, SetAttribute(CAttribute::SlowBlink))?;
+ }
+ if added.contains(Modifier::RAPID_BLINK) {
+ queue!(w, SetAttribute(CAttribute::RapidBlink))?;
+ }
+
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use pretty_assertions::assert_eq;
+ use ratatui::layout::Rect;
+ use ratatui::style::Style;
+
+ #[test]
+ fn diff_buffers_does_not_emit_clear_to_end_for_full_width_row() {
+ let area = Rect::new(0, 0, 3, 2);
+ let previous = Buffer::empty(area);
+ let mut next = Buffer::empty(area);
+
+ next.cell_mut((2, 0))
+ .expect("cell should exist")
+ .set_symbol("X");
+
+ let commands = diff_buffers(&previous, &next);
+
+ let clear_count = commands
+ .iter()
+ .filter(|command| matches!(command, DrawCommand::ClearToEnd { y, .. } if *y == 0))
+ .count();
+ assert_eq!(
+ 0, clear_count,
+ "expected diff_buffers not to emit ClearToEnd; commands: {commands:?}",
+ );
+ assert!(
+ commands
+ .iter()
+ .any(|command| matches!(command, DrawCommand::Put { x: 2, y: 0, .. })),
+ "expected diff_buffers to update the final cell; commands: {commands:?}",
+ );
+ }
+
+ #[test]
+ fn diff_buffers_clear_to_end_starts_after_wide_char() {
+ let area = Rect::new(0, 0, 10, 1);
+ let mut previous = Buffer::empty(area);
+ let mut next = Buffer::empty(area);
+
+ previous.set_string(0, 0, "中文", Style::default());
+ next.set_string(0, 0, "中", Style::default());
+
+ let commands = diff_buffers(&previous, &next);
+ assert!(
+ commands
+ .iter()
+ .any(|command| matches!(command, DrawCommand::ClearToEnd { x: 2, y: 0, .. })),
+ "expected clear-to-end to start after the remaining wide char; commands: {commands:?}"
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/diff_render.rs b/codex-rs/tui2/src/diff_render.rs
new file mode 100644
index 0000000000..24c5be597b
--- /dev/null
+++ b/codex-rs/tui2/src/diff_render.rs
@@ -0,0 +1,673 @@
+use diffy::Hunk;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::style::Color;
+use ratatui::style::Modifier;
+use ratatui::style::Style;
+use ratatui::style::Stylize;
+use ratatui::text::Line as RtLine;
+use ratatui::text::Span as RtSpan;
+use ratatui::widgets::Paragraph;
+use std::collections::HashMap;
+use std::path::Path;
+use std::path::PathBuf;
+
+use crate::exec_command::relativize_to_home;
+use crate::render::Insets;
+use crate::render::line_utils::prefix_lines;
+use crate::render::renderable::ColumnRenderable;
+use crate::render::renderable::InsetRenderable;
+use crate::render::renderable::Renderable;
+use codex_core::git_info::get_git_repo_root;
+use codex_core::protocol::FileChange;
+
+// Internal representation for diff line rendering
+enum DiffLineType {
+ Insert,
+ Delete,
+ Context,
+}
+
+pub struct DiffSummary {
+ changes: HashMap<PathBuf, FileChange>,
+ cwd: PathBuf,
+}
+
+impl DiffSummary {
+ pub fn new(changes: HashMap<PathBuf, FileChange>, cwd: PathBuf) -> Self {
+ Self { changes, cwd }
+ }
+}
+
+impl Renderable for FileChange {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ let mut lines = vec![];
+ render_change(self, &mut lines, area.width as usize);
+ Paragraph::new(lines).render(area, buf);
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ let mut lines = vec![];
+ render_change(self, &mut lines, width as usize);
+ lines.len() as u16
+ }
+}
+
+impl From<DiffSummary> for Box<dyn Renderable> {
+ fn from(val: DiffSummary) -> Self {
+ let mut rows: Vec<Box<dyn Renderable>> = vec![];
+
+ for (i, row) in collect_rows(&val.changes).into_iter().enumerate() {
+ if i > 0 {
+ rows.push(Box::new(RtLine::from("")));
+ }
+ let mut path = RtLine::from(display_path_for(&row.path, &val.cwd));
+ path.push_span(" ");
+ path.extend(render_line_count_summary(row.added, row.removed));
+ rows.push(Box::new(path));
+ rows.push(Box::new(RtLine::from("")));
+ rows.push(Box::new(InsetRenderable::new(
+ Box::new(row.change) as Box<dyn Renderable>,
+ Insets::tlbr(0, 2, 0, 0),
+ )));
+ }
+
+ Box::new(ColumnRenderable::with(rows))
+ }
+}
+
+pub(crate) fn create_diff_summary(
+ changes: &HashMap<PathBuf, FileChange>,
+ cwd: &Path,
+ wrap_cols: usize,
+) -> Vec<RtLine<'static>> {
+ let rows = collect_rows(changes);
+ render_changes_block(rows, wrap_cols, cwd)
+}
+
+// Shared row for per-file presentation
+#[derive(Clone)]
+struct Row {
+ #[allow(dead_code)]
+ path: PathBuf,
+ move_path: Option<PathBuf>,
+ added: usize,
+ removed: usize,
+ change: FileChange,
+}
+
+fn collect_rows(changes: &HashMap<PathBuf, FileChange>) -> Vec<Row> {
+ let mut rows: Vec<Row> = Vec::new();
+ for (path, change) in changes.iter() {
+ let (added, removed) = match change {
+ FileChange::Add { content } => (content.lines().count(), 0),
+ FileChange::Delete { content } => (0, content.lines().count()),
+ FileChange::Update { unified_diff, .. } => calculate_add_remove_from_diff(unified_diff),
+ };
+ let move_path = match change {
+ FileChange::Update {
+ move_path: Some(new),
+ ..
+ } => Some(new.clone()),
+ _ => None,
+ };
+ rows.push(Row {
+ path: path.clone(),
+ move_path,
+ added,
+ removed,
+ change: change.clone(),
+ });
+ }
+ rows.sort_by_key(|r| r.path.clone());
+ rows
+}
+
+fn render_line_count_summary(added: usize, removed: usize) -> Vec<RtSpan<'static>> {
+ let mut spans = Vec::new();
+ spans.push("(".into());
+ spans.push(format!("+{added}").green());
+ spans.push(" ".into());
+ spans.push(format!("-{removed}").red());
+ spans.push(")".into());
+ spans
+}
+
+fn render_changes_block(rows: Vec<Row>, wrap_cols: usize, cwd: &Path) -> Vec<RtLine<'static>> {
+ let mut out: Vec<RtLine<'static>> = Vec::new();
+
+ let render_path = |row: &Row| -> Vec<RtSpan<'static>> {
+ let mut spans = Vec::new();
+ spans.push(display_path_for(&row.path, cwd).into());
+ if let Some(move_path) = &row.move_path {
+ spans.push(format!(" → {}", display_path_for(move_path, cwd)).into());
+ }
+ spans
+ };
+
+ // Header
+ let total_added: usize = rows.iter().map(|r| r.added).sum();
+ let total_removed: usize = rows.iter().map(|r| r.removed).sum();
+ let file_count = rows.len();
+ let noun = if file_count == 1 { "file" } else { "files" };
+ let mut header_spans: Vec<RtSpan<'static>> = vec!["• ".dim()];
+ if let [row] = &rows[..] {
+ let verb = match &row.change {
+ FileChange::Add { .. } => "Added",
+ FileChange::Delete { .. } => "Deleted",
+ _ => "Edited",
+ };
+ header_spans.push(verb.bold());
+ header_spans.push(" ".into());
+ header_spans.extend(render_path(row));
+ header_spans.push(" ".into());
+ header_spans.extend(render_line_count_summary(row.added, row.removed));
+ } else {
+ header_spans.push("Edited".bold());
+ header_spans.push(format!(" {file_count} {noun} ").into());
+ header_spans.extend(render_line_count_summary(total_added, total_removed));
+ }
+ out.push(RtLine::from(header_spans));
+
+ for (idx, r) in rows.into_iter().enumerate() {
+ // Insert a blank separator between file chunks (except before the first)
+ if idx > 0 {
+ out.push("".into());
+ }
+ // File header line (skip when single-file header already shows the name)
+ let skip_file_header = file_count == 1;
+ if !skip_file_header {
+ let mut header: Vec<RtSpan<'static>> = Vec::new();
+ header.push(" └ ".dim());
+ header.extend(render_path(&r));
+ header.push(" ".into());
+ header.extend(render_line_count_summary(r.added, r.removed));
+ out.push(RtLine::from(header));
+ }
+
+ let mut lines = vec![];
+ render_change(&r.change, &mut lines, wrap_cols - 4);
+ out.extend(prefix_lines(lines, " ".into(), " ".into()));
+ }
+
+ out
+}
+
+fn render_change(change: &FileChange, out: &mut Vec<RtLine<'static>>, width: usize) {
+ match change {
+ FileChange::Add { content } => {
+ let line_number_width = line_number_width(content.lines().count());
+ for (i, raw) in content.lines().enumerate() {
+ out.extend(push_wrapped_diff_line(
+ i + 1,
+ DiffLineType::Insert,
+ raw,
+ width,
+ line_number_width,
+ ));
+ }
+ }
+ FileChange::Delete { content } => {
+ let line_number_width = line_number_width(content.lines().count());
+ for (i, raw) in content.lines().enumerate() {
+ out.extend(push_wrapped_diff_line(
+ i + 1,
+ DiffLineType::Delete,
+ raw,
+ width,
+ line_number_width,
+ ));
+ }
+ }
+ FileChange::Update { unified_diff, .. } => {
+ if let Ok(patch) = diffy::Patch::from_str(unified_diff) {
+ let mut max_line_number = 0;
+ for h in patch.hunks() {
+ let mut old_ln = h.old_range().start();
+ let mut new_ln = h.new_range().start();
+ for l in h.lines() {
+ match l {
+ diffy::Line::Insert(_) => {
+ max_line_number = max_line_number.max(new_ln);
+ new_ln += 1;
+ }
+ diffy::Line::Delete(_) => {
+ max_line_number = max_line_number.max(old_ln);
+ old_ln += 1;
+ }
+ diffy::Line::Context(_) => {
+ max_line_number = max_line_number.max(new_ln);
+ old_ln += 1;
+ new_ln += 1;
+ }
+ }
+ }
+ }
+ let line_number_width = line_number_width(max_line_number);
+ let mut is_first_hunk = true;
+ for h in patch.hunks() {
+ if !is_first_hunk {
+ let spacer = format!("{:width$} ", "", width = line_number_width.max(1));
+ let spacer_span = RtSpan::styled(spacer, style_gutter());
+ out.push(RtLine::from(vec![spacer_span, "⋮".dim()]));
+ }
+ is_first_hunk = false;
+
+ let mut old_ln = h.old_range().start();
+ let mut new_ln = h.new_range().start();
+ for l in h.lines() {
+ match l {
+ diffy::Line::Insert(text) => {
+ let s = text.trim_end_matches('\n');
+ out.extend(push_wrapped_diff_line(
+ new_ln,
+ DiffLineType::Insert,
+ s,
+ width,
+ line_number_width,
+ ));
+ new_ln += 1;
+ }
+ diffy::Line::Delete(text) => {
+ let s = text.trim_end_matches('\n');
+ out.extend(push_wrapped_diff_line(
+ old_ln,
+ DiffLineType::Delete,
+ s,
+ width,
+ line_number_width,
+ ));
+ old_ln += 1;
+ }
+ diffy::Line::Context(text) => {
+ let s = text.trim_end_matches('\n');
+ out.extend(push_wrapped_diff_line(
+ new_ln,
+ DiffLineType::Context,
+ s,
+ width,
+ line_number_width,
+ ));
+ old_ln += 1;
+ new_ln += 1;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+pub(crate) fn display_path_for(path: &Path, cwd: &Path) -> String {
+ let path_in_same_repo = match (get_git_repo_root(cwd), get_git_repo_root(path)) {
+ (Some(cwd_repo), Some(path_repo)) => cwd_repo == path_repo,
+ _ => false,
+ };
+ let chosen = if path_in_same_repo {
+ pathdiff::diff_paths(path, cwd).unwrap_or_else(|| path.to_path_buf())
+ } else {
+ relativize_to_home(path)
+ .map(|p| PathBuf::from_iter([Path::new("~"), p.as_path()]))
+ .unwrap_or_else(|| path.to_path_buf())
+ };
+ chosen.display().to_string()
+}
+
+fn calculate_add_remove_from_diff(diff: &str) -> (usize, usize) {
+ if let Ok(patch) = diffy::Patch::from_str(diff) {
+ patch
+ .hunks()
+ .iter()
+ .flat_map(Hunk::lines)
+ .fold((0, 0), |(a, d), l| match l {
+ diffy::Line::Insert(_) => (a + 1, d),
+ diffy::Line::Delete(_) => (a, d + 1),
+ diffy::Line::Context(_) => (a, d),
+ })
+ } else {
+ // For unparsable diffs, return 0 for both counts.
+ (0, 0)
+ }
+}
+
+fn push_wrapped_diff_line(
+ line_number: usize,
+ kind: DiffLineType,
+ text: &str,
+ width: usize,
+ line_number_width: usize,
+) -> Vec<RtLine<'static>> {
+ let ln_str = line_number.to_string();
+ let mut remaining_text: &str = text;
+
+ // Reserve a fixed number of spaces (equal to the widest line number plus a
+ // trailing spacer) so the sign column stays aligned across the diff block.
+ let gutter_width = line_number_width.max(1);
+ let prefix_cols = gutter_width + 1;
+
+ let mut first = true;
+ let (sign_char, line_style) = match kind {
+ DiffLineType::Insert => ('+', style_add()),
+ DiffLineType::Delete => ('-', style_del()),
+ DiffLineType::Context => (' ', style_context()),
+ };
+ let mut lines: Vec<RtLine<'static>> = Vec::new();
+
+ loop {
+ // Fit the content for the current terminal row:
+ // compute how many columns are available after the prefix, then split
+ // at a UTF-8 character boundary so this row's chunk fits exactly.
+ let available_content_cols = width.saturating_sub(prefix_cols + 1).max(1);
+ let split_at_byte_index = remaining_text
+ .char_indices()
+ .nth(available_content_cols)
+ .map(|(i, _)| i)
+ .unwrap_or_else(|| remaining_text.len());
+ let (chunk, rest) = remaining_text.split_at(split_at_byte_index);
+ remaining_text = rest;
+
+ if first {
+ // Build gutter (right-aligned line number plus spacer) as a dimmed span
+ let gutter = format!("{ln_str:>gutter_width$} ");
+ // Content with a sign ('+'/'-'/' ') styled per diff kind
+ let content = format!("{sign_char}{chunk}");
+ lines.push(RtLine::from(vec![
+ RtSpan::styled(gutter, style_gutter()),
+ RtSpan::styled(content, line_style),
+ ]));
+ first = false;
+ } else {
+ // Continuation lines keep a space for the sign column so content aligns
+ let gutter = format!("{:gutter_width$} ", "");
+ lines.push(RtLine::from(vec![
+ RtSpan::styled(gutter, style_gutter()),
+ RtSpan::styled(chunk.to_string(), line_style),
+ ]));
+ }
+ if remaining_text.is_empty() {
+ break;
+ }
+ }
+ lines
+}
+
+fn line_number_width(max_line_number: usize) -> usize {
+ if max_line_number == 0 {
+ 1
+ } else {
+ max_line_number.to_string().len()
+ }
+}
+
+fn style_gutter() -> Style {
+ Style::default().add_modifier(Modifier::DIM)
+}
+
+fn style_context() -> Style {
+ Style::default()
+}
+
+fn style_add() -> Style {
+ Style::default().fg(Color::Green)
+}
+
+fn style_del() -> Style {
+ Style::default().fg(Color::Red)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use insta::assert_snapshot;
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+ use ratatui::text::Text;
+ use ratatui::widgets::Paragraph;
+ use ratatui::widgets::WidgetRef;
+ use ratatui::widgets::Wrap;
+ fn diff_summary_for_tests(changes: &HashMap<PathBuf, FileChange>) -> Vec<RtLine<'static>> {
+ create_diff_summary(changes, &PathBuf::from("/"), 80)
+ }
+
+ fn snapshot_lines(name: &str, lines: Vec<RtLine<'static>>, width: u16, height: u16) {
+ let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("terminal");
+ terminal
+ .draw(|f| {
+ Paragraph::new(Text::from(lines))
+ .wrap(Wrap { trim: false })
+ .render_ref(f.area(), f.buffer_mut())
+ })
+ .expect("draw");
+ assert_snapshot!(name, terminal.backend());
+ }
+
+ fn snapshot_lines_text(name: &str, lines: &[RtLine<'static>]) {
+ // Convert Lines to plain text rows and trim trailing spaces so it's
+ // easier to validate indentation visually in snapshots.
+ let text = lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.as_ref())
+ .collect::<String>()
+ })
+ .map(|s| s.trim_end().to_string())
+ .collect::<Vec<_>>()
+ .join("\n");
+ assert_snapshot!(name, text);
+ }
+
+ #[test]
+ fn ui_snapshot_wrap_behavior_insert() {
+ // Narrow width to force wrapping within our diff line rendering
+ let long_line = "this is a very long line that should wrap across multiple terminal columns and continue";
+
+ // Call the wrapping function directly so we can precisely control the width
+ let lines =
+ push_wrapped_diff_line(1, DiffLineType::Insert, long_line, 80, line_number_width(1));
+
+ // Render into a small terminal to capture the visual layout
+ snapshot_lines("wrap_behavior_insert", lines, 90, 8);
+ }
+
+ #[test]
+ fn ui_snapshot_apply_update_block() {
+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();
+ let original = "line one\nline two\nline three\n";
+ let modified = "line one\nline two changed\nline three\n";
+ let patch = diffy::create_patch(original, modified).to_string();
+
+ changes.insert(
+ PathBuf::from("example.txt"),
+ FileChange::Update {
+ unified_diff: patch,
+ move_path: None,
+ },
+ );
+
+ let lines = diff_summary_for_tests(&changes);
+
+ snapshot_lines("apply_update_block", lines, 80, 12);
+ }
+
+ #[test]
+ fn ui_snapshot_apply_update_with_rename_block() {
+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();
+ let original = "A\nB\nC\n";
+ let modified = "A\nB changed\nC\n";
+ let patch = diffy::create_patch(original, modified).to_string();
+
+ changes.insert(
+ PathBuf::from("old_name.rs"),
+ FileChange::Update {
+ unified_diff: patch,
+ move_path: Some(PathBuf::from("new_name.rs")),
+ },
+ );
+
+ let lines = diff_summary_for_tests(&changes);
+
+ snapshot_lines("apply_update_with_rename_block", lines, 80, 12);
+ }
+
+ #[test]
+ fn ui_snapshot_apply_multiple_files_block() {
+ // Two files: one update and one add, to exercise combined header and per-file rows
+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();
+
+ // File a.txt: single-line replacement (one delete, one insert)
+ let patch_a = diffy::create_patch("one\n", "one changed\n").to_string();
+ changes.insert(
+ PathBuf::from("a.txt"),
+ FileChange::Update {
+ unified_diff: patch_a,
+ move_path: None,
+ },
+ );
+
+ // File b.txt: newly added with one line
+ changes.insert(
+ PathBuf::from("b.txt"),
+ FileChange::Add {
+ content: "new\n".to_string(),
+ },
+ );
+
+ let lines = diff_summary_for_tests(&changes);
+
+ snapshot_lines("apply_multiple_files_block", lines, 80, 14);
+ }
+
+ #[test]
+ fn ui_snapshot_apply_add_block() {
+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();
+ changes.insert(
+ PathBuf::from("new_file.txt"),
+ FileChange::Add {
+ content: "alpha\nbeta\n".to_string(),
+ },
+ );
+
+ let lines = diff_summary_for_tests(&changes);
+
+ snapshot_lines("apply_add_block", lines, 80, 10);
+ }
+
+ #[test]
+ fn ui_snapshot_apply_delete_block() {
+ // Write a temporary file so the delete renderer can read original content
+ let tmp_path = PathBuf::from("tmp_delete_example.txt");
+ std::fs::write(&tmp_path, "first\nsecond\nthird\n").expect("write tmp file");
+
+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();
+ changes.insert(
+ tmp_path.clone(),
+ FileChange::Delete {
+ content: "first\nsecond\nthird\n".to_string(),
+ },
+ );
+
+ let lines = diff_summary_for_tests(&changes);
+
+ // Cleanup best-effort; rendering has already read the file
+ let _ = std::fs::remove_file(&tmp_path);
+
+ snapshot_lines("apply_delete_block", lines, 80, 12);
+ }
+
+ #[test]
+ fn ui_snapshot_apply_update_block_wraps_long_lines() {
+ // Create a patch with a long modified line to force wrapping
+ let original = "line 1\nshort\nline 3\n";
+ let modified = "line 1\nshort this_is_a_very_long_modified_line_that_should_wrap_across_multiple_terminal_columns_and_continue_even_further_beyond_eighty_columns_to_force_multiple_wraps\nline 3\n";
+ let patch = diffy::create_patch(original, modified).to_string();
+
+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();
+ changes.insert(
+ PathBuf::from("long_example.txt"),
+ FileChange::Update {
+ unified_diff: patch,
+ move_path: None,
+ },
+ );
+
+ let lines = create_diff_summary(&changes, &PathBuf::from("/"), 72);
+
+ // Render with backend width wider than wrap width to avoid Paragraph auto-wrap.
+ snapshot_lines("apply_update_block_wraps_long_lines", lines, 80, 12);
+ }
+
+ #[test]
+ fn ui_snapshot_apply_update_block_wraps_long_lines_text() {
+ // This mirrors the desired layout example: sign only on first inserted line,
+ // subsequent wrapped pieces start aligned under the line number gutter.
+ let original = "1\n2\n3\n4\n";
+ let modified = "1\nadded long line which wraps and_if_there_is_a_long_token_it_will_be_broken\n3\n4 context line which also wraps across\n";
+ let patch = diffy::create_patch(original, modified).to_string();
+
+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();
+ changes.insert(
+ PathBuf::from("wrap_demo.txt"),
+ FileChange::Update {
+ unified_diff: patch,
+ move_path: None,
+ },
+ );
+
+ let lines = create_diff_summary(&changes, &PathBuf::from("/"), 28);
+ snapshot_lines_text("apply_update_block_wraps_long_lines_text", &lines);
+ }
+
+ #[test]
+ fn ui_snapshot_apply_update_block_line_numbers_three_digits_text() {
+ let original = (1..=110).map(|i| format!("line {i}\n")).collect::<String>();
+ let modified = (1..=110)
+ .map(|i| {
+ if i == 100 {
+ format!("line {i} changed\n")
+ } else {
+ format!("line {i}\n")
+ }
+ })
+ .collect::<String>();
+ let patch = diffy::create_patch(&original, &modified).to_string();
+
+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();
+ changes.insert(
+ PathBuf::from("hundreds.txt"),
+ FileChange::Update {
+ unified_diff: patch,
+ move_path: None,
+ },
+ );
+
+ let lines = create_diff_summary(&changes, &PathBuf::from("/"), 80);
+ snapshot_lines_text("apply_update_block_line_numbers_three_digits_text", &lines);
+ }
+
+ #[test]
+ fn ui_snapshot_apply_update_block_relativizes_path() {
+ let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/"));
+ let abs_old = cwd.join("abs_old.rs");
+ let abs_new = cwd.join("abs_new.rs");
+
+ let original = "X\nY\n";
+ let modified = "X changed\nY\n";
+ let patch = diffy::create_patch(original, modified).to_string();
+
+ let mut changes: HashMap<PathBuf, FileChange> = HashMap::new();
+ changes.insert(
+ abs_old,
+ FileChange::Update {
+ unified_diff: patch,
+ move_path: Some(abs_new),
+ },
+ );
+
+ let lines = create_diff_summary(&changes, &cwd, 80);
+
+ snapshot_lines("apply_update_block_relativizes_path", lines, 80, 10);
+ }
+}
diff --git a/codex-rs/tui2/src/exec_cell/mod.rs b/codex-rs/tui2/src/exec_cell/mod.rs
new file mode 100644
index 0000000000..906091113e
--- /dev/null
+++ b/codex-rs/tui2/src/exec_cell/mod.rs
@@ -0,0 +1,12 @@
+mod model;
+mod render;
+
+pub(crate) use model::CommandOutput;
+#[cfg(test)]
+pub(crate) use model::ExecCall;
+pub(crate) use model::ExecCell;
+pub(crate) use render::OutputLinesParams;
+pub(crate) use render::TOOL_CALL_MAX_LINES;
+pub(crate) use render::new_active_exec_command;
+pub(crate) use render::output_lines;
+pub(crate) use render::spinner;
diff --git a/codex-rs/tui2/src/exec_cell/model.rs b/codex-rs/tui2/src/exec_cell/model.rs
new file mode 100644
index 0000000000..76316968c6
--- /dev/null
+++ b/codex-rs/tui2/src/exec_cell/model.rs
@@ -0,0 +1,150 @@
+use std::time::Duration;
+use std::time::Instant;
+
+use codex_core::protocol::ExecCommandSource;
+use codex_protocol::parse_command::ParsedCommand;
+
+#[derive(Clone, Debug, Default)]
+pub(crate) struct CommandOutput {
+ pub(crate) exit_code: i32,
+ /// The aggregated stderr + stdout interleaved.
+ pub(crate) aggregated_output: String,
+ /// The formatted output of the command, as seen by the model.
+ pub(crate) formatted_output: String,
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct ExecCall {
+ pub(crate) call_id: String,
+ pub(crate) command: Vec<String>,
+ pub(crate) parsed: Vec<ParsedCommand>,
+ pub(crate) output: Option<CommandOutput>,
+ pub(crate) source: ExecCommandSource,
+ pub(crate) start_time: Option<Instant>,
+ pub(crate) duration: Option<Duration>,
+ pub(crate) interaction_input: Option<String>,
+}
+
+#[derive(Debug)]
+pub(crate) struct ExecCell {
+ pub(crate) calls: Vec<ExecCall>,
+ animations_enabled: bool,
+}
+
+impl ExecCell {
+ pub(crate) fn new(call: ExecCall, animations_enabled: bool) -> Self {
+ Self {
+ calls: vec![call],
+ animations_enabled,
+ }
+ }
+
+ pub(crate) fn with_added_call(
+ &self,
+ call_id: String,
+ command: Vec<String>,
+ parsed: Vec<ParsedCommand>,
+ source: ExecCommandSource,
+ interaction_input: Option<String>,
+ ) -> Option<Self> {
+ let call = ExecCall {
+ call_id,
+ command,
+ parsed,
+ output: None,
+ source,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input,
+ };
+ if self.is_exploring_cell() && Self::is_exploring_call(&call) {
+ Some(Self {
+ calls: [self.calls.clone(), vec![call]].concat(),
+ animations_enabled: self.animations_enabled,
+ })
+ } else {
+ None
+ }
+ }
+
+ pub(crate) fn complete_call(
+ &mut self,
+ call_id: &str,
+ output: CommandOutput,
+ duration: Duration,
+ ) {
+ if let Some(call) = self.calls.iter_mut().rev().find(|c| c.call_id == call_id) {
+ call.output = Some(output);
+ call.duration = Some(duration);
+ call.start_time = None;
+ }
+ }
+
+ pub(crate) fn should_flush(&self) -> bool {
+ !self.is_exploring_cell() && self.calls.iter().all(|c| c.output.is_some())
+ }
+
+ pub(crate) fn mark_failed(&mut self) {
+ for call in self.calls.iter_mut() {
+ if call.output.is_none() {
+ let elapsed = call
+ .start_time
+ .map(|st| st.elapsed())
+ .unwrap_or_else(|| Duration::from_millis(0));
+ call.start_time = None;
+ call.duration = Some(elapsed);
+ call.output = Some(CommandOutput {
+ exit_code: 1,
+ formatted_output: String::new(),
+ aggregated_output: String::new(),
+ });
+ }
+ }
+ }
+
+ pub(crate) fn is_exploring_cell(&self) -> bool {
+ self.calls.iter().all(Self::is_exploring_call)
+ }
+
+ pub(crate) fn is_active(&self) -> bool {
+ self.calls.iter().any(|c| c.output.is_none())
+ }
+
+ pub(crate) fn active_start_time(&self) -> Option<Instant> {
+ self.calls
+ .iter()
+ .find(|c| c.output.is_none())
+ .and_then(|c| c.start_time)
+ }
+
+ pub(crate) fn animations_enabled(&self) -> bool {
+ self.animations_enabled
+ }
+
+ pub(crate) fn iter_calls(&self) -> impl Iterator<Item = &ExecCall> {
+ self.calls.iter()
+ }
+
+ pub(super) fn is_exploring_call(call: &ExecCall) -> bool {
+ !matches!(call.source, ExecCommandSource::UserShell)
+ && !call.parsed.is_empty()
+ && call.parsed.iter().all(|p| {
+ matches!(
+ p,
+ ParsedCommand::Read { .. }
+ | ParsedCommand::ListFiles { .. }
+ | ParsedCommand::Search { .. }
+ )
+ })
+ }
+}
+
+impl ExecCall {
+ pub(crate) fn is_user_shell_command(&self) -> bool {
+ matches!(self.source, ExecCommandSource::UserShell)
+ }
+
+ pub(crate) fn is_unified_exec_interaction(&self) -> bool {
+ matches!(self.source, ExecCommandSource::UnifiedExecInteraction)
+ }
+}
diff --git a/codex-rs/tui2/src/exec_cell/render.rs b/codex-rs/tui2/src/exec_cell/render.rs
new file mode 100644
index 0000000000..6517bcf470
--- /dev/null
+++ b/codex-rs/tui2/src/exec_cell/render.rs
@@ -0,0 +1,705 @@
+use std::time::Instant;
+
+use super::model::CommandOutput;
+use super::model::ExecCall;
+use super::model::ExecCell;
+use crate::exec_command::strip_bash_lc_and_escape;
+use crate::history_cell::HistoryCell;
+use crate::render::highlight::highlight_bash_to_lines;
+use crate::render::line_utils::prefix_lines;
+use crate::render::line_utils::push_owned_lines;
+use crate::shimmer::shimmer_spans;
+use crate::wrapping::RtOptions;
+use crate::wrapping::word_wrap_line;
+use crate::wrapping::word_wrap_lines;
+use codex_ansi_escape::ansi_escape_line;
+use codex_common::elapsed::format_duration;
+use codex_core::bash::extract_bash_command;
+use codex_core::protocol::ExecCommandSource;
+use codex_protocol::parse_command::ParsedCommand;
+use itertools::Itertools;
+use ratatui::prelude::*;
+use ratatui::style::Modifier;
+use ratatui::style::Stylize;
+use textwrap::WordSplitter;
+use unicode_width::UnicodeWidthStr;
+
+pub(crate) const TOOL_CALL_MAX_LINES: usize = 5;
+const USER_SHELL_TOOL_CALL_MAX_LINES: usize = 50;
+const MAX_INTERACTION_PREVIEW_CHARS: usize = 80;
+
+pub(crate) struct OutputLinesParams {
+ pub(crate) line_limit: usize,
+ pub(crate) only_err: bool,
+ pub(crate) include_angle_pipe: bool,
+ pub(crate) include_prefix: bool,
+}
+
+pub(crate) fn new_active_exec_command(
+ call_id: String,
+ command: Vec<String>,
+ parsed: Vec<ParsedCommand>,
+ source: ExecCommandSource,
+ interaction_input: Option<String>,
+ animations_enabled: bool,
+) -> ExecCell {
+ ExecCell::new(
+ ExecCall {
+ call_id,
+ command,
+ parsed,
+ output: None,
+ source,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input,
+ },
+ animations_enabled,
+ )
+}
+
+fn format_unified_exec_interaction(command: &[String], input: Option<&str>) -> String {
+ let command_display = if let Some((_, script)) = extract_bash_command(command) {
+ script.to_string()
+ } else {
+ command.join(" ")
+ };
+ match input {
+ Some(data) if !data.is_empty() => {
+ let preview = summarize_interaction_input(data);
+ format!("Interacted with `{command_display}`, sent `{preview}`")
+ }
+ _ => format!("Waited for `{command_display}`"),
+ }
+}
+
+fn summarize_interaction_input(input: &str) -> String {
+ let single_line = input.replace('\n', "\\n");
+ let sanitized = single_line.replace('`', "\\`");
+ if sanitized.chars().count() <= MAX_INTERACTION_PREVIEW_CHARS {
+ return sanitized;
+ }
+
+ let mut preview = String::new();
+ for ch in sanitized.chars().take(MAX_INTERACTION_PREVIEW_CHARS) {
+ preview.push(ch);
+ }
+ preview.push_str("...");
+ preview
+}
+
+#[derive(Clone)]
+pub(crate) struct OutputLines {
+ pub(crate) lines: Vec<Line<'static>>,
+ pub(crate) omitted: Option<usize>,
+}
+
+pub(crate) fn output_lines(
+ output: Option<&CommandOutput>,
+ params: OutputLinesParams,
+) -> OutputLines {
+ let OutputLinesParams {
+ line_limit,
+ only_err,
+ include_angle_pipe,
+ include_prefix,
+ } = params;
+ let CommandOutput {
+ aggregated_output, ..
+ } = match output {
+ Some(output) if only_err && output.exit_code == 0 => {
+ return OutputLines {
+ lines: Vec::new(),
+ omitted: None,
+ };
+ }
+ Some(output) => output,
+ None => {
+ return OutputLines {
+ lines: Vec::new(),
+ omitted: None,
+ };
+ }
+ };
+
+ let src = aggregated_output;
+ let lines: Vec<&str> = src.lines().collect();
+ let total = lines.len();
+ let mut out: Vec<Line<'static>> = Vec::new();
+
+ let head_end = total.min(line_limit);
+ for (i, raw) in lines[..head_end].iter().enumerate() {
+ let mut line = ansi_escape_line(raw);
+ let prefix = if !include_prefix {
+ ""
+ } else if i == 0 && include_angle_pipe {
+ " └ "
+ } else {
+ " "
+ };
+ line.spans.insert(0, prefix.into());
+ line.spans.iter_mut().for_each(|span| {
+ span.style = span.style.add_modifier(Modifier::DIM);
+ });
+ out.push(line);
+ }
+
+ let show_ellipsis = total > 2 * line_limit;
+ let omitted = if show_ellipsis {
+ Some(total - 2 * line_limit)
+ } else {
+ None
+ };
+ if show_ellipsis {
+ let omitted = total - 2 * line_limit;
+ out.push(format!("… +{omitted} lines").into());
+ }
+
+ let tail_start = if show_ellipsis {
+ total - line_limit
+ } else {
+ head_end
+ };
+ for raw in lines[tail_start..].iter() {
+ let mut line = ansi_escape_line(raw);
+ if include_prefix {
+ line.spans.insert(0, " ".into());
+ }
+ line.spans.iter_mut().for_each(|span| {
+ span.style = span.style.add_modifier(Modifier::DIM);
+ });
+ out.push(line);
+ }
+
+ OutputLines {
+ lines: out,
+ omitted,
+ }
+}
+
+pub(crate) fn spinner(start_time: Option<Instant>, animations_enabled: bool) -> Span<'static> {
+ if !animations_enabled {
+ return "•".dim();
+ }
+ let elapsed = start_time.map(|st| st.elapsed()).unwrap_or_default();
+ if supports_color::on_cached(supports_color::Stream::Stdout)
+ .map(|level| level.has_16m)
+ .unwrap_or(false)
+ {
+ shimmer_spans("•")[0].clone()
+ } else {
+ let blink_on = (elapsed.as_millis() / 600).is_multiple_of(2);
+ if blink_on { "•".into() } else { "◦".dim() }
+ }
+}
+
+impl HistoryCell for ExecCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ if self.is_exploring_cell() {
+ self.exploring_display_lines(width)
+ } else {
+ self.command_display_lines(width)
+ }
+ }
+
+ fn desired_transcript_height(&self, width: u16) -> u16 {
+ self.transcript_lines(width).len() as u16
+ }
+
+ fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let mut lines: Vec<Line<'static>> = vec![];
+ for (i, call) in self.iter_calls().enumerate() {
+ if i > 0 {
+ lines.push("".into());
+ }
+ let script = strip_bash_lc_and_escape(&call.command);
+ let highlighted_script = highlight_bash_to_lines(&script);
+ let cmd_display = word_wrap_lines(
+ &highlighted_script,
+ RtOptions::new(width as usize)
+ .initial_indent("$ ".magenta().into())
+ .subsequent_indent(" ".into()),
+ );
+ lines.extend(cmd_display);
+
+ if let Some(output) = call.output.as_ref() {
+ if !call.is_unified_exec_interaction() {
+ let wrap_width = width.max(1) as usize;
+ let wrap_opts = RtOptions::new(wrap_width);
+ for unwrapped in output.formatted_output.lines().map(ansi_escape_line) {
+ let wrapped = word_wrap_line(&unwrapped, wrap_opts.clone());
+ push_owned_lines(&wrapped, &mut lines);
+ }
+ }
+ let duration = call
+ .duration
+ .map(format_duration)
+ .unwrap_or_else(|| "unknown".to_string());
+ let mut result: Line = if output.exit_code == 0 {
+ Line::from("✓".green().bold())
+ } else {
+ Line::from(vec![
+ "✗".red().bold(),
+ format!(" ({})", output.exit_code).into(),
+ ])
+ };
+ result.push_span(format!(" • {duration}").dim());
+ lines.push(result);
+ }
+ }
+ lines
+ }
+}
+
+impl ExecCell {
+ fn exploring_display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let mut out: Vec<Line<'static>> = Vec::new();
+ out.push(Line::from(vec![
+ if self.is_active() {
+ spinner(self.active_start_time(), self.animations_enabled())
+ } else {
+ "•".dim()
+ },
+ " ".into(),
+ if self.is_active() {
+ "Exploring".bold()
+ } else {
+ "Explored".bold()
+ },
+ ]));
+
+ let mut calls = self.calls.clone();
+ let mut out_indented = Vec::new();
+ while !calls.is_empty() {
+ let mut call = calls.remove(0);
+ if call
+ .parsed
+ .iter()
+ .all(|parsed| matches!(parsed, ParsedCommand::Read { .. }))
+ {
+ while let Some(next) = calls.first() {
+ if next
+ .parsed
+ .iter()
+ .all(|parsed| matches!(parsed, ParsedCommand::Read { .. }))
+ {
+ call.parsed.extend(next.parsed.clone());
+ calls.remove(0);
+ } else {
+ break;
+ }
+ }
+ }
+
+ let reads_only = call
+ .parsed
+ .iter()
+ .all(|parsed| matches!(parsed, ParsedCommand::Read { .. }));
+
+ let call_lines: Vec<(&str, Vec<Span<'static>>)> = if reads_only {
+ let names = call
+ .parsed
+ .iter()
+ .map(|parsed| match parsed {
+ ParsedCommand::Read { name, .. } => name.clone(),
+ _ => unreachable!(),
+ })
+ .unique();
+ vec![(
+ "Read",
+ Itertools::intersperse(names.into_iter().map(Into::into), ", ".dim()).collect(),
+ )]
+ } else {
+ let mut lines = Vec::new();
+ for parsed in &call.parsed {
+ match parsed {
+ ParsedCommand::Read { name, .. } => {
+ lines.push(("Read", vec![name.clone().into()]));
+ }
+ ParsedCommand::ListFiles { cmd, path } => {
+ lines.push(("List", vec![path.clone().unwrap_or(cmd.clone()).into()]));
+ }
+ ParsedCommand::Search { cmd, query, path } => {
+ let spans = match (query, path) {
+ (Some(q), Some(p)) => {
+ vec![q.clone().into(), " in ".dim(), p.clone().into()]
+ }
+ (Some(q), None) => vec![q.clone().into()],
+ _ => vec![cmd.clone().into()],
+ };
+ lines.push(("Search", spans));
+ }
+ ParsedCommand::Unknown { cmd } => {
+ lines.push(("Run", vec![cmd.clone().into()]));
+ }
+ }
+ }
+ lines
+ };
+
+ for (title, line) in call_lines {
+ let line = Line::from(line);
+ let initial_indent = Line::from(vec![title.cyan(), " ".into()]);
+ let subsequent_indent = " ".repeat(initial_indent.width()).into();
+ let wrapped = word_wrap_line(
+ &line,
+ RtOptions::new(width as usize)
+ .initial_indent(initial_indent)
+ .subsequent_indent(subsequent_indent),
+ );
+ push_owned_lines(&wrapped, &mut out_indented);
+ }
+ }
+
+ out.extend(prefix_lines(out_indented, " └ ".dim(), " ".into()));
+ out
+ }
+
+ fn command_display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let [call] = &self.calls.as_slice() else {
+ panic!("Expected exactly one call in a command display cell");
+ };
+ let layout = EXEC_DISPLAY_LAYOUT;
+ let success = call.output.as_ref().map(|o| o.exit_code == 0);
+ let bullet = match success {
+ Some(true) => "•".green().bold(),
+ Some(false) => "•".red().bold(),
+ None => spinner(call.start_time, self.animations_enabled()),
+ };
+ let is_interaction = call.is_unified_exec_interaction();
+ let title = if is_interaction {
+ ""
+ } else if self.is_active() {
+ "Running"
+ } else if call.is_user_shell_command() {
+ "You ran"
+ } else {
+ "Ran"
+ };
+
+ let mut header_line = if is_interaction {
+ Line::from(vec![bullet.clone(), " ".into()])
+ } else {
+ Line::from(vec![bullet.clone(), " ".into(), title.bold(), " ".into()])
+ };
+ let header_prefix_width = header_line.width();
+
+ let cmd_display = if call.is_unified_exec_interaction() {
+ format_unified_exec_interaction(&call.command, call.interaction_input.as_deref())
+ } else {
+ strip_bash_lc_and_escape(&call.command)
+ };
+ let highlighted_lines = highlight_bash_to_lines(&cmd_display);
+
+ let continuation_wrap_width = layout.command_continuation.wrap_width(width);
+ let continuation_opts =
+ RtOptions::new(continuation_wrap_width).word_splitter(WordSplitter::NoHyphenation);
+
+ let mut continuation_lines: Vec<Line<'static>> = Vec::new();
+
+ if let Some((first, rest)) = highlighted_lines.split_first() {
+ let available_first_width = (width as usize).saturating_sub(header_prefix_width).max(1);
+ let first_opts =
+ RtOptions::new(available_first_width).word_splitter(WordSplitter::NoHyphenation);
+ let mut first_wrapped: Vec<Line<'static>> = Vec::new();
+ push_owned_lines(&word_wrap_line(first, first_opts), &mut first_wrapped);
+ let mut first_wrapped_iter = first_wrapped.into_iter();
+ if let Some(first_segment) = first_wrapped_iter.next() {
+ header_line.extend(first_segment);
+ }
+ continuation_lines.extend(first_wrapped_iter);
+
+ for line in rest {
+ push_owned_lines(
+ &word_wrap_line(line, continuation_opts.clone()),
+ &mut continuation_lines,
+ );
+ }
+ }
+
+ let mut lines: Vec<Line<'static>> = vec![header_line];
+
+ let continuation_lines = Self::limit_lines_from_start(
+ &continuation_lines,
+ layout.command_continuation_max_lines,
+ );
+ if !continuation_lines.is_empty() {
+ lines.extend(prefix_lines(
+ continuation_lines,
+ Span::from(layout.command_continuation.initial_prefix).dim(),
+ Span::from(layout.command_continuation.subsequent_prefix).dim(),
+ ));
+ }
+
+ if let Some(output) = call.output.as_ref() {
+ let line_limit = if call.is_user_shell_command() {
+ USER_SHELL_TOOL_CALL_MAX_LINES
+ } else {
+ TOOL_CALL_MAX_LINES
+ };
+ let raw_output = output_lines(
+ Some(output),
+ OutputLinesParams {
+ line_limit,
+ only_err: false,
+ include_angle_pipe: false,
+ include_prefix: false,
+ },
+ );
+ let display_limit = if call.is_user_shell_command() {
+ USER_SHELL_TOOL_CALL_MAX_LINES
+ } else {
+ layout.output_max_lines
+ };
+
+ if raw_output.lines.is_empty() {
+ if !call.is_unified_exec_interaction() {
+ lines.extend(prefix_lines(
+ vec![Line::from("(no output)".dim())],
+ Span::from(layout.output_block.initial_prefix).dim(),
+ Span::from(layout.output_block.subsequent_prefix),
+ ));
+ }
+ } else {
+ // Wrap first so that truncation is applied to on-screen lines
+ // rather than logical lines. This ensures that a small number
+ // of very long lines cannot flood the viewport.
+ let mut wrapped_output: Vec<Line<'static>> = Vec::new();
+ let output_wrap_width = layout.output_block.wrap_width(width);
+ let output_opts =
+ RtOptions::new(output_wrap_width).word_splitter(WordSplitter::NoHyphenation);
+ for line in &raw_output.lines {
+ push_owned_lines(
+ &word_wrap_line(line, output_opts.clone()),
+ &mut wrapped_output,
+ );
+ }
+
+ let trimmed_output =
+ Self::truncate_lines_middle(&wrapped_output, display_limit, raw_output.omitted);
+
+ if !trimmed_output.is_empty() {
+ lines.extend(prefix_lines(
+ trimmed_output,
+ Span::from(layout.output_block.initial_prefix).dim(),
+ Span::from(layout.output_block.subsequent_prefix),
+ ));
+ }
+ }
+ }
+
+ lines
+ }
+
+ fn limit_lines_from_start(lines: &[Line<'static>], keep: usize) -> Vec<Line<'static>> {
+ if lines.len() <= keep {
+ return lines.to_vec();
+ }
+ if keep == 0 {
+ return vec![Self::ellipsis_line(lines.len())];
+ }
+
+ let mut out: Vec<Line<'static>> = lines[..keep].to_vec();
+ out.push(Self::ellipsis_line(lines.len() - keep));
+ out
+ }
+
+ fn truncate_lines_middle(
+ lines: &[Line<'static>],
+ max: usize,
+ omitted_hint: Option<usize>,
+ ) -> Vec<Line<'static>> {
+ if max == 0 {
+ return Vec::new();
+ }
+ if lines.len() <= max {
+ return lines.to_vec();
+ }
+ if max == 1 {
+ // Carry forward any previously omitted count and add any
+ // additionally hidden content lines from this truncation.
+ let base = omitted_hint.unwrap_or(0);
+ // When an existing ellipsis is present, `lines` already includes
+ // that single representation line; exclude it from the count of
+ // additionally omitted content lines.
+ let extra = lines
+ .len()
+ .saturating_sub(usize::from(omitted_hint.is_some()));
+ let omitted = base + extra;
+ return vec![Self::ellipsis_line(omitted)];
+ }
+
+ let head = (max - 1) / 2;
+ let tail = max - head - 1;
+ let mut out: Vec<Line<'static>> = Vec::new();
+
+ if head > 0 {
+ out.extend(lines[..head].iter().cloned());
+ }
+
+ let base = omitted_hint.unwrap_or(0);
+ let additional = lines
+ .len()
+ .saturating_sub(head + tail)
+ .saturating_sub(usize::from(omitted_hint.is_some()));
+ out.push(Self::ellipsis_line(base + additional));
+
+ if tail > 0 {
+ out.extend(lines[lines.len() - tail..].iter().cloned());
+ }
+
+ out
+ }
+
+ fn ellipsis_line(omitted: usize) -> Line<'static> {
+ Line::from(vec![format!("… +{omitted} lines").dim()])
+ }
+}
+
+#[derive(Clone, Copy)]
+struct PrefixedBlock {
+ initial_prefix: &'static str,
+ subsequent_prefix: &'static str,
+}
+
+impl PrefixedBlock {
+ const fn new(initial_prefix: &'static str, subsequent_prefix: &'static str) -> Self {
+ Self {
+ initial_prefix,
+ subsequent_prefix,
+ }
+ }
+
+ fn wrap_width(self, total_width: u16) -> usize {
+ let prefix_width = UnicodeWidthStr::width(self.initial_prefix)
+ .max(UnicodeWidthStr::width(self.subsequent_prefix));
+ usize::from(total_width).saturating_sub(prefix_width).max(1)
+ }
+}
+
+#[derive(Clone, Copy)]
+struct ExecDisplayLayout {
+ command_continuation: PrefixedBlock,
+ command_continuation_max_lines: usize,
+ output_block: PrefixedBlock,
+ output_max_lines: usize,
+}
+
+impl ExecDisplayLayout {
+ const fn new(
+ command_continuation: PrefixedBlock,
+ command_continuation_max_lines: usize,
+ output_block: PrefixedBlock,
+ output_max_lines: usize,
+ ) -> Self {
+ Self {
+ command_continuation,
+ command_continuation_max_lines,
+ output_block,
+ output_max_lines,
+ }
+ }
+}
+
+const EXEC_DISPLAY_LAYOUT: ExecDisplayLayout = ExecDisplayLayout::new(
+ PrefixedBlock::new(" │ ", " │ "),
+ 2,
+ PrefixedBlock::new(" └ ", " "),
+ 5,
+);
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use codex_core::protocol::ExecCommandSource;
+
+ #[test]
+ fn user_shell_output_is_limited_by_screen_lines() {
+ // Construct a user shell exec cell whose aggregated output consists of a
+ // small number of very long logical lines. These will wrap into many
+ // on-screen lines at narrow widths.
+ //
+ // Use a short marker so it survives wrapping intact inside each
+ // rendered screen line; the previous test used a marker longer than
+ // the wrap width, so it was split across lines and the assertion
+ // never actually saw it.
+ let marker = "Z";
+ let long_chunk = marker.repeat(800);
+ let aggregated_output = format!("{long_chunk}\n{long_chunk}\n");
+
+ // Baseline: how many screen lines would we get if we simply wrapped
+ // all logical lines without any truncation?
+ let output = CommandOutput {
+ exit_code: 0,
+ aggregated_output,
+ formatted_output: String::new(),
+ };
+ let width = 20;
+ let layout = EXEC_DISPLAY_LAYOUT;
+ let raw_output = output_lines(
+ Some(&output),
+ OutputLinesParams {
+ // Large enough to include all logical lines without
+ // triggering the ellipsis in `output_lines`.
+ line_limit: 100,
+ only_err: false,
+ include_angle_pipe: false,
+ include_prefix: false,
+ },
+ );
+ let output_wrap_width = layout.output_block.wrap_width(width);
+ let output_opts =
+ RtOptions::new(output_wrap_width).word_splitter(WordSplitter::NoHyphenation);
+ let mut full_wrapped_output: Vec<Line<'static>> = Vec::new();
+ for line in &raw_output.lines {
+ push_owned_lines(
+ &word_wrap_line(line, output_opts.clone()),
+ &mut full_wrapped_output,
+ );
+ }
+ let full_screen_lines = full_wrapped_output
+ .iter()
+ .filter(|line| line.spans.iter().any(|span| span.content.contains(marker)))
+ .count();
+
+ // Sanity check: this scenario should produce more screen lines than
+ // the user shell per-call limit when no truncation is applied. If
+ // this ever fails, the test no longer exercises the regression.
+ assert!(
+ full_screen_lines > USER_SHELL_TOOL_CALL_MAX_LINES,
+ "expected unbounded wrapping to produce more than {USER_SHELL_TOOL_CALL_MAX_LINES} screen lines, got {full_screen_lines}",
+ );
+
+ let call = ExecCall {
+ call_id: "call-id".to_string(),
+ command: vec!["bash".into(), "-lc".into(), "echo long".into()],
+ parsed: Vec::new(),
+ output: Some(output),
+ source: ExecCommandSource::UserShell,
+ start_time: None,
+ duration: None,
+ interaction_input: None,
+ };
+
+ let cell = ExecCell::new(call, false);
+
+ // Use a narrow width so each logical line wraps into many on-screen lines.
+ let lines = cell.command_display_lines(width);
+
+ // Count how many rendered lines contain our marker text. This approximates
+ // the number of visible output "screen lines" for this command.
+ let output_screen_lines = lines
+ .iter()
+ .filter(|line| line.spans.iter().any(|span| span.content.contains(marker)))
+ .count();
+
+ // Regression guard: previously this scenario could render hundreds of
+ // wrapped lines because truncation happened before wrapping. Now the
+ // truncation is applied after wrapping, so the number of visible
+ // screen lines is bounded by USER_SHELL_TOOL_CALL_MAX_LINES.
+ assert!(
+ output_screen_lines <= USER_SHELL_TOOL_CALL_MAX_LINES,
+ "expected at most {USER_SHELL_TOOL_CALL_MAX_LINES} screen lines of user shell output, got {output_screen_lines}",
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/exec_command.rs b/codex-rs/tui2/src/exec_command.rs
new file mode 100644
index 0000000000..8ce6c2632e
--- /dev/null
+++ b/codex-rs/tui2/src/exec_command.rs
@@ -0,0 +1,70 @@
+use std::path::Path;
+use std::path::PathBuf;
+
+use codex_core::parse_command::extract_shell_command;
+use dirs::home_dir;
+use shlex::try_join;
+
+pub(crate) fn escape_command(command: &[String]) -> String {
+ try_join(command.iter().map(String::as_str)).unwrap_or_else(|_| command.join(" "))
+}
+
+pub(crate) fn strip_bash_lc_and_escape(command: &[String]) -> String {
+ if let Some((_, script)) = extract_shell_command(command) {
+ return script.to_string();
+ }
+ escape_command(command)
+}
+
+/// If `path` is absolute and inside $HOME, return the part *after* the home
+/// directory; otherwise, return the path as-is. Note if `path` is the homedir,
+/// this will return and empty path.
+pub(crate) fn relativize_to_home<P>(path: P) -> Option<PathBuf>
+where
+ P: AsRef<Path>,
+{
+ let path = path.as_ref();
+ if !path.is_absolute() {
+ // If the path is not absolute, we can’t do anything with it.
+ return None;
+ }
+
+ let home_dir = home_dir()?;
+ let rel = path.strip_prefix(&home_dir).ok()?;
+ Some(rel.to_path_buf())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_escape_command() {
+ let args = vec!["foo".into(), "bar baz".into(), "weird&stuff".into()];
+ let cmdline = escape_command(&args);
+ assert_eq!(cmdline, "foo 'bar baz' 'weird&stuff'");
+ }
+
+ #[test]
+ fn test_strip_bash_lc_and_escape() {
+ // Test bash
+ let args = vec!["bash".into(), "-lc".into(), "echo hello".into()];
+ let cmdline = strip_bash_lc_and_escape(&args);
+ assert_eq!(cmdline, "echo hello");
+
+ // Test zsh
+ let args = vec!["zsh".into(), "-lc".into(), "echo hello".into()];
+ let cmdline = strip_bash_lc_and_escape(&args);
+ assert_eq!(cmdline, "echo hello");
+
+ // Test absolute path to zsh
+ let args = vec!["/usr/bin/zsh".into(), "-lc".into(), "echo hello".into()];
+ let cmdline = strip_bash_lc_and_escape(&args);
+ assert_eq!(cmdline, "echo hello");
+
+ // Test absolute path to bash
+ let args = vec!["/bin/bash".into(), "-lc".into(), "echo hello".into()];
+ let cmdline = strip_bash_lc_and_escape(&args);
+ assert_eq!(cmdline, "echo hello");
+ }
+}
diff --git a/codex-rs/tui2/src/file_search.rs b/codex-rs/tui2/src/file_search.rs
new file mode 100644
index 0000000000..af46512640
--- /dev/null
+++ b/codex-rs/tui2/src/file_search.rs
@@ -0,0 +1,199 @@
+//! Helper that owns the debounce/cancellation logic for `@` file searches.
+//!
+//! `ChatComposer` publishes *every* change of the `@token` as
+//! `AppEvent::StartFileSearch(query)`.
+//! This struct receives those events and decides when to actually spawn the
+//! expensive search (handled in the main `App` thread). It tries to ensure:
+//!
+//! - Even when the user types long text quickly, they will start seeing results
+//! after a short delay using an early version of what they typed.
+//! - At most one search is in-flight at any time.
+//!
+//! It works as follows:
+//!
+//! 1. First query starts a debounce timer.
+//! 2. While the timer is pending, the latest query from the user is stored.
+//! 3. When the timer fires, it is cleared, and a search is done for the most
+//! recent query.
+//! 4. If there is a in-flight search that is not a prefix of the latest thing
+//! the user typed, it is cancelled.
+
+use codex_file_search as file_search;
+use std::num::NonZeroUsize;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::sync::Mutex;
+use std::sync::atomic::AtomicBool;
+use std::sync::atomic::Ordering;
+use std::thread;
+use std::time::Duration;
+
+use crate::app_event::AppEvent;
+use crate::app_event_sender::AppEventSender;
+
+const MAX_FILE_SEARCH_RESULTS: NonZeroUsize = NonZeroUsize::new(20).unwrap();
+const NUM_FILE_SEARCH_THREADS: NonZeroUsize = NonZeroUsize::new(2).unwrap();
+
+/// How long to wait after a keystroke before firing the first search when none
+/// is currently running. Keeps early queries more meaningful.
+const FILE_SEARCH_DEBOUNCE: Duration = Duration::from_millis(100);
+
+const ACTIVE_SEARCH_COMPLETE_POLL_INTERVAL: Duration = Duration::from_millis(20);
+
+/// State machine for file-search orchestration.
+pub(crate) struct FileSearchManager {
+ /// Unified state guarded by one mutex.
+ state: Arc<Mutex<SearchState>>,
+
+ search_dir: PathBuf,
+ app_tx: AppEventSender,
+}
+
+struct SearchState {
+ /// Latest query typed by user (updated every keystroke).
+ latest_query: String,
+
+ /// true if a search is currently scheduled.
+ is_search_scheduled: bool,
+
+ /// If there is an active search, this will be the query being searched.
+ active_search: Option<ActiveSearch>,
+}
+
+struct ActiveSearch {
+ query: String,
+ cancellation_token: Arc<AtomicBool>,
+}
+
+impl FileSearchManager {
+ pub fn new(search_dir: PathBuf, tx: AppEventSender) -> Self {
+ Self {
+ state: Arc::new(Mutex::new(SearchState {
+ latest_query: String::new(),
+ is_search_scheduled: false,
+ active_search: None,
+ })),
+ search_dir,
+ app_tx: tx,
+ }
+ }
+
+ /// Call whenever the user edits the `@` token.
+ pub fn on_user_query(&self, query: String) {
+ {
+ #[expect(clippy::unwrap_used)]
+ let mut st = self.state.lock().unwrap();
+ if query == st.latest_query {
+ // No change, nothing to do.
+ return;
+ }
+
+ // Update latest query.
+ st.latest_query.clear();
+ st.latest_query.push_str(&query);
+
+ // If there is an in-flight search that is definitely obsolete,
+ // cancel it now.
+ if let Some(active_search) = &st.active_search
+ && !query.starts_with(&active_search.query)
+ {
+ active_search
+ .cancellation_token
+ .store(true, Ordering::Relaxed);
+ st.active_search = None;
+ }
+
+ // Schedule a search to run after debounce.
+ if !st.is_search_scheduled {
+ st.is_search_scheduled = true;
+ } else {
+ return;
+ }
+ }
+
+ // If we are here, we set `st.is_search_scheduled = true` before
+ // dropping the lock. This means we are the only thread that can spawn a
+ // debounce timer.
+ let state = self.state.clone();
+ let search_dir = self.search_dir.clone();
+ let tx_clone = self.app_tx.clone();
+ thread::spawn(move || {
+ // Always do a minimum debounce, but then poll until the
+ // `active_search` is cleared.
+ thread::sleep(FILE_SEARCH_DEBOUNCE);
+ loop {
+ #[expect(clippy::unwrap_used)]
+ if state.lock().unwrap().active_search.is_none() {
+ break;
+ }
+ thread::sleep(ACTIVE_SEARCH_COMPLETE_POLL_INTERVAL);
+ }
+
+ // The debounce timer has expired, so start a search using the
+ // latest query.
+ let cancellation_token = Arc::new(AtomicBool::new(false));
+ let token = cancellation_token.clone();
+ let query = {
+ #[expect(clippy::unwrap_used)]
+ let mut st = state.lock().unwrap();
+ let query = st.latest_query.clone();
+ st.is_search_scheduled = false;
+ st.active_search = Some(ActiveSearch {
+ query: query.clone(),
+ cancellation_token: token,
+ });
+ query
+ };
+
+ FileSearchManager::spawn_file_search(
+ query,
+ search_dir,
+ tx_clone,
+ cancellation_token,
+ state,
+ );
+ });
+ }
+
+ fn spawn_file_search(
+ query: String,
+ search_dir: PathBuf,
+ tx: AppEventSender,
+ cancellation_token: Arc<AtomicBool>,
+ search_state: Arc<Mutex<SearchState>>,
+ ) {
+ let compute_indices = true;
+ std::thread::spawn(move || {
+ let matches = file_search::run(
+ &query,
+ MAX_FILE_SEARCH_RESULTS,
+ &search_dir,
+ Vec::new(),
+ NUM_FILE_SEARCH_THREADS,
+ cancellation_token.clone(),
+ compute_indices,
+ true,
+ )
+ .map(|res| res.matches)
+ .unwrap_or_default();
+
+ let is_cancelled = cancellation_token.load(Ordering::Relaxed);
+ if !is_cancelled {
+ tx.send(AppEvent::FileSearchResult { query, matches });
+ }
+
+ // Reset the active search state. Do a pointer comparison to verify
+ // that we are clearing the ActiveSearch that corresponds to the
+ // cancellation token we were given.
+ {
+ #[expect(clippy::unwrap_used)]
+ let mut st = search_state.lock().unwrap();
+ if let Some(active_search) = &st.active_search
+ && Arc::ptr_eq(&active_search.cancellation_token, &cancellation_token)
+ {
+ st.active_search = None;
+ }
+ }
+ });
+ }
+}
diff --git a/codex-rs/tui2/src/frames.rs b/codex-rs/tui2/src/frames.rs
new file mode 100644
index 0000000000..19a70578d4
--- /dev/null
+++ b/codex-rs/tui2/src/frames.rs
@@ -0,0 +1,71 @@
+use std::time::Duration;
+
+// Embed animation frames for each variant at compile time.
+macro_rules! frames_for {
+ ($dir:literal) => {
+ [
+ include_str!(concat!("../frames/", $dir, "/frame_1.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_2.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_3.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_4.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_5.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_6.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_7.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_8.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_9.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_10.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_11.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_12.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_13.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_14.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_15.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_16.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_17.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_18.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_19.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_20.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_21.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_22.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_23.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_24.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_25.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_26.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_27.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_28.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_29.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_30.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_31.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_32.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_33.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_34.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_35.txt")),
+ include_str!(concat!("../frames/", $dir, "/frame_36.txt")),
+ ]
+ };
+}
+
+pub(crate) const FRAMES_DEFAULT: [&str; 36] = frames_for!("default");
+pub(crate) const FRAMES_CODEX: [&str; 36] = frames_for!("codex");
+pub(crate) const FRAMES_OPENAI: [&str; 36] = frames_for!("openai");
+pub(crate) const FRAMES_BLOCKS: [&str; 36] = frames_for!("blocks");
+pub(crate) const FRAMES_DOTS: [&str; 36] = frames_for!("dots");
+pub(crate) const FRAMES_HASH: [&str; 36] = frames_for!("hash");
+pub(crate) const FRAMES_HBARS: [&str; 36] = frames_for!("hbars");
+pub(crate) const FRAMES_VBARS: [&str; 36] = frames_for!("vbars");
+pub(crate) const FRAMES_SHAPES: [&str; 36] = frames_for!("shapes");
+pub(crate) const FRAMES_SLUG: [&str; 36] = frames_for!("slug");
+
+pub(crate) const ALL_VARIANTS: &[&[&str]] = &[
+ &FRAMES_DEFAULT,
+ &FRAMES_CODEX,
+ &FRAMES_OPENAI,
+ &FRAMES_BLOCKS,
+ &FRAMES_DOTS,
+ &FRAMES_HASH,
+ &FRAMES_HBARS,
+ &FRAMES_VBARS,
+ &FRAMES_SHAPES,
+ &FRAMES_SLUG,
+];
+
+pub(crate) const FRAME_TICK_DEFAULT: Duration = Duration::from_millis(80);
diff --git a/codex-rs/tui2/src/get_git_diff.rs b/codex-rs/tui2/src/get_git_diff.rs
new file mode 100644
index 0000000000..78ab53d92f
--- /dev/null
+++ b/codex-rs/tui2/src/get_git_diff.rs
@@ -0,0 +1,119 @@
+//! Utility to compute the current Git diff for the working directory.
+//!
+//! The implementation mirrors the behaviour of the TypeScript version in
+//! `codex-cli`: it returns the diff for tracked changes as well as any
+//! untracked files. When the current directory is not inside a Git
+//! repository, the function returns `Ok((false, String::new()))`.
+
+use std::io;
+use std::path::Path;
+use std::process::Stdio;
+use tokio::process::Command;
+
+/// Return value of [`get_git_diff`].
+///
+/// * `bool` – Whether the current working directory is inside a Git repo.
+/// * `String` – The concatenated diff (may be empty).
+pub(crate) async fn get_git_diff() -> io::Result<(bool, String)> {
+ // First check if we are inside a Git repository.
+ if !inside_git_repo().await? {
+ return Ok((false, String::new()));
+ }
+
+ // Run tracked diff and untracked file listing in parallel.
+ let (tracked_diff_res, untracked_output_res) = tokio::join!(
+ run_git_capture_diff(&["diff", "--color"]),
+ run_git_capture_stdout(&["ls-files", "--others", "--exclude-standard"]),
+ );
+ let tracked_diff = tracked_diff_res?;
+ let untracked_output = untracked_output_res?;
+
+ let mut untracked_diff = String::new();
+ let null_device: &Path = if cfg!(windows) {
+ Path::new("NUL")
+ } else {
+ Path::new("/dev/null")
+ };
+
+ let null_path = null_device.to_str().unwrap_or("/dev/null").to_string();
+ let mut join_set: tokio::task::JoinSet<io::Result<String>> = tokio::task::JoinSet::new();
+ for file in untracked_output
+ .split('\n')
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ {
+ let null_path = null_path.clone();
+ let file = file.to_string();
+ join_set.spawn(async move {
+ let args = ["diff", "--color", "--no-index", "--", &null_path, &file];
+ run_git_capture_diff(&args).await
+ });
+ }
+ while let Some(res) = join_set.join_next().await {
+ match res {
+ Ok(Ok(diff)) => untracked_diff.push_str(&diff),
+ Ok(Err(err)) if err.kind() == io::ErrorKind::NotFound => {}
+ Ok(Err(err)) => return Err(err),
+ Err(_) => {}
+ }
+ }
+
+ Ok((true, format!("{tracked_diff}{untracked_diff}")))
+}
+
+/// Helper that executes `git` with the given `args` and returns `stdout` as a
+/// UTF-8 string. Any non-zero exit status is considered an *error*.
+async fn run_git_capture_stdout(args: &[&str]) -> io::Result<String> {
+ let output = Command::new("git")
+ .args(args)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .output()
+ .await?;
+
+ if output.status.success() {
+ Ok(String::from_utf8_lossy(&output.stdout).into_owned())
+ } else {
+ Err(io::Error::other(format!(
+ "git {:?} failed with status {}",
+ args, output.status
+ )))
+ }
+}
+
+/// Like [`run_git_capture_stdout`] but treats exit status 1 as success and
+/// returns stdout. Git returns 1 for diffs when differences are present.
+async fn run_git_capture_diff(args: &[&str]) -> io::Result<String> {
+ let output = Command::new("git")
+ .args(args)
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .output()
+ .await?;
+
+ if output.status.success() || output.status.code() == Some(1) {
+ Ok(String::from_utf8_lossy(&output.stdout).into_owned())
+ } else {
+ Err(io::Error::other(format!(
+ "git {:?} failed with status {}",
+ args, output.status
+ )))
+ }
+}
+
+/// Determine if the current directory is inside a Git repository.
+async fn inside_git_repo() -> io::Result<bool> {
+ let status = Command::new("git")
+ .args(["rev-parse", "--is-inside-work-tree"])
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .status()
+ .await;
+
+ match status {
+ Ok(s) if s.success() => Ok(true),
+ Ok(_) => Ok(false),
+ Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false), // git not installed
+ Err(e) => Err(e),
+ }
+}
diff --git a/codex-rs/tui2/src/history_cell.rs b/codex-rs/tui2/src/history_cell.rs
new file mode 100644
index 0000000000..4147067366
--- /dev/null
+++ b/codex-rs/tui2/src/history_cell.rs
@@ -0,0 +1,2435 @@
+use crate::diff_render::create_diff_summary;
+use crate::diff_render::display_path_for;
+use crate::exec_cell::CommandOutput;
+use crate::exec_cell::OutputLinesParams;
+use crate::exec_cell::TOOL_CALL_MAX_LINES;
+use crate::exec_cell::output_lines;
+use crate::exec_cell::spinner;
+use crate::exec_command::relativize_to_home;
+use crate::exec_command::strip_bash_lc_and_escape;
+use crate::markdown::append_markdown;
+use crate::render::line_utils::line_to_static;
+use crate::render::line_utils::prefix_lines;
+use crate::render::line_utils::push_owned_lines;
+use crate::render::renderable::Renderable;
+use crate::style::user_message_style;
+use crate::text_formatting::format_and_truncate_tool_result;
+use crate::text_formatting::truncate_text;
+use crate::tooltips;
+use crate::ui_consts::LIVE_PREFIX_COLS;
+use crate::update_action::UpdateAction;
+use crate::version::CODEX_CLI_VERSION;
+use crate::wrapping::RtOptions;
+use crate::wrapping::word_wrap_line;
+use crate::wrapping::word_wrap_lines;
+use base64::Engine;
+use codex_common::format_env_display::format_env_display;
+use codex_core::config::Config;
+use codex_core::config::types::McpServerTransportConfig;
+use codex_core::config::types::ReasoningSummaryFormat;
+use codex_core::protocol::FileChange;
+use codex_core::protocol::McpAuthStatus;
+use codex_core::protocol::McpInvocation;
+use codex_core::protocol::SessionConfiguredEvent;
+use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
+use codex_protocol::plan_tool::PlanItemArg;
+use codex_protocol::plan_tool::StepStatus;
+use codex_protocol::plan_tool::UpdatePlanArgs;
+use image::DynamicImage;
+use image::ImageReader;
+use mcp_types::EmbeddedResourceResource;
+use mcp_types::Resource;
+use mcp_types::ResourceLink;
+use mcp_types::ResourceTemplate;
+use ratatui::prelude::*;
+use ratatui::style::Modifier;
+use ratatui::style::Style;
+use ratatui::style::Styled;
+use ratatui::style::Stylize;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::Wrap;
+use std::any::Any;
+use std::collections::HashMap;
+use std::io::Cursor;
+use std::path::Path;
+use std::path::PathBuf;
+use std::time::Duration;
+use std::time::Instant;
+use tracing::error;
+use unicode_width::UnicodeWidthStr;
+
+/// Represents an event to display in the conversation history. Returns its
+/// `Vec<Line<'static>>` representation to make it easier to display in a
+/// scrollable list.
+pub(crate) trait HistoryCell: std::fmt::Debug + Send + Sync + Any {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>>;
+
+ fn desired_height(&self, width: u16) -> u16 {
+ Paragraph::new(Text::from(self.display_lines(width)))
+ .wrap(Wrap { trim: false })
+ .line_count(width)
+ .try_into()
+ .unwrap_or(0)
+ }
+
+ fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
+ self.display_lines(width)
+ }
+
+ fn desired_transcript_height(&self, width: u16) -> u16 {
+ let lines = self.transcript_lines(width);
+ // Workaround for ratatui bug: if there's only one line and it's whitespace-only, ratatui gives 2 lines.
+ if let [line] = &lines[..]
+ && line
+ .spans
+ .iter()
+ .all(|s| s.content.chars().all(char::is_whitespace))
+ {
+ return 1;
+ }
+
+ Paragraph::new(Text::from(lines))
+ .wrap(Wrap { trim: false })
+ .line_count(width)
+ .try_into()
+ .unwrap_or(0)
+ }
+
+ fn is_stream_continuation(&self) -> bool {
+ false
+ }
+}
+
+impl Renderable for Box<dyn HistoryCell> {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ let lines = self.display_lines(area.width);
+ let y = if area.height == 0 {
+ 0
+ } else {
+ let overflow = lines.len().saturating_sub(usize::from(area.height));
+ u16::try_from(overflow).unwrap_or(u16::MAX)
+ };
+ Paragraph::new(Text::from(lines))
+ .scroll((y, 0))
+ .render(area, buf);
+ }
+ fn desired_height(&self, width: u16) -> u16 {
+ HistoryCell::desired_height(self.as_ref(), width)
+ }
+}
+
+impl dyn HistoryCell {
+ pub(crate) fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ pub(crate) fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct UserHistoryCell {
+ pub message: String,
+}
+
+impl HistoryCell for UserHistoryCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let mut lines: Vec<Line<'static>> = Vec::new();
+
+ let wrap_width = width
+ .saturating_sub(
+ LIVE_PREFIX_COLS + 1, /* keep a one-column right margin for wrapping */
+ )
+ .max(1);
+
+ let style = user_message_style();
+
+ let wrapped = word_wrap_lines(
+ self.message.lines().map(|l| Line::from(l).style(style)),
+ // Wrap algorithm matches textarea.rs.
+ RtOptions::new(usize::from(wrap_width))
+ .wrap_algorithm(textwrap::WrapAlgorithm::FirstFit),
+ );
+
+ lines.push(Line::from("").style(style));
+ lines.extend(prefix_lines(wrapped, "› ".bold().dim(), " ".into()));
+ lines.push(Line::from("").style(style));
+ lines
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct ReasoningSummaryCell {
+ _header: String,
+ content: String,
+ transcript_only: bool,
+}
+
+impl ReasoningSummaryCell {
+ pub(crate) fn new(header: String, content: String, transcript_only: bool) -> Self {
+ Self {
+ _header: header,
+ content,
+ transcript_only,
+ }
+ }
+
+ fn lines(&self, width: u16) -> Vec<Line<'static>> {
+ let mut lines: Vec<Line<'static>> = Vec::new();
+ append_markdown(
+ &self.content,
+ Some((width as usize).saturating_sub(2)),
+ &mut lines,
+ );
+ let summary_style = Style::default().dim().italic();
+ let summary_lines = lines
+ .into_iter()
+ .map(|mut line| {
+ line.spans = line
+ .spans
+ .into_iter()
+ .map(|span| span.patch_style(summary_style))
+ .collect();
+ line
+ })
+ .collect::<Vec<_>>();
+
+ word_wrap_lines(
+ &summary_lines,
+ RtOptions::new(width as usize)
+ .initial_indent("• ".dim().into())
+ .subsequent_indent(" ".into()),
+ )
+ }
+}
+
+impl HistoryCell for ReasoningSummaryCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ if self.transcript_only {
+ Vec::new()
+ } else {
+ self.lines(width)
+ }
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ if self.transcript_only {
+ 0
+ } else {
+ self.lines(width).len() as u16
+ }
+ }
+
+ fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
+ self.lines(width)
+ }
+
+ fn desired_transcript_height(&self, width: u16) -> u16 {
+ self.lines(width).len() as u16
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct AgentMessageCell {
+ lines: Vec<Line<'static>>,
+ is_first_line: bool,
+}
+
+impl AgentMessageCell {
+ pub(crate) fn new(lines: Vec<Line<'static>>, is_first_line: bool) -> Self {
+ Self {
+ lines,
+ is_first_line,
+ }
+ }
+}
+
+impl HistoryCell for AgentMessageCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ word_wrap_lines(
+ &self.lines,
+ RtOptions::new(width as usize)
+ .initial_indent(if self.is_first_line {
+ "• ".dim().into()
+ } else {
+ " ".into()
+ })
+ .subsequent_indent(" ".into()),
+ )
+ }
+
+ fn is_stream_continuation(&self) -> bool {
+ !self.is_first_line
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct PlainHistoryCell {
+ lines: Vec<Line<'static>>,
+}
+
+impl PlainHistoryCell {
+ pub(crate) fn new(lines: Vec<Line<'static>>) -> Self {
+ Self { lines }
+ }
+}
+
+impl HistoryCell for PlainHistoryCell {
+ fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
+ self.lines.clone()
+ }
+}
+
+#[cfg_attr(debug_assertions, allow(dead_code))]
+#[derive(Debug)]
+pub(crate) struct UpdateAvailableHistoryCell {
+ latest_version: String,
+ update_action: Option<UpdateAction>,
+}
+
+#[cfg_attr(debug_assertions, allow(dead_code))]
+impl UpdateAvailableHistoryCell {
+ pub(crate) fn new(latest_version: String, update_action: Option<UpdateAction>) -> Self {
+ Self {
+ latest_version,
+ update_action,
+ }
+ }
+}
+
+impl HistoryCell for UpdateAvailableHistoryCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ use ratatui_macros::line;
+ use ratatui_macros::text;
+ let update_instruction = if let Some(update_action) = self.update_action {
+ line!["Run ", update_action.command_str().cyan(), " to update."]
+ } else {
+ line![
+ "See ",
+ "https://github.com/openai/codex".cyan().underlined(),
+ " for installation options."
+ ]
+ };
+
+ let content = text![
+ line![
+ padded_emoji("✨").bold().cyan(),
+ "Update available!".bold().cyan(),
+ " ",
+ format!("{CODEX_CLI_VERSION} -> {}", self.latest_version).bold(),
+ ],
+ update_instruction,
+ "",
+ "See full release notes:",
+ "https://github.com/openai/codex/releases/latest"
+ .cyan()
+ .underlined(),
+ ];
+
+ let inner_width = content
+ .width()
+ .min(usize::from(width.saturating_sub(4)))
+ .max(1);
+ with_border_with_inner_width(content.lines, inner_width)
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct PrefixedWrappedHistoryCell {
+ text: Text<'static>,
+ initial_prefix: Line<'static>,
+ subsequent_prefix: Line<'static>,
+}
+
+impl PrefixedWrappedHistoryCell {
+ pub(crate) fn new(
+ text: impl Into<Text<'static>>,
+ initial_prefix: impl Into<Line<'static>>,
+ subsequent_prefix: impl Into<Line<'static>>,
+ ) -> Self {
+ Self {
+ text: text.into(),
+ initial_prefix: initial_prefix.into(),
+ subsequent_prefix: subsequent_prefix.into(),
+ }
+ }
+}
+
+impl HistoryCell for PrefixedWrappedHistoryCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ if width == 0 {
+ return Vec::new();
+ }
+ let opts = RtOptions::new(width.max(1) as usize)
+ .initial_indent(self.initial_prefix.clone())
+ .subsequent_indent(self.subsequent_prefix.clone());
+ let wrapped = word_wrap_lines(&self.text, opts);
+ let mut out = Vec::new();
+ push_owned_lines(&wrapped, &mut out);
+ out
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ self.display_lines(width).len() as u16
+ }
+}
+
+fn truncate_exec_snippet(full_cmd: &str) -> String {
+ let mut snippet = match full_cmd.split_once('\n') {
+ Some((first, _)) => format!("{first} ..."),
+ None => full_cmd.to_string(),
+ };
+ snippet = truncate_text(&snippet, 80);
+ snippet
+}
+
+fn exec_snippet(command: &[String]) -> String {
+ let full_cmd = strip_bash_lc_and_escape(command);
+ truncate_exec_snippet(&full_cmd)
+}
+
+pub fn new_approval_decision_cell(
+ command: Vec<String>,
+ decision: codex_core::protocol::ReviewDecision,
+) -> Box<dyn HistoryCell> {
+ use codex_core::protocol::ReviewDecision::*;
+
+ let (symbol, summary): (Span<'static>, Vec<Span<'static>>) = match decision {
+ Approved => {
+ let snippet = Span::from(exec_snippet(&command)).dim();
+ (
+ "✔ ".green(),
+ vec![
+ "You ".into(),
+ "approved".bold(),
+ " codex to run ".into(),
+ snippet,
+ " this time".bold(),
+ ],
+ )
+ }
+ ApprovedExecpolicyAmendment { .. } => {
+ let snippet = Span::from(exec_snippet(&command)).dim();
+ (
+ "✔ ".green(),
+ vec![
+ "You ".into(),
+ "approved".bold(),
+ " codex to run ".into(),
+ snippet,
+ " and applied the execpolicy amendment".bold(),
+ ],
+ )
+ }
+ ApprovedForSession => {
+ let snippet = Span::from(exec_snippet(&command)).dim();
+ (
+ "✔ ".green(),
+ vec![
+ "You ".into(),
+ "approved".bold(),
+ " codex to run ".into(),
+ snippet,
+ " every time this session".bold(),
+ ],
+ )
+ }
+ Denied => {
+ let snippet = Span::from(exec_snippet(&command)).dim();
+ (
+ "✗ ".red(),
+ vec![
+ "You ".into(),
+ "did not approve".bold(),
+ " codex to run ".into(),
+ snippet,
+ ],
+ )
+ }
+ Abort => {
+ let snippet = Span::from(exec_snippet(&command)).dim();
+ (
+ "✗ ".red(),
+ vec![
+ "You ".into(),
+ "canceled".bold(),
+ " the request to run ".into(),
+ snippet,
+ ],
+ )
+ }
+ };
+
+ Box::new(PrefixedWrappedHistoryCell::new(
+ Line::from(summary),
+ symbol,
+ " ",
+ ))
+}
+
+/// Cyan history cell line showing the current review status.
+pub(crate) fn new_review_status_line(message: String) -> PlainHistoryCell {
+ PlainHistoryCell {
+ lines: vec![Line::from(message.cyan())],
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct PatchHistoryCell {
+ changes: HashMap<PathBuf, FileChange>,
+ cwd: PathBuf,
+}
+
+impl HistoryCell for PatchHistoryCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ create_diff_summary(&self.changes, &self.cwd, width as usize)
+ }
+}
+
+#[derive(Debug)]
+struct CompletedMcpToolCallWithImageOutput {
+ _image: DynamicImage,
+}
+impl HistoryCell for CompletedMcpToolCallWithImageOutput {
+ fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
+ vec!["tool result (image output)".into()]
+ }
+}
+
+pub(crate) const SESSION_HEADER_MAX_INNER_WIDTH: usize = 56; // Just an eyeballed value
+
+pub(crate) fn card_inner_width(width: u16, max_inner_width: usize) -> Option<usize> {
+ if width < 4 {
+ return None;
+ }
+ let inner_width = std::cmp::min(width.saturating_sub(4) as usize, max_inner_width);
+ Some(inner_width)
+}
+
+/// Render `lines` inside a border sized to the widest span in the content.
+pub(crate) fn with_border(lines: Vec<Line<'static>>) -> Vec<Line<'static>> {
+ with_border_internal(lines, None)
+}
+
+/// Render `lines` inside a border whose inner width is at least `inner_width`.
+///
+/// This is useful when callers have already clamped their content to a
+/// specific width and want the border math centralized here instead of
+/// duplicating padding logic in the TUI widgets themselves.
+pub(crate) fn with_border_with_inner_width(
+ lines: Vec<Line<'static>>,
+ inner_width: usize,
+) -> Vec<Line<'static>> {
+ with_border_internal(lines, Some(inner_width))
+}
+
+fn with_border_internal(
+ lines: Vec<Line<'static>>,
+ forced_inner_width: Option<usize>,
+) -> Vec<Line<'static>> {
+ let max_line_width = lines
+ .iter()
+ .map(|line| {
+ line.iter()
+ .map(|span| UnicodeWidthStr::width(span.content.as_ref()))
+ .sum::<usize>()
+ })
+ .max()
+ .unwrap_or(0);
+ let content_width = forced_inner_width
+ .unwrap_or(max_line_width)
+ .max(max_line_width);
+
+ let mut out = Vec::with_capacity(lines.len() + 2);
+ let border_inner_width = content_width + 2;
+ out.push(vec![format!("╭{}╮", "─".repeat(border_inner_width)).dim()].into());
+
+ for line in lines.into_iter() {
+ let used_width: usize = line
+ .iter()
+ .map(|span| UnicodeWidthStr::width(span.content.as_ref()))
+ .sum();
+ let span_count = line.spans.len();
+ let mut spans: Vec<Span<'static>> = Vec::with_capacity(span_count + 4);
+ spans.push(Span::from("│ ").dim());
+ spans.extend(line.into_iter());
+ if used_width < content_width {
+ spans.push(Span::from(" ".repeat(content_width - used_width)).dim());
+ }
+ spans.push(Span::from(" │").dim());
+ out.push(Line::from(spans));
+ }
+
+ out.push(vec![format!("╰{}╯", "─".repeat(border_inner_width)).dim()].into());
+
+ out
+}
+
+/// Return the emoji followed by a hair space (U+200A).
+/// Using only the hair space avoids excessive padding after the emoji while
+/// still providing a small visual gap across terminals.
+pub(crate) fn padded_emoji(emoji: &str) -> String {
+ format!("{emoji}\u{200A}")
+}
+
+#[derive(Debug)]
+struct TooltipHistoryCell {
+ tip: &'static str,
+}
+
+impl TooltipHistoryCell {
+ fn new(tip: &'static str) -> Self {
+ Self { tip }
+ }
+}
+
+impl HistoryCell for TooltipHistoryCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let indent = " ";
+ let indent_width = UnicodeWidthStr::width(indent);
+ let wrap_width = usize::from(width.max(1))
+ .saturating_sub(indent_width)
+ .max(1);
+ let mut lines: Vec<Line<'static>> = Vec::new();
+ append_markdown(
+ &format!("**Tip:** {}", self.tip),
+ Some(wrap_width),
+ &mut lines,
+ );
+
+ prefix_lines(lines, indent.into(), indent.into())
+ }
+}
+
+#[derive(Debug)]
+pub struct SessionInfoCell(CompositeHistoryCell);
+
+impl HistoryCell for SessionInfoCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ self.0.display_lines(width)
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ self.0.desired_height(width)
+ }
+
+ fn transcript_lines(&self, width: u16) -> Vec<Line<'static>> {
+ self.0.transcript_lines(width)
+ }
+}
+
+pub(crate) fn new_session_info(
+ config: &Config,
+ requested_model: &str,
+ event: SessionConfiguredEvent,
+ is_first_event: bool,
+) -> SessionInfoCell {
+ let SessionConfiguredEvent {
+ model,
+ reasoning_effort,
+ ..
+ } = event;
+ // Header box rendered as history (so it appears at the very top)
+ let header = SessionHeaderHistoryCell::new(
+ model.clone(),
+ reasoning_effort,
+ config.cwd.clone(),
+ CODEX_CLI_VERSION,
+ );
+ let mut parts: Vec<Box<dyn HistoryCell>> = vec![Box::new(header)];
+
+ if is_first_event {
+ // Help lines below the header (new copy and list)
+ let help_lines: Vec<Line<'static>> = vec![
+ " To get started, describe a task or try one of these commands:"
+ .dim()
+ .into(),
+ Line::from(""),
+ Line::from(vec![
+ " ".into(),
+ "/init".into(),
+ " - create an AGENTS.md file with instructions for Codex".dim(),
+ ]),
+ Line::from(vec![
+ " ".into(),
+ "/status".into(),
+ " - show current session configuration".dim(),
+ ]),
+ Line::from(vec![
+ " ".into(),
+ "/approvals".into(),
+ " - choose what Codex can do without approval".dim(),
+ ]),
+ Line::from(vec![
+ " ".into(),
+ "/model".into(),
+ " - choose what model and reasoning effort to use".dim(),
+ ]),
+ Line::from(vec![
+ " ".into(),
+ "/review".into(),
+ " - review any changes and find issues".dim(),
+ ]),
+ ];
+
+ parts.push(Box::new(PlainHistoryCell { lines: help_lines }));
+ } else {
+ if config.show_tooltips
+ && let Some(tooltips) = tooltips::random_tooltip().map(TooltipHistoryCell::new)
+ {
+ parts.push(Box::new(tooltips));
+ }
+ if requested_model != model {
+ let lines = vec![
+ "model changed:".magenta().bold().into(),
+ format!("requested: {requested_model}").into(),
+ format!("used: {model}").into(),
+ ];
+ parts.push(Box::new(PlainHistoryCell { lines }));
+ }
+ }
+
+ SessionInfoCell(CompositeHistoryCell { parts })
+}
+
+pub(crate) fn new_user_prompt(message: String) -> UserHistoryCell {
+ UserHistoryCell { message }
+}
+
+#[derive(Debug)]
+struct SessionHeaderHistoryCell {
+ version: &'static str,
+ model: String,
+ reasoning_effort: Option<ReasoningEffortConfig>,
+ directory: PathBuf,
+}
+
+impl SessionHeaderHistoryCell {
+ fn new(
+ model: String,
+ reasoning_effort: Option<ReasoningEffortConfig>,
+ directory: PathBuf,
+ version: &'static str,
+ ) -> Self {
+ Self {
+ version,
+ model,
+ reasoning_effort,
+ directory,
+ }
+ }
+
+ fn format_directory(&self, max_width: Option<usize>) -> String {
+ Self::format_directory_inner(&self.directory, max_width)
+ }
+
+ fn format_directory_inner(directory: &Path, max_width: Option<usize>) -> String {
+ let formatted = if let Some(rel) = relativize_to_home(directory) {
+ if rel.as_os_str().is_empty() {
+ "~".to_string()
+ } else {
+ format!("~{}{}", std::path::MAIN_SEPARATOR, rel.display())
+ }
+ } else {
+ directory.display().to_string()
+ };
+
+ if let Some(max_width) = max_width {
+ if max_width == 0 {
+ return String::new();
+ }
+ if UnicodeWidthStr::width(formatted.as_str()) > max_width {
+ return crate::text_formatting::center_truncate_path(&formatted, max_width);
+ }
+ }
+
+ formatted
+ }
+
+ fn reasoning_label(&self) -> Option<&'static str> {
+ self.reasoning_effort.map(|effort| match effort {
+ ReasoningEffortConfig::Minimal => "minimal",
+ ReasoningEffortConfig::Low => "low",
+ ReasoningEffortConfig::Medium => "medium",
+ ReasoningEffortConfig::High => "high",
+ ReasoningEffortConfig::XHigh => "xhigh",
+ ReasoningEffortConfig::None => "none",
+ })
+ }
+}
+
+impl HistoryCell for SessionHeaderHistoryCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let Some(inner_width) = card_inner_width(width, SESSION_HEADER_MAX_INNER_WIDTH) else {
+ return Vec::new();
+ };
+
+ let make_row = |spans: Vec<Span<'static>>| Line::from(spans);
+
+ // Title line rendered inside the box: ">_ OpenAI Codex (vX)"
+ let title_spans: Vec<Span<'static>> = vec![
+ Span::from(">_ ").dim(),
+ Span::from("OpenAI Codex").bold(),
+ Span::from(" ").dim(),
+ Span::from(format!("(v{})", self.version)).dim(),
+ ];
+
+ const CHANGE_MODEL_HINT_COMMAND: &str = "/model";
+ const CHANGE_MODEL_HINT_EXPLANATION: &str = " to change";
+ const DIR_LABEL: &str = "directory:";
+ let label_width = DIR_LABEL.len();
+ let model_label = format!(
+ "{model_label:<label_width$}",
+ model_label = "model:",
+ label_width = label_width
+ );
+ let reasoning_label = self.reasoning_label();
+ let mut model_spans: Vec<Span<'static>> = vec![
+ Span::from(format!("{model_label} ")).dim(),
+ Span::from(self.model.clone()),
+ ];
+ if let Some(reasoning) = reasoning_label {
+ model_spans.push(Span::from(" "));
+ model_spans.push(Span::from(reasoning));
+ }
+ model_spans.push(" ".dim());
+ model_spans.push(CHANGE_MODEL_HINT_COMMAND.cyan());
+ model_spans.push(CHANGE_MODEL_HINT_EXPLANATION.dim());
+
+ let dir_label = format!("{DIR_LABEL:<label_width$}");
+ let dir_prefix = format!("{dir_label} ");
+ let dir_prefix_width = UnicodeWidthStr::width(dir_prefix.as_str());
+ let dir_max_width = inner_width.saturating_sub(dir_prefix_width);
+ let dir = self.format_directory(Some(dir_max_width));
+ let dir_spans = vec![Span::from(dir_prefix).dim(), Span::from(dir)];
+
+ let lines = vec![
+ make_row(title_spans),
+ make_row(Vec::new()),
+ make_row(model_spans),
+ make_row(dir_spans),
+ ];
+
+ with_border(lines)
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct CompositeHistoryCell {
+ parts: Vec<Box<dyn HistoryCell>>,
+}
+
+impl CompositeHistoryCell {
+ pub(crate) fn new(parts: Vec<Box<dyn HistoryCell>>) -> Self {
+ Self { parts }
+ }
+}
+
+impl HistoryCell for CompositeHistoryCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let mut out: Vec<Line<'static>> = Vec::new();
+ let mut first = true;
+ for part in &self.parts {
+ let mut lines = part.display_lines(width);
+ if !lines.is_empty() {
+ if !first {
+ out.push(Line::from(""));
+ }
+ out.append(&mut lines);
+ first = false;
+ }
+ }
+ out
+ }
+}
+
+#[derive(Debug)]
+pub(crate) struct McpToolCallCell {
+ call_id: String,
+ invocation: McpInvocation,
+ start_time: Instant,
+ duration: Option<Duration>,
+ result: Option<Result<mcp_types::CallToolResult, String>>,
+ animations_enabled: bool,
+}
+
+impl McpToolCallCell {
+ pub(crate) fn new(
+ call_id: String,
+ invocation: McpInvocation,
+ animations_enabled: bool,
+ ) -> Self {
+ Self {
+ call_id,
+ invocation,
+ start_time: Instant::now(),
+ duration: None,
+ result: None,
+ animations_enabled,
+ }
+ }
+
+ pub(crate) fn call_id(&self) -> &str {
+ &self.call_id
+ }
+
+ pub(crate) fn complete(
+ &mut self,
+ duration: Duration,
+ result: Result<mcp_types::CallToolResult, String>,
+ ) -> Option<Box<dyn HistoryCell>> {
+ let image_cell = try_new_completed_mcp_tool_call_with_image_output(&result)
+ .map(|cell| Box::new(cell) as Box<dyn HistoryCell>);
+ self.duration = Some(duration);
+ self.result = Some(result);
+ image_cell
+ }
+
+ fn success(&self) -> Option<bool> {
+ match self.result.as_ref() {
+ Some(Ok(result)) => Some(!result.is_error.unwrap_or(false)),
+ Some(Err(_)) => Some(false),
+ None => None,
+ }
+ }
+
+ pub(crate) fn mark_failed(&mut self) {
+ let elapsed = self.start_time.elapsed();
+ self.duration = Some(elapsed);
+ self.result = Some(Err("interrupted".to_string()));
+ }
+
+ fn render_content_block(block: &mcp_types::ContentBlock, width: usize) -> String {
+ match block {
+ mcp_types::ContentBlock::TextContent(text) => {
+ format_and_truncate_tool_result(&text.text, TOOL_CALL_MAX_LINES, width)
+ }
+ mcp_types::ContentBlock::ImageContent(_) => "<image content>".to_string(),
+ mcp_types::ContentBlock::AudioContent(_) => "<audio content>".to_string(),
+ mcp_types::ContentBlock::EmbeddedResource(resource) => {
+ let uri = match &resource.resource {
+ EmbeddedResourceResource::TextResourceContents(text) => text.uri.clone(),
+ EmbeddedResourceResource::BlobResourceContents(blob) => blob.uri.clone(),
+ };
+ format!("embedded resource: {uri}")
+ }
+ mcp_types::ContentBlock::ResourceLink(ResourceLink { uri, .. }) => {
+ format!("link: {uri}")
+ }
+ }
+ }
+}
+
+impl HistoryCell for McpToolCallCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let mut lines: Vec<Line<'static>> = Vec::new();
+ let status = self.success();
+ let bullet = match status {
+ Some(true) => "•".green().bold(),
+ Some(false) => "•".red().bold(),
+ None => spinner(Some(self.start_time), self.animations_enabled),
+ };
+ let header_text = if status.is_some() {
+ "Called"
+ } else {
+ "Calling"
+ };
+
+ let invocation_line = line_to_static(&format_mcp_invocation(self.invocation.clone()));
+ let mut compact_spans = vec![bullet.clone(), " ".into(), header_text.bold(), " ".into()];
+ let mut compact_header = Line::from(compact_spans.clone());
+ let reserved = compact_header.width();
+
+ let inline_invocation =
+ invocation_line.width() <= (width as usize).saturating_sub(reserved);
+
+ if inline_invocation {
+ compact_header.extend(invocation_line.spans.clone());
+ lines.push(compact_header);
+ } else {
+ compact_spans.pop(); // drop trailing space for standalone header
+ lines.push(Line::from(compact_spans));
+
+ let opts = RtOptions::new((width as usize).saturating_sub(4))
+ .initial_indent("".into())
+ .subsequent_indent(" ".into());
+ let wrapped = word_wrap_line(&invocation_line, opts);
+ let body_lines: Vec<Line<'static>> = wrapped.iter().map(line_to_static).collect();
+ lines.extend(prefix_lines(body_lines, " └ ".dim(), " ".into()));
+ }
+
+ let mut detail_lines: Vec<Line<'static>> = Vec::new();
+ // Reserve four columns for the tree prefix (" └ "/" ") and ensure the wrapper still has at least one cell to work with.
+ let detail_wrap_width = (width as usize).saturating_sub(4).max(1);
+
+ if let Some(result) = &self.result {
+ match result {
+ Ok(mcp_types::CallToolResult { content, .. }) => {
+ if !content.is_empty() {
+ for block in content {
+ let text = Self::render_content_block(block, detail_wrap_width);
+ for segment in text.split('\n') {
+ let line = Line::from(segment.to_string().dim());
+ let wrapped = word_wrap_line(
+ &line,
+ RtOptions::new(detail_wrap_width)
+ .initial_indent("".into())
+ .subsequent_indent(" ".into()),
+ );
+ detail_lines.extend(wrapped.iter().map(line_to_static));
+ }
+ }
+ }
+ }
+ Err(err) => {
+ let err_text = format_and_truncate_tool_result(
+ &format!("Error: {err}"),
+ TOOL_CALL_MAX_LINES,
+ width as usize,
+ );
+ let err_line = Line::from(err_text.dim());
+ let wrapped = word_wrap_line(
+ &err_line,
+ RtOptions::new(detail_wrap_width)
+ .initial_indent("".into())
+ .subsequent_indent(" ".into()),
+ );
+ detail_lines.extend(wrapped.iter().map(line_to_static));
+ }
+ }
+ }
+
+ if !detail_lines.is_empty() {
+ let initial_prefix: Span<'static> = if inline_invocation {
+ " └ ".dim()
+ } else {
+ " ".into()
+ };
+ lines.extend(prefix_lines(detail_lines, initial_prefix, " ".into()));
+ }
+
+ lines
+ }
+}
+
+pub(crate) fn new_active_mcp_tool_call(
+ call_id: String,
+ invocation: McpInvocation,
+ animations_enabled: bool,
+) -> McpToolCallCell {
+ McpToolCallCell::new(call_id, invocation, animations_enabled)
+}
+
+pub(crate) fn new_web_search_call(query: String) -> PlainHistoryCell {
+ let lines: Vec<Line<'static>> = vec![Line::from(vec![padded_emoji("🌐").into(), query.into()])];
+ PlainHistoryCell { lines }
+}
+
+/// If the first content is an image, return a new cell with the image.
+/// TODO(rgwood-dd): Handle images properly even if they're not the first result.
+fn try_new_completed_mcp_tool_call_with_image_output(
+ result: &Result<mcp_types::CallToolResult, String>,
+) -> Option<CompletedMcpToolCallWithImageOutput> {
+ match result {
+ Ok(mcp_types::CallToolResult { content, .. }) => {
+ if let Some(mcp_types::ContentBlock::ImageContent(image)) = content.first() {
+ let raw_data = match base64::engine::general_purpose::STANDARD.decode(&image.data) {
+ Ok(data) => data,
+ Err(e) => {
+ error!("Failed to decode image data: {e}");
+ return None;
+ }
+ };
+ let reader = match ImageReader::new(Cursor::new(raw_data)).with_guessed_format() {
+ Ok(reader) => reader,
+ Err(e) => {
+ error!("Failed to guess image format: {e}");
+ return None;
+ }
+ };
+
+ let image = match reader.decode() {
+ Ok(image) => image,
+ Err(e) => {
+ error!("Image decoding failed: {e}");
+ return None;
+ }
+ };
+
+ Some(CompletedMcpToolCallWithImageOutput { _image: image })
+ } else {
+ None
+ }
+ }
+ _ => None,
+ }
+}
+
+#[allow(clippy::disallowed_methods)]
+pub(crate) fn new_warning_event(message: String) -> PrefixedWrappedHistoryCell {
+ PrefixedWrappedHistoryCell::new(message.yellow(), "⚠ ".yellow(), " ")
+}
+
+#[derive(Debug)]
+pub(crate) struct DeprecationNoticeCell {
+ summary: String,
+ details: Option<String>,
+}
+
+pub(crate) fn new_deprecation_notice(
+ summary: String,
+ details: Option<String>,
+) -> DeprecationNoticeCell {
+ DeprecationNoticeCell { summary, details }
+}
+
+impl HistoryCell for DeprecationNoticeCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let mut lines: Vec<Line<'static>> = Vec::new();
+ lines.push(vec!["⚠ ".red().bold(), self.summary.clone().red()].into());
+
+ let wrap_width = width.saturating_sub(4).max(1) as usize;
+
+ if let Some(details) = &self.details {
+ let line = textwrap::wrap(details, wrap_width)
+ .into_iter()
+ .map(|s| s.to_string().dim().into())
+ .collect::<Vec<_>>();
+ lines.extend(line);
+ }
+
+ lines
+ }
+}
+
+/// Render a summary of configured MCP servers from the current `Config`.
+pub(crate) fn empty_mcp_output() -> PlainHistoryCell {
+ let lines: Vec<Line<'static>> = vec![
+ "/mcp".magenta().into(),
+ "".into(),
+ vec!["🔌 ".into(), "MCP Tools".bold()].into(),
+ "".into(),
+ " • No MCP servers configured.".italic().into(),
+ Line::from(vec![
+ " See the ".into(),
+ "\u{1b}]8;;https://github.com/openai/codex/blob/main/docs/config.md#mcp_servers\u{7}MCP docs\u{1b}]8;;\u{7}".underlined(),
+ " to configure them.".into(),
+ ])
+ .style(Style::default().add_modifier(Modifier::DIM)),
+ ];
+
+ PlainHistoryCell { lines }
+}
+
+/// Render MCP tools grouped by connection using the fully-qualified tool names.
+pub(crate) fn new_mcp_tools_output(
+ config: &Config,
+ tools: HashMap<String, mcp_types::Tool>,
+ resources: HashMap<String, Vec<Resource>>,
+ resource_templates: HashMap<String, Vec<ResourceTemplate>>,
+ auth_statuses: &HashMap<String, McpAuthStatus>,
+) -> PlainHistoryCell {
+ let mut lines: Vec<Line<'static>> = vec![
+ "/mcp".magenta().into(),
+ "".into(),
+ vec!["🔌 ".into(), "MCP Tools".bold()].into(),
+ "".into(),
+ ];
+
+ if tools.is_empty() {
+ lines.push(" • No MCP tools available.".italic().into());
+ lines.push("".into());
+ return PlainHistoryCell { lines };
+ }
+
+ let mut servers: Vec<_> = config.mcp_servers.iter().collect();
+ servers.sort_by(|(a, _), (b, _)| a.cmp(b));
+
+ for (server, cfg) in servers {
+ let prefix = format!("mcp__{server}__");
+ let mut names: Vec<String> = tools
+ .keys()
+ .filter(|k| k.starts_with(&prefix))
+ .map(|k| k[prefix.len()..].to_string())
+ .collect();
+ names.sort();
+
+ let auth_status = auth_statuses
+ .get(server.as_str())
+ .copied()
+ .unwrap_or(McpAuthStatus::Unsupported);
+ let mut header: Vec<Span<'static>> = vec![" • ".into(), server.clone().into()];
+ if !cfg.enabled {
+ header.push(" ".into());
+ header.push("(disabled)".red());
+ lines.push(header.into());
+ lines.push(Line::from(""));
+ continue;
+ }
+ lines.push(header.into());
+ lines.push(vec![" • Status: ".into(), "enabled".green()].into());
+ lines.push(vec![" • Auth: ".into(), auth_status.to_string().into()].into());
+
+ match &cfg.transport {
+ McpServerTransportConfig::Stdio {
+ command,
+ args,
+ env,
+ env_vars,
+ cwd,
+ } => {
+ let args_suffix = if args.is_empty() {
+ String::new()
+ } else {
+ format!(" {}", args.join(" "))
+ };
+ let cmd_display = format!("{command}{args_suffix}");
+ lines.push(vec![" • Command: ".into(), cmd_display.into()].into());
+
+ if let Some(cwd) = cwd.as_ref() {
+ lines.push(vec![" • Cwd: ".into(), cwd.display().to_string().into()].into());
+ }
+
+ let env_display = format_env_display(env.as_ref(), env_vars);
+ if env_display != "-" {
+ lines.push(vec![" • Env: ".into(), env_display.into()].into());
+ }
+ }
+ McpServerTransportConfig::StreamableHttp {
+ url,
+ http_headers,
+ env_http_headers,
+ ..
+ } => {
+ lines.push(vec![" • URL: ".into(), url.clone().into()].into());
+ if let Some(headers) = http_headers.as_ref()
+ && !headers.is_empty()
+ {
+ let mut pairs: Vec<_> = headers.iter().collect();
+ pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
+ let display = pairs
+ .into_iter()
+ .map(|(name, _)| format!("{name}=*****"))
+ .collect::<Vec<_>>()
+ .join(", ");
+ lines.push(vec![" • HTTP headers: ".into(), display.into()].into());
+ }
+ if let Some(headers) = env_http_headers.as_ref()
+ && !headers.is_empty()
+ {
+ let mut pairs: Vec<_> = headers.iter().collect();
+ pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
+ let display = pairs
+ .into_iter()
+ .map(|(name, var)| format!("{name}={var}"))
+ .collect::<Vec<_>>()
+ .join(", ");
+ lines.push(vec![" • Env HTTP headers: ".into(), display.into()].into());
+ }
+ }
+ }
+
+ if names.is_empty() {
+ lines.push(" • Tools: (none)".into());
+ } else {
+ lines.push(vec![" • Tools: ".into(), names.join(", ").into()].into());
+ }
+
+ let server_resources: Vec<Resource> =
+ resources.get(server.as_str()).cloned().unwrap_or_default();
+ if server_resources.is_empty() {
+ lines.push(" • Resources: (none)".into());
+ } else {
+ let mut spans: Vec<Span<'static>> = vec![" • Resources: ".into()];
+
+ for (idx, resource) in server_resources.iter().enumerate() {
+ if idx > 0 {
+ spans.push(", ".into());
+ }
+
+ let label = resource.title.as_ref().unwrap_or(&resource.name);
+ spans.push(label.clone().into());
+ spans.push(" ".into());
+ spans.push(format!("({})", resource.uri).dim());
+ }
+
+ lines.push(spans.into());
+ }
+
+ let server_templates: Vec<ResourceTemplate> = resource_templates
+ .get(server.as_str())
+ .cloned()
+ .unwrap_or_default();
+ if server_templates.is_empty() {
+ lines.push(" • Resource templates: (none)".into());
+ } else {
+ let mut spans: Vec<Span<'static>> = vec![" • Resource templates: ".into()];
+
+ for (idx, template) in server_templates.iter().enumerate() {
+ if idx > 0 {
+ spans.push(", ".into());
+ }
+
+ let label = template.title.as_ref().unwrap_or(&template.name);
+ spans.push(label.clone().into());
+ spans.push(" ".into());
+ spans.push(format!("({})", template.uri_template).dim());
+ }
+
+ lines.push(spans.into());
+ }
+
+ lines.push(Line::from(""));
+ }
+
+ PlainHistoryCell { lines }
+}
+pub(crate) fn new_info_event(message: String, hint: Option<String>) -> PlainHistoryCell {
+ let mut line = vec!["• ".dim(), message.into()];
+ if let Some(hint) = hint {
+ line.push(" ".into());
+ line.push(hint.dark_gray());
+ }
+ let lines: Vec<Line<'static>> = vec![line.into()];
+ PlainHistoryCell { lines }
+}
+
+pub(crate) fn new_error_event(message: String) -> PlainHistoryCell {
+ // Use a hair space (U+200A) to create a subtle, near-invisible separation
+ // before the text. VS16 is intentionally omitted to keep spacing tighter
+ // in terminals like Ghostty.
+ let lines: Vec<Line<'static>> = vec![vec![format!("■ {message}").red()].into()];
+ PlainHistoryCell { lines }
+}
+
+/// Render a user‑friendly plan update styled like a checkbox todo list.
+pub(crate) fn new_plan_update(update: UpdatePlanArgs) -> PlanUpdateCell {
+ let UpdatePlanArgs { explanation, plan } = update;
+ PlanUpdateCell { explanation, plan }
+}
+
+#[derive(Debug)]
+pub(crate) struct PlanUpdateCell {
+ explanation: Option<String>,
+ plan: Vec<PlanItemArg>,
+}
+
+impl HistoryCell for PlanUpdateCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let render_note = |text: &str| -> Vec<Line<'static>> {
+ let wrap_width = width.saturating_sub(4).max(1) as usize;
+ textwrap::wrap(text, wrap_width)
+ .into_iter()
+ .map(|s| s.to_string().dim().italic().into())
+ .collect()
+ };
+
+ let render_step = |status: &StepStatus, text: &str| -> Vec<Line<'static>> {
+ let (box_str, step_style) = match status {
+ StepStatus::Completed => ("✔ ", Style::default().crossed_out().dim()),
+ StepStatus::InProgress => ("□ ", Style::default().cyan().bold()),
+ StepStatus::Pending => ("□ ", Style::default().dim()),
+ };
+ let wrap_width = (width as usize)
+ .saturating_sub(4)
+ .saturating_sub(box_str.width())
+ .max(1);
+ let parts = textwrap::wrap(text, wrap_width);
+ let step_text = parts
+ .into_iter()
+ .map(|s| s.to_string().set_style(step_style).into())
+ .collect();
+ prefix_lines(step_text, box_str.into(), " ".into())
+ };
+
+ let mut lines: Vec<Line<'static>> = vec![];
+ lines.push(vec!["• ".dim(), "Updated Plan".bold()].into());
+
+ let mut indented_lines = vec![];
+ let note = self
+ .explanation
+ .as_ref()
+ .map(|s| s.trim())
+ .filter(|t| !t.is_empty());
+ if let Some(expl) = note {
+ indented_lines.extend(render_note(expl));
+ };
+
+ if self.plan.is_empty() {
+ indented_lines.push(Line::from("(no steps provided)".dim().italic()));
+ } else {
+ for PlanItemArg { step, status } in self.plan.iter() {
+ indented_lines.extend(render_step(status, step));
+ }
+ }
+ lines.extend(prefix_lines(indented_lines, " └ ".dim(), " ".into()));
+
+ lines
+ }
+}
+
+/// Create a new `PendingPatch` cell that lists the file‑level summary of
+/// a proposed patch. The summary lines should already be formatted (e.g.
+/// "A path/to/file.rs").
+pub(crate) fn new_patch_event(
+ changes: HashMap<PathBuf, FileChange>,
+ cwd: &Path,
+) -> PatchHistoryCell {
+ PatchHistoryCell {
+ changes,
+ cwd: cwd.to_path_buf(),
+ }
+}
+
+pub(crate) fn new_patch_apply_failure(stderr: String) -> PlainHistoryCell {
+ let mut lines: Vec<Line<'static>> = Vec::new();
+
+ // Failure title
+ lines.push(Line::from("✘ Failed to apply patch".magenta().bold()));
+
+ if !stderr.trim().is_empty() {
+ let output = output_lines(
+ Some(&CommandOutput {
+ exit_code: 1,
+ formatted_output: String::new(),
+ aggregated_output: stderr,
+ }),
+ OutputLinesParams {
+ line_limit: TOOL_CALL_MAX_LINES,
+ only_err: true,
+ include_angle_pipe: true,
+ include_prefix: true,
+ },
+ );
+ lines.extend(output.lines);
+ }
+
+ PlainHistoryCell { lines }
+}
+
+pub(crate) fn new_view_image_tool_call(path: PathBuf, cwd: &Path) -> PlainHistoryCell {
+ let display_path = display_path_for(&path, cwd);
+
+ let lines: Vec<Line<'static>> = vec![
+ vec!["• ".dim(), "Viewed Image".bold()].into(),
+ vec![" └ ".dim(), display_path.dim()].into(),
+ ];
+
+ PlainHistoryCell { lines }
+}
+
+pub(crate) fn new_reasoning_summary_block(
+ full_reasoning_buffer: String,
+ reasoning_summary_format: ReasoningSummaryFormat,
+) -> Box<dyn HistoryCell> {
+ if reasoning_summary_format == ReasoningSummaryFormat::Experimental {
+ // Experimental format is following:
+ // ** header **
+ //
+ // reasoning summary
+ //
+ // So we need to strip header from reasoning summary
+ let full_reasoning_buffer = full_reasoning_buffer.trim();
+ if let Some(open) = full_reasoning_buffer.find("**") {
+ let after_open = &full_reasoning_buffer[(open + 2)..];
+ if let Some(close) = after_open.find("**") {
+ let after_close_idx = open + 2 + close + 2;
+ // if we don't have anything beyond `after_close_idx`
+ // then we don't have a summary to inject into history
+ if after_close_idx < full_reasoning_buffer.len() {
+ let header_buffer = full_reasoning_buffer[..after_close_idx].to_string();
+ let summary_buffer = full_reasoning_buffer[after_close_idx..].to_string();
+ return Box::new(ReasoningSummaryCell::new(
+ header_buffer,
+ summary_buffer,
+ false,
+ ));
+ }
+ }
+ }
+ }
+ Box::new(ReasoningSummaryCell::new(
+ "".to_string(),
+ full_reasoning_buffer,
+ true,
+ ))
+}
+
+#[derive(Debug)]
+pub struct FinalMessageSeparator {
+ elapsed_seconds: Option<u64>,
+}
+impl FinalMessageSeparator {
+ pub(crate) fn new(elapsed_seconds: Option<u64>) -> Self {
+ Self { elapsed_seconds }
+ }
+}
+impl HistoryCell for FinalMessageSeparator {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let elapsed_seconds = self
+ .elapsed_seconds
+ .map(super::status_indicator_widget::fmt_elapsed_compact);
+ if let Some(elapsed_seconds) = elapsed_seconds {
+ let worked_for = format!("─ Worked for {elapsed_seconds} ─");
+ let worked_for_width = worked_for.width();
+ vec![
+ Line::from_iter([
+ worked_for,
+ "─".repeat((width as usize).saturating_sub(worked_for_width)),
+ ])
+ .dim(),
+ ]
+ } else {
+ vec![Line::from_iter(["─".repeat(width as usize).dim()])]
+ }
+ }
+}
+
+fn format_mcp_invocation<'a>(invocation: McpInvocation) -> Line<'a> {
+ let args_str = invocation
+ .arguments
+ .as_ref()
+ .map(|v: &serde_json::Value| {
+ // Use compact form to keep things short but readable.
+ serde_json::to_string(v).unwrap_or_else(|_| v.to_string())
+ })
+ .unwrap_or_default();
+
+ let invocation_spans = vec![
+ invocation.server.clone().cyan(),
+ ".".into(),
+ invocation.tool.cyan(),
+ "(".into(),
+ args_str.dim(),
+ ")".into(),
+ ];
+ invocation_spans.into()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::exec_cell::CommandOutput;
+ use crate::exec_cell::ExecCall;
+ use crate::exec_cell::ExecCell;
+ use codex_core::config::Config;
+ use codex_core::config::ConfigOverrides;
+ use codex_core::config::ConfigToml;
+ use codex_core::config::types::McpServerConfig;
+ use codex_core::config::types::McpServerTransportConfig;
+ use codex_core::openai_models::models_manager::ModelsManager;
+ use codex_core::protocol::McpAuthStatus;
+ use codex_protocol::parse_command::ParsedCommand;
+ use dirs::home_dir;
+ use pretty_assertions::assert_eq;
+ use serde_json::json;
+ use std::collections::HashMap;
+
+ use codex_core::protocol::ExecCommandSource;
+ use mcp_types::CallToolResult;
+ use mcp_types::ContentBlock;
+ use mcp_types::TextContent;
+ use mcp_types::Tool;
+ use mcp_types::ToolInputSchema;
+
+ fn test_config() -> Config {
+ Config::load_from_base_config_with_overrides(
+ ConfigToml::default(),
+ ConfigOverrides::default(),
+ std::env::temp_dir(),
+ )
+ .expect("config")
+ }
+
+ fn render_lines(lines: &[Line<'static>]) -> Vec<String> {
+ lines
+ .iter()
+ .map(|line| {
+ line.spans
+ .iter()
+ .map(|span| span.content.as_ref())
+ .collect::<String>()
+ })
+ .collect()
+ }
+
+ fn render_transcript(cell: &dyn HistoryCell) -> Vec<String> {
+ render_lines(&cell.transcript_lines(u16::MAX))
+ }
+
+ #[test]
+ fn mcp_tools_output_masks_sensitive_values() {
+ let mut config = test_config();
+ let mut env = HashMap::new();
+ env.insert("TOKEN".to_string(), "secret".to_string());
+ let stdio_config = McpServerConfig {
+ transport: McpServerTransportConfig::Stdio {
+ command: "docs-server".to_string(),
+ args: vec![],
+ env: Some(env),
+ env_vars: vec!["APP_TOKEN".to_string()],
+ cwd: None,
+ },
+ enabled: true,
+ startup_timeout_sec: None,
+ tool_timeout_sec: None,
+ enabled_tools: None,
+ disabled_tools: None,
+ };
+ config.mcp_servers.insert("docs".to_string(), stdio_config);
+
+ let mut headers = HashMap::new();
+ headers.insert("Authorization".to_string(), "Bearer secret".to_string());
+ let mut env_headers = HashMap::new();
+ env_headers.insert("X-API-Key".to_string(), "API_KEY_ENV".to_string());
+ let http_config = McpServerConfig {
+ transport: McpServerTransportConfig::StreamableHttp {
+ url: "https://example.com/mcp".to_string(),
+ bearer_token_env_var: Some("MCP_TOKEN".to_string()),
+ http_headers: Some(headers),
+ env_http_headers: Some(env_headers),
+ },
+ enabled: true,
+ startup_timeout_sec: None,
+ tool_timeout_sec: None,
+ enabled_tools: None,
+ disabled_tools: None,
+ };
+ config.mcp_servers.insert("http".to_string(), http_config);
+
+ let mut tools: HashMap<String, Tool> = HashMap::new();
+ tools.insert(
+ "mcp__docs__list".to_string(),
+ Tool {
+ annotations: None,
+ description: None,
+ input_schema: ToolInputSchema {
+ properties: None,
+ required: None,
+ r#type: "object".to_string(),
+ },
+ name: "list".to_string(),
+ output_schema: None,
+ title: None,
+ },
+ );
+ tools.insert(
+ "mcp__http__ping".to_string(),
+ Tool {
+ annotations: None,
+ description: None,
+ input_schema: ToolInputSchema {
+ properties: None,
+ required: None,
+ r#type: "object".to_string(),
+ },
+ name: "ping".to_string(),
+ output_schema: None,
+ title: None,
+ },
+ );
+
+ let auth_statuses: HashMap<String, McpAuthStatus> = HashMap::new();
+ let cell = new_mcp_tools_output(
+ &config,
+ tools,
+ HashMap::new(),
+ HashMap::new(),
+ &auth_statuses,
+ );
+ let rendered = render_lines(&cell.display_lines(120)).join("\n");
+
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn empty_agent_message_cell_transcript() {
+ let cell = AgentMessageCell::new(vec![Line::default()], false);
+ assert_eq!(cell.transcript_lines(80), vec![Line::from(" ")]);
+ assert_eq!(cell.desired_transcript_height(80), 1);
+ }
+
+ #[test]
+ fn prefixed_wrapped_history_cell_indents_wrapped_lines() {
+ let summary = Line::from(vec![
+ "You ".into(),
+ "approved".bold(),
+ " codex to run ".into(),
+ "echo something really long to ensure wrapping happens".dim(),
+ " this time".bold(),
+ ]);
+ let cell = PrefixedWrappedHistoryCell::new(summary, "✔ ".green(), " ");
+ let rendered = render_lines(&cell.display_lines(24));
+ assert_eq!(
+ rendered,
+ vec![
+ "✔ You approved codex".to_string(),
+ " to run echo something".to_string(),
+ " really long to ensure".to_string(),
+ " wrapping happens this".to_string(),
+ " time".to_string(),
+ ]
+ );
+ }
+
+ #[test]
+ fn active_mcp_tool_call_snapshot() {
+ let invocation = McpInvocation {
+ server: "search".into(),
+ tool: "find_docs".into(),
+ arguments: Some(json!({
+ "query": "ratatui styling",
+ "limit": 3,
+ })),
+ };
+
+ let cell = new_active_mcp_tool_call("call-1".into(), invocation, true);
+ let rendered = render_lines(&cell.display_lines(80)).join("\n");
+
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn completed_mcp_tool_call_success_snapshot() {
+ let invocation = McpInvocation {
+ server: "search".into(),
+ tool: "find_docs".into(),
+ arguments: Some(json!({
+ "query": "ratatui styling",
+ "limit": 3,
+ })),
+ };
+
+ let result = CallToolResult {
+ content: vec![ContentBlock::TextContent(TextContent {
+ annotations: None,
+ text: "Found styling guidance in styles.md".into(),
+ r#type: "text".into(),
+ })],
+ is_error: None,
+ structured_content: None,
+ };
+
+ let mut cell = new_active_mcp_tool_call("call-2".into(), invocation, true);
+ assert!(
+ cell.complete(Duration::from_millis(1420), Ok(result))
+ .is_none()
+ );
+
+ let rendered = render_lines(&cell.display_lines(80)).join("\n");
+
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn completed_mcp_tool_call_error_snapshot() {
+ let invocation = McpInvocation {
+ server: "search".into(),
+ tool: "find_docs".into(),
+ arguments: Some(json!({
+ "query": "ratatui styling",
+ "limit": 3,
+ })),
+ };
+
+ let mut cell = new_active_mcp_tool_call("call-3".into(), invocation, true);
+ assert!(
+ cell.complete(Duration::from_secs(2), Err("network timeout".into()))
+ .is_none()
+ );
+
+ let rendered = render_lines(&cell.display_lines(80)).join("\n");
+
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn completed_mcp_tool_call_multiple_outputs_snapshot() {
+ let invocation = McpInvocation {
+ server: "search".into(),
+ tool: "find_docs".into(),
+ arguments: Some(json!({
+ "query": "ratatui styling",
+ "limit": 3,
+ })),
+ };
+
+ let result = CallToolResult {
+ content: vec![
+ ContentBlock::TextContent(TextContent {
+ annotations: None,
+ text: "Found styling guidance in styles.md and additional notes in CONTRIBUTING.md.".into(),
+ r#type: "text".into(),
+ }),
+ ContentBlock::ResourceLink(ResourceLink {
+ annotations: None,
+ description: Some("Link to styles documentation".into()),
+ mime_type: None,
+ name: "styles.md".into(),
+ size: None,
+ title: Some("Styles".into()),
+ r#type: "resource_link".into(),
+ uri: "file:///docs/styles.md".into(),
+ }),
+ ],
+ is_error: None,
+ structured_content: None,
+ };
+
+ let mut cell = new_active_mcp_tool_call("call-4".into(), invocation, true);
+ assert!(
+ cell.complete(Duration::from_millis(640), Ok(result))
+ .is_none()
+ );
+
+ let rendered = render_lines(&cell.display_lines(48)).join("\n");
+
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn completed_mcp_tool_call_wrapped_outputs_snapshot() {
+ let invocation = McpInvocation {
+ server: "metrics".into(),
+ tool: "get_nearby_metric".into(),
+ arguments: Some(json!({
+ "query": "very_long_query_that_needs_wrapping_to_display_properly_in_the_history",
+ "limit": 1,
+ })),
+ };
+
+ let result = CallToolResult {
+ content: vec![ContentBlock::TextContent(TextContent {
+ annotations: None,
+ text: "Line one of the response, which is quite long and needs wrapping.\nLine two continues the response with more detail.".into(),
+ r#type: "text".into(),
+ })],
+ is_error: None,
+ structured_content: None,
+ };
+
+ let mut cell = new_active_mcp_tool_call("call-5".into(), invocation, true);
+ assert!(
+ cell.complete(Duration::from_millis(1280), Ok(result))
+ .is_none()
+ );
+
+ let rendered = render_lines(&cell.display_lines(40)).join("\n");
+
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn completed_mcp_tool_call_multiple_outputs_inline_snapshot() {
+ let invocation = McpInvocation {
+ server: "metrics".into(),
+ tool: "summary".into(),
+ arguments: Some(json!({
+ "metric": "trace.latency",
+ "window": "15m",
+ })),
+ };
+
+ let result = CallToolResult {
+ content: vec![
+ ContentBlock::TextContent(TextContent {
+ annotations: None,
+ text: "Latency summary: p50=120ms, p95=480ms.".into(),
+ r#type: "text".into(),
+ }),
+ ContentBlock::TextContent(TextContent {
+ annotations: None,
+ text: "No anomalies detected.".into(),
+ r#type: "text".into(),
+ }),
+ ],
+ is_error: None,
+ structured_content: None,
+ };
+
+ let mut cell = new_active_mcp_tool_call("call-6".into(), invocation, true);
+ assert!(
+ cell.complete(Duration::from_millis(320), Ok(result))
+ .is_none()
+ );
+
+ let rendered = render_lines(&cell.display_lines(120)).join("\n");
+
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn session_header_includes_reasoning_level_when_present() {
+ let cell = SessionHeaderHistoryCell::new(
+ "gpt-4o".to_string(),
+ Some(ReasoningEffortConfig::High),
+ std::env::temp_dir(),
+ "test",
+ );
+
+ let lines = render_lines(&cell.display_lines(80));
+ let model_line = lines
+ .into_iter()
+ .find(|line| line.contains("model:"))
+ .expect("model line");
+
+ assert!(model_line.contains("gpt-4o high"));
+ assert!(model_line.contains("/model to change"));
+ }
+
+ #[test]
+ fn session_header_directory_center_truncates() {
+ let mut dir = home_dir().expect("home directory");
+ for part in ["hello", "the", "fox", "is", "very", "fast"] {
+ dir.push(part);
+ }
+
+ let formatted = SessionHeaderHistoryCell::format_directory_inner(&dir, Some(24));
+ let sep = std::path::MAIN_SEPARATOR;
+ let expected = format!("~{sep}hello{sep}the{sep}…{sep}very{sep}fast");
+ assert_eq!(formatted, expected);
+ }
+
+ #[test]
+ fn session_header_directory_front_truncates_long_segment() {
+ let mut dir = home_dir().expect("home directory");
+ dir.push("supercalifragilisticexpialidocious");
+
+ let formatted = SessionHeaderHistoryCell::format_directory_inner(&dir, Some(18));
+ let sep = std::path::MAIN_SEPARATOR;
+ let expected = format!("~{sep}…cexpialidocious");
+ assert_eq!(formatted, expected);
+ }
+
+ #[test]
+ fn coalesces_sequential_reads_within_one_call() {
+ // Build one exec cell with a Search followed by two Reads
+ let call_id = "c1".to_string();
+ let mut cell = ExecCell::new(
+ ExecCall {
+ call_id: call_id.clone(),
+ command: vec!["bash".into(), "-lc".into(), "echo".into()],
+ parsed: vec![
+ ParsedCommand::Search {
+ query: Some("shimmer_spans".into()),
+ path: None,
+ cmd: "rg shimmer_spans".into(),
+ },
+ ParsedCommand::Read {
+ name: "shimmer.rs".into(),
+ cmd: "cat shimmer.rs".into(),
+ path: "shimmer.rs".into(),
+ },
+ ParsedCommand::Read {
+ name: "status_indicator_widget.rs".into(),
+ cmd: "cat status_indicator_widget.rs".into(),
+ path: "status_indicator_widget.rs".into(),
+ },
+ ],
+ output: None,
+ source: ExecCommandSource::Agent,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input: None,
+ },
+ true,
+ );
+ // Mark call complete so markers are ✓
+ cell.complete_call(&call_id, CommandOutput::default(), Duration::from_millis(1));
+
+ let lines = cell.display_lines(80);
+ let rendered = render_lines(&lines).join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn coalesces_reads_across_multiple_calls() {
+ let mut cell = ExecCell::new(
+ ExecCall {
+ call_id: "c1".to_string(),
+ command: vec!["bash".into(), "-lc".into(), "echo".into()],
+ parsed: vec![ParsedCommand::Search {
+ query: Some("shimmer_spans".into()),
+ path: None,
+ cmd: "rg shimmer_spans".into(),
+ }],
+ output: None,
+ source: ExecCommandSource::Agent,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input: None,
+ },
+ true,
+ );
+ // Call 1: Search only
+ cell.complete_call("c1", CommandOutput::default(), Duration::from_millis(1));
+ // Call 2: Read A
+ cell = cell
+ .with_added_call(
+ "c2".into(),
+ vec!["bash".into(), "-lc".into(), "echo".into()],
+ vec![ParsedCommand::Read {
+ name: "shimmer.rs".into(),
+ cmd: "cat shimmer.rs".into(),
+ path: "shimmer.rs".into(),
+ }],
+ ExecCommandSource::Agent,
+ None,
+ )
+ .unwrap();
+ cell.complete_call("c2", CommandOutput::default(), Duration::from_millis(1));
+ // Call 3: Read B
+ cell = cell
+ .with_added_call(
+ "c3".into(),
+ vec!["bash".into(), "-lc".into(), "echo".into()],
+ vec![ParsedCommand::Read {
+ name: "status_indicator_widget.rs".into(),
+ cmd: "cat status_indicator_widget.rs".into(),
+ path: "status_indicator_widget.rs".into(),
+ }],
+ ExecCommandSource::Agent,
+ None,
+ )
+ .unwrap();
+ cell.complete_call("c3", CommandOutput::default(), Duration::from_millis(1));
+
+ let lines = cell.display_lines(80);
+ let rendered = render_lines(&lines).join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn coalesced_reads_dedupe_names() {
+ let mut cell = ExecCell::new(
+ ExecCall {
+ call_id: "c1".to_string(),
+ command: vec!["bash".into(), "-lc".into(), "echo".into()],
+ parsed: vec![
+ ParsedCommand::Read {
+ name: "auth.rs".into(),
+ cmd: "cat auth.rs".into(),
+ path: "auth.rs".into(),
+ },
+ ParsedCommand::Read {
+ name: "auth.rs".into(),
+ cmd: "cat auth.rs".into(),
+ path: "auth.rs".into(),
+ },
+ ParsedCommand::Read {
+ name: "shimmer.rs".into(),
+ cmd: "cat shimmer.rs".into(),
+ path: "shimmer.rs".into(),
+ },
+ ],
+ output: None,
+ source: ExecCommandSource::Agent,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input: None,
+ },
+ true,
+ );
+ cell.complete_call("c1", CommandOutput::default(), Duration::from_millis(1));
+ let lines = cell.display_lines(80);
+ let rendered = render_lines(&lines).join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn multiline_command_wraps_with_extra_indent_on_subsequent_lines() {
+ // Create a completed exec cell with a multiline command
+ let cmd = "set -o pipefail\ncargo test --all-features --quiet".to_string();
+ let call_id = "c1".to_string();
+ let mut cell = ExecCell::new(
+ ExecCall {
+ call_id: call_id.clone(),
+ command: vec!["bash".into(), "-lc".into(), cmd],
+ parsed: Vec::new(),
+ output: None,
+ source: ExecCommandSource::Agent,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input: None,
+ },
+ true,
+ );
+ // Mark call complete so it renders as "Ran"
+ cell.complete_call(&call_id, CommandOutput::default(), Duration::from_millis(1));
+
+ // Small width to force wrapping on both lines
+ let width: u16 = 28;
+ let lines = cell.display_lines(width);
+ let rendered = render_lines(&lines).join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn single_line_command_compact_when_fits() {
+ let call_id = "c1".to_string();
+ let mut cell = ExecCell::new(
+ ExecCall {
+ call_id: call_id.clone(),
+ command: vec!["echo".into(), "ok".into()],
+ parsed: Vec::new(),
+ output: None,
+ source: ExecCommandSource::Agent,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input: None,
+ },
+ true,
+ );
+ cell.complete_call(&call_id, CommandOutput::default(), Duration::from_millis(1));
+ // Wide enough that it fits inline
+ let lines = cell.display_lines(80);
+ let rendered = render_lines(&lines).join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn single_line_command_wraps_with_four_space_continuation() {
+ let call_id = "c1".to_string();
+ let long = "a_very_long_token_without_spaces_to_force_wrapping".to_string();
+ let mut cell = ExecCell::new(
+ ExecCall {
+ call_id: call_id.clone(),
+ command: vec!["bash".into(), "-lc".into(), long],
+ parsed: Vec::new(),
+ output: None,
+ source: ExecCommandSource::Agent,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input: None,
+ },
+ true,
+ );
+ cell.complete_call(&call_id, CommandOutput::default(), Duration::from_millis(1));
+ let lines = cell.display_lines(24);
+ let rendered = render_lines(&lines).join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn multiline_command_without_wrap_uses_branch_then_eight_spaces() {
+ let call_id = "c1".to_string();
+ let cmd = "echo one\necho two".to_string();
+ let mut cell = ExecCell::new(
+ ExecCall {
+ call_id: call_id.clone(),
+ command: vec!["bash".into(), "-lc".into(), cmd],
+ parsed: Vec::new(),
+ output: None,
+ source: ExecCommandSource::Agent,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input: None,
+ },
+ true,
+ );
+ cell.complete_call(&call_id, CommandOutput::default(), Duration::from_millis(1));
+ let lines = cell.display_lines(80);
+ let rendered = render_lines(&lines).join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn multiline_command_both_lines_wrap_with_correct_prefixes() {
+ let call_id = "c1".to_string();
+ let cmd = "first_token_is_long_enough_to_wrap\nsecond_token_is_also_long_enough_to_wrap"
+ .to_string();
+ let mut cell = ExecCell::new(
+ ExecCall {
+ call_id: call_id.clone(),
+ command: vec!["bash".into(), "-lc".into(), cmd],
+ parsed: Vec::new(),
+ output: None,
+ source: ExecCommandSource::Agent,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input: None,
+ },
+ true,
+ );
+ cell.complete_call(&call_id, CommandOutput::default(), Duration::from_millis(1));
+ let lines = cell.display_lines(28);
+ let rendered = render_lines(&lines).join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn stderr_tail_more_than_five_lines_snapshot() {
+ // Build an exec cell with a non-zero exit and 10 lines on stderr to exercise
+ // the head/tail rendering and gutter prefixes.
+ let call_id = "c_err".to_string();
+ let mut cell = ExecCell::new(
+ ExecCall {
+ call_id: call_id.clone(),
+ command: vec!["bash".into(), "-lc".into(), "seq 1 10 1>&2 && false".into()],
+ parsed: Vec::new(),
+ output: None,
+ source: ExecCommandSource::Agent,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input: None,
+ },
+ true,
+ );
+ let stderr: String = (1..=10)
+ .map(|n| n.to_string())
+ .collect::<Vec<_>>()
+ .join("\n");
+ cell.complete_call(
+ &call_id,
+ CommandOutput {
+ exit_code: 1,
+ formatted_output: String::new(),
+ aggregated_output: stderr,
+ },
+ Duration::from_millis(1),
+ );
+
+ let rendered = cell
+ .display_lines(80)
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.as_ref())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn ran_cell_multiline_with_stderr_snapshot() {
+ // Build an exec cell that completes (so it renders as "Ran") with a
+ // command long enough that it must render on its own line under the
+ // header, and include a couple of stderr lines to verify the output
+ // block prefixes and wrapping.
+ let call_id = "c_wrap_err".to_string();
+ let long_cmd =
+ "echo this_is_a_very_long_single_token_that_will_wrap_across_the_available_width";
+ let mut cell = ExecCell::new(
+ ExecCall {
+ call_id: call_id.clone(),
+ command: vec!["bash".into(), "-lc".into(), long_cmd.to_string()],
+ parsed: Vec::new(),
+ output: None,
+ source: ExecCommandSource::Agent,
+ start_time: Some(Instant::now()),
+ duration: None,
+ interaction_input: None,
+ },
+ true,
+ );
+
+ let stderr = "error: first line on stderr\nerror: second line on stderr".to_string();
+ cell.complete_call(
+ &call_id,
+ CommandOutput {
+ exit_code: 1,
+ formatted_output: String::new(),
+ aggregated_output: stderr,
+ },
+ Duration::from_millis(5),
+ );
+
+ // Narrow width to force the command to render under the header line.
+ let width: u16 = 28;
+ let rendered = cell
+ .display_lines(width)
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.as_ref())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+ #[test]
+ fn user_history_cell_wraps_and_prefixes_each_line_snapshot() {
+ let msg = "one two three four five six seven";
+ let cell = UserHistoryCell {
+ message: msg.to_string(),
+ };
+
+ // Small width to force wrapping more clearly. Effective wrap width is width-2 due to the ▌ prefix and trailing space.
+ let width: u16 = 12;
+ let lines = cell.display_lines(width);
+ let rendered = render_lines(&lines).join("\n");
+
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn plan_update_with_note_and_wrapping_snapshot() {
+ // Long explanation forces wrapping; include long step text to verify step wrapping and alignment.
+ let update = UpdatePlanArgs {
+ explanation: Some(
+ "I’ll update Grafana call error handling by adding retries and clearer messages when the backend is unreachable."
+ .to_string(),
+ ),
+ plan: vec![
+ PlanItemArg {
+ step: "Investigate existing error paths and logging around HTTP timeouts".into(),
+ status: StepStatus::Completed,
+ },
+ PlanItemArg {
+ step: "Harden Grafana client error handling with retry/backoff and user‑friendly messages".into(),
+ status: StepStatus::InProgress,
+ },
+ PlanItemArg {
+ step: "Add tests for transient failure scenarios and surfacing to the UI".into(),
+ status: StepStatus::Pending,
+ },
+ ],
+ };
+
+ let cell = new_plan_update(update);
+ // Narrow width to force wrapping for both the note and steps
+ let lines = cell.display_lines(32);
+ let rendered = render_lines(&lines).join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+
+ #[test]
+ fn plan_update_without_note_snapshot() {
+ let update = UpdatePlanArgs {
+ explanation: None,
+ plan: vec![
+ PlanItemArg {
+ step: "Define error taxonomy".into(),
+ status: StepStatus::InProgress,
+ },
+ PlanItemArg {
+ step: "Implement mapping to user messages".into(),
+ status: StepStatus::Pending,
+ },
+ ],
+ };
+
+ let cell = new_plan_update(update);
+ let lines = cell.display_lines(40);
+ let rendered = render_lines(&lines).join("\n");
+ insta::assert_snapshot!(rendered);
+ }
+ #[test]
+ fn reasoning_summary_block() {
+ let reasoning_format = ReasoningSummaryFormat::Experimental;
+ let cell = new_reasoning_summary_block(
+ "**High level reasoning**\n\nDetailed reasoning goes here.".to_string(),
+ reasoning_format,
+ );
+
+ let rendered_display = render_lines(&cell.display_lines(80));
+ assert_eq!(rendered_display, vec!["• Detailed reasoning goes here."]);
+
+ let rendered_transcript = render_transcript(cell.as_ref());
+ assert_eq!(rendered_transcript, vec!["• Detailed reasoning goes here."]);
+ }
+
+ #[test]
+ fn reasoning_summary_block_returns_reasoning_cell_when_feature_disabled() {
+ let reasoning_format = ReasoningSummaryFormat::Experimental;
+ let cell = new_reasoning_summary_block(
+ "Detailed reasoning goes here.".to_string(),
+ reasoning_format,
+ );
+
+ let rendered = render_transcript(cell.as_ref());
+ assert_eq!(rendered, vec!["• Detailed reasoning goes here."]);
+ }
+
+ #[test]
+ fn reasoning_summary_block_respects_config_overrides() {
+ let mut config = test_config();
+ config.model = Some("gpt-3.5-turbo".to_string());
+ config.model_supports_reasoning_summaries = Some(true);
+ config.model_reasoning_summary_format = Some(ReasoningSummaryFormat::Experimental);
+ let model_family =
+ ModelsManager::construct_model_family_offline(&config.model.clone().unwrap(), &config);
+ assert_eq!(
+ model_family.reasoning_summary_format,
+ ReasoningSummaryFormat::Experimental
+ );
+
+ let cell = new_reasoning_summary_block(
+ "**High level reasoning**\n\nDetailed reasoning goes here.".to_string(),
+ model_family.reasoning_summary_format,
+ );
+
+ let rendered_display = render_lines(&cell.display_lines(80));
+ assert_eq!(rendered_display, vec!["• Detailed reasoning goes here."]);
+ }
+
+ #[test]
+ fn reasoning_summary_block_falls_back_when_header_is_missing() {
+ let reasoning_format = ReasoningSummaryFormat::Experimental;
+ let cell = new_reasoning_summary_block(
+ "**High level reasoning without closing".to_string(),
+ reasoning_format,
+ );
+
+ let rendered = render_transcript(cell.as_ref());
+ assert_eq!(rendered, vec!["• **High level reasoning without closing"]);
+ }
+
+ #[test]
+ fn reasoning_summary_block_falls_back_when_summary_is_missing() {
+ let reasoning_format = ReasoningSummaryFormat::Experimental;
+ let cell = new_reasoning_summary_block(
+ "**High level reasoning without closing**".to_string(),
+ reasoning_format.clone(),
+ );
+
+ let rendered = render_transcript(cell.as_ref());
+ assert_eq!(rendered, vec!["• High level reasoning without closing"]);
+
+ let cell = new_reasoning_summary_block(
+ "**High level reasoning without closing**\n\n ".to_string(),
+ reasoning_format,
+ );
+
+ let rendered = render_transcript(cell.as_ref());
+ assert_eq!(rendered, vec!["• High level reasoning without closing"]);
+ }
+
+ #[test]
+ fn reasoning_summary_block_splits_header_and_summary_when_present() {
+ let reasoning_format = ReasoningSummaryFormat::Experimental;
+ let cell = new_reasoning_summary_block(
+ "**High level plan**\n\nWe should fix the bug next.".to_string(),
+ reasoning_format,
+ );
+
+ let rendered_display = render_lines(&cell.display_lines(80));
+ assert_eq!(rendered_display, vec!["• We should fix the bug next."]);
+
+ let rendered_transcript = render_transcript(cell.as_ref());
+ assert_eq!(rendered_transcript, vec!["• We should fix the bug next."]);
+ }
+
+ #[test]
+ fn deprecation_notice_renders_summary_with_details() {
+ let cell = new_deprecation_notice(
+ "Feature flag `foo`".to_string(),
+ Some("Use flag `bar` instead.".to_string()),
+ );
+ let lines = cell.display_lines(80);
+ let rendered = render_lines(&lines);
+ assert_eq!(
+ rendered,
+ vec![
+ "⚠ Feature flag `foo`".to_string(),
+ "Use flag `bar` instead.".to_string(),
+ ]
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/insert_history.rs b/codex-rs/tui2/src/insert_history.rs
new file mode 100644
index 0000000000..36ef47da5e
--- /dev/null
+++ b/codex-rs/tui2/src/insert_history.rs
@@ -0,0 +1,530 @@
+use std::fmt;
+use std::io;
+use std::io::Write;
+
+use crate::wrapping::word_wrap_lines_borrowed;
+use crossterm::Command;
+use crossterm::cursor::MoveTo;
+use crossterm::queue;
+use crossterm::style::Color as CColor;
+use crossterm::style::Colors;
+use crossterm::style::Print;
+use crossterm::style::SetAttribute;
+use crossterm::style::SetBackgroundColor;
+use crossterm::style::SetColors;
+use crossterm::style::SetForegroundColor;
+use crossterm::terminal::Clear;
+use crossterm::terminal::ClearType;
+use ratatui::layout::Size;
+use ratatui::prelude::Backend;
+use ratatui::style::Color;
+use ratatui::style::Modifier;
+use ratatui::text::Line;
+use ratatui::text::Span;
+
+/// Insert `lines` above the viewport using the terminal's backend writer
+/// (avoids direct stdout references).
+pub fn insert_history_lines<B>(
+ terminal: &mut crate::custom_terminal::Terminal<B>,
+ lines: Vec<Line>,
+) -> io::Result<()>
+where
+ B: Backend + Write,
+{
+ let screen_size = terminal.backend().size().unwrap_or(Size::new(0, 0));
+
+ let mut area = terminal.viewport_area;
+ let mut should_update_area = false;
+ let last_cursor_pos = terminal.last_known_cursor_pos;
+ let writer = terminal.backend_mut();
+
+ // Pre-wrap lines using word-aware wrapping so terminal scrollback sees the same
+ // formatting as the TUI. This avoids character-level hard wrapping by the terminal.
+ let wrapped = word_wrap_lines_borrowed(&lines, area.width.max(1) as usize);
+ let wrapped_lines = wrapped.len() as u16;
+ let cursor_top = if area.bottom() < screen_size.height {
+ // If the viewport is not at the bottom of the screen, scroll it down to make room.
+ // Don't scroll it past the bottom of the screen.
+ let scroll_amount = wrapped_lines.min(screen_size.height - area.bottom());
+
+ // Emit ANSI to scroll the lower region (from the top of the viewport to the bottom
+ // of the screen) downward by `scroll_amount` lines. We do this by:
+ // 1) Limiting the scroll region to [area.top()+1 .. screen_height] (1-based bounds)
+ // 2) Placing the cursor at the top margin of that region
+ // 3) Emitting Reverse Index (RI, ESC M) `scroll_amount` times
+ // 4) Resetting the scroll region back to full screen
+ let top_1based = area.top() + 1; // Convert 0-based row to 1-based for DECSTBM
+ queue!(writer, SetScrollRegion(top_1based..screen_size.height))?;
+ queue!(writer, MoveTo(0, area.top()))?;
+ for _ in 0..scroll_amount {
+ // Reverse Index (RI): ESC M
+ queue!(writer, Print("\x1bM"))?;
+ }
+ queue!(writer, ResetScrollRegion)?;
+
+ let cursor_top = area.top().saturating_sub(1);
+ area.y += scroll_amount;
+ should_update_area = true;
+ cursor_top
+ } else {
+ area.top().saturating_sub(1)
+ };
+
+ // Limit the scroll region to the lines from the top of the screen to the
+ // top of the viewport. With this in place, when we add lines inside this
+ // area, only the lines in this area will be scrolled. We place the cursor
+ // at the end of the scroll region, and add lines starting there.
+ //
+ // ┌─Screen───────────────────────┐
+ // │┌╌Scroll region╌╌╌╌╌╌╌╌╌╌╌╌╌╌┐│
+ // │┆ ┆│
+ // │┆ ┆│
+ // │┆ ┆│
+ // │█╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┘│
+ // │╭─Viewport───────────────────╮│
+ // ││ ││
+ // │╰────────────────────────────╯│
+ // └──────────────────────────────┘
+ queue!(writer, SetScrollRegion(1..area.top()))?;
+
+ // NB: we are using MoveTo instead of set_cursor_position here to avoid messing with the
+ // terminal's last_known_cursor_position, which hopefully will still be accurate after we
+ // fetch/restore the cursor position. insert_history_lines should be cursor-position-neutral :)
+ queue!(writer, MoveTo(0, cursor_top))?;
+
+ for line in wrapped {
+ queue!(writer, Print("\r\n"))?;
+ queue!(
+ writer,
+ SetColors(Colors::new(
+ line.style
+ .fg
+ .map(std::convert::Into::into)
+ .unwrap_or(CColor::Reset),
+ line.style
+ .bg
+ .map(std::convert::Into::into)
+ .unwrap_or(CColor::Reset)
+ ))
+ )?;
+ queue!(writer, Clear(ClearType::UntilNewLine))?;
+ // Merge line-level style into each span so that ANSI colors reflect
+ // line styles (e.g., blockquotes with green fg).
+ let merged_spans: Vec<Span> = line
+ .spans
+ .iter()
+ .map(|s| Span {
+ style: s.style.patch(line.style),
+ content: s.content.clone(),
+ })
+ .collect();
+ write_spans(writer, merged_spans.iter())?;
+ }
+
+ queue!(writer, ResetScrollRegion)?;
+
+ // Restore the cursor position to where it was before we started.
+ queue!(writer, MoveTo(last_cursor_pos.x, last_cursor_pos.y))?;
+
+ let _ = writer;
+ if should_update_area {
+ terminal.set_viewport_area(area);
+ }
+
+ Ok(())
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct SetScrollRegion(pub std::ops::Range<u16>);
+
+impl Command for SetScrollRegion {
+ fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
+ write!(f, "\x1b[{};{}r", self.0.start, self.0.end)
+ }
+
+ #[cfg(windows)]
+ fn execute_winapi(&self) -> std::io::Result<()> {
+ panic!("tried to execute SetScrollRegion command using WinAPI, use ANSI instead");
+ }
+
+ #[cfg(windows)]
+ fn is_ansi_code_supported(&self) -> bool {
+ // TODO(nornagon): is this supported on Windows?
+ true
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ResetScrollRegion;
+
+impl Command for ResetScrollRegion {
+ fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
+ write!(f, "\x1b[r")
+ }
+
+ #[cfg(windows)]
+ fn execute_winapi(&self) -> std::io::Result<()> {
+ panic!("tried to execute ResetScrollRegion command using WinAPI, use ANSI instead");
+ }
+
+ #[cfg(windows)]
+ fn is_ansi_code_supported(&self) -> bool {
+ // TODO(nornagon): is this supported on Windows?
+ true
+ }
+}
+
+struct ModifierDiff {
+ pub from: Modifier,
+ pub to: Modifier,
+}
+
+impl ModifierDiff {
+ fn queue<W>(self, mut w: W) -> io::Result<()>
+ where
+ W: io::Write,
+ {
+ use crossterm::style::Attribute as CAttribute;
+ let removed = self.from - self.to;
+ if removed.contains(Modifier::REVERSED) {
+ queue!(w, SetAttribute(CAttribute::NoReverse))?;
+ }
+ if removed.contains(Modifier::BOLD) {
+ queue!(w, SetAttribute(CAttribute::NormalIntensity))?;
+ if self.to.contains(Modifier::DIM) {
+ queue!(w, SetAttribute(CAttribute::Dim))?;
+ }
+ }
+ if removed.contains(Modifier::ITALIC) {
+ queue!(w, SetAttribute(CAttribute::NoItalic))?;
+ }
+ if removed.contains(Modifier::UNDERLINED) {
+ queue!(w, SetAttribute(CAttribute::NoUnderline))?;
+ }
+ if removed.contains(Modifier::DIM) {
+ queue!(w, SetAttribute(CAttribute::NormalIntensity))?;
+ }
+ if removed.contains(Modifier::CROSSED_OUT) {
+ queue!(w, SetAttribute(CAttribute::NotCrossedOut))?;
+ }
+ if removed.contains(Modifier::SLOW_BLINK) || removed.contains(Modifier::RAPID_BLINK) {
+ queue!(w, SetAttribute(CAttribute::NoBlink))?;
+ }
+
+ let added = self.to - self.from;
+ if added.contains(Modifier::REVERSED) {
+ queue!(w, SetAttribute(CAttribute::Reverse))?;
+ }
+ if added.contains(Modifier::BOLD) {
+ queue!(w, SetAttribute(CAttribute::Bold))?;
+ }
+ if added.contains(Modifier::ITALIC) {
+ queue!(w, SetAttribute(CAttribute::Italic))?;
+ }
+ if added.contains(Modifier::UNDERLINED) {
+ queue!(w, SetAttribute(CAttribute::Underlined))?;
+ }
+ if added.contains(Modifier::DIM) {
+ queue!(w, SetAttribute(CAttribute::Dim))?;
+ }
+ if added.contains(Modifier::CROSSED_OUT) {
+ queue!(w, SetAttribute(CAttribute::CrossedOut))?;
+ }
+ if added.contains(Modifier::SLOW_BLINK) {
+ queue!(w, SetAttribute(CAttribute::SlowBlink))?;
+ }
+ if added.contains(Modifier::RAPID_BLINK) {
+ queue!(w, SetAttribute(CAttribute::RapidBlink))?;
+ }
+
+ Ok(())
+ }
+}
+
+fn write_spans<'a, I>(mut writer: &mut impl Write, content: I) -> io::Result<()>
+where
+ I: IntoIterator<Item = &'a Span<'a>>,
+{
+ let mut fg = Color::Reset;
+ let mut bg = Color::Reset;
+ let mut last_modifier = Modifier::empty();
+ for span in content {
+ let mut modifier = Modifier::empty();
+ modifier.insert(span.style.add_modifier);
+ modifier.remove(span.style.sub_modifier);
+ if modifier != last_modifier {
+ let diff = ModifierDiff {
+ from: last_modifier,
+ to: modifier,
+ };
+ diff.queue(&mut writer)?;
+ last_modifier = modifier;
+ }
+ let next_fg = span.style.fg.unwrap_or(Color::Reset);
+ let next_bg = span.style.bg.unwrap_or(Color::Reset);
+ if next_fg != fg || next_bg != bg {
+ queue!(
+ writer,
+ SetColors(Colors::new(next_fg.into(), next_bg.into()))
+ )?;
+ fg = next_fg;
+ bg = next_bg;
+ }
+
+ queue!(writer, Print(span.content.clone()))?;
+ }
+
+ queue!(
+ writer,
+ SetForegroundColor(CColor::Reset),
+ SetBackgroundColor(CColor::Reset),
+ SetAttribute(crossterm::style::Attribute::Reset),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::markdown_render::render_markdown_text;
+ use crate::test_backend::VT100Backend;
+ use ratatui::layout::Rect;
+ use ratatui::style::Color;
+
+ #[test]
+ fn writes_bold_then_regular_spans() {
+ use ratatui::style::Stylize;
+
+ let spans = ["A".bold(), "B".into()];
+
+ let mut actual: Vec<u8> = Vec::new();
+ write_spans(&mut actual, spans.iter()).unwrap();
+
+ let mut expected: Vec<u8> = Vec::new();
+ queue!(
+ expected,
+ SetAttribute(crossterm::style::Attribute::Bold),
+ Print("A"),
+ SetAttribute(crossterm::style::Attribute::NormalIntensity),
+ Print("B"),
+ SetForegroundColor(CColor::Reset),
+ SetBackgroundColor(CColor::Reset),
+ SetAttribute(crossterm::style::Attribute::Reset),
+ )
+ .unwrap();
+
+ assert_eq!(
+ String::from_utf8(actual).unwrap(),
+ String::from_utf8(expected).unwrap()
+ );
+ }
+
+ #[test]
+ fn vt100_blockquote_line_emits_green_fg() {
+ // Set up a small off-screen terminal
+ let width: u16 = 40;
+ let height: u16 = 10;
+ let backend = VT100Backend::new(width, height);
+ let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal");
+ // Place viewport on the last line so history inserts scroll upward
+ let viewport = Rect::new(0, height - 1, width, 1);
+ term.set_viewport_area(viewport);
+
+ // Build a blockquote-like line: apply line-level green style and prefix "> "
+ let mut line: Line<'static> = Line::from(vec!["> ".into(), "Hello world".into()]);
+ line = line.style(Color::Green);
+ insert_history_lines(&mut term, vec![line])
+ .expect("Failed to insert history lines in test");
+
+ let mut saw_colored = false;
+ 'outer: for row in 0..height {
+ for col in 0..width {
+ if let Some(cell) = term.backend().vt100().screen().cell(row, col)
+ && cell.has_contents()
+ && cell.fgcolor() != vt100::Color::Default
+ {
+ saw_colored = true;
+ break 'outer;
+ }
+ }
+ }
+ assert!(
+ saw_colored,
+ "expected at least one colored cell in vt100 output"
+ );
+ }
+
+ #[test]
+ fn vt100_blockquote_wrap_preserves_color_on_all_wrapped_lines() {
+ // Force wrapping by using a narrow viewport width and a long blockquote line.
+ let width: u16 = 20;
+ let height: u16 = 8;
+ let backend = VT100Backend::new(width, height);
+ let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal");
+ // Viewport is the last line so history goes directly above it.
+ let viewport = Rect::new(0, height - 1, width, 1);
+ term.set_viewport_area(viewport);
+
+ // Create a long blockquote with a distinct prefix and enough text to wrap.
+ let mut line: Line<'static> = Line::from(vec![
+ "> ".into(),
+ "This is a long quoted line that should wrap".into(),
+ ]);
+ line = line.style(Color::Green);
+
+ insert_history_lines(&mut term, vec![line])
+ .expect("Failed to insert history lines in test");
+
+ // Parse and inspect the final screen buffer.
+ let screen = term.backend().vt100().screen();
+
+ // Collect rows that are non-empty; these should correspond to our wrapped lines.
+ let mut non_empty_rows: Vec<u16> = Vec::new();
+ for row in 0..height {
+ let mut any = false;
+ for col in 0..width {
+ if let Some(cell) = screen.cell(row, col)
+ && cell.has_contents()
+ && cell.contents() != "\0"
+ && cell.contents() != " "
+ {
+ any = true;
+ break;
+ }
+ }
+ if any {
+ non_empty_rows.push(row);
+ }
+ }
+
+ // Expect at least two rows due to wrapping.
+ assert!(
+ non_empty_rows.len() >= 2,
+ "expected wrapped output to span >=2 rows, got {non_empty_rows:?}",
+ );
+
+ // For each non-empty row, ensure all non-space cells are using a non-default fg color.
+ for row in non_empty_rows {
+ for col in 0..width {
+ if let Some(cell) = screen.cell(row, col) {
+ let contents = cell.contents();
+ if !contents.is_empty() && contents != " " {
+ assert!(
+ cell.fgcolor() != vt100::Color::Default,
+ "expected non-default fg on row {row} col {col}, got {:?}",
+ cell.fgcolor()
+ );
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn vt100_colored_prefix_then_plain_text_resets_color() {
+ let width: u16 = 40;
+ let height: u16 = 6;
+ let backend = VT100Backend::new(width, height);
+ let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal");
+ let viewport = Rect::new(0, height - 1, width, 1);
+ term.set_viewport_area(viewport);
+
+ // First span colored, rest plain.
+ let line: Line<'static> = Line::from(vec![
+ Span::styled("1. ", ratatui::style::Style::default().fg(Color::LightBlue)),
+ Span::raw("Hello world"),
+ ]);
+
+ insert_history_lines(&mut term, vec![line])
+ .expect("Failed to insert history lines in test");
+
+ let screen = term.backend().vt100().screen();
+
+ // Find the first non-empty row; verify first three cells are colored, following cells default.
+ 'rows: for row in 0..height {
+ let mut has_text = false;
+ for col in 0..width {
+ if let Some(cell) = screen.cell(row, col)
+ && cell.has_contents()
+ && cell.contents() != " "
+ {
+ has_text = true;
+ break;
+ }
+ }
+ if !has_text {
+ continue;
+ }
+
+ // Expect "1. Hello world" starting at col 0.
+ for col in 0..3 {
+ let cell = screen.cell(row, col).unwrap();
+ assert!(
+ cell.fgcolor() != vt100::Color::Default,
+ "expected colored prefix at col {col}, got {:?}",
+ cell.fgcolor()
+ );
+ }
+ for col in 3..(3 + "Hello world".len() as u16) {
+ let cell = screen.cell(row, col).unwrap();
+ assert_eq!(
+ cell.fgcolor(),
+ vt100::Color::Default,
+ "expected default color for plain text at col {col}, got {:?}",
+ cell.fgcolor()
+ );
+ }
+ break 'rows;
+ }
+ }
+
+ #[test]
+ fn vt100_deep_nested_mixed_list_third_level_marker_is_colored() {
+ // Markdown with five levels (ordered → unordered → ordered → unordered → unordered).
+ let md = "1. First\n - Second level\n 1. Third level (ordered)\n - Fourth level (bullet)\n - Fifth level to test indent consistency\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<Line<'static>> = text.lines.clone();
+
+ let width: u16 = 60;
+ let height: u16 = 12;
+ let backend = VT100Backend::new(width, height);
+ let mut term = crate::custom_terminal::Terminal::with_options(backend).expect("terminal");
+ let viewport = ratatui::layout::Rect::new(0, height - 1, width, 1);
+ term.set_viewport_area(viewport);
+
+ insert_history_lines(&mut term, lines).expect("Failed to insert history lines in test");
+
+ let screen = term.backend().vt100().screen();
+
+ // Reconstruct screen rows as strings to locate the 3rd level line.
+ let rows: Vec<String> = screen.rows(0, width).collect();
+
+ let needle = "1. Third level (ordered)";
+ let row_idx = rows
+ .iter()
+ .position(|r| r.contains(needle))
+ .unwrap_or_else(|| {
+ panic!("expected to find row containing {needle:?}, have rows: {rows:?}")
+ });
+ let col_start = rows[row_idx].find(needle).unwrap() as u16; // column where '1' starts
+
+ // Verify that the numeric marker ("1.") at the third level is colored
+ // (non-default fg) and the content after the following space resets to default.
+ for c in [col_start, col_start + 1] {
+ let cell = screen.cell(row_idx as u16, c).unwrap();
+ assert!(
+ cell.fgcolor() != vt100::Color::Default,
+ "expected colored 3rd-level marker at row {row_idx} col {c}, got {:?}",
+ cell.fgcolor()
+ );
+ }
+ let content_col = col_start + 3; // skip '1', '.', and the space
+ if let Some(cell) = screen.cell(row_idx as u16, content_col) {
+ assert_eq!(
+ cell.fgcolor(),
+ vt100::Color::Default,
+ "expected default color for 3rd-level content at row {row_idx} col {content_col}, got {:?}",
+ cell.fgcolor()
+ );
+ }
+ }
+}
diff --git a/codex-rs/tui2/src/key_hint.rs b/codex-rs/tui2/src/key_hint.rs
new file mode 100644
index 0000000000..f277f07384
--- /dev/null
+++ b/codex-rs/tui2/src/key_hint.rs
@@ -0,0 +1,112 @@
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use crossterm::event::KeyModifiers;
+use ratatui::style::Style;
+use ratatui::style::Stylize;
+use ratatui::text::Span;
+
+#[cfg(test)]
+const ALT_PREFIX: &str = "⌥ + ";
+#[cfg(all(not(test), target_os = "macos"))]
+const ALT_PREFIX: &str = "⌥ + ";
+#[cfg(all(not(test), not(target_os = "macos")))]
+const ALT_PREFIX: &str = "alt + ";
+const CTRL_PREFIX: &str = "ctrl + ";
+const SHIFT_PREFIX: &str = "shift + ";
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) struct KeyBinding {
+ key: KeyCode,
+ modifiers: KeyModifiers,
+}
+
+impl KeyBinding {
+ pub(crate) const fn new(key: KeyCode, modifiers: KeyModifiers) -> Self {
+ Self { key, modifiers }
+ }
+
+ pub fn is_press(&self, event: KeyEvent) -> bool {
+ self.key == event.code
+ && self.modifiers == event.modifiers
+ && (event.kind == KeyEventKind::Press || event.kind == KeyEventKind::Repeat)
+ }
+}
+
+pub(crate) const fn plain(key: KeyCode) -> KeyBinding {
+ KeyBinding::new(key, KeyModifiers::NONE)
+}
+
+pub(crate) const fn alt(key: KeyCode) -> KeyBinding {
+ KeyBinding::new(key, KeyModifiers::ALT)
+}
+
+pub(crate) const fn shift(key: KeyCode) -> KeyBinding {
+ KeyBinding::new(key, KeyModifiers::SHIFT)
+}
+
+pub(crate) const fn ctrl(key: KeyCode) -> KeyBinding {
+ KeyBinding::new(key, KeyModifiers::CONTROL)
+}
+
+pub(crate) const fn ctrl_alt(key: KeyCode) -> KeyBinding {
+ KeyBinding::new(key, KeyModifiers::CONTROL.union(KeyModifiers::ALT))
+}
+
+fn modifiers_to_string(modifiers: KeyModifiers) -> String {
+ let mut result = String::new();
+ if modifiers.contains(KeyModifiers::CONTROL) {
+ result.push_str(CTRL_PREFIX);
+ }
+ if modifiers.contains(KeyModifiers::SHIFT) {
+ result.push_str(SHIFT_PREFIX);
+ }
+ if modifiers.contains(KeyModifiers::ALT) {
+ result.push_str(ALT_PREFIX);
+ }
+ result
+}
+
+impl From<KeyBinding> for Span<'static> {
+ fn from(binding: KeyBinding) -> Self {
+ (&binding).into()
+ }
+}
+impl From<&KeyBinding> for Span<'static> {
+ fn from(binding: &KeyBinding) -> Self {
+ let KeyBinding { key, modifiers } = binding;
+ let modifiers = modifiers_to_string(*modifiers);
+ let key = match key {
+ KeyCode::Enter => "enter".to_string(),
+ KeyCode::Char(' ') => "space".to_string(),
+ KeyCode::Up => "↑".to_string(),
+ KeyCode::Down => "↓".to_string(),
+ KeyCode::Left => "←".to_string(),
+ KeyCode::Right => "→".to_string(),
+ KeyCode::PageUp => "pgup".to_string(),
+ KeyCode::PageDown => "pgdn".to_string(),
+ _ => format!("{key}").to_ascii_lowercase(),
+ };
+ Span::styled(format!("{modifiers}{key}"), key_hint_style())
+ }
+}
+
+fn key_hint_style() -> Style {
+ Style::default().dim()
+}
+
+pub(crate) fn has_ctrl_or_alt(mods: KeyModifiers) -> bool {
+ (mods.contains(KeyModifiers::CONTROL) || mods.contains(KeyModifiers::ALT)) && !is_altgr(mods)
+}
+
+#[cfg(windows)]
+#[inline]
+pub(crate) fn is_altgr(mods: KeyModifiers) -> bool {
+ mods.contains(KeyModifiers::ALT) && mods.contains(KeyModifiers::CONTROL)
+}
+
+#[cfg(not(windows))]
+#[inline]
+pub(crate) fn is_altgr(_mods: KeyModifiers) -> bool {
+ false
+}
diff --git a/codex-rs/tui2/src/lib.rs b/codex-rs/tui2/src/lib.rs
index 502efa76a0..d9793a07a0 100644
--- a/codex-rs/tui2/src/lib.rs
+++ b/codex-rs/tui2/src/lib.rs
@@ -1,24 +1,691 @@
+// Forbid accidental stdout/stderr writes in the *library* portion of the TUI.
+// The standalone `codex-tui` binary prints a short help message before the
+// alternate‑screen mode starts; that file opts‑out locally via `allow`.
#![deny(clippy::print_stdout, clippy::print_stderr)]
#![deny(clippy::disallowed_methods)]
-
+use additional_dirs::add_dir_warning_message;
+use app::App;
+pub use app::AppExitInfo;
+use codex_app_server_protocol::AuthMode;
+use codex_common::oss::ensure_oss_provider_ready;
+use codex_common::oss::get_default_model_for_oss_provider;
+use codex_core::AuthManager;
+use codex_core::CodexAuth;
+use codex_core::INTERACTIVE_SESSION_SOURCES;
+use codex_core::RolloutRecorder;
+use codex_core::auth::enforce_login_restrictions;
+use codex_core::config::Config;
+use codex_core::config::ConfigOverrides;
+use codex_core::config::find_codex_home;
+use codex_core::config::load_config_as_toml_with_cli_overrides;
+use codex_core::config::resolve_oss_provider;
+use codex_core::find_conversation_path_by_id_str;
+use codex_core::get_platform_sandbox;
+use codex_core::protocol::AskForApproval;
+use codex_protocol::config_types::SandboxMode;
+use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
+use std::fs::OpenOptions;
use std::path::PathBuf;
+use tracing::error;
+use tracing_appender::non_blocking;
+use tracing_subscriber::EnvFilter;
+use tracing_subscriber::filter::Targets;
+use tracing_subscriber::prelude::*;
+
+mod additional_dirs;
+mod app;
+mod app_backtrack;
+mod app_event;
+mod app_event_sender;
+mod ascii_animation;
+mod bottom_pane;
+mod chatwidget;
+mod cli;
+mod clipboard_paste;
+mod color;
+pub mod custom_terminal;
+mod diff_render;
+mod exec_cell;
+mod exec_command;
+mod file_search;
+mod frames;
+mod get_git_diff;
+mod history_cell;
+pub mod insert_history;
+mod key_hint;
+pub mod live_wrap;
+mod markdown;
+mod markdown_render;
+mod markdown_stream;
+mod model_migration;
+pub mod onboarding;
+mod oss_selection;
+mod pager_overlay;
+pub mod public_widgets;
+mod render;
+mod resume_picker;
+mod selection_list;
+mod session_log;
+mod shimmer;
+mod skill_error_prompt;
+mod slash_command;
+mod status;
+mod status_indicator_widget;
+mod streaming;
+mod style;
+mod terminal_palette;
+mod text_formatting;
+mod tooltips;
+mod tui;
+mod ui_consts;
+pub mod update_action;
+mod update_prompt;
+mod updates;
+mod version;
+
+mod wrapping;
-pub use codex_tui::AppExitInfo;
-pub use codex_tui::Cli;
-pub use codex_tui::update_action;
+#[cfg(test)]
+pub mod test_backend;
+
+use crate::onboarding::TrustDirectorySelection;
+use crate::onboarding::onboarding_screen::OnboardingScreenArgs;
+use crate::onboarding::onboarding_screen::run_onboarding_app;
+use crate::tui::Tui;
+pub use cli::Cli;
+pub use markdown_render::render_markdown_text;
+pub use public_widgets::composer_input::ComposerAction;
+pub use public_widgets::composer_input::ComposerInput;
+use std::io::Write as _;
+
+// (tests access modules directly within the crate)
-/// Entry point for the experimental TUI v2 crate.
-///
-/// Currently this is a thin shim that delegates to the existing `codex-tui`
-/// implementation so behavior and rendering remain identical while the new
-/// viewport is developed behind a feature toggle.
pub async fn run_main(
- cli: Cli,
+ mut cli: Cli,
codex_linux_sandbox_exe: Option<PathBuf>,
) -> std::io::Result<AppExitInfo> {
- #[allow(clippy::print_stdout)] // for now
+ let (sandbox_mode, approval_policy) = if cli.full_auto {
+ (
+ Some(SandboxMode::WorkspaceWrite),
+ Some(AskForApproval::OnRequest),
+ )
+ } else if cli.dangerously_bypass_approvals_and_sandbox {
+ (
+ Some(SandboxMode::DangerFullAccess),
+ Some(AskForApproval::Never),
+ )
+ } else {
+ (
+ cli.sandbox_mode.map(Into::<SandboxMode>::into),
+ cli.approval_policy.map(Into::into),
+ )
+ };
+
+ // Map the legacy --search flag to the new feature toggle.
+ if cli.web_search {
+ cli.config_overrides
+ .raw_overrides
+ .push("features.web_search_request=true".to_string());
+ }
+
+ // When using `--oss`, let the bootstrapper pick the model (defaulting to
+ // gpt-oss:20b) and ensure it is present locally. Also, force the built‑in
+ let raw_overrides = cli.config_overrides.raw_overrides.clone();
+ // `oss` model provider.
+ let overrides_cli = codex_common::CliConfigOverrides { raw_overrides };
+ let cli_kv_overrides = match overrides_cli.parse_overrides() {
+ // Parse `-c` overrides from the CLI.
+ Ok(v) => v,
+ #[allow(clippy::print_stderr)]
+ Err(e) => {
+ eprintln!("Error parsing -c overrides: {e}");
+ std::process::exit(1);
+ }
+ };
+
+ // we load config.toml here to determine project state.
+ #[allow(clippy::print_stderr)]
+ let codex_home = match find_codex_home() {
+ Ok(codex_home) => codex_home.to_path_buf(),
+ Err(err) => {
+ eprintln!("Error finding codex home: {err}");
+ std::process::exit(1);
+ }
+ };
+
+ #[allow(clippy::print_stderr)]
+ let config_toml =
+ match load_config_as_toml_with_cli_overrides(&codex_home, cli_kv_overrides.clone()).await {
+ Ok(config_toml) => config_toml,
+ Err(err) => {
+ eprintln!("Error loading config.toml: {err}");
+ std::process::exit(1);
+ }
+ };
+
+ let model_provider_override = if cli.oss {
+ let resolved = resolve_oss_provider(
+ cli.oss_provider.as_deref(),
+ &config_toml,
+ cli.config_profile.clone(),
+ );
+
+ if let Some(provider) = resolved {
+ Some(provider)
+ } else {
+ // No provider configured, prompt the user
+ let provider = oss_selection::select_oss_provider(&codex_home).await?;
+ if provider == "__CANCELLED__" {
+ return Err(std::io::Error::other(
+ "OSS provider selection was cancelled by user",
+ ));
+ }
+ Some(provider)
+ }
+ } else {
+ None
+ };
+
+ // When using `--oss`, let the bootstrapper pick the model based on selected provider
+ let model = if let Some(model) = &cli.model {
+ Some(model.clone())
+ } else if cli.oss {
+ // Use the provider from model_provider_override
+ model_provider_override
+ .as_ref()
+ .and_then(|provider_id| get_default_model_for_oss_provider(provider_id))
+ .map(std::borrow::ToOwned::to_owned)
+ } else {
+ None // No model specified, will use the default.
+ };
+
+ // canonicalize the cwd
+ let cwd = cli.cwd.clone().map(|p| p.canonicalize().unwrap_or(p));
+ let additional_dirs = cli.add_dir.clone();
+
+ let overrides = ConfigOverrides {
+ model,
+ review_model: None,
+ approval_policy,
+ sandbox_mode,
+ cwd,
+ model_provider: model_provider_override.clone(),
+ config_profile: cli.config_profile.clone(),
+ codex_linux_sandbox_exe,
+ base_instructions: None,
+ developer_instructions: None,
+ compact_prompt: None,
+ include_apply_patch_tool: None,
+ show_raw_agent_reasoning: cli.oss.then_some(true),
+ tools_web_search_request: None,
+ additional_writable_roots: additional_dirs,
+ };
+
+ let config = load_config_or_exit(cli_kv_overrides.clone(), overrides.clone()).await;
+
+ if let Some(warning) = add_dir_warning_message(&cli.add_dir, &config.sandbox_policy) {
+ #[allow(clippy::print_stderr)]
+ {
+ eprintln!("Error adding directories: {warning}");
+ std::process::exit(1);
+ }
+ }
+
+ #[allow(clippy::print_stderr)]
+ if let Err(err) = enforce_login_restrictions(&config).await {
+ eprintln!("{err}");
+ std::process::exit(1);
+ }
+
+ let active_profile = config.active_profile.clone();
+ let log_dir = codex_core::config::log_dir(&config)?;
+ std::fs::create_dir_all(&log_dir)?;
+ // Open (or create) your log file, appending to it.
+ let mut log_file_opts = OpenOptions::new();
+ log_file_opts.create(true).append(true);
+
+ // Ensure the file is only readable and writable by the current user.
+ // Doing the equivalent to `chmod 600` on Windows is quite a bit more code
+ // and requires the Windows API crates, so we can reconsider that when
+ // Codex CLI is officially supported on Windows.
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ log_file_opts.mode(0o600);
+ }
+
+ let log_file = log_file_opts.open(log_dir.join("codex-tui.log"))?;
+
+ // Wrap file in non‑blocking writer.
+ let (non_blocking, _guard) = non_blocking(log_file);
+
+ // use RUST_LOG env var, default to info for codex crates.
+ let env_filter = || {
+ EnvFilter::try_from_default_env().unwrap_or_else(|_| {
+ EnvFilter::new("codex_core=info,codex_tui=info,codex_rmcp_client=info")
+ })
+ };
+
+ let file_layer = tracing_subscriber::fmt::layer()
+ .with_writer(non_blocking)
+ .with_target(false)
+ .with_span_events(tracing_subscriber::fmt::format::FmtSpan::CLOSE)
+ .with_filter(env_filter());
+
+ let feedback = codex_feedback::CodexFeedback::new();
+ let targets = Targets::new().with_default(tracing::Level::TRACE);
+
+ let feedback_layer = tracing_subscriber::fmt::layer()
+ .with_writer(feedback.make_writer())
+ .with_ansi(false)
+ .with_target(false)
+ .with_filter(targets);
+
+ if cli.oss && model_provider_override.is_some() {
+ // We're in the oss section, so provider_id should be Some
+ // Let's handle None case gracefully though just in case
+ let provider_id = match model_provider_override.as_ref() {
+ Some(id) => id,
+ None => {
+ error!("OSS provider unexpectedly not set when oss flag is used");
+ return Err(std::io::Error::other(
+ "OSS provider not set but oss flag was used",
+ ));
+ }
+ };
+ ensure_oss_provider_ready(provider_id, &config).await?;
+ }
+
+ let otel = codex_core::otel_init::build_provider(&config, env!("CARGO_PKG_VERSION"));
+
+ #[allow(clippy::print_stderr)]
+ let otel = match otel {
+ Ok(otel) => otel,
+ Err(e) => {
+ eprintln!("Could not create otel exporter: {e}");
+ std::process::exit(1);
+ }
+ };
+
+ if let Some(provider) = otel.as_ref() {
+ let otel_layer = OpenTelemetryTracingBridge::new(&provider.logger).with_filter(
+ tracing_subscriber::filter::filter_fn(codex_core::otel_init::codex_export_filter),
+ );
+
+ let _ = tracing_subscriber::registry()
+ .with(file_layer)
+ .with(feedback_layer)
+ .with(otel_layer)
+ .try_init();
+ } else {
+ let _ = tracing_subscriber::registry()
+ .with(file_layer)
+ .with(feedback_layer)
+ .try_init();
+ };
+
+ run_ratatui_app(
+ cli,
+ config,
+ overrides,
+ cli_kv_overrides,
+ active_profile,
+ feedback,
+ )
+ .await
+ .map_err(|err| std::io::Error::other(err.to_string()))
+}
+
+async fn run_ratatui_app(
+ cli: Cli,
+ initial_config: Config,
+ overrides: ConfigOverrides,
+ cli_kv_overrides: Vec<(String, toml::Value)>,
+ active_profile: Option<String>,
+ feedback: codex_feedback::CodexFeedback,
+) -> color_eyre::Result<AppExitInfo> {
+ color_eyre::install()?;
+
+ // Forward panic reports through tracing so they appear in the UI status
+ // line, but do not swallow the default/color-eyre panic handler.
+ // Chain to the previous hook so users still get a rich panic report
+ // (including backtraces) after we restore the terminal.
+ let prev_hook = std::panic::take_hook();
+ std::panic::set_hook(Box::new(move |info| {
+ tracing::error!("panic: {info}");
+ prev_hook(info);
+ }));
+ let mut terminal = tui::init()?;
+ terminal.clear()?;
+
+ let mut tui = Tui::new(terminal);
+
+ #[cfg(not(debug_assertions))]
{
- println!("Note: You are running the experimental TUI v2 implementation.");
+ use crate::update_prompt::UpdatePromptOutcome;
+
+ let skip_update_prompt = cli.prompt.as_ref().is_some_and(|prompt| !prompt.is_empty());
+ if !skip_update_prompt {
+ match update_prompt::run_update_prompt_if_needed(&mut tui, &initial_config).await? {
+ UpdatePromptOutcome::Continue => {}
+ UpdatePromptOutcome::RunUpdate(action) => {
+ crate::tui::restore()?;
+ return Ok(AppExitInfo {
+ token_usage: codex_core::protocol::TokenUsage::default(),
+ conversation_id: None,
+ update_action: Some(action),
+ });
+ }
+ }
+ }
+ }
+
+ // Initialize high-fidelity session event logging if enabled.
+ session_log::maybe_init(&initial_config);
+
+ let auth_manager = AuthManager::shared(
+ initial_config.codex_home.clone(),
+ false,
+ initial_config.cli_auth_credentials_store_mode,
+ );
+ let login_status = get_login_status(&initial_config);
+ let should_show_trust_screen = should_show_trust_screen(&initial_config);
+ let should_show_onboarding =
+ should_show_onboarding(login_status, &initial_config, should_show_trust_screen);
+
+ let config = if should_show_onboarding {
+ let onboarding_result = run_onboarding_app(
+ OnboardingScreenArgs {
+ show_login_screen: should_show_login_screen(login_status, &initial_config),
+ show_trust_screen: should_show_trust_screen,
+ login_status,
+ auth_manager: auth_manager.clone(),
+ config: initial_config.clone(),
+ },
+ &mut tui,
+ )
+ .await?;
+ if onboarding_result.should_exit {
+ restore();
+ session_log::log_session_end();
+ let _ = tui.terminal.clear();
+ return Ok(AppExitInfo {
+ token_usage: codex_core::protocol::TokenUsage::default(),
+ conversation_id: None,
+ update_action: None,
+ });
+ }
+ // if the user acknowledged windows or made an explicit decision ato trust the directory, reload the config accordingly
+ if onboarding_result
+ .directory_trust_decision
+ .map(|d| d == TrustDirectorySelection::Trust)
+ .unwrap_or(false)
+ {
+ load_config_or_exit(cli_kv_overrides, overrides).await
+ } else {
+ initial_config
+ }
+ } else {
+ initial_config
+ };
+
+ // Determine resume behavior: explicit id, then resume last, then picker.
+ let resume_selection = if let Some(id_str) = cli.resume_session_id.as_deref() {
+ match find_conversation_path_by_id_str(&config.codex_home, id_str).await? {
+ Some(path) => resume_picker::ResumeSelection::Resume(path),
+ None => {
+ error!("Error finding conversation path: {id_str}");
+ restore();
+ session_log::log_session_end();
+ let _ = tui.terminal.clear();
+ if let Err(err) = writeln!(
+ std::io::stdout(),
+ "No saved session found with ID {id_str}. Run `codex resume` without an ID to choose from existing sessions."
+ ) {
+ error!("Failed to write resume error message: {err}");
+ }
+ return Ok(AppExitInfo {
+ token_usage: codex_core::protocol::TokenUsage::default(),
+ conversation_id: None,
+ update_action: None,
+ });
+ }
+ }
+ } else if cli.resume_last {
+ let provider_filter = vec![config.model_provider_id.clone()];
+ match RolloutRecorder::list_conversations(
+ &config.codex_home,
+ 1,
+ None,
+ INTERACTIVE_SESSION_SOURCES,
+ Some(provider_filter.as_slice()),
+ &config.model_provider_id,
+ )
+ .await
+ {
+ Ok(page) => page
+ .items
+ .first()
+ .map(|it| resume_picker::ResumeSelection::Resume(it.path.clone()))
+ .unwrap_or(resume_picker::ResumeSelection::StartFresh),
+ Err(_) => resume_picker::ResumeSelection::StartFresh,
+ }
+ } else if cli.resume_picker {
+ match resume_picker::run_resume_picker(
+ &mut tui,
+ &config.codex_home,
+ &config.model_provider_id,
+ cli.resume_show_all,
+ )
+ .await?
+ {
+ resume_picker::ResumeSelection::Exit => {
+ restore();
+ session_log::log_session_end();
+ return Ok(AppExitInfo {
+ token_usage: codex_core::protocol::TokenUsage::default(),
+ conversation_id: None,
+ update_action: None,
+ });
+ }
+ other => other,
+ }
+ } else {
+ resume_picker::ResumeSelection::StartFresh
+ };
+
+ let Cli { prompt, images, .. } = cli;
+
+ let app_result = App::run(
+ &mut tui,
+ auth_manager,
+ config,
+ active_profile,
+ prompt,
+ images,
+ resume_selection,
+ feedback,
+ should_show_trust_screen, // Proxy to: is it a first run in this directory?
+ )
+ .await;
+
+ restore();
+ // Mark the end of the recorded session.
+ session_log::log_session_end();
+ // ignore error when collecting usage – report underlying error instead
+ app_result
+}
+
+#[expect(
+ clippy::print_stderr,
+ reason = "TUI should no longer be displayed, so we can write to stderr."
+)]
+fn restore() {
+ if let Err(err) = tui::restore() {
+ eprintln!(
+ "failed to restore terminal. Run `reset` or restart your terminal to recover: {err}"
+ );
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LoginStatus {
+ AuthMode(AuthMode),
+ NotAuthenticated,
+}
+
+fn get_login_status(config: &Config) -> LoginStatus {
+ if config.model_provider.requires_openai_auth {
+ // Reading the OpenAI API key is an async operation because it may need
+ // to refresh the token. Block on it.
+ let codex_home = config.codex_home.clone();
+ match CodexAuth::from_auth_storage(&codex_home, config.cli_auth_credentials_store_mode) {
+ Ok(Some(auth)) => LoginStatus::AuthMode(auth.mode),
+ Ok(None) => LoginStatus::NotAuthenticated,
+ Err(err) => {
+ error!("Failed to read auth.json: {err}");
+ LoginStatus::NotAuthenticated
+ }
+ }
+ } else {
+ LoginStatus::NotAuthenticated
+ }
+}
+
+async fn load_config_or_exit(
+ cli_kv_overrides: Vec<(String, toml::Value)>,
+ overrides: ConfigOverrides,
+) -> Config {
+ #[allow(clippy::print_stderr)]
+ match Config::load_with_cli_overrides(cli_kv_overrides, overrides).await {
+ Ok(config) => config,
+ Err(err) => {
+ eprintln!("Error loading configuration: {err}");
+ std::process::exit(1);
+ }
+ }
+}
+
+/// Determine if user has configured a sandbox / approval policy,
+/// or if the current cwd project is already trusted. If not, we need to
+/// show the trust screen.
+fn should_show_trust_screen(config: &Config) -> bool {
+ if cfg!(target_os = "windows") && get_platform_sandbox().is_none() {
+ // If the experimental sandbox is not enabled, Native Windows cannot enforce sandboxed write access; skip the trust prompt entirely.
+ return false;
+ }
+ if config.did_user_set_custom_approval_policy_or_sandbox_mode {
+ // Respect explicit approval/sandbox overrides made by the user.
+ return false;
+ }
+ // otherwise, show only if no trust decision has been made
+ config.active_project.trust_level.is_none()
+}
+
+fn should_show_onboarding(
+ login_status: LoginStatus,
+ config: &Config,
+ show_trust_screen: bool,
+) -> bool {
+ if show_trust_screen {
+ return true;
+ }
+
+ should_show_login_screen(login_status, config)
+}
+
+fn should_show_login_screen(login_status: LoginStatus, config: &Config) -> bool {
+ // Only show the login screen for providers that actually require OpenAI auth
+ // (OpenAI or equivalents). For OSS/other providers, skip login entirely.
+ if !config.model_provider.requires_openai_auth {
+ return false;
+ }
+
+ login_status == LoginStatus::NotAuthenticated
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use codex_core::config::ConfigOverrides;
+ use codex_core::config::ConfigToml;
+ use codex_core::config::ProjectConfig;
+ use serial_test::serial;
+ use tempfile::TempDir;
+
+ #[test]
+ #[serial]
+ fn windows_skips_trust_prompt_without_sandbox() -> std::io::Result<()> {
+ let temp_dir = TempDir::new()?;
+ let mut config = Config::load_from_base_config_with_overrides(
+ ConfigToml::default(),
+ ConfigOverrides::default(),
+ temp_dir.path().to_path_buf(),
+ )?;
+ config.did_user_set_custom_approval_policy_or_sandbox_mode = false;
+ config.active_project = ProjectConfig { trust_level: None };
+ config.set_windows_sandbox_globally(false);
+
+ let should_show = should_show_trust_screen(&config);
+ if cfg!(target_os = "windows") {
+ assert!(
+ !should_show,
+ "Windows trust prompt should always be skipped on native Windows"
+ );
+ } else {
+ assert!(
+ should_show,
+ "Non-Windows should still show trust prompt when project is untrusted"
+ );
+ }
+ Ok(())
+ }
+ #[test]
+ #[serial]
+ fn windows_shows_trust_prompt_with_sandbox() -> std::io::Result<()> {
+ let temp_dir = TempDir::new()?;
+ let mut config = Config::load_from_base_config_with_overrides(
+ ConfigToml::default(),
+ ConfigOverrides::default(),
+ temp_dir.path().to_path_buf(),
+ )?;
+ config.did_user_set_custom_approval_policy_or_sandbox_mode = false;
+ config.active_project = ProjectConfig { trust_level: None };
+ config.set_windows_sandbox_globally(true);
+
+ let should_show = should_show_trust_screen(&config);
+ if cfg!(target_os = "windows") {
+ assert!(
+ should_show,
+ "Windows trust prompt should be shown on native Windows with sandbox enabled"
+ );
+ } else {
+ assert!(
+ should_show,
+ "Non-Windows should still show trust prompt when project is untrusted"
+ );
+ }
+ Ok(())
+ }
+ #[test]
+ fn untrusted_project_skips_trust_prompt() -> std::io::Result<()> {
+ use codex_protocol::config_types::TrustLevel;
+ let temp_dir = TempDir::new()?;
+ let mut config = Config::load_from_base_config_with_overrides(
+ ConfigToml::default(),
+ ConfigOverrides::default(),
+ temp_dir.path().to_path_buf(),
+ )?;
+ config.did_user_set_custom_approval_policy_or_sandbox_mode = false;
+ config.active_project = ProjectConfig {
+ trust_level: Some(TrustLevel::Untrusted),
+ };
+
+ let should_show = should_show_trust_screen(&config);
+ assert!(
+ !should_show,
+ "Trust prompt should not be shown for projects explicitly marked as untrusted"
+ );
+ Ok(())
}
- codex_tui::run_main(cli, codex_linux_sandbox_exe).await
}
diff --git a/codex-rs/tui2/src/live_wrap.rs b/codex-rs/tui2/src/live_wrap.rs
new file mode 100644
index 0000000000..e78710dc6c
--- /dev/null
+++ b/codex-rs/tui2/src/live_wrap.rs
@@ -0,0 +1,290 @@
+use unicode_width::UnicodeWidthChar;
+use unicode_width::UnicodeWidthStr;
+
+/// A single visual row produced by RowBuilder.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Row {
+ pub text: String,
+ /// True if this row ends with an explicit line break (as opposed to a hard wrap).
+ pub explicit_break: bool,
+}
+
+impl Row {
+ pub fn width(&self) -> usize {
+ self.text.width()
+ }
+}
+
+/// Incrementally wraps input text into visual rows of at most `width` cells.
+///
+/// Step 1: plain-text only. ANSI-carry and styled spans will be added later.
+pub struct RowBuilder {
+ target_width: usize,
+ /// Buffer for the current logical line (until a '\n' is seen).
+ current_line: String,
+ /// Output rows built so far for the current logical line and previous ones.
+ rows: Vec<Row>,
+}
+
+impl RowBuilder {
+ pub fn new(target_width: usize) -> Self {
+ Self {
+ target_width: target_width.max(1),
+ current_line: String::new(),
+ rows: Vec::new(),
+ }
+ }
+
+ pub fn width(&self) -> usize {
+ self.target_width
+ }
+
+ pub fn set_width(&mut self, width: usize) {
+ self.target_width = width.max(1);
+ // Rewrap everything we have (simple approach for Step 1).
+ let mut all = String::new();
+ for row in self.rows.drain(..) {
+ all.push_str(&row.text);
+ if row.explicit_break {
+ all.push('\n');
+ }
+ }
+ all.push_str(&self.current_line);
+ self.current_line.clear();
+ self.push_fragment(&all);
+ }
+
+ /// Push an input fragment. May contain newlines.
+ pub fn push_fragment(&mut self, fragment: &str) {
+ if fragment.is_empty() {
+ return;
+ }
+ let mut start = 0usize;
+ for (i, ch) in fragment.char_indices() {
+ if ch == '\n' {
+ // Flush anything pending before the newline.
+ if start < i {
+ self.current_line.push_str(&fragment[start..i]);
+ }
+ self.flush_current_line(true);
+ start = i + ch.len_utf8();
+ }
+ }
+ if start < fragment.len() {
+ self.current_line.push_str(&fragment[start..]);
+ self.wrap_current_line();
+ }
+ }
+
+ /// Mark the end of the current logical line (equivalent to pushing a '\n').
+ pub fn end_line(&mut self) {
+ self.flush_current_line(true);
+ }
+
+ /// Drain and return all produced rows.
+ pub fn drain_rows(&mut self) -> Vec<Row> {
+ std::mem::take(&mut self.rows)
+ }
+
+ /// Return a snapshot of produced rows (non-draining).
+ pub fn rows(&self) -> &[Row] {
+ &self.rows
+ }
+
+ /// Rows suitable for display, including the current partial line if any.
+ pub fn display_rows(&self) -> Vec<Row> {
+ let mut out = self.rows.clone();
+ if !self.current_line.is_empty() {
+ out.push(Row {
+ text: self.current_line.clone(),
+ explicit_break: false,
+ });
+ }
+ out
+ }
+
+ /// Drain the oldest rows that exceed `max_keep` display rows (including the
+ /// current partial line, if any). Returns the drained rows in order.
+ pub fn drain_commit_ready(&mut self, max_keep: usize) -> Vec<Row> {
+ let display_count = self.rows.len() + if self.current_line.is_empty() { 0 } else { 1 };
+ if display_count <= max_keep {
+ return Vec::new();
+ }
+ let to_commit = display_count - max_keep;
+ let commit_count = to_commit.min(self.rows.len());
+ let mut drained = Vec::with_capacity(commit_count);
+ for _ in 0..commit_count {
+ drained.push(self.rows.remove(0));
+ }
+ drained
+ }
+
+ fn flush_current_line(&mut self, explicit_break: bool) {
+ // Wrap any remaining content in the current line and then finalize with explicit_break.
+ self.wrap_current_line();
+ // If the current line ended exactly on a width boundary and is non-empty, represent
+ // the explicit break as an empty explicit row so that fragmentation invariance holds.
+ if explicit_break {
+ if self.current_line.is_empty() {
+ // We ended on a boundary previously; add an empty explicit row.
+ self.rows.push(Row {
+ text: String::new(),
+ explicit_break: true,
+ });
+ } else {
+ // There is leftover content that did not wrap yet; push it now with the explicit flag.
+ let mut s = String::new();
+ std::mem::swap(&mut s, &mut self.current_line);
+ self.rows.push(Row {
+ text: s,
+ explicit_break: true,
+ });
+ }
+ }
+ // Reset current line buffer for next logical line.
+ self.current_line.clear();
+ }
+
+ fn wrap_current_line(&mut self) {
+ // While the current_line exceeds width, cut a prefix.
+ loop {
+ if self.current_line.is_empty() {
+ break;
+ }
+ let (prefix, suffix, taken) =
+ take_prefix_by_width(&self.current_line, self.target_width);
+ if taken == 0 {
+ // Avoid infinite loop on pathological inputs; take one scalar and continue.
+ if let Some((i, ch)) = self.current_line.char_indices().next() {
+ let len = i + ch.len_utf8();
+ let p = self.current_line[..len].to_string();
+ self.rows.push(Row {
+ text: p,
+ explicit_break: false,
+ });
+ self.current_line = self.current_line[len..].to_string();
+ continue;
+ }
+ break;
+ }
+ if suffix.is_empty() {
+ // Fits entirely; keep in buffer (do not push yet) so we can append more later.
+ break;
+ } else {
+ // Emit wrapped prefix as a non-explicit row and continue with the remainder.
+ self.rows.push(Row {
+ text: prefix,
+ explicit_break: false,
+ });
+ self.current_line = suffix.to_string();
+ }
+ }
+ }
+}
+
+/// Take a prefix of `text` whose visible width is at most `max_cols`.
+/// Returns (prefix, suffix, prefix_width).
+pub fn take_prefix_by_width(text: &str, max_cols: usize) -> (String, &str, usize) {
+ if max_cols == 0 || text.is_empty() {
+ return (String::new(), text, 0);
+ }
+ let mut cols = 0usize;
+ let mut end_idx = 0usize;
+ for (i, ch) in text.char_indices() {
+ let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0);
+ if cols.saturating_add(ch_width) > max_cols {
+ break;
+ }
+ cols += ch_width;
+ end_idx = i + ch.len_utf8();
+ if cols == max_cols {
+ break;
+ }
+ }
+ let prefix = text[..end_idx].to_string();
+ let suffix = &text[end_idx..];
+ (prefix, suffix, cols)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use pretty_assertions::assert_eq;
+
+ #[test]
+ fn rows_do_not_exceed_width_ascii() {
+ let mut rb = RowBuilder::new(10);
+ rb.push_fragment("hello whirl this is a test");
+ let rows = rb.rows().to_vec();
+ assert_eq!(
+ rows,
+ vec![
+ Row {
+ text: "hello whir".to_string(),
+ explicit_break: false
+ },
+ Row {
+ text: "l this is ".to_string(),
+ explicit_break: false
+ }
+ ]
+ );
+ }
+
+ #[test]
+ fn rows_do_not_exceed_width_emoji_cjk() {
+ // 😀 is width 2; 你/好 are width 2.
+ let mut rb = RowBuilder::new(6);
+ rb.push_fragment("😀😀 你好");
+ let rows = rb.rows().to_vec();
+ // At width 6, we expect the first row to fit exactly two emojis and a space
+ // (2 + 2 + 1 = 5) plus one more column for the first CJK char (2 would overflow),
+ // so only the two emojis and the space fit; the rest remains buffered.
+ assert_eq!(
+ rows,
+ vec![Row {
+ text: "😀😀 ".to_string(),
+ explicit_break: false
+ }]
+ );
+ }
+
+ #[test]
+ fn fragmentation_invariance_long_token() {
+ let s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 26 chars
+ let mut rb_all = RowBuilder::new(7);
+ rb_all.push_fragment(s);
+ let all_rows = rb_all.rows().to_vec();
+
+ let mut rb_chunks = RowBuilder::new(7);
+ for i in (0..s.len()).step_by(3) {
+ let end = (i + 3).min(s.len());
+ rb_chunks.push_fragment(&s[i..end]);
+ }
+ let chunk_rows = rb_chunks.rows().to_vec();
+
+ assert_eq!(all_rows, chunk_rows);
+ }
+
+ #[test]
+ fn newline_splits_rows() {
+ let mut rb = RowBuilder::new(10);
+ rb.push_fragment("hello\nworld");
+ let rows = rb.display_rows();
+ assert!(rows.iter().any(|r| r.explicit_break));
+ assert_eq!(rows[0].text, "hello");
+ // Second row should begin with 'world'
+ assert!(rows.iter().any(|r| r.text.starts_with("world")));
+ }
+
+ #[test]
+ fn rewrap_on_width_change() {
+ let mut rb = RowBuilder::new(10);
+ rb.push_fragment("abcdefghijK");
+ assert!(!rb.rows().is_empty());
+ rb.set_width(5);
+ for r in rb.rows() {
+ assert!(r.width() <= 5);
+ }
+ }
+}
diff --git a/codex-rs/tui2/src/main.rs b/codex-rs/tui2/src/main.rs
index b50d994d80..f180c79336 100644
--- a/codex-rs/tui2/src/main.rs
+++ b/codex-rs/tui2/src/main.rs
@@ -1,7 +1,6 @@
use clap::Parser;
use codex_arg0::arg0_dispatch_or_else;
use codex_common::CliConfigOverrides;
-use codex_core::protocol::FinalOutput;
use codex_tui2::Cli;
use codex_tui2::run_main;
@@ -25,7 +24,7 @@ fn main() -> anyhow::Result<()> {
let exit_info = run_main(inner, codex_linux_sandbox_exe).await?;
let token_usage = exit_info.token_usage;
if !token_usage.is_zero() {
- println!("{}", FinalOutput::from(token_usage));
+ println!("{}", codex_core::protocol::FinalOutput::from(token_usage),);
}
Ok(())
})
diff --git a/codex-rs/tui2/src/markdown.rs b/codex-rs/tui2/src/markdown.rs
new file mode 100644
index 0000000000..2ea307066b
--- /dev/null
+++ b/codex-rs/tui2/src/markdown.rs
@@ -0,0 +1,105 @@
+use ratatui::text::Line;
+pub(crate) fn append_markdown(
+ markdown_source: &str,
+ width: Option<usize>,
+ lines: &mut Vec<Line<'static>>,
+) {
+ let rendered = crate::markdown_render::render_markdown_text_with_width(markdown_source, width);
+ crate::render::line_utils::push_owned_lines(&rendered.lines, lines);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use pretty_assertions::assert_eq;
+ use ratatui::text::Line;
+
+ fn lines_to_strings(lines: &[Line<'static>]) -> Vec<String> {
+ lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect()
+ }
+
+ #[test]
+ fn citations_render_as_plain_text() {
+ let src = "Before 【F:/x.rs†L1】\nAfter 【F:/x.rs†L3】\n";
+ let mut out = Vec::new();
+ append_markdown(src, None, &mut out);
+ let rendered = lines_to_strings(&out);
+ assert_eq!(
+ rendered,
+ vec![
+ "Before 【F:/x.rs†L1】".to_string(),
+ "After 【F:/x.rs†L3】".to_string()
+ ]
+ );
+ }
+
+ #[test]
+ fn indented_code_blocks_preserve_leading_whitespace() {
+ // Basic sanity: indented code with surrounding blank lines should produce the indented line.
+ let src = "Before\n\n code 1\n\nAfter\n";
+ let mut out = Vec::new();
+ append_markdown(src, None, &mut out);
+ let lines = lines_to_strings(&out);
+ assert_eq!(lines, vec!["Before", "", " code 1", "", "After"]);
+ }
+
+ #[test]
+ fn append_markdown_preserves_full_text_line() {
+ let src = "Hi! How can I help with codex-rs today? Want me to explore the repo, run tests, or work on a specific change?\n";
+ let mut out = Vec::new();
+ append_markdown(src, None, &mut out);
+ assert_eq!(
+ out.len(),
+ 1,
+ "expected a single rendered line for plain text"
+ );
+ let rendered: String = out
+ .iter()
+ .flat_map(|l| l.spans.iter())
+ .map(|s| s.content.clone())
+ .collect::<Vec<_>>()
+ .join("");
+ assert_eq!(
+ rendered,
+ "Hi! How can I help with codex-rs today? Want me to explore the repo, run tests, or work on a specific change?"
+ );
+ }
+
+ #[test]
+ fn append_markdown_matches_tui_markdown_for_ordered_item() {
+ let mut out = Vec::new();
+ append_markdown("1. Tight item\n", None, &mut out);
+ let lines = lines_to_strings(&out);
+ assert_eq!(lines, vec!["1. Tight item".to_string()]);
+ }
+
+ #[test]
+ fn append_markdown_keeps_ordered_list_line_unsplit_in_context() {
+ let src = "Loose vs. tight list items:\n1. Tight item\n";
+ let mut out = Vec::new();
+ append_markdown(src, None, &mut out);
+
+ let lines = lines_to_strings(&out);
+
+ // Expect to find the ordered list line rendered as a single line,
+ // not split into a marker-only line followed by the text.
+ assert!(
+ lines.iter().any(|s| s == "1. Tight item"),
+ "expected '1. Tight item' rendered as a single line; got: {lines:?}"
+ );
+ assert!(
+ !lines
+ .windows(2)
+ .any(|w| w[0].trim_end() == "1." && w[1] == "Tight item"),
+ "did not expect a split into ['1.', 'Tight item']; got: {lines:?}"
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/markdown_render.rs b/codex-rs/tui2/src/markdown_render.rs
new file mode 100644
index 0000000000..19cf944928
--- /dev/null
+++ b/codex-rs/tui2/src/markdown_render.rs
@@ -0,0 +1,678 @@
+use crate::render::line_utils::line_to_static;
+use crate::wrapping::RtOptions;
+use crate::wrapping::word_wrap_line;
+use pulldown_cmark::CodeBlockKind;
+use pulldown_cmark::CowStr;
+use pulldown_cmark::Event;
+use pulldown_cmark::HeadingLevel;
+use pulldown_cmark::Options;
+use pulldown_cmark::Parser;
+use pulldown_cmark::Tag;
+use pulldown_cmark::TagEnd;
+use ratatui::style::Style;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::text::Text;
+
+struct MarkdownStyles {
+ h1: Style,
+ h2: Style,
+ h3: Style,
+ h4: Style,
+ h5: Style,
+ h6: Style,
+ code: Style,
+ emphasis: Style,
+ strong: Style,
+ strikethrough: Style,
+ ordered_list_marker: Style,
+ unordered_list_marker: Style,
+ link: Style,
+ blockquote: Style,
+}
+
+impl Default for MarkdownStyles {
+ fn default() -> Self {
+ use ratatui::style::Stylize;
+
+ Self {
+ h1: Style::new().bold().underlined(),
+ h2: Style::new().bold(),
+ h3: Style::new().bold().italic(),
+ h4: Style::new().italic(),
+ h5: Style::new().italic(),
+ h6: Style::new().italic(),
+ code: Style::new().cyan(),
+ emphasis: Style::new().italic(),
+ strong: Style::new().bold(),
+ strikethrough: Style::new().crossed_out(),
+ ordered_list_marker: Style::new().light_blue(),
+ unordered_list_marker: Style::new(),
+ link: Style::new().cyan().underlined(),
+ blockquote: Style::new().green(),
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+struct IndentContext {
+ prefix: Vec<Span<'static>>,
+ marker: Option<Vec<Span<'static>>>,
+ is_list: bool,
+}
+
+impl IndentContext {
+ fn new(prefix: Vec<Span<'static>>, marker: Option<Vec<Span<'static>>>, is_list: bool) -> Self {
+ Self {
+ prefix,
+ marker,
+ is_list,
+ }
+ }
+}
+
+pub fn render_markdown_text(input: &str) -> Text<'static> {
+ render_markdown_text_with_width(input, None)
+}
+
+pub(crate) fn render_markdown_text_with_width(input: &str, width: Option<usize>) -> Text<'static> {
+ let mut options = Options::empty();
+ options.insert(Options::ENABLE_STRIKETHROUGH);
+ let parser = Parser::new_ext(input, options);
+ let mut w = Writer::new(parser, width);
+ w.run();
+ w.text
+}
+
+struct Writer<'a, I>
+where
+ I: Iterator<Item = Event<'a>>,
+{
+ iter: I,
+ text: Text<'static>,
+ styles: MarkdownStyles,
+ inline_styles: Vec<Style>,
+ indent_stack: Vec<IndentContext>,
+ list_indices: Vec<Option<u64>>,
+ link: Option<String>,
+ needs_newline: bool,
+ pending_marker_line: bool,
+ in_paragraph: bool,
+ in_code_block: bool,
+ wrap_width: Option<usize>,
+ current_line_content: Option<Line<'static>>,
+ current_initial_indent: Vec<Span<'static>>,
+ current_subsequent_indent: Vec<Span<'static>>,
+ current_line_style: Style,
+ current_line_in_code_block: bool,
+}
+
+impl<'a, I> Writer<'a, I>
+where
+ I: Iterator<Item = Event<'a>>,
+{
+ fn new(iter: I, wrap_width: Option<usize>) -> Self {
+ Self {
+ iter,
+ text: Text::default(),
+ styles: MarkdownStyles::default(),
+ inline_styles: Vec::new(),
+ indent_stack: Vec::new(),
+ list_indices: Vec::new(),
+ link: None,
+ needs_newline: false,
+ pending_marker_line: false,
+ in_paragraph: false,
+ in_code_block: false,
+ wrap_width,
+ current_line_content: None,
+ current_initial_indent: Vec::new(),
+ current_subsequent_indent: Vec::new(),
+ current_line_style: Style::default(),
+ current_line_in_code_block: false,
+ }
+ }
+
+ fn run(&mut self) {
+ while let Some(ev) = self.iter.next() {
+ self.handle_event(ev);
+ }
+ self.flush_current_line();
+ }
+
+ fn handle_event(&mut self, event: Event<'a>) {
+ match event {
+ Event::Start(tag) => self.start_tag(tag),
+ Event::End(tag) => self.end_tag(tag),
+ Event::Text(text) => self.text(text),
+ Event::Code(code) => self.code(code),
+ Event::SoftBreak => self.soft_break(),
+ Event::HardBreak => self.hard_break(),
+ Event::Rule => {
+ self.flush_current_line();
+ if !self.text.lines.is_empty() {
+ self.push_blank_line();
+ }
+ self.push_line(Line::from("———"));
+ self.needs_newline = true;
+ }
+ Event::Html(html) => self.html(html, false),
+ Event::InlineHtml(html) => self.html(html, true),
+ Event::FootnoteReference(_) => {}
+ Event::TaskListMarker(_) => {}
+ }
+ }
+
+ fn start_tag(&mut self, tag: Tag<'a>) {
+ match tag {
+ Tag::Paragraph => self.start_paragraph(),
+ Tag::Heading { level, .. } => self.start_heading(level),
+ Tag::BlockQuote => self.start_blockquote(),
+ Tag::CodeBlock(kind) => {
+ let indent = match kind {
+ CodeBlockKind::Fenced(_) => None,
+ CodeBlockKind::Indented => Some(Span::from(" ".repeat(4))),
+ };
+ let lang = match kind {
+ CodeBlockKind::Fenced(lang) => Some(lang.to_string()),
+ CodeBlockKind::Indented => None,
+ };
+ self.start_codeblock(lang, indent)
+ }
+ Tag::List(start) => self.start_list(start),
+ Tag::Item => self.start_item(),
+ Tag::Emphasis => self.push_inline_style(self.styles.emphasis),
+ Tag::Strong => self.push_inline_style(self.styles.strong),
+ Tag::Strikethrough => self.push_inline_style(self.styles.strikethrough),
+ Tag::Link { dest_url, .. } => self.push_link(dest_url.to_string()),
+ Tag::HtmlBlock
+ | Tag::FootnoteDefinition(_)
+ | Tag::Table(_)
+ | Tag::TableHead
+ | Tag::TableRow
+ | Tag::TableCell
+ | Tag::Image { .. }
+ | Tag::MetadataBlock(_) => {}
+ }
+ }
+
+ fn end_tag(&mut self, tag: TagEnd) {
+ match tag {
+ TagEnd::Paragraph => self.end_paragraph(),
+ TagEnd::Heading(_) => self.end_heading(),
+ TagEnd::BlockQuote => self.end_blockquote(),
+ TagEnd::CodeBlock => self.end_codeblock(),
+ TagEnd::List(_) => self.end_list(),
+ TagEnd::Item => {
+ self.indent_stack.pop();
+ self.pending_marker_line = false;
+ }
+ TagEnd::Emphasis | TagEnd::Strong | TagEnd::Strikethrough => self.pop_inline_style(),
+ TagEnd::Link => self.pop_link(),
+ TagEnd::HtmlBlock
+ | TagEnd::FootnoteDefinition
+ | TagEnd::Table
+ | TagEnd::TableHead
+ | TagEnd::TableRow
+ | TagEnd::TableCell
+ | TagEnd::Image
+ | TagEnd::MetadataBlock(_) => {}
+ }
+ }
+
+ fn start_paragraph(&mut self) {
+ if self.needs_newline {
+ self.push_blank_line();
+ }
+ self.push_line(Line::default());
+ self.needs_newline = false;
+ self.in_paragraph = true;
+ }
+
+ fn end_paragraph(&mut self) {
+ self.needs_newline = true;
+ self.in_paragraph = false;
+ self.pending_marker_line = false;
+ }
+
+ fn start_heading(&mut self, level: HeadingLevel) {
+ if self.needs_newline {
+ self.push_line(Line::default());
+ self.needs_newline = false;
+ }
+ let heading_style = match level {
+ HeadingLevel::H1 => self.styles.h1,
+ HeadingLevel::H2 => self.styles.h2,
+ HeadingLevel::H3 => self.styles.h3,
+ HeadingLevel::H4 => self.styles.h4,
+ HeadingLevel::H5 => self.styles.h5,
+ HeadingLevel::H6 => self.styles.h6,
+ };
+ let content = format!("{} ", "#".repeat(level as usize));
+ self.push_line(Line::from(vec![Span::styled(content, heading_style)]));
+ self.push_inline_style(heading_style);
+ self.needs_newline = false;
+ }
+
+ fn end_heading(&mut self) {
+ self.needs_newline = true;
+ self.pop_inline_style();
+ }
+
+ fn start_blockquote(&mut self) {
+ if self.needs_newline {
+ self.push_blank_line();
+ self.needs_newline = false;
+ }
+ self.indent_stack
+ .push(IndentContext::new(vec![Span::from("> ")], None, false));
+ }
+
+ fn end_blockquote(&mut self) {
+ self.indent_stack.pop();
+ self.needs_newline = true;
+ }
+
+ fn text(&mut self, text: CowStr<'a>) {
+ if self.pending_marker_line {
+ self.push_line(Line::default());
+ }
+ self.pending_marker_line = false;
+ if self.in_code_block && !self.needs_newline {
+ let has_content = self
+ .current_line_content
+ .as_ref()
+ .map(|line| !line.spans.is_empty())
+ .unwrap_or_else(|| {
+ self.text
+ .lines
+ .last()
+ .map(|line| !line.spans.is_empty())
+ .unwrap_or(false)
+ });
+ if has_content {
+ self.push_line(Line::default());
+ }
+ }
+ for (i, line) in text.lines().enumerate() {
+ if self.needs_newline {
+ self.push_line(Line::default());
+ self.needs_newline = false;
+ }
+ if i > 0 {
+ self.push_line(Line::default());
+ }
+ let content = line.to_string();
+ let span = Span::styled(
+ content,
+ self.inline_styles.last().copied().unwrap_or_default(),
+ );
+ self.push_span(span);
+ }
+ self.needs_newline = false;
+ }
+
+ fn code(&mut self, code: CowStr<'a>) {
+ if self.pending_marker_line {
+ self.push_line(Line::default());
+ self.pending_marker_line = false;
+ }
+ let span = Span::from(code.into_string()).style(self.styles.code);
+ self.push_span(span);
+ }
+
+ fn html(&mut self, html: CowStr<'a>, inline: bool) {
+ self.pending_marker_line = false;
+ for (i, line) in html.lines().enumerate() {
+ if self.needs_newline {
+ self.push_line(Line::default());
+ self.needs_newline = false;
+ }
+ if i > 0 {
+ self.push_line(Line::default());
+ }
+ let style = self.inline_styles.last().copied().unwrap_or_default();
+ self.push_span(Span::styled(line.to_string(), style));
+ }
+ self.needs_newline = !inline;
+ }
+
+ fn hard_break(&mut self) {
+ self.push_line(Line::default());
+ }
+
+ fn soft_break(&mut self) {
+ self.push_line(Line::default());
+ }
+
+ fn start_list(&mut self, index: Option<u64>) {
+ if self.list_indices.is_empty() && self.needs_newline {
+ self.push_line(Line::default());
+ }
+ self.list_indices.push(index);
+ }
+
+ fn end_list(&mut self) {
+ self.list_indices.pop();
+ self.needs_newline = true;
+ }
+
+ fn start_item(&mut self) {
+ self.pending_marker_line = true;
+ let depth = self.list_indices.len();
+ let is_ordered = self
+ .list_indices
+ .last()
+ .map(Option::is_some)
+ .unwrap_or(false);
+ let width = depth * 4 - 3;
+ let marker = if let Some(last_index) = self.list_indices.last_mut() {
+ match last_index {
+ None => Some(vec![Span::styled(
+ " ".repeat(width - 1) + "- ",
+ self.styles.unordered_list_marker,
+ )]),
+ Some(index) => {
+ *index += 1;
+ Some(vec![Span::styled(
+ format!("{:width$}. ", *index - 1),
+ self.styles.ordered_list_marker,
+ )])
+ }
+ }
+ } else {
+ None
+ };
+ let indent_prefix = if depth == 0 {
+ Vec::new()
+ } else {
+ let indent_len = if is_ordered { width + 2 } else { width + 1 };
+ vec![Span::from(" ".repeat(indent_len))]
+ };
+ self.indent_stack
+ .push(IndentContext::new(indent_prefix, marker, true));
+ self.needs_newline = false;
+ }
+
+ fn start_codeblock(&mut self, _lang: Option<String>, indent: Option<Span<'static>>) {
+ self.flush_current_line();
+ if !self.text.lines.is_empty() {
+ self.push_blank_line();
+ }
+ self.in_code_block = true;
+ self.indent_stack.push(IndentContext::new(
+ vec![indent.unwrap_or_default()],
+ None,
+ false,
+ ));
+ self.needs_newline = true;
+ }
+
+ fn end_codeblock(&mut self) {
+ self.needs_newline = true;
+ self.in_code_block = false;
+ self.indent_stack.pop();
+ }
+
+ fn push_inline_style(&mut self, style: Style) {
+ let current = self.inline_styles.last().copied().unwrap_or_default();
+ let merged = current.patch(style);
+ self.inline_styles.push(merged);
+ }
+
+ fn pop_inline_style(&mut self) {
+ self.inline_styles.pop();
+ }
+
+ fn push_link(&mut self, dest_url: String) {
+ self.link = Some(dest_url);
+ }
+
+ fn pop_link(&mut self) {
+ if let Some(link) = self.link.take() {
+ self.push_span(" (".into());
+ self.push_span(Span::styled(link, self.styles.link));
+ self.push_span(")".into());
+ }
+ }
+
+ fn flush_current_line(&mut self) {
+ if let Some(line) = self.current_line_content.take() {
+ let style = self.current_line_style;
+ // NB we don't wrap code in code blocks, in order to preserve whitespace for copy/paste.
+ if !self.current_line_in_code_block
+ && let Some(width) = self.wrap_width
+ {
+ let opts = RtOptions::new(width)
+ .initial_indent(self.current_initial_indent.clone().into())
+ .subsequent_indent(self.current_subsequent_indent.clone().into());
+ for wrapped in word_wrap_line(&line, opts) {
+ let owned = line_to_static(&wrapped).style(style);
+ self.text.lines.push(owned);
+ }
+ } else {
+ let mut spans = self.current_initial_indent.clone();
+ let mut line = line;
+ spans.append(&mut line.spans);
+ self.text.lines.push(Line::from_iter(spans).style(style));
+ }
+ self.current_initial_indent.clear();
+ self.current_subsequent_indent.clear();
+ self.current_line_in_code_block = false;
+ }
+ }
+
+ fn push_line(&mut self, line: Line<'static>) {
+ self.flush_current_line();
+ let blockquote_active = self
+ .indent_stack
+ .iter()
+ .any(|ctx| ctx.prefix.iter().any(|s| s.content.contains('>')));
+ let style = if blockquote_active {
+ self.styles.blockquote
+ } else {
+ line.style
+ };
+ let was_pending = self.pending_marker_line;
+
+ self.current_initial_indent = self.prefix_spans(was_pending);
+ self.current_subsequent_indent = self.prefix_spans(false);
+ self.current_line_style = style;
+ self.current_line_content = Some(line);
+ self.current_line_in_code_block = self.in_code_block;
+
+ self.pending_marker_line = false;
+ }
+
+ fn push_span(&mut self, span: Span<'static>) {
+ if let Some(line) = self.current_line_content.as_mut() {
+ line.push_span(span);
+ } else {
+ self.push_line(Line::from(vec![span]));
+ }
+ }
+
+ fn push_blank_line(&mut self) {
+ self.flush_current_line();
+ if self.indent_stack.iter().all(|ctx| ctx.is_list) {
+ self.text.lines.push(Line::default());
+ } else {
+ self.push_line(Line::default());
+ self.flush_current_line();
+ }
+ }
+
+ fn prefix_spans(&self, pending_marker_line: bool) -> Vec<Span<'static>> {
+ let mut prefix: Vec<Span<'static>> = Vec::new();
+ let last_marker_index = if pending_marker_line {
+ self.indent_stack
+ .iter()
+ .enumerate()
+ .rev()
+ .find_map(|(i, ctx)| if ctx.marker.is_some() { Some(i) } else { None })
+ } else {
+ None
+ };
+ let last_list_index = self.indent_stack.iter().rposition(|ctx| ctx.is_list);
+
+ for (i, ctx) in self.indent_stack.iter().enumerate() {
+ if pending_marker_line {
+ if Some(i) == last_marker_index
+ && let Some(marker) = &ctx.marker
+ {
+ prefix.extend(marker.iter().cloned());
+ continue;
+ }
+ if ctx.is_list && last_marker_index.is_some_and(|idx| idx > i) {
+ continue;
+ }
+ } else if ctx.is_list && Some(i) != last_list_index {
+ continue;
+ }
+ prefix.extend(ctx.prefix.iter().cloned());
+ }
+
+ prefix
+ }
+}
+
+#[cfg(test)]
+mod markdown_render_tests {
+ include!("markdown_render_tests.rs");
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use pretty_assertions::assert_eq;
+ use ratatui::text::Text;
+
+ fn lines_to_strings(text: &Text<'_>) -> Vec<String> {
+ text.lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect()
+ }
+
+ #[test]
+ fn wraps_plain_text_when_width_provided() {
+ let markdown = "This is a simple sentence that should wrap.";
+ let rendered = render_markdown_text_with_width(markdown, Some(16));
+ let lines = lines_to_strings(&rendered);
+ assert_eq!(
+ lines,
+ vec![
+ "This is a simple".to_string(),
+ "sentence that".to_string(),
+ "should wrap.".to_string(),
+ ]
+ );
+ }
+
+ #[test]
+ fn wraps_list_items_preserving_indent() {
+ let markdown = "- first second third fourth";
+ let rendered = render_markdown_text_with_width(markdown, Some(14));
+ let lines = lines_to_strings(&rendered);
+ assert_eq!(
+ lines,
+ vec!["- first second".to_string(), " third fourth".to_string(),]
+ );
+ }
+
+ #[test]
+ fn wraps_nested_lists() {
+ let markdown =
+ "- outer item with several words to wrap\n - inner item that also needs wrapping";
+ let rendered = render_markdown_text_with_width(markdown, Some(20));
+ let lines = lines_to_strings(&rendered);
+ assert_eq!(
+ lines,
+ vec![
+ "- outer item with".to_string(),
+ " several words".to_string(),
+ " to wrap".to_string(),
+ " - inner item".to_string(),
+ " that also".to_string(),
+ " needs wrapping".to_string(),
+ ]
+ );
+ }
+
+ #[test]
+ fn wraps_ordered_lists() {
+ let markdown = "1. ordered item contains many words for wrapping";
+ let rendered = render_markdown_text_with_width(markdown, Some(18));
+ let lines = lines_to_strings(&rendered);
+ assert_eq!(
+ lines,
+ vec![
+ "1. ordered item".to_string(),
+ " contains many".to_string(),
+ " words for".to_string(),
+ " wrapping".to_string(),
+ ]
+ );
+ }
+
+ #[test]
+ fn wraps_blockquotes() {
+ let markdown = "> block quote with content that should wrap nicely";
+ let rendered = render_markdown_text_with_width(markdown, Some(22));
+ let lines = lines_to_strings(&rendered);
+ assert_eq!(
+ lines,
+ vec![
+ "> block quote with".to_string(),
+ "> content that should".to_string(),
+ "> wrap nicely".to_string(),
+ ]
+ );
+ }
+
+ #[test]
+ fn wraps_blockquotes_inside_lists() {
+ let markdown = "- list item\n > block quote inside list that wraps";
+ let rendered = render_markdown_text_with_width(markdown, Some(24));
+ let lines = lines_to_strings(&rendered);
+ assert_eq!(
+ lines,
+ vec![
+ "- list item".to_string(),
+ " > block quote inside".to_string(),
+ " > list that wraps".to_string(),
+ ]
+ );
+ }
+
+ #[test]
+ fn wraps_list_items_containing_blockquotes() {
+ let markdown = "1. item with quote\n > quoted text that should wrap";
+ let rendered = render_markdown_text_with_width(markdown, Some(24));
+ let lines = lines_to_strings(&rendered);
+ assert_eq!(
+ lines,
+ vec![
+ "1. item with quote".to_string(),
+ " > quoted text that".to_string(),
+ " > should wrap".to_string(),
+ ]
+ );
+ }
+
+ #[test]
+ fn does_not_wrap_code_blocks() {
+ let markdown = "````\nfn main() { println!(\"hi from a long line\"); }\n````";
+ let rendered = render_markdown_text_with_width(markdown, Some(10));
+ let lines = lines_to_strings(&rendered);
+ assert_eq!(
+ lines,
+ vec!["fn main() { println!(\"hi from a long line\"); }".to_string(),]
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/markdown_render_tests.rs b/codex-rs/tui2/src/markdown_render_tests.rs
new file mode 100644
index 0000000000..c549699695
--- /dev/null
+++ b/codex-rs/tui2/src/markdown_render_tests.rs
@@ -0,0 +1,995 @@
+use pretty_assertions::assert_eq;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::text::Text;
+
+use crate::markdown_render::render_markdown_text;
+use insta::assert_snapshot;
+
+#[test]
+fn empty() {
+ assert_eq!(render_markdown_text(""), Text::default());
+}
+
+#[test]
+fn paragraph_single() {
+ assert_eq!(
+ render_markdown_text("Hello, world!"),
+ Text::from("Hello, world!")
+ );
+}
+
+#[test]
+fn paragraph_soft_break() {
+ assert_eq!(
+ render_markdown_text("Hello\nWorld"),
+ Text::from_iter(["Hello", "World"])
+ );
+}
+
+#[test]
+fn paragraph_multiple() {
+ assert_eq!(
+ render_markdown_text("Paragraph 1\n\nParagraph 2"),
+ Text::from_iter(["Paragraph 1", "", "Paragraph 2"])
+ );
+}
+
+#[test]
+fn headings() {
+ let md = "# Heading 1\n## Heading 2\n### Heading 3\n#### Heading 4\n##### Heading 5\n###### Heading 6\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["# ".bold().underlined(), "Heading 1".bold().underlined()]),
+ Line::default(),
+ Line::from_iter(["## ".bold(), "Heading 2".bold()]),
+ Line::default(),
+ Line::from_iter(["### ".bold().italic(), "Heading 3".bold().italic()]),
+ Line::default(),
+ Line::from_iter(["#### ".italic(), "Heading 4".italic()]),
+ Line::default(),
+ Line::from_iter(["##### ".italic(), "Heading 5".italic()]),
+ Line::default(),
+ Line::from_iter(["###### ".italic(), "Heading 6".italic()]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn blockquote_single() {
+ let text = render_markdown_text("> Blockquote");
+ let expected = Text::from(Line::from_iter(["> ", "Blockquote"]).green());
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn blockquote_soft_break() {
+ // Soft break via lazy continuation should render as a new line in blockquotes.
+ let text = render_markdown_text("> This is a blockquote\nwith a soft break\n");
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(
+ lines,
+ vec![
+ "> This is a blockquote".to_string(),
+ "> with a soft break".to_string()
+ ]
+ );
+}
+
+#[test]
+fn blockquote_multiple_with_break() {
+ let text = render_markdown_text("> Blockquote 1\n\n> Blockquote 2\n");
+ let expected = Text::from_iter([
+ Line::from_iter(["> ", "Blockquote 1"]).green(),
+ Line::default(),
+ Line::from_iter(["> ", "Blockquote 2"]).green(),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn blockquote_three_paragraphs_short_lines() {
+ let md = "> one\n>\n> two\n>\n> three\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["> ", "one"]).green(),
+ Line::from_iter(["> "]).green(),
+ Line::from_iter(["> ", "two"]).green(),
+ Line::from_iter(["> "]).green(),
+ Line::from_iter(["> ", "three"]).green(),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn blockquote_nested_two_levels() {
+ let md = "> Level 1\n>> Level 2\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["> ", "Level 1"]).green(),
+ Line::from_iter(["> "]).green(),
+ Line::from_iter(["> ", "> ", "Level 2"]).green(),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn blockquote_with_list_items() {
+ let md = "> - item 1\n> - item 2\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["> ", "- ", "item 1"]).green(),
+ Line::from_iter(["> ", "- ", "item 2"]).green(),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn blockquote_with_ordered_list() {
+ let md = "> 1. first\n> 2. second\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(vec![
+ Span::from("> "),
+ "1. ".light_blue(),
+ Span::from("first"),
+ ])
+ .green(),
+ Line::from_iter(vec![
+ Span::from("> "),
+ "2. ".light_blue(),
+ Span::from("second"),
+ ])
+ .green(),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn blockquote_list_then_nested_blockquote() {
+ let md = "> - parent\n> > child\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["> ", "- ", "parent"]).green(),
+ Line::from_iter(["> ", " ", "> ", "child"]).green(),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn list_item_with_inline_blockquote_on_same_line() {
+ let md = "1. > quoted\n";
+ let text = render_markdown_text(md);
+ let mut lines = text.lines.iter();
+ let first = lines.next().expect("one line");
+ // Expect content to include the ordered marker, a space, "> ", and the text
+ let s: String = first.spans.iter().map(|sp| sp.content.clone()).collect();
+ assert_eq!(s, "1. > quoted");
+}
+
+#[test]
+fn blockquote_surrounded_by_blank_lines() {
+ let md = "foo\n\n> bar\n\nbaz\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(
+ lines,
+ vec![
+ "foo".to_string(),
+ "".to_string(),
+ "> bar".to_string(),
+ "".to_string(),
+ "baz".to_string(),
+ ]
+ );
+}
+
+#[test]
+fn blockquote_in_ordered_list_on_next_line() {
+ // Blockquote begins on a new line within an ordered list item; it should
+ // render inline on the same marker line.
+ let md = "1.\n > quoted\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["1. > quoted".to_string()]);
+}
+
+#[test]
+fn blockquote_in_unordered_list_on_next_line() {
+ // Blockquote begins on a new line within an unordered list item; it should
+ // render inline on the same marker line.
+ let md = "-\n > quoted\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["- > quoted".to_string()]);
+}
+
+#[test]
+fn blockquote_two_paragraphs_inside_ordered_list_has_blank_line() {
+ // Two blockquote paragraphs inside a list item should be separated by a blank line.
+ let md = "1.\n > para 1\n >\n > para 2\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(
+ lines,
+ vec![
+ "1. > para 1".to_string(),
+ " > ".to_string(),
+ " > para 2".to_string(),
+ ],
+ "expected blockquote content to stay aligned after list marker"
+ );
+}
+
+#[test]
+fn blockquote_inside_nested_list() {
+ let md = "1. A\n - B\n > inner\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["1. A", " - B", " > inner"]);
+}
+
+#[test]
+fn list_item_text_then_blockquote() {
+ let md = "1. before\n > quoted\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["1. before", " > quoted"]);
+}
+
+#[test]
+fn list_item_blockquote_then_text() {
+ let md = "1.\n > quoted\n after\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["1. > quoted", " > after"]);
+}
+
+#[test]
+fn list_item_text_blockquote_text() {
+ let md = "1. before\n > quoted\n after\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["1. before", " > quoted", " > after"]);
+}
+
+#[test]
+fn blockquote_with_heading_and_paragraph() {
+ let md = "> # Heading\n> paragraph text\n";
+ let text = render_markdown_text(md);
+ // Validate on content shape; styling is handled elsewhere
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(
+ lines,
+ vec![
+ "> # Heading".to_string(),
+ "> ".to_string(),
+ "> paragraph text".to_string(),
+ ]
+ );
+}
+
+#[test]
+fn blockquote_heading_inherits_heading_style() {
+ let text = render_markdown_text("> # test header\n> in blockquote\n");
+ assert_eq!(
+ text.lines,
+ [
+ Line::from_iter([
+ "> ".into(),
+ "# ".bold().underlined(),
+ "test header".bold().underlined(),
+ ])
+ .green(),
+ Line::from_iter(["> "]).green(),
+ Line::from_iter(["> ", "in blockquote"]).green(),
+ ]
+ );
+}
+
+#[test]
+fn blockquote_with_code_block() {
+ let md = "> ```\n> code\n> ```\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["> code".to_string()]);
+}
+
+#[test]
+fn blockquote_with_multiline_code_block() {
+ let md = "> ```\n> first\n> second\n> ```\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["> first", "> second"]);
+}
+
+#[test]
+fn nested_blockquote_with_inline_and_fenced_code() {
+ /*
+ let md = \"> Nested quote with code:\n\
+ > > Inner quote and `inline code`\n\
+ > >\n\
+ > > ```\n\
+ > > # fenced code inside a quote\n\
+ > > echo \"hello from a quote\"\n\
+ > > ```\n";
+ */
+ let md = r#"> Nested quote with code:
+> > Inner quote and `inline code`
+> >
+> > ```
+> > # fenced code inside a quote
+> > echo "hello from a quote"
+> > ```
+"#;
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(
+ lines,
+ vec![
+ "> Nested quote with code:".to_string(),
+ "> ".to_string(),
+ "> > Inner quote and inline code".to_string(),
+ "> > ".to_string(),
+ "> > # fenced code inside a quote".to_string(),
+ "> > echo \"hello from a quote\"".to_string(),
+ ]
+ );
+}
+
+#[test]
+fn list_unordered_single() {
+ let text = render_markdown_text("- List item 1\n");
+ let expected = Text::from_iter([Line::from_iter(["- ", "List item 1"])]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn list_unordered_multiple() {
+ let text = render_markdown_text("- List item 1\n- List item 2\n");
+ let expected = Text::from_iter([
+ Line::from_iter(["- ", "List item 1"]),
+ Line::from_iter(["- ", "List item 2"]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn list_ordered() {
+ let text = render_markdown_text("1. List item 1\n2. List item 2\n");
+ let expected = Text::from_iter([
+ Line::from_iter(["1. ".light_blue(), "List item 1".into()]),
+ Line::from_iter(["2. ".light_blue(), "List item 2".into()]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn list_nested() {
+ let text = render_markdown_text("- List item 1\n - Nested list item 1\n");
+ let expected = Text::from_iter([
+ Line::from_iter(["- ", "List item 1"]),
+ Line::from_iter([" - ", "Nested list item 1"]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn list_ordered_custom_start() {
+ let text = render_markdown_text("3. First\n4. Second\n");
+ let expected = Text::from_iter([
+ Line::from_iter(["3. ".light_blue(), "First".into()]),
+ Line::from_iter(["4. ".light_blue(), "Second".into()]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn nested_unordered_in_ordered() {
+ let md = "1. Outer\n - Inner A\n - Inner B\n2. Next\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["1. ".light_blue(), "Outer".into()]),
+ Line::from_iter([" - ", "Inner A"]),
+ Line::from_iter([" - ", "Inner B"]),
+ Line::from_iter(["2. ".light_blue(), "Next".into()]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn nested_ordered_in_unordered() {
+ let md = "- Outer\n 1. One\n 2. Two\n- Last\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["- ", "Outer"]),
+ Line::from_iter([" 1. ".light_blue(), "One".into()]),
+ Line::from_iter([" 2. ".light_blue(), "Two".into()]),
+ Line::from_iter(["- ", "Last"]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn loose_list_item_multiple_paragraphs() {
+ let md = "1. First paragraph\n\n Second paragraph of same item\n\n2. Next item\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["1. ".light_blue(), "First paragraph".into()]),
+ Line::default(),
+ Line::from_iter([" ", "Second paragraph of same item"]),
+ Line::from_iter(["2. ".light_blue(), "Next item".into()]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn tight_item_with_soft_break() {
+ let md = "- item line1\n item line2\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["- ", "item line1"]),
+ Line::from_iter([" ", "item line2"]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn deeply_nested_mixed_three_levels() {
+ let md = "1. A\n - B\n 1. C\n2. D\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["1. ".light_blue(), "A".into()]),
+ Line::from_iter([" - ", "B"]),
+ Line::from_iter([" 1. ".light_blue(), "C".into()]),
+ Line::from_iter(["2. ".light_blue(), "D".into()]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn loose_items_due_to_blank_line_between_items() {
+ let md = "1. First\n\n2. Second\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["1. ".light_blue(), "First".into()]),
+ Line::from_iter(["2. ".light_blue(), "Second".into()]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn mixed_tight_then_loose_in_one_list() {
+ let md = "1. Tight\n\n2.\n Loose\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["1. ".light_blue(), "Tight".into()]),
+ Line::from_iter(["2. ".light_blue(), "Loose".into()]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn ordered_item_with_indented_continuation_is_tight() {
+ let md = "1. Foo\n Bar\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["1. ".light_blue(), "Foo".into()]),
+ Line::from_iter([" ", "Bar"]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn inline_code() {
+ let text = render_markdown_text("Example of `Inline code`");
+ let expected = Line::from_iter(["Example of ".into(), "Inline code".cyan()]).into();
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn strong() {
+ assert_eq!(
+ render_markdown_text("**Strong**"),
+ Text::from(Line::from("Strong".bold()))
+ );
+}
+
+#[test]
+fn emphasis() {
+ assert_eq!(
+ render_markdown_text("*Emphasis*"),
+ Text::from(Line::from("Emphasis".italic()))
+ );
+}
+
+#[test]
+fn strikethrough() {
+ assert_eq!(
+ render_markdown_text("~~Strikethrough~~"),
+ Text::from(Line::from("Strikethrough".crossed_out()))
+ );
+}
+
+#[test]
+fn strong_emphasis() {
+ let text = render_markdown_text("**Strong *emphasis***");
+ let expected = Text::from(Line::from_iter([
+ "Strong ".bold(),
+ "emphasis".bold().italic(),
+ ]));
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn link() {
+ let text = render_markdown_text("[Link](https://example.com)");
+ let expected = Text::from(Line::from_iter([
+ "Link".into(),
+ " (".into(),
+ "https://example.com".cyan().underlined(),
+ ")".into(),
+ ]));
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn code_block_unhighlighted() {
+ let text = render_markdown_text("```rust\nfn main() {}\n```\n");
+ let expected = Text::from_iter([Line::from_iter(["", "fn main() {}"])]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn code_block_multiple_lines_root() {
+ let md = "```\nfirst\nsecond\n```\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["", "first"]),
+ Line::from_iter(["", "second"]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn code_block_indented() {
+ let md = " function greet() {\n console.log(\"Hi\");\n }\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter([" ", "function greet() {"]),
+ Line::from_iter([" ", " console.log(\"Hi\");"]),
+ Line::from_iter([" ", "}"]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn horizontal_rule_renders_em_dashes() {
+ let md = "Before\n\n---\n\nAfter\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["Before", "", "———", "", "After"]);
+}
+
+#[test]
+fn code_block_with_inner_triple_backticks_outer_four() {
+ let md = r#"````text
+Here is a code block that shows another fenced block:
+
+```md
+# Inside fence
+- bullet
+- `inline code`
+```
+````
+"#;
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(
+ lines,
+ vec![
+ "Here is a code block that shows another fenced block:".to_string(),
+ String::new(),
+ "```md".to_string(),
+ "# Inside fence".to_string(),
+ "- bullet".to_string(),
+ "- `inline code`".to_string(),
+ "```".to_string(),
+ ]
+ );
+}
+
+#[test]
+fn code_block_inside_unordered_list_item_is_indented() {
+ let md = "- Item\n\n ```\n code line\n ```\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["- Item", "", " code line"]);
+}
+
+#[test]
+fn code_block_multiple_lines_inside_unordered_list() {
+ let md = "- Item\n\n ```\n first\n second\n ```\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["- Item", "", " first", " second"]);
+}
+
+#[test]
+fn code_block_inside_unordered_list_item_multiple_lines() {
+ let md = "- Item\n\n ```\n first\n second\n ```\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(lines, vec!["- Item", "", " first", " second"]);
+}
+
+#[test]
+fn markdown_render_complex_snapshot() {
+ let md = r#"# H1: Markdown Streaming Test
+Intro paragraph with bold **text**, italic *text*, and inline code `x=1`.
+Combined bold-italic ***both*** and escaped asterisks \*literal\*.
+Auto-link: <https://example.com> and reference link [ref][r1].
+Link with title: [hover me](https://example.com "Example") and mailto <mailto:[email protected]>.
+Image: ![alt text](https://example.com/img.png "Title")
+> Blockquote level 1
+>> Blockquote level 2 with `inline code`
+- Unordered list item 1
+ - Nested bullet with italics _inner_
+- Unordered list item 2 with ~~strikethrough~~
+1. Ordered item one
+2. Ordered item two with sublist:
+ 1) Alt-numbered subitem
+- [ ] Task: unchecked
+- [x] Task: checked with link [home](https://example.org)
+---
+Table below (alignment test):
+| Left | Center | Right |
+|:-----|:------:|------:|
+| a | b | c |
+Inline HTML: <sup>sup</sup> and <sub>sub</sub>.
+HTML block:
+<div style="border:1px solid #ccc;padding:2px">inline block</div>
+Escapes: \_underscores\_, backslash \\, ticks ``code with `backtick` inside``.
+Emoji shortcodes: :sparkles: :tada: (if supported).
+Hard break test (line ends with two spaces)
+Next line should be close to previous.
+Footnote reference here[^1] and another[^longnote].
+Horizontal rule with asterisks:
+***
+Fenced code block (JSON):
+```json
+{ "a": 1, "b": [true, false] }
+```
+Fenced code with tildes and triple backticks inside:
+~~~markdown
+To close ``` you need tildes.
+~~~
+Indented code block:
+ for i in range(3): print(i)
+Definition-like list:
+Term
+: Definition with `code`.
+Character entities: &amp; &lt; &gt; &quot; &#39;
+[^1]: This is the first footnote.
+[^longnote]: A longer footnote with a link to [Rust](https://www.rust-lang.org/).
+Escaped pipe in text: a \| b \| c.
+URL with parentheses: [link](https://example.com/path_(with)_parens).
+[r1]: https://example.com/ref "Reference link title"
+"#;
+
+ let text = render_markdown_text(md);
+ // Convert to plain text lines for snapshot (ignore styles)
+ let rendered = text
+ .lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ assert_snapshot!(rendered);
+}
+
+#[test]
+fn ordered_item_with_code_block_and_nested_bullet() {
+ let md = "1. **item 1**\n\n2. **item 2**\n ```\n code\n ```\n - `PROCESS_START` (a `OnceLock<Instant>`) keeps the start time for the entire process.\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|line| {
+ line.spans
+ .iter()
+ .map(|span| span.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(
+ lines,
+ vec![
+ "1. item 1".to_string(),
+ "2. item 2".to_string(),
+ String::new(),
+ " code".to_string(),
+ " - PROCESS_START (a OnceLock<Instant>) keeps the start time for the entire process.".to_string(),
+ ]
+ );
+}
+
+#[test]
+fn nested_five_levels_mixed_lists() {
+ let md = "1. First\n - Second level\n 1. Third level (ordered)\n - Fourth level (bullet)\n - Fifth level to test indent consistency\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["1. ".light_blue(), "First".into()]),
+ Line::from_iter([" - ", "Second level"]),
+ Line::from_iter([" 1. ".light_blue(), "Third level (ordered)".into()]),
+ Line::from_iter([" - ", "Fourth level (bullet)"]),
+ Line::from_iter([
+ " - ",
+ "Fifth level to test indent consistency",
+ ]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn html_inline_is_verbatim() {
+ let md = "Hello <span>world</span>!";
+ let text = render_markdown_text(md);
+ let expected: Text = Line::from_iter(["Hello ", "<span>", "world", "</span>", "!"]).into();
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn html_block_is_verbatim_multiline() {
+ let md = "<div>\n <span>hi</span>\n</div>\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["<div>"]),
+ Line::from_iter([" <span>hi</span>"]),
+ Line::from_iter(["</div>"]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn html_in_tight_ordered_item_soft_breaks_with_space() {
+ let md = "1. Foo\n <i>Bar</i>\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["1. ".light_blue(), "Foo".into()]),
+ Line::from_iter([" ", "<i>", "Bar", "</i>"]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn html_continuation_paragraph_in_unordered_item_indented() {
+ let md = "- Item\n\n <em>continued</em>\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["- ", "Item"]),
+ Line::default(),
+ Line::from_iter([" ", "<em>", "continued", "</em>"]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn unordered_item_continuation_paragraph_is_indented() {
+ let md = "- Intro\n\n Continuation paragraph line 1\n Continuation paragraph line 2\n";
+ let text = render_markdown_text(md);
+ let lines: Vec<String> = text
+ .lines
+ .iter()
+ .map(|line| {
+ line.spans
+ .iter()
+ .map(|span| span.content.clone())
+ .collect::<String>()
+ })
+ .collect();
+ assert_eq!(
+ lines,
+ vec![
+ "- Intro".to_string(),
+ String::new(),
+ " Continuation paragraph line 1".to_string(),
+ " Continuation paragraph line 2".to_string(),
+ ]
+ );
+}
+
+#[test]
+fn ordered_item_continuation_paragraph_is_indented() {
+ let md = "1. Intro\n\n More details about intro\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["1. ".light_blue(), "Intro".into()]),
+ Line::default(),
+ Line::from_iter([" ", "More details about intro"]),
+ ]);
+ assert_eq!(text, expected);
+}
+
+#[test]
+fn nested_item_continuation_paragraph_is_indented() {
+ let md = "1. A\n - B\n\n Continuation for B\n2. C\n";
+ let text = render_markdown_text(md);
+ let expected = Text::from_iter([
+ Line::from_iter(["1. ".light_blue(), "A".into()]),
+ Line::from_iter([" - ", "B"]),
+ Line::default(),
+ Line::from_iter([" ", "Continuation for B"]),
+ Line::from_iter(["2. ".light_blue(), "C".into()]),
+ ]);
+ assert_eq!(text, expected);
+}
diff --git a/codex-rs/tui2/src/markdown_stream.rs b/codex-rs/tui2/src/markdown_stream.rs
new file mode 100644
index 0000000000..6ac457eee2
--- /dev/null
+++ b/codex-rs/tui2/src/markdown_stream.rs
@@ -0,0 +1,670 @@
+use ratatui::text::Line;
+
+use crate::markdown;
+
+/// Newline-gated accumulator that renders markdown and commits only fully
+/// completed logical lines.
+pub(crate) struct MarkdownStreamCollector {
+ buffer: String,
+ committed_line_count: usize,
+ width: Option<usize>,
+}
+
+impl MarkdownStreamCollector {
+ pub fn new(width: Option<usize>) -> Self {
+ Self {
+ buffer: String::new(),
+ committed_line_count: 0,
+ width,
+ }
+ }
+
+ pub fn clear(&mut self) {
+ self.buffer.clear();
+ self.committed_line_count = 0;
+ }
+
+ pub fn push_delta(&mut self, delta: &str) {
+ tracing::trace!("push_delta: {delta:?}");
+ self.buffer.push_str(delta);
+ }
+
+ /// Render the full buffer and return only the newly completed logical lines
+ /// since the last commit. When the buffer does not end with a newline, the
+ /// final rendered line is considered incomplete and is not emitted.
+ pub fn commit_complete_lines(&mut self) -> Vec<Line<'static>> {
+ let source = self.buffer.clone();
+ let last_newline_idx = source.rfind('\n');
+ let source = if let Some(last_newline_idx) = last_newline_idx {
+ source[..=last_newline_idx].to_string()
+ } else {
+ return Vec::new();
+ };
+ let mut rendered: Vec<Line<'static>> = Vec::new();
+ markdown::append_markdown(&source, self.width, &mut rendered);
+ let mut complete_line_count = rendered.len();
+ if complete_line_count > 0
+ && crate::render::line_utils::is_blank_line_spaces_only(
+ &rendered[complete_line_count - 1],
+ )
+ {
+ complete_line_count -= 1;
+ }
+
+ if self.committed_line_count >= complete_line_count {
+ return Vec::new();
+ }
+
+ let out_slice = &rendered[self.committed_line_count..complete_line_count];
+
+ let out = out_slice.to_vec();
+ self.committed_line_count = complete_line_count;
+ out
+ }
+
+ /// Finalize the stream: emit all remaining lines beyond the last commit.
+ /// If the buffer does not end with a newline, a temporary one is appended
+ /// for rendering. Optionally unwraps ```markdown language fences in
+ /// non-test builds.
+ pub fn finalize_and_drain(&mut self) -> Vec<Line<'static>> {
+ let raw_buffer = self.buffer.clone();
+ let mut source: String = raw_buffer.clone();
+ if !source.ends_with('\n') {
+ source.push('\n');
+ }
+ tracing::debug!(
+ raw_len = raw_buffer.len(),
+ source_len = source.len(),
+ "markdown finalize (raw length: {}, rendered length: {})",
+ raw_buffer.len(),
+ source.len()
+ );
+ tracing::trace!("markdown finalize (raw source):\n---\n{source}\n---");
+
+ let mut rendered: Vec<Line<'static>> = Vec::new();
+ markdown::append_markdown(&source, self.width, &mut rendered);
+
+ let out = if self.committed_line_count >= rendered.len() {
+ Vec::new()
+ } else {
+ rendered[self.committed_line_count..].to_vec()
+ };
+
+ // Reset collector state for next stream.
+ self.clear();
+ out
+ }
+}
+
+#[cfg(test)]
+pub(crate) fn simulate_stream_markdown_for_tests(
+ deltas: &[&str],
+ finalize: bool,
+) -> Vec<Line<'static>> {
+ let mut collector = MarkdownStreamCollector::new(None);
+ let mut out = Vec::new();
+ for d in deltas {
+ collector.push_delta(d);
+ if d.contains('\n') {
+ out.extend(collector.commit_complete_lines());
+ }
+ }
+ if finalize {
+ out.extend(collector.finalize_and_drain());
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ratatui::style::Color;
+
+ #[tokio::test]
+ async fn no_commit_until_newline() {
+ let mut c = super::MarkdownStreamCollector::new(None);
+ c.push_delta("Hello, world");
+ let out = c.commit_complete_lines();
+ assert!(out.is_empty(), "should not commit without newline");
+ c.push_delta("!\n");
+ let out2 = c.commit_complete_lines();
+ assert_eq!(out2.len(), 1, "one completed line after newline");
+ }
+
+ #[tokio::test]
+ async fn finalize_commits_partial_line() {
+ let mut c = super::MarkdownStreamCollector::new(None);
+ c.push_delta("Line without newline");
+ let out = c.finalize_and_drain();
+ assert_eq!(out.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn e2e_stream_blockquote_simple_is_green() {
+ let out = super::simulate_stream_markdown_for_tests(&["> Hello\n"], true);
+ assert_eq!(out.len(), 1);
+ let l = &out[0];
+ assert_eq!(
+ l.style.fg,
+ Some(Color::Green),
+ "expected blockquote line fg green, got {:?}",
+ l.style.fg
+ );
+ }
+
+ #[tokio::test]
+ async fn e2e_stream_blockquote_nested_is_green() {
+ let out = super::simulate_stream_markdown_for_tests(&["> Level 1\n>> Level 2\n"], true);
+ // Filter out any blank lines that may be inserted at paragraph starts.
+ let non_blank: Vec<_> = out
+ .into_iter()
+ .filter(|l| {
+ let s = l
+ .spans
+ .iter()
+ .map(|sp| sp.content.clone())
+ .collect::<Vec<_>>()
+ .join("");
+ let t = s.trim();
+ // Ignore quote-only blank lines like ">" inserted at paragraph boundaries.
+ !(t.is_empty() || t == ">")
+ })
+ .collect();
+ assert_eq!(non_blank.len(), 2);
+ assert_eq!(non_blank[0].style.fg, Some(Color::Green));
+ assert_eq!(non_blank[1].style.fg, Some(Color::Green));
+ }
+
+ #[tokio::test]
+ async fn e2e_stream_blockquote_with_list_items_is_green() {
+ let out = super::simulate_stream_markdown_for_tests(&["> - item 1\n> - item 2\n"], true);
+ assert_eq!(out.len(), 2);
+ assert_eq!(out[0].style.fg, Some(Color::Green));
+ assert_eq!(out[1].style.fg, Some(Color::Green));
+ }
+
+ #[tokio::test]
+ async fn e2e_stream_nested_mixed_lists_ordered_marker_is_light_blue() {
+ let md = [
+ "1. First\n",
+ " - Second level\n",
+ " 1. Third level (ordered)\n",
+ " - Fourth level (bullet)\n",
+ " - Fifth level to test indent consistency\n",
+ ];
+ let out = super::simulate_stream_markdown_for_tests(&md, true);
+ // Find the line that contains the third-level ordered text
+ let find_idx = out.iter().position(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<String>()
+ .contains("Third level (ordered)")
+ });
+ let idx = find_idx.expect("expected third-level ordered line");
+ let line = &out[idx];
+ // Expect at least one span on this line to be styled light blue
+ let has_light_blue = line
+ .spans
+ .iter()
+ .any(|s| s.style.fg == Some(ratatui::style::Color::LightBlue));
+ assert!(
+ has_light_blue,
+ "expected an ordered-list marker span with light blue fg on: {line:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn e2e_stream_blockquote_wrap_preserves_green_style() {
+ let long = "> This is a very long quoted line that should wrap across multiple columns to verify style preservation.";
+ let out = super::simulate_stream_markdown_for_tests(&[long, "\n"], true);
+ // Wrap to a narrow width to force multiple output lines.
+ let wrapped =
+ crate::wrapping::word_wrap_lines(out.iter(), crate::wrapping::RtOptions::new(24));
+ // Filter out purely blank lines
+ let non_blank: Vec<_> = wrapped
+ .into_iter()
+ .filter(|l| {
+ let s = l
+ .spans
+ .iter()
+ .map(|sp| sp.content.clone())
+ .collect::<Vec<_>>()
+ .join("");
+ !s.trim().is_empty()
+ })
+ .collect();
+ assert!(
+ non_blank.len() >= 2,
+ "expected wrapped blockquote to span multiple lines"
+ );
+ for (i, l) in non_blank.iter().enumerate() {
+ assert_eq!(
+ l.spans[0].style.fg,
+ Some(Color::Green),
+ "wrapped line {} should preserve green style, got {:?}",
+ i,
+ l.spans[0].style.fg
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn heading_starts_on_new_line_when_following_paragraph() {
+ // Stream a paragraph line, then a heading on the next line.
+ // Expect two distinct rendered lines: "Hello." and "Heading".
+ let mut c = super::MarkdownStreamCollector::new(None);
+ c.push_delta("Hello.\n");
+ let out1 = c.commit_complete_lines();
+ let s1: Vec<String> = out1
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<Vec<_>>()
+ .join("")
+ })
+ .collect();
+ assert_eq!(
+ out1.len(),
+ 1,
+ "first commit should contain only the paragraph line, got {}: {:?}",
+ out1.len(),
+ s1
+ );
+
+ c.push_delta("## Heading\n");
+ let out2 = c.commit_complete_lines();
+ let s2: Vec<String> = out2
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<Vec<_>>()
+ .join("")
+ })
+ .collect();
+ assert_eq!(
+ s2,
+ vec!["", "## Heading"],
+ "expected a blank separator then the heading line"
+ );
+
+ let line_to_string = |l: &ratatui::text::Line<'_>| -> String {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<Vec<_>>()
+ .join("")
+ };
+
+ assert_eq!(line_to_string(&out1[0]), "Hello.");
+ assert_eq!(line_to_string(&out2[1]), "## Heading");
+ }
+
+ #[tokio::test]
+ async fn heading_not_inlined_when_split_across_chunks() {
+ // Paragraph without trailing newline, then a chunk that starts with the newline
+ // and the heading text, then a final newline. The collector should first commit
+ // only the paragraph line, and later commit the heading as its own line.
+ let mut c = super::MarkdownStreamCollector::new(None);
+ c.push_delta("Sounds good!");
+ // No commit yet
+ assert!(c.commit_complete_lines().is_empty());
+
+ // Introduce the newline that completes the paragraph and the start of the heading.
+ c.push_delta("\n## Adding Bird subcommand");
+ let out1 = c.commit_complete_lines();
+ let s1: Vec<String> = out1
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<Vec<_>>()
+ .join("")
+ })
+ .collect();
+ assert_eq!(
+ s1,
+ vec!["Sounds good!"],
+ "expected paragraph followed by blank separator before heading chunk"
+ );
+
+ // Now finish the heading line with the trailing newline.
+ c.push_delta("\n");
+ let out2 = c.commit_complete_lines();
+ let s2: Vec<String> = out2
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<Vec<_>>()
+ .join("")
+ })
+ .collect();
+ assert_eq!(
+ s2,
+ vec!["", "## Adding Bird subcommand"],
+ "expected the heading line only on the final commit"
+ );
+
+ // Sanity check raw markdown rendering for a simple line does not produce spurious extras.
+ let mut rendered: Vec<ratatui::text::Line<'static>> = Vec::new();
+ crate::markdown::append_markdown("Hello.\n", None, &mut rendered);
+ let rendered_strings: Vec<String> = rendered
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<Vec<_>>()
+ .join("")
+ })
+ .collect();
+ assert_eq!(
+ rendered_strings,
+ vec!["Hello."],
+ "unexpected markdown lines: {rendered_strings:?}"
+ );
+ }
+
+ fn lines_to_plain_strings(lines: &[ratatui::text::Line<'_>]) -> Vec<String> {
+ lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<Vec<_>>()
+ .join("")
+ })
+ .collect()
+ }
+
+ #[tokio::test]
+ async fn lists_and_fences_commit_without_duplication() {
+ // List case
+ assert_streamed_equals_full(&["- a\n- ", "b\n- c\n"]).await;
+
+ // Fenced code case: stream in small chunks
+ assert_streamed_equals_full(&["```", "\nco", "de 1\ncode 2\n", "```\n"]).await;
+ }
+
+ #[tokio::test]
+ async fn utf8_boundary_safety_and_wide_chars() {
+ // Emoji (wide), CJK, control char, digit + combining macron sequences
+ let input = "🙂🙂🙂\n汉字漢字\nA\u{0003}0\u{0304}\n";
+ let deltas = vec![
+ "🙂",
+ "🙂",
+ "🙂\n汉",
+ "字漢",
+ "字\nA",
+ "\u{0003}",
+ "0",
+ "\u{0304}",
+ "\n",
+ ];
+
+ let streamed = simulate_stream_markdown_for_tests(&deltas, true);
+ let streamed_str = lines_to_plain_strings(&streamed);
+
+ let mut rendered_all: Vec<ratatui::text::Line<'static>> = Vec::new();
+ crate::markdown::append_markdown(input, None, &mut rendered_all);
+ let rendered_all_str = lines_to_plain_strings(&rendered_all);
+
+ assert_eq!(
+ streamed_str, rendered_all_str,
+ "utf8/wide-char streaming should equal full render without duplication or truncation"
+ );
+ }
+
+ #[tokio::test]
+ async fn e2e_stream_deep_nested_third_level_marker_is_light_blue() {
+ let md = "1. First\n - Second level\n 1. Third level (ordered)\n - Fourth level (bullet)\n - Fifth level to test indent consistency\n";
+ let streamed = super::simulate_stream_markdown_for_tests(&[md], true);
+ let streamed_strs = lines_to_plain_strings(&streamed);
+
+ // Locate the third-level line in the streamed output; avoid relying on exact indent.
+ let target_suffix = "1. Third level (ordered)";
+ let mut found = None;
+ for line in &streamed {
+ let s: String = line.spans.iter().map(|sp| sp.content.clone()).collect();
+ if s.contains(target_suffix) {
+ found = Some(line.clone());
+ break;
+ }
+ }
+ let line = found.unwrap_or_else(|| {
+ panic!("expected to find the third-level ordered list line; got: {streamed_strs:?}")
+ });
+
+ // The marker (including indent and "1.") is expected to be in the first span
+ // and colored LightBlue; following content should be default color.
+ assert!(
+ !line.spans.is_empty(),
+ "expected non-empty spans for the third-level line"
+ );
+ let marker_span = &line.spans[0];
+ assert_eq!(
+ marker_span.style.fg,
+ Some(Color::LightBlue),
+ "expected LightBlue 3rd-level ordered marker, got {:?}",
+ marker_span.style.fg
+ );
+ // Find the first non-empty non-space content span and verify it is default color.
+ let mut content_fg = None;
+ for sp in &line.spans[1..] {
+ let t = sp.content.trim();
+ if !t.is_empty() {
+ content_fg = Some(sp.style.fg);
+ break;
+ }
+ }
+ assert_eq!(
+ content_fg.flatten(),
+ None,
+ "expected default color for 3rd-level content, got {content_fg:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn empty_fenced_block_is_dropped_and_separator_preserved_before_heading() {
+ // An empty fenced code block followed by a heading should not render the fence,
+ // but should preserve a blank separator line so the heading starts on a new line.
+ let deltas = vec!["```bash\n```\n", "## Heading\n"]; // empty block and close in same commit
+ let streamed = simulate_stream_markdown_for_tests(&deltas, true);
+ let texts = lines_to_plain_strings(&streamed);
+ assert!(
+ texts.iter().all(|s| !s.contains("```")),
+ "no fence markers expected: {texts:?}"
+ );
+ // Expect the heading and no fence markers. A blank separator may or may not be rendered at start.
+ assert!(
+ texts.iter().any(|s| s == "## Heading"),
+ "expected heading line: {texts:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn paragraph_then_empty_fence_then_heading_keeps_heading_on_new_line() {
+ let deltas = vec!["Para.\n", "```\n```\n", "## Title\n"]; // empty fence block in one commit
+ let streamed = simulate_stream_markdown_for_tests(&deltas, true);
+ let texts = lines_to_plain_strings(&streamed);
+ let para_idx = match texts.iter().position(|s| s == "Para.") {
+ Some(i) => i,
+ None => panic!("para present"),
+ };
+ let head_idx = match texts.iter().position(|s| s == "## Title") {
+ Some(i) => i,
+ None => panic!("heading present"),
+ };
+ assert!(
+ head_idx > para_idx,
+ "heading should not merge with paragraph: {texts:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn loose_list_with_split_dashes_matches_full_render() {
+ // Minimized failing sequence discovered by the helper: two chunks
+ // that still reproduce the mismatch.
+ let deltas = vec!["- item.\n\n", "-"];
+
+ let streamed = simulate_stream_markdown_for_tests(&deltas, true);
+ let streamed_strs = lines_to_plain_strings(&streamed);
+
+ let full: String = deltas.iter().copied().collect();
+ let mut rendered_all: Vec<ratatui::text::Line<'static>> = Vec::new();
+ crate::markdown::append_markdown(&full, None, &mut rendered_all);
+ let rendered_all_strs = lines_to_plain_strings(&rendered_all);
+
+ assert_eq!(
+ streamed_strs, rendered_all_strs,
+ "streamed output should match full render without dangling '-' lines"
+ );
+ }
+
+ #[tokio::test]
+ async fn loose_vs_tight_list_items_streaming_matches_full() {
+ // Deltas extracted from the session log around 2025-08-27T00:33:18.216Z
+ let deltas = vec![
+ "\n\n",
+ "Loose",
+ " vs",
+ ".",
+ " tight",
+ " list",
+ " items",
+ ":\n",
+ "1",
+ ".",
+ " Tight",
+ " item",
+ "\n",
+ "2",
+ ".",
+ " Another",
+ " tight",
+ " item",
+ "\n\n",
+ "1",
+ ".",
+ " Loose",
+ " item",
+ " with",
+ " its",
+ " own",
+ " paragraph",
+ ".\n\n",
+ " ",
+ " This",
+ " paragraph",
+ " belongs",
+ " to",
+ " the",
+ " same",
+ " list",
+ " item",
+ ".\n\n",
+ "2",
+ ".",
+ " Second",
+ " loose",
+ " item",
+ " with",
+ " a",
+ " nested",
+ " list",
+ " after",
+ " a",
+ " blank",
+ " line",
+ ".\n\n",
+ " ",
+ " -",
+ " Nested",
+ " bullet",
+ " under",
+ " a",
+ " loose",
+ " item",
+ "\n",
+ " ",
+ " -",
+ " Another",
+ " nested",
+ " bullet",
+ "\n\n",
+ ];
+
+ let streamed = simulate_stream_markdown_for_tests(&deltas, true);
+ let streamed_strs = lines_to_plain_strings(&streamed);
+
+ // Compute a full render for diagnostics only.
+ let full: String = deltas.iter().copied().collect();
+ let mut rendered_all: Vec<ratatui::text::Line<'static>> = Vec::new();
+ crate::markdown::append_markdown(&full, None, &mut rendered_all);
+
+ // Also assert exact expected plain strings for clarity.
+ let expected = vec![
+ "Loose vs. tight list items:".to_string(),
+ "".to_string(),
+ "1. Tight item".to_string(),
+ "2. Another tight item".to_string(),
+ "3. Loose item with its own paragraph.".to_string(),
+ "".to_string(),
+ " This paragraph belongs to the same list item.".to_string(),
+ "4. Second loose item with a nested list after a blank line.".to_string(),
+ " - Nested bullet under a loose item".to_string(),
+ " - Another nested bullet".to_string(),
+ ];
+ assert_eq!(
+ streamed_strs, expected,
+ "expected exact rendered lines for loose/tight section"
+ );
+ }
+
+ // Targeted tests derived from fuzz findings. Each asserts streamed == full render.
+ async fn assert_streamed_equals_full(deltas: &[&str]) {
+ let streamed = simulate_stream_markdown_for_tests(deltas, true);
+ let streamed_strs = lines_to_plain_strings(&streamed);
+ let full: String = deltas.iter().copied().collect();
+ let mut rendered: Vec<ratatui::text::Line<'static>> = Vec::new();
+ crate::markdown::append_markdown(&full, None, &mut rendered);
+ let rendered_strs = lines_to_plain_strings(&rendered);
+ assert_eq!(streamed_strs, rendered_strs, "full:\n---\n{full}\n---");
+ }
+
+ #[tokio::test]
+ async fn fuzz_class_bullet_duplication_variant_1() {
+ assert_streamed_equals_full(&[
+ "aph.\n- let one\n- bull",
+ "et two\n\n second paragraph \n",
+ ])
+ .await;
+ }
+
+ #[tokio::test]
+ async fn fuzz_class_bullet_duplication_variant_2() {
+ assert_streamed_equals_full(&[
+ "- e\n c",
+ "e\n- bullet two\n\n second paragraph in bullet two\n",
+ ])
+ .await;
+ }
+
+ #[tokio::test]
+ async fn streaming_html_block_then_text_matches_full() {
+ assert_streamed_equals_full(&[
+ "HTML block:\n",
+ "<div>inline block</div>\n",
+ "more stuff\n",
+ ])
+ .await;
+ }
+}
diff --git a/codex-rs/tui2/src/model_migration.rs b/codex-rs/tui2/src/model_migration.rs
new file mode 100644
index 0000000000..cbce1f1bb0
--- /dev/null
+++ b/codex-rs/tui2/src/model_migration.rs
@@ -0,0 +1,458 @@
+use crate::key_hint;
+use crate::render::Insets;
+use crate::render::renderable::ColumnRenderable;
+use crate::render::renderable::Renderable;
+use crate::render::renderable::RenderableExt as _;
+use crate::selection_list::selection_option_row;
+use crate::tui::FrameRequester;
+use crate::tui::Tui;
+use crate::tui::TuiEvent;
+use codex_core::openai_models::model_presets::HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG;
+use codex_core::openai_models::model_presets::HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use crossterm::event::KeyModifiers;
+use ratatui::prelude::Stylize as _;
+use ratatui::prelude::Widget;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::widgets::Clear;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::WidgetRef;
+use ratatui::widgets::Wrap;
+use tokio_stream::StreamExt;
+
+/// Outcome of the migration prompt.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum ModelMigrationOutcome {
+ Accepted,
+ Rejected,
+ Exit,
+}
+
+#[derive(Clone)]
+pub(crate) struct ModelMigrationCopy {
+ pub heading: Vec<Span<'static>>,
+ pub content: Vec<Line<'static>>,
+ pub can_opt_out: bool,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum MigrationMenuOption {
+ TryNewModel,
+ UseExistingModel,
+}
+
+impl MigrationMenuOption {
+ fn all() -> [Self; 2] {
+ [Self::TryNewModel, Self::UseExistingModel]
+ }
+
+ fn label(self) -> &'static str {
+ match self {
+ Self::TryNewModel => "Try new model",
+ Self::UseExistingModel => "Use existing model",
+ }
+ }
+}
+
+pub(crate) fn migration_copy_for_config(migration_config_key: &str) -> ModelMigrationCopy {
+ match migration_config_key {
+ HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG => gpt5_migration_copy(),
+ HIDE_GPT_5_1_CODEX_MAX_MIGRATION_PROMPT_CONFIG => gpt_5_1_codex_max_migration_copy(),
+ _ => gpt_5_1_codex_max_migration_copy(),
+ }
+}
+
+pub(crate) async fn run_model_migration_prompt(
+ tui: &mut Tui,
+ copy: ModelMigrationCopy,
+) -> ModelMigrationOutcome {
+ // Render the prompt on the terminal's alternate screen so exiting or cancelling
+ // does not leave a large blank region in the normal scrollback. This does not
+ // change the prompt's appearance – only where it is drawn.
+ struct AltScreenGuard<'a> {
+ tui: &'a mut Tui,
+ }
+ impl<'a> AltScreenGuard<'a> {
+ fn enter(tui: &'a mut Tui) -> Self {
+ let _ = tui.enter_alt_screen();
+ Self { tui }
+ }
+ }
+ impl Drop for AltScreenGuard<'_> {
+ fn drop(&mut self) {
+ let _ = self.tui.leave_alt_screen();
+ }
+ }
+
+ let alt = AltScreenGuard::enter(tui);
+
+ let mut screen = ModelMigrationScreen::new(alt.tui.frame_requester(), copy);
+
+ let _ = alt.tui.draw(u16::MAX, |frame| {
+ frame.render_widget_ref(&screen, frame.area());
+ });
+
+ let events = alt.tui.event_stream();
+ tokio::pin!(events);
+
+ while !screen.is_done() {
+ if let Some(event) = events.next().await {
+ match event {
+ TuiEvent::Key(key_event) => screen.handle_key(key_event),
+ TuiEvent::Paste(_) => {}
+ TuiEvent::Draw => {
+ let _ = alt.tui.draw(u16::MAX, |frame| {
+ frame.render_widget_ref(&screen, frame.area());
+ });
+ }
+ }
+ } else {
+ screen.accept();
+ break;
+ }
+ }
+
+ screen.outcome()
+}
+
+struct ModelMigrationScreen {
+ request_frame: FrameRequester,
+ copy: ModelMigrationCopy,
+ done: bool,
+ outcome: ModelMigrationOutcome,
+ highlighted_option: MigrationMenuOption,
+}
+
+impl ModelMigrationScreen {
+ fn new(request_frame: FrameRequester, copy: ModelMigrationCopy) -> Self {
+ Self {
+ request_frame,
+ copy,
+ done: false,
+ outcome: ModelMigrationOutcome::Accepted,
+ highlighted_option: MigrationMenuOption::TryNewModel,
+ }
+ }
+
+ fn finish_with(&mut self, outcome: ModelMigrationOutcome) {
+ self.outcome = outcome;
+ self.done = true;
+ self.request_frame.schedule_frame();
+ }
+
+ fn accept(&mut self) {
+ self.finish_with(ModelMigrationOutcome::Accepted);
+ }
+
+ fn reject(&mut self) {
+ self.finish_with(ModelMigrationOutcome::Rejected);
+ }
+
+ fn exit(&mut self) {
+ self.finish_with(ModelMigrationOutcome::Exit);
+ }
+
+ fn confirm_selection(&mut self) {
+ if self.copy.can_opt_out {
+ match self.highlighted_option {
+ MigrationMenuOption::TryNewModel => self.accept(),
+ MigrationMenuOption::UseExistingModel => self.reject(),
+ }
+ } else {
+ self.accept();
+ }
+ }
+
+ fn highlight_option(&mut self, option: MigrationMenuOption) {
+ if self.highlighted_option != option {
+ self.highlighted_option = option;
+ self.request_frame.schedule_frame();
+ }
+ }
+
+ fn handle_key(&mut self, key_event: KeyEvent) {
+ if key_event.kind == KeyEventKind::Release {
+ return;
+ }
+
+ if key_event.modifiers.contains(KeyModifiers::CONTROL)
+ && matches!(key_event.code, KeyCode::Char('c') | KeyCode::Char('d'))
+ {
+ self.exit();
+ return;
+ }
+
+ if !self.copy.can_opt_out {
+ if matches!(key_event.code, KeyCode::Esc | KeyCode::Enter) {
+ self.accept();
+ }
+ return;
+ }
+
+ match key_event.code {
+ KeyCode::Up | KeyCode::Char('k') => {
+ self.highlight_option(MigrationMenuOption::TryNewModel);
+ }
+ KeyCode::Down | KeyCode::Char('j') => {
+ self.highlight_option(MigrationMenuOption::UseExistingModel);
+ }
+ KeyCode::Char('1') => {
+ self.highlight_option(MigrationMenuOption::TryNewModel);
+ self.accept();
+ }
+ KeyCode::Char('2') => {
+ self.highlight_option(MigrationMenuOption::UseExistingModel);
+ self.reject();
+ }
+ KeyCode::Enter | KeyCode::Esc => {
+ self.confirm_selection();
+ }
+ _ => {}
+ }
+ }
+
+ fn is_done(&self) -> bool {
+ self.done
+ }
+
+ fn outcome(&self) -> ModelMigrationOutcome {
+ self.outcome
+ }
+}
+
+impl WidgetRef for &ModelMigrationScreen {
+ fn render_ref(&self, area: ratatui::layout::Rect, buf: &mut ratatui::buffer::Buffer) {
+ Clear.render(area, buf);
+
+ let mut column = ColumnRenderable::new();
+
+ column.push("");
+ let mut heading = vec![Span::raw("> ")];
+ heading.extend(self.copy.heading.clone());
+ column.push(Line::from(heading));
+ column.push(Line::from(""));
+
+ for (idx, line) in self.copy.content.iter().enumerate() {
+ if idx != 0 {
+ column.push(Line::from(""));
+ }
+
+ column.push(
+ Paragraph::new(line.clone())
+ .wrap(Wrap { trim: false })
+ .inset(Insets::tlbr(0, 2, 0, 0)),
+ );
+ }
+
+ if self.copy.can_opt_out {
+ column.push(Line::from(""));
+ column.push(
+ Paragraph::new("Choose how you'd like Codex to proceed.")
+ .wrap(Wrap { trim: false })
+ .inset(Insets::tlbr(0, 2, 0, 0)),
+ );
+ column.push(Line::from(""));
+
+ for (idx, option) in MigrationMenuOption::all().into_iter().enumerate() {
+ column.push(selection_option_row(
+ idx,
+ option.label().to_string(),
+ self.highlighted_option == option,
+ ));
+ }
+
+ column.push(Line::from(""));
+ column.push(
+ Line::from(vec![
+ "Use ".dim(),
+ key_hint::plain(KeyCode::Up).into(),
+ "/".dim(),
+ key_hint::plain(KeyCode::Down).into(),
+ " to move, press ".dim(),
+ key_hint::plain(KeyCode::Enter).into(),
+ " to confirm".dim(),
+ ])
+ .inset(Insets::tlbr(0, 2, 0, 0)),
+ );
+ }
+
+ column.render(area, buf);
+ }
+}
+
+fn gpt_5_1_codex_max_migration_copy() -> ModelMigrationCopy {
+ ModelMigrationCopy {
+ heading: vec!["Codex just got an upgrade. Introducing gpt-5.1-codex-max".bold()],
+ content: vec![
+ Line::from(
+ "Codex is now powered by gpt-5.1-codex-max, our latest frontier agentic coding model. It is smarter and faster than its predecessors and capable of long-running project-scale work.",
+ ),
+ Line::from(vec![
+ "Learn more at ".into(),
+ "https://openai.com/index/gpt-5-1-codex-max/"
+ .cyan()
+ .underlined(),
+ ".".into(),
+ ]),
+ ],
+ can_opt_out: true,
+ }
+}
+
+fn gpt5_migration_copy() -> ModelMigrationCopy {
+ ModelMigrationCopy {
+ heading: vec!["Introducing our gpt-5.1 models".bold()],
+ content: vec![
+ Line::from(
+ "We've upgraded our family of models supported in Codex to gpt-5.1, gpt-5.1-codex and gpt-5.1-codex-mini.",
+ ),
+ Line::from(
+ "You can continue using legacy models by specifying them directly with the -m option or in your config.toml.",
+ ),
+ Line::from(vec![
+ "Learn more at ".into(),
+ "https://openai.com/index/gpt-5-1/".cyan().underlined(),
+ ".".into(),
+ ]),
+ Line::from(vec!["Press enter to continue".dim()]),
+ ],
+ can_opt_out: false,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::ModelMigrationScreen;
+ use super::gpt_5_1_codex_max_migration_copy;
+ use super::migration_copy_for_config;
+ use crate::custom_terminal::Terminal;
+ use crate::test_backend::VT100Backend;
+ use crate::tui::FrameRequester;
+ use codex_core::openai_models::model_presets::HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG;
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use insta::assert_snapshot;
+ use ratatui::layout::Rect;
+
+ #[test]
+ fn prompt_snapshot() {
+ let width: u16 = 60;
+ let height: u16 = 20;
+ let backend = VT100Backend::new(width, height);
+ let mut terminal = Terminal::with_options(backend).expect("terminal");
+ terminal.set_viewport_area(Rect::new(0, 0, width, height));
+
+ let screen = ModelMigrationScreen::new(
+ FrameRequester::test_dummy(),
+ gpt_5_1_codex_max_migration_copy(),
+ );
+
+ {
+ let mut frame = terminal.get_frame();
+ frame.render_widget_ref(&screen, frame.area());
+ }
+ terminal.flush().expect("flush");
+
+ assert_snapshot!("model_migration_prompt", terminal.backend());
+ }
+
+ #[test]
+ fn prompt_snapshot_gpt5_family() {
+ let backend = VT100Backend::new(65, 12);
+ let mut terminal = Terminal::with_options(backend).expect("terminal");
+ terminal.set_viewport_area(Rect::new(0, 0, 65, 12));
+
+ let screen = ModelMigrationScreen::new(
+ FrameRequester::test_dummy(),
+ migration_copy_for_config(HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG),
+ );
+ {
+ let mut frame = terminal.get_frame();
+ frame.render_widget_ref(&screen, frame.area());
+ }
+ terminal.flush().expect("flush");
+ assert_snapshot!("model_migration_prompt_gpt5_family", terminal.backend());
+ }
+
+ #[test]
+ fn prompt_snapshot_gpt5_codex() {
+ let backend = VT100Backend::new(60, 12);
+ let mut terminal = Terminal::with_options(backend).expect("terminal");
+ terminal.set_viewport_area(Rect::new(0, 0, 60, 12));
+
+ let screen = ModelMigrationScreen::new(
+ FrameRequester::test_dummy(),
+ migration_copy_for_config(HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG),
+ );
+ {
+ let mut frame = terminal.get_frame();
+ frame.render_widget_ref(&screen, frame.area());
+ }
+ terminal.flush().expect("flush");
+ assert_snapshot!("model_migration_prompt_gpt5_codex", terminal.backend());
+ }
+
+ #[test]
+ fn prompt_snapshot_gpt5_codex_mini() {
+ let backend = VT100Backend::new(60, 12);
+ let mut terminal = Terminal::with_options(backend).expect("terminal");
+ terminal.set_viewport_area(Rect::new(0, 0, 60, 12));
+
+ let screen = ModelMigrationScreen::new(
+ FrameRequester::test_dummy(),
+ migration_copy_for_config(HIDE_GPT5_1_MIGRATION_PROMPT_CONFIG),
+ );
+ {
+ let mut frame = terminal.get_frame();
+ frame.render_widget_ref(&screen, frame.area());
+ }
+ terminal.flush().expect("flush");
+ assert_snapshot!("model_migration_prompt_gpt5_codex_mini", terminal.backend());
+ }
+
+ #[test]
+ fn escape_key_accepts_prompt() {
+ let mut screen = ModelMigrationScreen::new(
+ FrameRequester::test_dummy(),
+ gpt_5_1_codex_max_migration_copy(),
+ );
+
+ // Simulate pressing Escape
+ screen.handle_key(KeyEvent::new(
+ KeyCode::Esc,
+ crossterm::event::KeyModifiers::NONE,
+ ));
+ assert!(screen.is_done());
+ // Esc should not be treated as Exit – it accepts like Enter.
+ assert!(matches!(
+ screen.outcome(),
+ super::ModelMigrationOutcome::Accepted
+ ));
+ }
+
+ #[test]
+ fn selecting_use_existing_model_rejects_upgrade() {
+ let mut screen = ModelMigrationScreen::new(
+ FrameRequester::test_dummy(),
+ gpt_5_1_codex_max_migration_copy(),
+ );
+
+ screen.handle_key(KeyEvent::new(
+ KeyCode::Down,
+ crossterm::event::KeyModifiers::NONE,
+ ));
+ screen.handle_key(KeyEvent::new(
+ KeyCode::Enter,
+ crossterm::event::KeyModifiers::NONE,
+ ));
+
+ assert!(screen.is_done());
+ assert!(matches!(
+ screen.outcome(),
+ super::ModelMigrationOutcome::Rejected
+ ));
+ }
+}
diff --git a/codex-rs/tui2/src/onboarding/auth.rs b/codex-rs/tui2/src/onboarding/auth.rs
new file mode 100644
index 0000000000..86ddcfb64e
--- /dev/null
+++ b/codex-rs/tui2/src/onboarding/auth.rs
@@ -0,0 +1,709 @@
+#![allow(clippy::unwrap_used)]
+
+use codex_core::AuthManager;
+use codex_core::auth::AuthCredentialsStoreMode;
+use codex_core::auth::CLIENT_ID;
+use codex_core::auth::login_with_api_key;
+use codex_core::auth::read_openai_api_key_from_env;
+use codex_login::ServerOptions;
+use codex_login::ShutdownHandle;
+use codex_login::run_login_server;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use crossterm::event::KeyModifiers;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Constraint;
+use ratatui::layout::Layout;
+use ratatui::layout::Rect;
+use ratatui::prelude::Widget;
+use ratatui::style::Color;
+use ratatui::style::Modifier;
+use ratatui::style::Style;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::widgets::Block;
+use ratatui::widgets::BorderType;
+use ratatui::widgets::Borders;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::WidgetRef;
+use ratatui::widgets::Wrap;
+
+use codex_app_server_protocol::AuthMode;
+use codex_protocol::config_types::ForcedLoginMethod;
+use std::sync::RwLock;
+
+use crate::LoginStatus;
+use crate::onboarding::onboarding_screen::KeyboardHandler;
+use crate::onboarding::onboarding_screen::StepStateProvider;
+use crate::shimmer::shimmer_spans;
+use crate::tui::FrameRequester;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use super::onboarding_screen::StepState;
+
+#[derive(Clone)]
+pub(crate) enum SignInState {
+ PickMode,
+ ChatGptContinueInBrowser(ContinueInBrowserState),
+ ChatGptSuccessMessage,
+ ChatGptSuccess,
+ ApiKeyEntry(ApiKeyInputState),
+ ApiKeyConfigured,
+}
+
+const API_KEY_DISABLED_MESSAGE: &str = "API key login is disabled.";
+
+#[derive(Clone, Default)]
+pub(crate) struct ApiKeyInputState {
+ value: String,
+ prepopulated_from_env: bool,
+}
+
+#[derive(Clone)]
+/// Used to manage the lifecycle of SpawnedLogin and ensure it gets cleaned up.
+pub(crate) struct ContinueInBrowserState {
+ auth_url: String,
+ shutdown_flag: Option<ShutdownHandle>,
+}
+
+impl Drop for ContinueInBrowserState {
+ fn drop(&mut self) {
+ if let Some(handle) = &self.shutdown_flag {
+ handle.shutdown();
+ }
+ }
+}
+
+impl KeyboardHandler for AuthModeWidget {
+ fn handle_key_event(&mut self, key_event: KeyEvent) {
+ if self.handle_api_key_entry_key_event(&key_event) {
+ return;
+ }
+
+ match key_event.code {
+ KeyCode::Up | KeyCode::Char('k') => {
+ if self.is_chatgpt_login_allowed() {
+ self.highlighted_mode = AuthMode::ChatGPT;
+ }
+ }
+ KeyCode::Down | KeyCode::Char('j') => {
+ if self.is_api_login_allowed() {
+ self.highlighted_mode = AuthMode::ApiKey;
+ }
+ }
+ KeyCode::Char('1') => {
+ if self.is_chatgpt_login_allowed() {
+ self.start_chatgpt_login();
+ }
+ }
+ KeyCode::Char('2') => {
+ if self.is_api_login_allowed() {
+ self.start_api_key_entry();
+ } else {
+ self.disallow_api_login();
+ }
+ }
+ KeyCode::Enter => {
+ let sign_in_state = { (*self.sign_in_state.read().unwrap()).clone() };
+ match sign_in_state {
+ SignInState::PickMode => match self.highlighted_mode {
+ AuthMode::ChatGPT if self.is_chatgpt_login_allowed() => {
+ self.start_chatgpt_login();
+ }
+ AuthMode::ApiKey if self.is_api_login_allowed() => {
+ self.start_api_key_entry();
+ }
+ AuthMode::ChatGPT => {}
+ AuthMode::ApiKey => {
+ self.disallow_api_login();
+ }
+ },
+ SignInState::ChatGptSuccessMessage => {
+ *self.sign_in_state.write().unwrap() = SignInState::ChatGptSuccess;
+ }
+ _ => {}
+ }
+ }
+ KeyCode::Esc => {
+ tracing::info!("Esc pressed");
+ let sign_in_state = { (*self.sign_in_state.read().unwrap()).clone() };
+ if matches!(sign_in_state, SignInState::ChatGptContinueInBrowser(_)) {
+ *self.sign_in_state.write().unwrap() = SignInState::PickMode;
+ self.request_frame.schedule_frame();
+ }
+ }
+ _ => {}
+ }
+ }
+
+ fn handle_paste(&mut self, pasted: String) {
+ let _ = self.handle_api_key_entry_paste(pasted);
+ }
+}
+
+#[derive(Clone)]
+pub(crate) struct AuthModeWidget {
+ pub request_frame: FrameRequester,
+ pub highlighted_mode: AuthMode,
+ pub error: Option<String>,
+ pub sign_in_state: Arc<RwLock<SignInState>>,
+ pub codex_home: PathBuf,
+ pub cli_auth_credentials_store_mode: AuthCredentialsStoreMode,
+ pub login_status: LoginStatus,
+ pub auth_manager: Arc<AuthManager>,
+ pub forced_chatgpt_workspace_id: Option<String>,
+ pub forced_login_method: Option<ForcedLoginMethod>,
+ pub animations_enabled: bool,
+}
+
+impl AuthModeWidget {
+ fn is_api_login_allowed(&self) -> bool {
+ !matches!(self.forced_login_method, Some(ForcedLoginMethod::Chatgpt))
+ }
+
+ fn is_chatgpt_login_allowed(&self) -> bool {
+ !matches!(self.forced_login_method, Some(ForcedLoginMethod::Api))
+ }
+
+ fn disallow_api_login(&mut self) {
+ self.highlighted_mode = AuthMode::ChatGPT;
+ self.error = Some(API_KEY_DISABLED_MESSAGE.to_string());
+ *self.sign_in_state.write().unwrap() = SignInState::PickMode;
+ self.request_frame.schedule_frame();
+ }
+
+ fn render_pick_mode(&self, area: Rect, buf: &mut Buffer) {
+ let mut lines: Vec<Line> = vec![
+ Line::from(vec![
+ " ".into(),
+ "Sign in with ChatGPT to use Codex as part of your paid plan".into(),
+ ]),
+ Line::from(vec![
+ " ".into(),
+ "or connect an API key for usage-based billing".into(),
+ ]),
+ "".into(),
+ ];
+
+ let create_mode_item = |idx: usize,
+ selected_mode: AuthMode,
+ text: &str,
+ description: &str|
+ -> Vec<Line<'static>> {
+ let is_selected = self.highlighted_mode == selected_mode;
+ let caret = if is_selected { ">" } else { " " };
+
+ let line1 = if is_selected {
+ Line::from(vec![
+ format!("{} {}. ", caret, idx + 1).cyan().dim(),
+ text.to_string().cyan(),
+ ])
+ } else {
+ format!(" {}. {text}", idx + 1).into()
+ };
+
+ let line2 = if is_selected {
+ Line::from(format!(" {description}"))
+ .fg(Color::Cyan)
+ .add_modifier(Modifier::DIM)
+ } else {
+ Line::from(format!(" {description}"))
+ .style(Style::default().add_modifier(Modifier::DIM))
+ };
+
+ vec![line1, line2]
+ };
+
+ let chatgpt_description = if self.is_chatgpt_login_allowed() {
+ "Usage included with Plus, Pro, Team, and Enterprise plans"
+ } else {
+ "ChatGPT login is disabled"
+ };
+ lines.extend(create_mode_item(
+ 0,
+ AuthMode::ChatGPT,
+ "Sign in with ChatGPT",
+ chatgpt_description,
+ ));
+ lines.push("".into());
+ if self.is_api_login_allowed() {
+ lines.extend(create_mode_item(
+ 1,
+ AuthMode::ApiKey,
+ "Provide your own API key",
+ "Pay for what you use",
+ ));
+ lines.push("".into());
+ } else {
+ lines.push(
+ " API key login is disabled by this workspace. Sign in with ChatGPT to continue."
+ .dim()
+ .into(),
+ );
+ lines.push("".into());
+ }
+ lines.push(
+ // AE: Following styles.md, this should probably be Cyan because it's a user input tip.
+ // But leaving this for a future cleanup.
+ " Press Enter to continue".dim().into(),
+ );
+ if let Some(err) = &self.error {
+ lines.push("".into());
+ lines.push(err.as_str().red().into());
+ }
+
+ Paragraph::new(lines)
+ .wrap(Wrap { trim: false })
+ .render(area, buf);
+ }
+
+ fn render_continue_in_browser(&self, area: Rect, buf: &mut Buffer) {
+ let mut spans = vec![" ".into()];
+ if self.animations_enabled {
+ // Schedule a follow-up frame to keep the shimmer animation going.
+ self.request_frame
+ .schedule_frame_in(std::time::Duration::from_millis(100));
+ spans.extend(shimmer_spans("Finish signing in via your browser"));
+ } else {
+ spans.push("Finish signing in via your browser".into());
+ }
+ let mut lines = vec![spans.into(), "".into()];
+
+ let sign_in_state = self.sign_in_state.read().unwrap();
+ if let SignInState::ChatGptContinueInBrowser(state) = &*sign_in_state
+ && !state.auth_url.is_empty()
+ {
+ lines.push(" If the link doesn't open automatically, open the following link to authenticate:".into());
+ lines.push("".into());
+ lines.push(Line::from(state.auth_url.as_str().cyan().underlined()));
+ lines.push("".into());
+ }
+
+ lines.push(" Press Esc to cancel".dim().into());
+ Paragraph::new(lines)
+ .wrap(Wrap { trim: false })
+ .render(area, buf);
+ }
+
+ fn render_chatgpt_success_message(&self, area: Rect, buf: &mut Buffer) {
+ let lines = vec![
+ "✓ Signed in with your ChatGPT account".fg(Color::Green).into(),
+ "".into(),
+ " Before you start:".into(),
+ "".into(),
+ " Decide how much autonomy you want to grant Codex".into(),
+ Line::from(vec![
+ " For more details see the ".into(),
+ "\u{1b}]8;;https://github.com/openai/codex\u{7}Codex docs\u{1b}]8;;\u{7}".underlined(),
+ ])
+ .dim(),
+ "".into(),
+ " Codex can make mistakes".into(),
+ " Review the code it writes and commands it runs".dim().into(),
+ "".into(),
+ " Powered by your ChatGPT account".into(),
+ Line::from(vec![
+ " Uses your plan's rate limits and ".into(),
+ "\u{1b}]8;;https://chatgpt.com/#settings\u{7}training data preferences\u{1b}]8;;\u{7}".underlined(),
+ ])
+ .dim(),
+ "".into(),
+ " Press Enter to continue".fg(Color::Cyan).into(),
+ ];
+
+ Paragraph::new(lines)
+ .wrap(Wrap { trim: false })
+ .render(area, buf);
+ }
+
+ fn render_chatgpt_success(&self, area: Rect, buf: &mut Buffer) {
+ let lines = vec![
+ "✓ Signed in with your ChatGPT account"
+ .fg(Color::Green)
+ .into(),
+ ];
+
+ Paragraph::new(lines)
+ .wrap(Wrap { trim: false })
+ .render(area, buf);
+ }
+
+ fn render_api_key_configured(&self, area: Rect, buf: &mut Buffer) {
+ let lines = vec![
+ "✓ API key configured".fg(Color::Green).into(),
+ "".into(),
+ " Codex will use usage-based billing with your API key.".into(),
+ ];
+
+ Paragraph::new(lines)
+ .wrap(Wrap { trim: false })
+ .render(area, buf);
+ }
+
+ fn render_api_key_entry(&self, area: Rect, buf: &mut Buffer, state: &ApiKeyInputState) {
+ let [intro_area, input_area, footer_area] = Layout::vertical([
+ Constraint::Min(4),
+ Constraint::Length(3),
+ Constraint::Min(2),
+ ])
+ .areas(area);
+
+ let mut intro_lines: Vec<Line> = vec![
+ Line::from(vec![
+ "> ".into(),
+ "Use your own OpenAI API key for usage-based billing".bold(),
+ ]),
+ "".into(),
+ " Paste or type your API key below. It will be stored locally in auth.json.".into(),
+ "".into(),
+ ];
+ if state.prepopulated_from_env {
+ intro_lines.push(" Detected OPENAI_API_KEY environment variable.".into());
+ intro_lines.push(
+ " Paste a different key if you prefer to use another account."
+ .dim()
+ .into(),
+ );
+ intro_lines.push("".into());
+ }
+ Paragraph::new(intro_lines)
+ .wrap(Wrap { trim: false })
+ .render(intro_area, buf);
+
+ let content_line: Line = if state.value.is_empty() {
+ vec!["Paste or type your API key".dim()].into()
+ } else {
+ Line::from(state.value.clone())
+ };
+ Paragraph::new(content_line)
+ .wrap(Wrap { trim: false })
+ .block(
+ Block::default()
+ .title("API key")
+ .borders(Borders::ALL)
+ .border_type(BorderType::Rounded)
+ .border_style(Style::default().fg(Color::Cyan)),
+ )
+ .render(input_area, buf);
+
+ let mut footer_lines: Vec<Line> = vec![
+ " Press Enter to save".dim().into(),
+ " Press Esc to go back".dim().into(),
+ ];
+ if let Some(error) = &self.error {
+ footer_lines.push("".into());
+ footer_lines.push(error.as_str().red().into());
+ }
+ Paragraph::new(footer_lines)
+ .wrap(Wrap { trim: false })
+ .render(footer_area, buf);
+ }
+
+ fn handle_api_key_entry_key_event(&mut self, key_event: &KeyEvent) -> bool {
+ let mut should_save: Option<String> = None;
+ let mut should_request_frame = false;
+
+ {
+ let mut guard = self.sign_in_state.write().unwrap();
+ if let SignInState::ApiKeyEntry(state) = &mut *guard {
+ match key_event.code {
+ KeyCode::Esc => {
+ *guard = SignInState::PickMode;
+ self.error = None;
+ should_request_frame = true;
+ }
+ KeyCode::Enter => {
+ let trimmed = state.value.trim().to_string();
+ if trimmed.is_empty() {
+ self.error = Some("API key cannot be empty".to_string());
+ should_request_frame = true;
+ } else {
+ should_save = Some(trimmed);
+ }
+ }
+ KeyCode::Backspace => {
+ if state.prepopulated_from_env {
+ state.value.clear();
+ state.prepopulated_from_env = false;
+ } else {
+ state.value.pop();
+ }
+ self.error = None;
+ should_request_frame = true;
+ }
+ KeyCode::Char(c)
+ if key_event.kind == KeyEventKind::Press
+ && !key_event.modifiers.contains(KeyModifiers::SUPER)
+ && !key_event.modifiers.contains(KeyModifiers::CONTROL)
+ && !key_event.modifiers.contains(KeyModifiers::ALT) =>
+ {
+ if state.prepopulated_from_env {
+ state.value.clear();
+ state.prepopulated_from_env = false;
+ }
+ state.value.push(c);
+ self.error = None;
+ should_request_frame = true;
+ }
+ _ => {}
+ }
+ // handled; let guard drop before potential save
+ } else {
+ return false;
+ }
+ }
+
+ if let Some(api_key) = should_save {
+ self.save_api_key(api_key);
+ } else if should_request_frame {
+ self.request_frame.schedule_frame();
+ }
+ true
+ }
+
+ fn handle_api_key_entry_paste(&mut self, pasted: String) -> bool {
+ let trimmed = pasted.trim();
+ if trimmed.is_empty() {
+ return false;
+ }
+
+ let mut guard = self.sign_in_state.write().unwrap();
+ if let SignInState::ApiKeyEntry(state) = &mut *guard {
+ if state.prepopulated_from_env {
+ state.value = trimmed.to_string();
+ state.prepopulated_from_env = false;
+ } else {
+ state.value.push_str(trimmed);
+ }
+ self.error = None;
+ } else {
+ return false;
+ }
+
+ drop(guard);
+ self.request_frame.schedule_frame();
+ true
+ }
+
+ fn start_api_key_entry(&mut self) {
+ if !self.is_api_login_allowed() {
+ self.disallow_api_login();
+ return;
+ }
+ self.error = None;
+ let prefill_from_env = read_openai_api_key_from_env();
+ let mut guard = self.sign_in_state.write().unwrap();
+ match &mut *guard {
+ SignInState::ApiKeyEntry(state) => {
+ if state.value.is_empty() {
+ if let Some(prefill) = prefill_from_env {
+ state.value = prefill;
+ state.prepopulated_from_env = true;
+ } else {
+ state.prepopulated_from_env = false;
+ }
+ }
+ }
+ _ => {
+ *guard = SignInState::ApiKeyEntry(ApiKeyInputState {
+ value: prefill_from_env.clone().unwrap_or_default(),
+ prepopulated_from_env: prefill_from_env.is_some(),
+ });
+ }
+ }
+ drop(guard);
+ self.request_frame.schedule_frame();
+ }
+
+ fn save_api_key(&mut self, api_key: String) {
+ if !self.is_api_login_allowed() {
+ self.disallow_api_login();
+ return;
+ }
+ match login_with_api_key(
+ &self.codex_home,
+ &api_key,
+ self.cli_auth_credentials_store_mode,
+ ) {
+ Ok(()) => {
+ self.error = None;
+ self.login_status = LoginStatus::AuthMode(AuthMode::ApiKey);
+ self.auth_manager.reload();
+ *self.sign_in_state.write().unwrap() = SignInState::ApiKeyConfigured;
+ }
+ Err(err) => {
+ self.error = Some(format!("Failed to save API key: {err}"));
+ let mut guard = self.sign_in_state.write().unwrap();
+ if let SignInState::ApiKeyEntry(existing) = &mut *guard {
+ if existing.value.is_empty() {
+ existing.value.push_str(&api_key);
+ }
+ existing.prepopulated_from_env = false;
+ } else {
+ *guard = SignInState::ApiKeyEntry(ApiKeyInputState {
+ value: api_key,
+ prepopulated_from_env: false,
+ });
+ }
+ }
+ }
+
+ self.request_frame.schedule_frame();
+ }
+
+ fn start_chatgpt_login(&mut self) {
+ // If we're already authenticated with ChatGPT, don't start a new login –
+ // just proceed to the success message flow.
+ if matches!(self.login_status, LoginStatus::AuthMode(AuthMode::ChatGPT)) {
+ *self.sign_in_state.write().unwrap() = SignInState::ChatGptSuccess;
+ self.request_frame.schedule_frame();
+ return;
+ }
+
+ self.error = None;
+ let opts = ServerOptions::new(
+ self.codex_home.clone(),
+ CLIENT_ID.to_string(),
+ self.forced_chatgpt_workspace_id.clone(),
+ self.cli_auth_credentials_store_mode,
+ );
+ match run_login_server(opts) {
+ Ok(child) => {
+ let sign_in_state = self.sign_in_state.clone();
+ let request_frame = self.request_frame.clone();
+ let auth_manager = self.auth_manager.clone();
+ tokio::spawn(async move {
+ let auth_url = child.auth_url.clone();
+ {
+ *sign_in_state.write().unwrap() =
+ SignInState::ChatGptContinueInBrowser(ContinueInBrowserState {
+ auth_url,
+ shutdown_flag: Some(child.cancel_handle()),
+ });
+ }
+ request_frame.schedule_frame();
+ let r = child.block_until_done().await;
+ match r {
+ Ok(()) => {
+ // Force the auth manager to reload the new auth information.
+ auth_manager.reload();
+
+ *sign_in_state.write().unwrap() = SignInState::ChatGptSuccessMessage;
+ request_frame.schedule_frame();
+ }
+ _ => {
+ *sign_in_state.write().unwrap() = SignInState::PickMode;
+ // self.error = Some(e.to_string());
+ request_frame.schedule_frame();
+ }
+ }
+ });
+ }
+ Err(e) => {
+ *self.sign_in_state.write().unwrap() = SignInState::PickMode;
+ self.error = Some(e.to_string());
+ self.request_frame.schedule_frame();
+ }
+ }
+ }
+}
+
+impl StepStateProvider for AuthModeWidget {
+ fn get_step_state(&self) -> StepState {
+ let sign_in_state = self.sign_in_state.read().unwrap();
+ match &*sign_in_state {
+ SignInState::PickMode
+ | SignInState::ApiKeyEntry(_)
+ | SignInState::ChatGptContinueInBrowser(_)
+ | SignInState::ChatGptSuccessMessage => StepState::InProgress,
+ SignInState::ChatGptSuccess | SignInState::ApiKeyConfigured => StepState::Complete,
+ }
+ }
+}
+
+impl WidgetRef for AuthModeWidget {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ let sign_in_state = self.sign_in_state.read().unwrap();
+ match &*sign_in_state {
+ SignInState::PickMode => {
+ self.render_pick_mode(area, buf);
+ }
+ SignInState::ChatGptContinueInBrowser(_) => {
+ self.render_continue_in_browser(area, buf);
+ }
+ SignInState::ChatGptSuccessMessage => {
+ self.render_chatgpt_success_message(area, buf);
+ }
+ SignInState::ChatGptSuccess => {
+ self.render_chatgpt_success(area, buf);
+ }
+ SignInState::ApiKeyEntry(state) => {
+ self.render_api_key_entry(area, buf, state);
+ }
+ SignInState::ApiKeyConfigured => {
+ self.render_api_key_configured(area, buf);
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use pretty_assertions::assert_eq;
+ use tempfile::TempDir;
+
+ use codex_core::auth::AuthCredentialsStoreMode;
+
+ fn widget_forced_chatgpt() -> (AuthModeWidget, TempDir) {
+ let codex_home = TempDir::new().unwrap();
+ let codex_home_path = codex_home.path().to_path_buf();
+ let widget = AuthModeWidget {
+ request_frame: FrameRequester::test_dummy(),
+ highlighted_mode: AuthMode::ChatGPT,
+ error: None,
+ sign_in_state: Arc::new(RwLock::new(SignInState::PickMode)),
+ codex_home: codex_home_path.clone(),
+ cli_auth_credentials_store_mode: AuthCredentialsStoreMode::File,
+ login_status: LoginStatus::NotAuthenticated,
+ auth_manager: AuthManager::shared(
+ codex_home_path,
+ false,
+ AuthCredentialsStoreMode::File,
+ ),
+ forced_chatgpt_workspace_id: None,
+ forced_login_method: Some(ForcedLoginMethod::Chatgpt),
+ animations_enabled: true,
+ };
+ (widget, codex_home)
+ }
+
+ #[test]
+ fn api_key_flow_disabled_when_chatgpt_forced() {
+ let (mut widget, _tmp) = widget_forced_chatgpt();
+
+ widget.start_api_key_entry();
+
+ assert_eq!(widget.error.as_deref(), Some(API_KEY_DISABLED_MESSAGE));
+ assert!(matches!(
+ &*widget.sign_in_state.read().unwrap(),
+ SignInState::PickMode
+ ));
+ }
+
+ #[test]
+ fn saving_api_key_is_blocked_when_chatgpt_forced() {
+ let (mut widget, _tmp) = widget_forced_chatgpt();
+
+ widget.save_api_key("sk-test".to_string());
+
+ assert_eq!(widget.error.as_deref(), Some(API_KEY_DISABLED_MESSAGE));
+ assert!(matches!(
+ &*widget.sign_in_state.read().unwrap(),
+ SignInState::PickMode
+ ));
+ assert_eq!(widget.login_status, LoginStatus::NotAuthenticated);
+ }
+}
diff --git a/codex-rs/tui2/src/onboarding/mod.rs b/codex-rs/tui2/src/onboarding/mod.rs
new file mode 100644
index 0000000000..d4cfd6d1f4
--- /dev/null
+++ b/codex-rs/tui2/src/onboarding/mod.rs
@@ -0,0 +1,5 @@
+mod auth;
+pub mod onboarding_screen;
+mod trust_directory;
+pub use trust_directory::TrustDirectorySelection;
+mod welcome;
diff --git a/codex-rs/tui2/src/onboarding/onboarding_screen.rs b/codex-rs/tui2/src/onboarding/onboarding_screen.rs
new file mode 100644
index 0000000000..47c7811a3b
--- /dev/null
+++ b/codex-rs/tui2/src/onboarding/onboarding_screen.rs
@@ -0,0 +1,430 @@
+use codex_core::AuthManager;
+use codex_core::config::Config;
+use codex_core::git_info::get_git_repo_root;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::prelude::Widget;
+use ratatui::style::Color;
+use ratatui::widgets::Clear;
+use ratatui::widgets::WidgetRef;
+
+use codex_app_server_protocol::AuthMode;
+use codex_protocol::config_types::ForcedLoginMethod;
+
+use crate::LoginStatus;
+use crate::onboarding::auth::AuthModeWidget;
+use crate::onboarding::auth::SignInState;
+use crate::onboarding::trust_directory::TrustDirectorySelection;
+use crate::onboarding::trust_directory::TrustDirectoryWidget;
+use crate::onboarding::welcome::WelcomeWidget;
+use crate::tui::FrameRequester;
+use crate::tui::Tui;
+use crate::tui::TuiEvent;
+use color_eyre::eyre::Result;
+use std::sync::Arc;
+use std::sync::RwLock;
+
+#[allow(clippy::large_enum_variant)]
+enum Step {
+ Welcome(WelcomeWidget),
+ Auth(AuthModeWidget),
+ TrustDirectory(TrustDirectoryWidget),
+}
+
+pub(crate) trait KeyboardHandler {
+ fn handle_key_event(&mut self, key_event: KeyEvent);
+ fn handle_paste(&mut self, _pasted: String) {}
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum StepState {
+ Hidden,
+ InProgress,
+ Complete,
+}
+
+pub(crate) trait StepStateProvider {
+ fn get_step_state(&self) -> StepState;
+}
+
+pub(crate) struct OnboardingScreen {
+ request_frame: FrameRequester,
+ steps: Vec<Step>,
+ is_done: bool,
+ should_exit: bool,
+}
+
+pub(crate) struct OnboardingScreenArgs {
+ pub show_trust_screen: bool,
+ pub show_login_screen: bool,
+ pub login_status: LoginStatus,
+ pub auth_manager: Arc<AuthManager>,
+ pub config: Config,
+}
+
+pub(crate) struct OnboardingResult {
+ pub directory_trust_decision: Option<TrustDirectorySelection>,
+ pub should_exit: bool,
+}
+
+impl OnboardingScreen {
+ pub(crate) fn new(tui: &mut Tui, args: OnboardingScreenArgs) -> Self {
+ let OnboardingScreenArgs {
+ show_trust_screen,
+ show_login_screen,
+ login_status,
+ auth_manager,
+ config,
+ } = args;
+ let cwd = config.cwd.clone();
+ let forced_chatgpt_workspace_id = config.forced_chatgpt_workspace_id.clone();
+ let forced_login_method = config.forced_login_method;
+ let codex_home = config.codex_home;
+ let cli_auth_credentials_store_mode = config.cli_auth_credentials_store_mode;
+ let mut steps: Vec<Step> = Vec::new();
+ steps.push(Step::Welcome(WelcomeWidget::new(
+ !matches!(login_status, LoginStatus::NotAuthenticated),
+ tui.frame_requester(),
+ config.animations,
+ )));
+ if show_login_screen {
+ let highlighted_mode = match forced_login_method {
+ Some(ForcedLoginMethod::Api) => AuthMode::ApiKey,
+ _ => AuthMode::ChatGPT,
+ };
+ steps.push(Step::Auth(AuthModeWidget {
+ request_frame: tui.frame_requester(),
+ highlighted_mode,
+ error: None,
+ sign_in_state: Arc::new(RwLock::new(SignInState::PickMode)),
+ codex_home: codex_home.clone(),
+ cli_auth_credentials_store_mode,
+ login_status,
+ auth_manager,
+ forced_chatgpt_workspace_id,
+ forced_login_method,
+ animations_enabled: config.animations,
+ }))
+ }
+ let is_git_repo = get_git_repo_root(&cwd).is_some();
+ let highlighted = if is_git_repo {
+ TrustDirectorySelection::Trust
+ } else {
+ // Default to not trusting the directory if it's not a git repo.
+ TrustDirectorySelection::DontTrust
+ };
+ if show_trust_screen {
+ steps.push(Step::TrustDirectory(TrustDirectoryWidget {
+ cwd,
+ codex_home,
+ is_git_repo,
+ selection: None,
+ highlighted,
+ error: None,
+ }))
+ }
+ // TODO: add git warning.
+ Self {
+ request_frame: tui.frame_requester(),
+ steps,
+ is_done: false,
+ should_exit: false,
+ }
+ }
+
+ fn current_steps_mut(&mut self) -> Vec<&mut Step> {
+ let mut out: Vec<&mut Step> = Vec::new();
+ for step in self.steps.iter_mut() {
+ match step.get_step_state() {
+ StepState::Hidden => continue,
+ StepState::Complete => out.push(step),
+ StepState::InProgress => {
+ out.push(step);
+ break;
+ }
+ }
+ }
+ out
+ }
+
+ fn current_steps(&self) -> Vec<&Step> {
+ let mut out: Vec<&Step> = Vec::new();
+ for step in self.steps.iter() {
+ match step.get_step_state() {
+ StepState::Hidden => continue,
+ StepState::Complete => out.push(step),
+ StepState::InProgress => {
+ out.push(step);
+ break;
+ }
+ }
+ }
+ out
+ }
+
+ fn is_auth_in_progress(&self) -> bool {
+ self.steps.iter().any(|step| {
+ matches!(step, Step::Auth(_)) && matches!(step.get_step_state(), StepState::InProgress)
+ })
+ }
+
+ pub(crate) fn is_done(&self) -> bool {
+ self.is_done
+ || !self
+ .steps
+ .iter()
+ .any(|step| matches!(step.get_step_state(), StepState::InProgress))
+ }
+
+ pub fn directory_trust_decision(&self) -> Option<TrustDirectorySelection> {
+ self.steps
+ .iter()
+ .find_map(|step| {
+ if let Step::TrustDirectory(TrustDirectoryWidget { selection, .. }) = step {
+ Some(*selection)
+ } else {
+ None
+ }
+ })
+ .flatten()
+ }
+
+ pub fn should_exit(&self) -> bool {
+ self.should_exit
+ }
+}
+
+impl KeyboardHandler for OnboardingScreen {
+ fn handle_key_event(&mut self, key_event: KeyEvent) {
+ match key_event {
+ KeyEvent {
+ code: KeyCode::Char('d'),
+ modifiers: crossterm::event::KeyModifiers::CONTROL,
+ kind: KeyEventKind::Press,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('c'),
+ modifiers: crossterm::event::KeyModifiers::CONTROL,
+ kind: KeyEventKind::Press,
+ ..
+ }
+ | KeyEvent {
+ code: KeyCode::Char('q'),
+ kind: KeyEventKind::Press,
+ ..
+ } => {
+ if self.is_auth_in_progress() {
+ // If the user cancels the auth menu, exit the app rather than
+ // leave the user at a prompt in an unauthed state.
+ self.should_exit = true;
+ }
+ self.is_done = true;
+ }
+ _ => {
+ if let Some(Step::Welcome(widget)) = self
+ .steps
+ .iter_mut()
+ .find(|step| matches!(step, Step::Welcome(_)))
+ {
+ widget.handle_key_event(key_event);
+ }
+ if let Some(active_step) = self.current_steps_mut().into_iter().last() {
+ active_step.handle_key_event(key_event);
+ }
+ }
+ };
+ self.request_frame.schedule_frame();
+ }
+
+ fn handle_paste(&mut self, pasted: String) {
+ if pasted.is_empty() {
+ return;
+ }
+
+ if let Some(active_step) = self.current_steps_mut().into_iter().last() {
+ active_step.handle_paste(pasted);
+ }
+ self.request_frame.schedule_frame();
+ }
+}
+
+impl WidgetRef for &OnboardingScreen {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ Clear.render(area, buf);
+ // Render steps top-to-bottom, measuring each step's height dynamically.
+ let mut y = area.y;
+ let bottom = area.y.saturating_add(area.height);
+ let width = area.width;
+
+ // Helper to scan a temporary buffer and return number of used rows.
+ fn used_rows(tmp: &Buffer, width: u16, height: u16) -> u16 {
+ if width == 0 || height == 0 {
+ return 0;
+ }
+ let mut last_non_empty: Option<u16> = None;
+ for yy in 0..height {
+ let mut any = false;
+ for xx in 0..width {
+ let cell = &tmp[(xx, yy)];
+ let has_symbol = !cell.symbol().trim().is_empty();
+ let has_style = cell.fg != Color::Reset
+ || cell.bg != Color::Reset
+ || !cell.modifier.is_empty();
+ if has_symbol || has_style {
+ any = true;
+ break;
+ }
+ }
+ if any {
+ last_non_empty = Some(yy);
+ }
+ }
+ last_non_empty.map(|v| v + 2).unwrap_or(0)
+ }
+
+ let mut i = 0usize;
+ let current_steps = self.current_steps();
+
+ while i < current_steps.len() && y < bottom {
+ let step = &current_steps[i];
+ let max_h = bottom.saturating_sub(y);
+ if max_h == 0 || width == 0 {
+ break;
+ }
+ let scratch_area = Rect::new(0, 0, width, max_h);
+ let mut scratch = Buffer::empty(scratch_area);
+ step.render_ref(scratch_area, &mut scratch);
+ let h = used_rows(&scratch, width, max_h).min(max_h);
+ if h > 0 {
+ let target = Rect {
+ x: area.x,
+ y,
+ width,
+ height: h,
+ };
+ Clear.render(target, buf);
+ step.render_ref(target, buf);
+ y = y.saturating_add(h);
+ }
+ i += 1;
+ }
+ }
+}
+
+impl KeyboardHandler for Step {
+ fn handle_key_event(&mut self, key_event: KeyEvent) {
+ match self {
+ Step::Welcome(widget) => widget.handle_key_event(key_event),
+ Step::Auth(widget) => widget.handle_key_event(key_event),
+ Step::TrustDirectory(widget) => widget.handle_key_event(key_event),
+ }
+ }
+
+ fn handle_paste(&mut self, pasted: String) {
+ match self {
+ Step::Welcome(_) => {}
+ Step::Auth(widget) => widget.handle_paste(pasted),
+ Step::TrustDirectory(widget) => widget.handle_paste(pasted),
+ }
+ }
+}
+
+impl StepStateProvider for Step {
+ fn get_step_state(&self) -> StepState {
+ match self {
+ Step::Welcome(w) => w.get_step_state(),
+ Step::Auth(w) => w.get_step_state(),
+ Step::TrustDirectory(w) => w.get_step_state(),
+ }
+ }
+}
+
+impl WidgetRef for Step {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ match self {
+ Step::Welcome(widget) => {
+ widget.render_ref(area, buf);
+ }
+ Step::Auth(widget) => {
+ widget.render_ref(area, buf);
+ }
+ Step::TrustDirectory(widget) => {
+ widget.render_ref(area, buf);
+ }
+ }
+ }
+}
+
+pub(crate) async fn run_onboarding_app(
+ args: OnboardingScreenArgs,
+ tui: &mut Tui,
+) -> Result<OnboardingResult> {
+ use tokio_stream::StreamExt;
+
+ let mut onboarding_screen = OnboardingScreen::new(tui, args);
+ // One-time guard to fully clear the screen after ChatGPT login success message is shown
+ let mut did_full_clear_after_success = false;
+
+ tui.draw(u16::MAX, |frame| {
+ frame.render_widget_ref(&onboarding_screen, frame.area());
+ })?;
+
+ let tui_events = tui.event_stream();
+ tokio::pin!(tui_events);
+
+ while !onboarding_screen.is_done() {
+ if let Some(event) = tui_events.next().await {
+ match event {
+ TuiEvent::Key(key_event) => {
+ onboarding_screen.handle_key_event(key_event);
+ }
+ TuiEvent::Paste(text) => {
+ onboarding_screen.handle_paste(text);
+ }
+ TuiEvent::Draw => {
+ if !did_full_clear_after_success
+ && onboarding_screen.steps.iter().any(|step| {
+ if let Step::Auth(w) = step {
+ w.sign_in_state.read().is_ok_and(|g| {
+ matches!(&*g, super::auth::SignInState::ChatGptSuccessMessage)
+ })
+ } else {
+ false
+ }
+ })
+ {
+ // Reset any lingering SGR (underline/color) before clearing
+ let _ = ratatui::crossterm::execute!(
+ std::io::stdout(),
+ ratatui::crossterm::style::SetAttribute(
+ ratatui::crossterm::style::Attribute::Reset
+ ),
+ ratatui::crossterm::style::SetAttribute(
+ ratatui::crossterm::style::Attribute::NoUnderline
+ ),
+ ratatui::crossterm::style::SetForegroundColor(
+ ratatui::crossterm::style::Color::Reset
+ ),
+ ratatui::crossterm::style::SetBackgroundColor(
+ ratatui::crossterm::style::Color::Reset
+ )
+ );
+ let _ = tui.terminal.clear();
+ did_full_clear_after_success = true;
+ }
+ let _ = tui.draw(u16::MAX, |frame| {
+ frame.render_widget_ref(&onboarding_screen, frame.area());
+ });
+ }
+ }
+ }
+ }
+ Ok(OnboardingResult {
+ directory_trust_decision: onboarding_screen.directory_trust_decision(),
+ should_exit: onboarding_screen.should_exit(),
+ })
+}
diff --git a/codex-rs/tui2/src/onboarding/snapshots/codex_tui2__onboarding__trust_directory__tests__renders_snapshot_for_git_repo.snap b/codex-rs/tui2/src/onboarding/snapshots/codex_tui2__onboarding__trust_directory__tests__renders_snapshot_for_git_repo.snap
new file mode 100644
index 0000000000..cf0b6b8ed7
--- /dev/null
+++ b/codex-rs/tui2/src/onboarding/snapshots/codex_tui2__onboarding__trust_directory__tests__renders_snapshot_for_git_repo.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/onboarding/trust_directory.rs
+expression: terminal.backend()
+---
+> You are running Codex in /workspace/project
+
+ Since this folder is version controlled, you may wish to allow Codex
+ to work in this folder without asking for approval.
+
+› 1. Yes, allow Codex to work in this folder without asking for
+ approval
+ 2. No, ask me to approve edits and commands
+
+ Press enter to continue
diff --git a/codex-rs/tui2/src/onboarding/snapshots/codex_tui__onboarding__trust_directory__tests__renders_snapshot_for_git_repo.snap b/codex-rs/tui2/src/onboarding/snapshots/codex_tui__onboarding__trust_directory__tests__renders_snapshot_for_git_repo.snap
new file mode 100644
index 0000000000..71cbc3d6ea
--- /dev/null
+++ b/codex-rs/tui2/src/onboarding/snapshots/codex_tui__onboarding__trust_directory__tests__renders_snapshot_for_git_repo.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/onboarding/trust_directory.rs
+expression: terminal.backend()
+---
+> You are running Codex in /workspace/project
+
+ Since this folder is version controlled, you may wish to allow Codex
+ to work in this folder without asking for approval.
+
+› 1. Yes, allow Codex to work in this folder without asking for
+ approval
+ 2. No, ask me to approve edits and commands
+
+ Press enter to continue
diff --git a/codex-rs/tui2/src/onboarding/trust_directory.rs b/codex-rs/tui2/src/onboarding/trust_directory.rs
new file mode 100644
index 0000000000..cf5d6e9a1a
--- /dev/null
+++ b/codex-rs/tui2/src/onboarding/trust_directory.rs
@@ -0,0 +1,238 @@
+use std::path::PathBuf;
+
+use codex_core::config::set_project_trust_level;
+use codex_core::git_info::resolve_root_git_project_for_trust;
+use codex_protocol::config_types::TrustLevel;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::WidgetRef;
+use ratatui::widgets::Wrap;
+
+use crate::key_hint;
+use crate::onboarding::onboarding_screen::KeyboardHandler;
+use crate::onboarding::onboarding_screen::StepStateProvider;
+use crate::render::Insets;
+use crate::render::renderable::ColumnRenderable;
+use crate::render::renderable::Renderable;
+use crate::render::renderable::RenderableExt as _;
+use crate::selection_list::selection_option_row;
+
+use super::onboarding_screen::StepState;
+pub(crate) struct TrustDirectoryWidget {
+ pub codex_home: PathBuf,
+ pub cwd: PathBuf,
+ pub is_git_repo: bool,
+ pub selection: Option<TrustDirectorySelection>,
+ pub highlighted: TrustDirectorySelection,
+ pub error: Option<String>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum TrustDirectorySelection {
+ Trust,
+ DontTrust,
+}
+
+impl WidgetRef for &TrustDirectoryWidget {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ let mut column = ColumnRenderable::new();
+
+ column.push(Line::from(vec![
+ "> ".into(),
+ "You are running Codex in ".bold(),
+ self.cwd.to_string_lossy().to_string().into(),
+ ]));
+ column.push("");
+
+ let guidance = if self.is_git_repo {
+ "Since this folder is version controlled, you may wish to allow Codex to work in this folder without asking for approval."
+ } else {
+ "Since this folder is not version controlled, we recommend requiring approval of all edits and commands."
+ };
+
+ column.push(
+ Paragraph::new(guidance.to_string())
+ .wrap(Wrap { trim: true })
+ .inset(Insets::tlbr(0, 2, 0, 0)),
+ );
+ column.push("");
+
+ let mut options: Vec<(&str, TrustDirectorySelection)> = Vec::new();
+ if self.is_git_repo {
+ options.push((
+ "Yes, allow Codex to work in this folder without asking for approval",
+ TrustDirectorySelection::Trust,
+ ));
+ options.push((
+ "No, ask me to approve edits and commands",
+ TrustDirectorySelection::DontTrust,
+ ));
+ } else {
+ options.push((
+ "Allow Codex to work in this folder without asking for approval",
+ TrustDirectorySelection::Trust,
+ ));
+ options.push((
+ "Require approval of edits and commands",
+ TrustDirectorySelection::DontTrust,
+ ));
+ }
+
+ for (idx, (text, selection)) in options.iter().enumerate() {
+ column.push(selection_option_row(
+ idx,
+ text.to_string(),
+ self.highlighted == *selection,
+ ));
+ }
+
+ column.push("");
+
+ if let Some(error) = &self.error {
+ column.push(
+ Paragraph::new(error.to_string())
+ .red()
+ .wrap(Wrap { trim: true })
+ .inset(Insets::tlbr(0, 2, 0, 0)),
+ );
+ column.push("");
+ }
+
+ column.push(
+ Line::from(vec![
+ "Press ".dim(),
+ key_hint::plain(KeyCode::Enter).into(),
+ " to continue".dim(),
+ ])
+ .inset(Insets::tlbr(0, 2, 0, 0)),
+ );
+
+ column.render(area, buf);
+ }
+}
+
+impl KeyboardHandler for TrustDirectoryWidget {
+ fn handle_key_event(&mut self, key_event: KeyEvent) {
+ if key_event.kind == KeyEventKind::Release {
+ return;
+ }
+
+ match key_event.code {
+ KeyCode::Up | KeyCode::Char('k') => {
+ self.highlighted = TrustDirectorySelection::Trust;
+ }
+ KeyCode::Down | KeyCode::Char('j') => {
+ self.highlighted = TrustDirectorySelection::DontTrust;
+ }
+ KeyCode::Char('1') | KeyCode::Char('y') => self.handle_trust(),
+ KeyCode::Char('2') | KeyCode::Char('n') => self.handle_dont_trust(),
+ KeyCode::Enter => match self.highlighted {
+ TrustDirectorySelection::Trust => self.handle_trust(),
+ TrustDirectorySelection::DontTrust => self.handle_dont_trust(),
+ },
+ _ => {}
+ }
+ }
+}
+
+impl StepStateProvider for TrustDirectoryWidget {
+ fn get_step_state(&self) -> StepState {
+ match self.selection {
+ Some(_) => StepState::Complete,
+ None => StepState::InProgress,
+ }
+ }
+}
+
+impl TrustDirectoryWidget {
+ fn handle_trust(&mut self) {
+ let target =
+ resolve_root_git_project_for_trust(&self.cwd).unwrap_or_else(|| self.cwd.clone());
+ if let Err(e) = set_project_trust_level(&self.codex_home, &target, TrustLevel::Trusted) {
+ tracing::error!("Failed to set project trusted: {e:?}");
+ self.error = Some(format!("Failed to set trust for {}: {e}", target.display()));
+ }
+
+ self.selection = Some(TrustDirectorySelection::Trust);
+ }
+
+ fn handle_dont_trust(&mut self) {
+ self.highlighted = TrustDirectorySelection::DontTrust;
+ let target =
+ resolve_root_git_project_for_trust(&self.cwd).unwrap_or_else(|| self.cwd.clone());
+ if let Err(e) = set_project_trust_level(&self.codex_home, &target, TrustLevel::Untrusted) {
+ tracing::error!("Failed to set project untrusted: {e:?}");
+ self.error = Some(format!(
+ "Failed to set untrusted for {}: {e}",
+ target.display()
+ ));
+ }
+
+ self.selection = Some(TrustDirectorySelection::DontTrust);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use crate::test_backend::VT100Backend;
+
+ use super::*;
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyEventKind;
+ use crossterm::event::KeyModifiers;
+ use pretty_assertions::assert_eq;
+ use ratatui::Terminal;
+ use std::path::PathBuf;
+ use tempfile::TempDir;
+
+ #[test]
+ fn release_event_does_not_change_selection() {
+ let codex_home = TempDir::new().expect("temp home");
+ let mut widget = TrustDirectoryWidget {
+ codex_home: codex_home.path().to_path_buf(),
+ cwd: PathBuf::from("."),
+ is_git_repo: false,
+ selection: None,
+ highlighted: TrustDirectorySelection::DontTrust,
+ error: None,
+ };
+
+ let release = KeyEvent {
+ kind: KeyEventKind::Release,
+ ..KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)
+ };
+ widget.handle_key_event(release);
+ assert_eq!(widget.selection, None);
+
+ let press = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE);
+ widget.handle_key_event(press);
+ assert_eq!(widget.selection, Some(TrustDirectorySelection::DontTrust));
+ }
+
+ #[test]
+ fn renders_snapshot_for_git_repo() {
+ let codex_home = TempDir::new().expect("temp home");
+ let widget = TrustDirectoryWidget {
+ codex_home: codex_home.path().to_path_buf(),
+ cwd: PathBuf::from("/workspace/project"),
+ is_git_repo: true,
+ selection: None,
+ highlighted: TrustDirectorySelection::Trust,
+ error: None,
+ };
+
+ let mut terminal = Terminal::new(VT100Backend::new(70, 14)).expect("terminal");
+ terminal
+ .draw(|f| (&widget).render_ref(f.area(), f.buffer_mut()))
+ .expect("draw");
+
+ insta::assert_snapshot!(terminal.backend());
+ }
+}
diff --git a/codex-rs/tui2/src/onboarding/welcome.rs b/codex-rs/tui2/src/onboarding/welcome.rs
new file mode 100644
index 0000000000..8ff5e81982
--- /dev/null
+++ b/codex-rs/tui2/src/onboarding/welcome.rs
@@ -0,0 +1,153 @@
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use crossterm::event::KeyModifiers;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::prelude::Widget;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::widgets::Clear;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::WidgetRef;
+use ratatui::widgets::Wrap;
+
+use crate::ascii_animation::AsciiAnimation;
+use crate::onboarding::onboarding_screen::KeyboardHandler;
+use crate::onboarding::onboarding_screen::StepStateProvider;
+use crate::tui::FrameRequester;
+
+use super::onboarding_screen::StepState;
+
+const MIN_ANIMATION_HEIGHT: u16 = 20;
+const MIN_ANIMATION_WIDTH: u16 = 60;
+
+pub(crate) struct WelcomeWidget {
+ pub is_logged_in: bool,
+ animation: AsciiAnimation,
+ animations_enabled: bool,
+}
+
+impl KeyboardHandler for WelcomeWidget {
+ fn handle_key_event(&mut self, key_event: KeyEvent) {
+ if !self.animations_enabled {
+ return;
+ }
+ if key_event.kind == KeyEventKind::Press
+ && key_event.code == KeyCode::Char('.')
+ && key_event.modifiers.contains(KeyModifiers::CONTROL)
+ {
+ tracing::warn!("Welcome background to press '.'");
+ let _ = self.animation.pick_random_variant();
+ }
+ }
+}
+
+impl WelcomeWidget {
+ pub(crate) fn new(
+ is_logged_in: bool,
+ request_frame: FrameRequester,
+ animations_enabled: bool,
+ ) -> Self {
+ Self {
+ is_logged_in,
+ animation: AsciiAnimation::new(request_frame),
+ animations_enabled,
+ }
+ }
+}
+
+impl WidgetRef for &WelcomeWidget {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ Clear.render(area, buf);
+ if self.animations_enabled {
+ self.animation.schedule_next_frame();
+ }
+
+ // Skip the animation entirely when the viewport is too small so we don't clip frames.
+ let show_animation =
+ area.height >= MIN_ANIMATION_HEIGHT && area.width >= MIN_ANIMATION_WIDTH;
+
+ let mut lines: Vec<Line> = Vec::new();
+ if show_animation && self.animations_enabled {
+ let frame = self.animation.current_frame();
+ lines.extend(frame.lines().map(Into::into));
+ lines.push("".into());
+ }
+ lines.push(Line::from(vec![
+ " ".into(),
+ "Welcome to ".into(),
+ "Codex".bold(),
+ ", OpenAI's command-line coding agent".into(),
+ ]));
+
+ Paragraph::new(lines)
+ .wrap(Wrap { trim: false })
+ .render(area, buf);
+ }
+}
+
+impl StepStateProvider for WelcomeWidget {
+ fn get_step_state(&self) -> StepState {
+ match self.is_logged_in {
+ true => StepState::Hidden,
+ false => StepState::Complete,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ratatui::buffer::Buffer;
+ use ratatui::layout::Rect;
+
+ static VARIANT_A: [&str; 1] = ["frame-a"];
+ static VARIANT_B: [&str; 1] = ["frame-b"];
+ static VARIANTS: [&[&str]; 2] = [&VARIANT_A, &VARIANT_B];
+
+ #[test]
+ fn welcome_renders_animation_on_first_draw() {
+ let widget = WelcomeWidget::new(false, FrameRequester::test_dummy(), true);
+ let area = Rect::new(0, 0, MIN_ANIMATION_WIDTH, MIN_ANIMATION_HEIGHT);
+ let mut buf = Buffer::empty(area);
+ (&widget).render(area, &mut buf);
+
+ let mut found = false;
+ let mut last_non_empty: Option<u16> = None;
+ for y in 0..area.height {
+ for x in 0..area.width {
+ if !buf[(x, y)].symbol().trim().is_empty() {
+ found = true;
+ last_non_empty = Some(y);
+ break;
+ }
+ }
+ }
+
+ assert!(found, "expected welcome animation to render characters");
+ let measured_rows = last_non_empty.map(|v| v + 2).unwrap_or(0);
+ assert!(
+ measured_rows >= MIN_ANIMATION_HEIGHT,
+ "expected measurement to report at least {MIN_ANIMATION_HEIGHT} rows, got {measured_rows}"
+ );
+ }
+
+ #[test]
+ fn ctrl_dot_changes_animation_variant() {
+ let mut widget = WelcomeWidget {
+ is_logged_in: false,
+ animation: AsciiAnimation::with_variants(FrameRequester::test_dummy(), &VARIANTS, 0),
+ animations_enabled: true,
+ };
+
+ let before = widget.animation.current_frame();
+ widget.handle_key_event(KeyEvent::new(KeyCode::Char('.'), KeyModifiers::CONTROL));
+ let after = widget.animation.current_frame();
+
+ assert_ne!(
+ before, after,
+ "expected ctrl+. to switch welcome animation variant"
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/oss_selection.rs b/codex-rs/tui2/src/oss_selection.rs
new file mode 100644
index 0000000000..eb1ca18231
--- /dev/null
+++ b/codex-rs/tui2/src/oss_selection.rs
@@ -0,0 +1,369 @@
+use std::io;
+use std::sync::LazyLock;
+
+use codex_core::DEFAULT_LMSTUDIO_PORT;
+use codex_core::DEFAULT_OLLAMA_PORT;
+use codex_core::LMSTUDIO_OSS_PROVIDER_ID;
+use codex_core::OLLAMA_OSS_PROVIDER_ID;
+use codex_core::config::set_default_oss_provider;
+use crossterm::event::Event;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use crossterm::event::{self};
+use crossterm::execute;
+use crossterm::terminal::EnterAlternateScreen;
+use crossterm::terminal::LeaveAlternateScreen;
+use crossterm::terminal::disable_raw_mode;
+use crossterm::terminal::enable_raw_mode;
+use ratatui::Terminal;
+use ratatui::backend::CrosstermBackend;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Alignment;
+use ratatui::layout::Constraint;
+use ratatui::layout::Direction;
+use ratatui::layout::Layout;
+use ratatui::layout::Margin;
+use ratatui::layout::Rect;
+use ratatui::prelude::*;
+use ratatui::style::Color;
+use ratatui::style::Modifier;
+use ratatui::style::Style;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::Widget;
+use ratatui::widgets::WidgetRef;
+use ratatui::widgets::Wrap;
+use std::time::Duration;
+
+#[derive(Clone)]
+struct ProviderOption {
+ name: String,
+ status: ProviderStatus,
+}
+
+#[derive(Clone)]
+enum ProviderStatus {
+ Running,
+ NotRunning,
+ Unknown,
+}
+
+/// Options displayed in the *select* mode.
+///
+/// The `key` is matched case-insensitively.
+struct SelectOption {
+ label: Line<'static>,
+ description: &'static str,
+ key: KeyCode,
+ provider_id: &'static str,
+}
+
+static OSS_SELECT_OPTIONS: LazyLock<Vec<SelectOption>> = LazyLock::new(|| {
+ vec![
+ SelectOption {
+ label: Line::from(vec!["L".underlined(), "M Studio".into()]),
+ description: "Local LM Studio server (default port 1234)",
+ key: KeyCode::Char('l'),
+ provider_id: LMSTUDIO_OSS_PROVIDER_ID,
+ },
+ SelectOption {
+ label: Line::from(vec!["O".underlined(), "llama".into()]),
+ description: "Local Ollama server (default port 11434)",
+ key: KeyCode::Char('o'),
+ provider_id: OLLAMA_OSS_PROVIDER_ID,
+ },
+ ]
+});
+
+pub struct OssSelectionWidget<'a> {
+ select_options: &'a Vec<SelectOption>,
+ confirmation_prompt: Paragraph<'a>,
+
+ /// Currently selected index in *select* mode.
+ selected_option: usize,
+
+ /// Set to `true` once a decision has been sent – the parent view can then
+ /// remove this widget from its queue.
+ done: bool,
+
+ selection: Option<String>,
+}
+
+impl OssSelectionWidget<'_> {
+ fn new(lmstudio_status: ProviderStatus, ollama_status: ProviderStatus) -> io::Result<Self> {
+ let providers = vec![
+ ProviderOption {
+ name: "LM Studio".to_string(),
+ status: lmstudio_status,
+ },
+ ProviderOption {
+ name: "Ollama".to_string(),
+ status: ollama_status,
+ },
+ ];
+
+ let mut contents: Vec<Line> = vec![
+ Line::from(vec![
+ "? ".fg(Color::Blue),
+ "Select an open-source provider".bold(),
+ ]),
+ Line::from(""),
+ Line::from(" Choose which local AI server to use for your session."),
+ Line::from(""),
+ ];
+
+ // Add status indicators for each provider
+ for provider in &providers {
+ let (status_symbol, status_color) = get_status_symbol_and_color(&provider.status);
+ contents.push(Line::from(vec![
+ Span::raw(" "),
+ Span::styled(status_symbol, Style::default().fg(status_color)),
+ Span::raw(format!(" {} ", provider.name)),
+ ]));
+ }
+ contents.push(Line::from(""));
+ contents.push(Line::from(" ● Running ○ Not Running").add_modifier(Modifier::DIM));
+
+ contents.push(Line::from(""));
+ contents.push(
+ Line::from(" Press Enter to select • Ctrl+C to exit").add_modifier(Modifier::DIM),
+ );
+
+ let confirmation_prompt = Paragraph::new(contents).wrap(Wrap { trim: false });
+
+ Ok(Self {
+ select_options: &OSS_SELECT_OPTIONS,
+ confirmation_prompt,
+ selected_option: 0,
+ done: false,
+ selection: None,
+ })
+ }
+
+ fn get_confirmation_prompt_height(&self, width: u16) -> u16 {
+ // Should cache this for last value of width.
+ self.confirmation_prompt.line_count(width) as u16
+ }
+
+ /// Process a `KeyEvent` coming from crossterm. Always consumes the event
+ /// while the modal is visible.
+ /// Process a key event originating from crossterm. As the modal fully
+ /// captures input while visible, we don't need to report whether the event
+ /// was consumed—callers can assume it always is.
+ pub fn handle_key_event(&mut self, key: KeyEvent) -> Option<String> {
+ if key.kind == KeyEventKind::Press {
+ self.handle_select_key(key);
+ }
+ if self.done {
+ self.selection.clone()
+ } else {
+ None
+ }
+ }
+
+ /// Normalize a key for comparison.
+ /// - For `KeyCode::Char`, converts to lowercase for case-insensitive matching.
+ /// - Other key codes are returned unchanged.
+ fn normalize_keycode(code: KeyCode) -> KeyCode {
+ match code {
+ KeyCode::Char(c) => KeyCode::Char(c.to_ascii_lowercase()),
+ other => other,
+ }
+ }
+
+ fn handle_select_key(&mut self, key_event: KeyEvent) {
+ match key_event.code {
+ KeyCode::Char('c')
+ if key_event
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
+ self.send_decision("__CANCELLED__".to_string());
+ }
+ KeyCode::Left => {
+ self.selected_option = (self.selected_option + self.select_options.len() - 1)
+ % self.select_options.len();
+ }
+ KeyCode::Right => {
+ self.selected_option = (self.selected_option + 1) % self.select_options.len();
+ }
+ KeyCode::Enter => {
+ let opt = &self.select_options[self.selected_option];
+ self.send_decision(opt.provider_id.to_string());
+ }
+ KeyCode::Esc => {
+ self.send_decision(LMSTUDIO_OSS_PROVIDER_ID.to_string());
+ }
+ other => {
+ let normalized = Self::normalize_keycode(other);
+ if let Some(opt) = self
+ .select_options
+ .iter()
+ .find(|opt| Self::normalize_keycode(opt.key) == normalized)
+ {
+ self.send_decision(opt.provider_id.to_string());
+ }
+ }
+ }
+ }
+
+ fn send_decision(&mut self, selection: String) {
+ self.selection = Some(selection);
+ self.done = true;
+ }
+
+ /// Returns `true` once the user has made a decision and the widget no
+ /// longer needs to be displayed.
+ pub fn is_complete(&self) -> bool {
+ self.done
+ }
+
+ pub fn desired_height(&self, width: u16) -> u16 {
+ self.get_confirmation_prompt_height(width) + self.select_options.len() as u16
+ }
+}
+
+impl WidgetRef for &OssSelectionWidget<'_> {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ let prompt_height = self.get_confirmation_prompt_height(area.width);
+ let [prompt_chunk, response_chunk] = Layout::default()
+ .direction(Direction::Vertical)
+ .constraints([Constraint::Length(prompt_height), Constraint::Min(0)])
+ .areas(area);
+
+ let lines: Vec<Line> = self
+ .select_options
+ .iter()
+ .enumerate()
+ .map(|(idx, opt)| {
+ let style = if idx == self.selected_option {
+ Style::new().bg(Color::Cyan).fg(Color::Black)
+ } else {
+ Style::new().bg(Color::DarkGray)
+ };
+ opt.label.clone().alignment(Alignment::Center).style(style)
+ })
+ .collect();
+
+ let [title_area, button_area, description_area] = Layout::vertical([
+ Constraint::Length(1),
+ Constraint::Length(1),
+ Constraint::Min(0),
+ ])
+ .areas(response_chunk.inner(Margin::new(1, 0)));
+
+ Line::from("Select provider?").render(title_area, buf);
+
+ self.confirmation_prompt.clone().render(prompt_chunk, buf);
+ let areas = Layout::horizontal(
+ lines
+ .iter()
+ .map(|l| Constraint::Length(l.width() as u16 + 2)),
+ )
+ .spacing(1)
+ .split(button_area);
+ for (idx, area) in areas.iter().enumerate() {
+ let line = &lines[idx];
+ line.render(*area, buf);
+ }
+
+ Line::from(self.select_options[self.selected_option].description)
+ .style(Style::new().italic().fg(Color::DarkGray))
+ .render(description_area.inner(Margin::new(1, 0)), buf);
+ }
+}
+
+fn get_status_symbol_and_color(status: &ProviderStatus) -> (&'static str, Color) {
+ match status {
+ ProviderStatus::Running => ("●", Color::Green),
+ ProviderStatus::NotRunning => ("○", Color::Red),
+ ProviderStatus::Unknown => ("?", Color::Yellow),
+ }
+}
+
+pub async fn select_oss_provider(codex_home: &std::path::Path) -> io::Result<String> {
+ // Check provider statuses first
+ let lmstudio_status = check_lmstudio_status().await;
+ let ollama_status = check_ollama_status().await;
+
+ // Autoselect if only one is running
+ match (&lmstudio_status, &ollama_status) {
+ (ProviderStatus::Running, ProviderStatus::NotRunning) => {
+ let provider = LMSTUDIO_OSS_PROVIDER_ID.to_string();
+ return Ok(provider);
+ }
+ (ProviderStatus::NotRunning, ProviderStatus::Running) => {
+ let provider = OLLAMA_OSS_PROVIDER_ID.to_string();
+ return Ok(provider);
+ }
+ _ => {
+ // Both running or both not running - show UI
+ }
+ }
+
+ let mut widget = OssSelectionWidget::new(lmstudio_status, ollama_status)?;
+
+ enable_raw_mode()?;
+ let mut stdout = io::stdout();
+ execute!(stdout, EnterAlternateScreen)?;
+
+ let backend = CrosstermBackend::new(stdout);
+ let mut terminal = Terminal::new(backend)?;
+
+ let result = loop {
+ terminal.draw(|f| {
+ (&widget).render_ref(f.area(), f.buffer_mut());
+ })?;
+
+ if let Event::Key(key_event) = event::read()?
+ && let Some(selection) = widget.handle_key_event(key_event)
+ {
+ break Ok(selection);
+ }
+ };
+
+ disable_raw_mode()?;
+ execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
+
+ // If the user manually selected an OSS provider, we save it as the
+ // default one to use later.
+ if let Ok(ref provider) = result
+ && let Err(e) = set_default_oss_provider(codex_home, provider)
+ {
+ tracing::warn!("Failed to save OSS provider preference: {e}");
+ }
+
+ result
+}
+
+async fn check_lmstudio_status() -> ProviderStatus {
+ match check_port_status(DEFAULT_LMSTUDIO_PORT).await {
+ Ok(true) => ProviderStatus::Running,
+ Ok(false) => ProviderStatus::NotRunning,
+ Err(_) => ProviderStatus::Unknown,
+ }
+}
+
+async fn check_ollama_status() -> ProviderStatus {
+ match check_port_status(DEFAULT_OLLAMA_PORT).await {
+ Ok(true) => ProviderStatus::Running,
+ Ok(false) => ProviderStatus::NotRunning,
+ Err(_) => ProviderStatus::Unknown,
+ }
+}
+
+async fn check_port_status(port: u16) -> io::Result<bool> {
+ let client = reqwest::Client::builder()
+ .timeout(Duration::from_secs(2))
+ .build()
+ .map_err(io::Error::other)?;
+
+ let url = format!("http://localhost:{port}");
+
+ match client.get(&url).send().await {
+ Ok(response) => Ok(response.status().is_success()),
+ Err(_) => Ok(false), // Connection failed = not running
+ }
+}
diff --git a/codex-rs/tui2/src/pager_overlay.rs b/codex-rs/tui2/src/pager_overlay.rs
new file mode 100644
index 0000000000..46aaba8644
--- /dev/null
+++ b/codex-rs/tui2/src/pager_overlay.rs
@@ -0,0 +1,1037 @@
+use std::io::Result;
+use std::sync::Arc;
+use std::time::Duration;
+
+use crate::history_cell::HistoryCell;
+use crate::history_cell::UserHistoryCell;
+use crate::key_hint;
+use crate::key_hint::KeyBinding;
+use crate::render::Insets;
+use crate::render::renderable::InsetRenderable;
+use crate::render::renderable::Renderable;
+use crate::style::user_message_style;
+use crate::tui;
+use crate::tui::TuiEvent;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use ratatui::buffer::Buffer;
+use ratatui::buffer::Cell;
+use ratatui::layout::Rect;
+use ratatui::style::Style;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::text::Text;
+use ratatui::widgets::Clear;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::Widget;
+use ratatui::widgets::WidgetRef;
+use ratatui::widgets::Wrap;
+
+pub(crate) enum Overlay {
+ Transcript(TranscriptOverlay),
+ Static(StaticOverlay),
+}
+
+impl Overlay {
+ pub(crate) fn new_transcript(cells: Vec<Arc<dyn HistoryCell>>) -> Self {
+ Self::Transcript(TranscriptOverlay::new(cells))
+ }
+
+ pub(crate) fn new_static_with_lines(lines: Vec<Line<'static>>, title: String) -> Self {
+ Self::Static(StaticOverlay::with_title(lines, title))
+ }
+
+ pub(crate) fn new_static_with_renderables(
+ renderables: Vec<Box<dyn Renderable>>,
+ title: String,
+ ) -> Self {
+ Self::Static(StaticOverlay::with_renderables(renderables, title))
+ }
+
+ pub(crate) fn handle_event(&mut self, tui: &mut tui::Tui, event: TuiEvent) -> Result<()> {
+ match self {
+ Overlay::Transcript(o) => o.handle_event(tui, event),
+ Overlay::Static(o) => o.handle_event(tui, event),
+ }
+ }
+
+ pub(crate) fn is_done(&self) -> bool {
+ match self {
+ Overlay::Transcript(o) => o.is_done(),
+ Overlay::Static(o) => o.is_done(),
+ }
+ }
+}
+
+const KEY_UP: KeyBinding = key_hint::plain(KeyCode::Up);
+const KEY_DOWN: KeyBinding = key_hint::plain(KeyCode::Down);
+const KEY_K: KeyBinding = key_hint::plain(KeyCode::Char('k'));
+const KEY_J: KeyBinding = key_hint::plain(KeyCode::Char('j'));
+const KEY_PAGE_UP: KeyBinding = key_hint::plain(KeyCode::PageUp);
+const KEY_PAGE_DOWN: KeyBinding = key_hint::plain(KeyCode::PageDown);
+const KEY_SPACE: KeyBinding = key_hint::plain(KeyCode::Char(' '));
+const KEY_SHIFT_SPACE: KeyBinding = key_hint::shift(KeyCode::Char(' '));
+const KEY_HOME: KeyBinding = key_hint::plain(KeyCode::Home);
+const KEY_END: KeyBinding = key_hint::plain(KeyCode::End);
+const KEY_CTRL_F: KeyBinding = key_hint::ctrl(KeyCode::Char('f'));
+const KEY_CTRL_D: KeyBinding = key_hint::ctrl(KeyCode::Char('d'));
+const KEY_CTRL_B: KeyBinding = key_hint::ctrl(KeyCode::Char('b'));
+const KEY_CTRL_U: KeyBinding = key_hint::ctrl(KeyCode::Char('u'));
+const KEY_Q: KeyBinding = key_hint::plain(KeyCode::Char('q'));
+const KEY_ESC: KeyBinding = key_hint::plain(KeyCode::Esc);
+const KEY_ENTER: KeyBinding = key_hint::plain(KeyCode::Enter);
+const KEY_CTRL_T: KeyBinding = key_hint::ctrl(KeyCode::Char('t'));
+const KEY_CTRL_C: KeyBinding = key_hint::ctrl(KeyCode::Char('c'));
+
+// Common pager navigation hints rendered on the first line
+const PAGER_KEY_HINTS: &[(&[KeyBinding], &str)] = &[
+ (&[KEY_UP, KEY_DOWN], "to scroll"),
+ (&[KEY_PAGE_UP, KEY_PAGE_DOWN], "to page"),
+ (&[KEY_HOME, KEY_END], "to jump"),
+];
+
+// Render a single line of key hints from (key(s), description) pairs.
+fn render_key_hints(area: Rect, buf: &mut Buffer, pairs: &[(&[KeyBinding], &str)]) {
+ let mut spans: Vec<Span<'static>> = vec![" ".into()];
+ let mut first = true;
+ for (keys, desc) in pairs {
+ if !first {
+ spans.push(" ".into());
+ }
+ for (i, key) in keys.iter().enumerate() {
+ if i > 0 {
+ spans.push("/".into());
+ }
+ spans.push(Span::from(key));
+ }
+ spans.push(" ".into());
+ spans.push(Span::from(desc.to_string()));
+ first = false;
+ }
+ Paragraph::new(vec![Line::from(spans).dim()]).render_ref(area, buf);
+}
+
+/// Generic widget for rendering a pager view.
+struct PagerView {
+ renderables: Vec<Box<dyn Renderable>>,
+ scroll_offset: usize,
+ title: String,
+ last_content_height: Option<usize>,
+ last_rendered_height: Option<usize>,
+ /// If set, on next render ensure this chunk is visible.
+ pending_scroll_chunk: Option<usize>,
+}
+
+impl PagerView {
+ fn new(renderables: Vec<Box<dyn Renderable>>, title: String, scroll_offset: usize) -> Self {
+ Self {
+ renderables,
+ scroll_offset,
+ title,
+ last_content_height: None,
+ last_rendered_height: None,
+ pending_scroll_chunk: None,
+ }
+ }
+
+ fn content_height(&self, width: u16) -> usize {
+ self.renderables
+ .iter()
+ .map(|c| c.desired_height(width) as usize)
+ .sum()
+ }
+
+ fn render(&mut self, area: Rect, buf: &mut Buffer) {
+ Clear.render(area, buf);
+ self.render_header(area, buf);
+ let content_area = self.content_area(area);
+ self.update_last_content_height(content_area.height);
+ let content_height = self.content_height(content_area.width);
+ self.last_rendered_height = Some(content_height);
+ // If there is a pending request to scroll a specific chunk into view,
+ // satisfy it now that wrapping is up to date for this width.
+ if let Some(idx) = self.pending_scroll_chunk.take() {
+ self.ensure_chunk_visible(idx, content_area);
+ }
+ self.scroll_offset = self
+ .scroll_offset
+ .min(content_height.saturating_sub(content_area.height as usize));
+
+ self.render_content(content_area, buf);
+
+ self.render_bottom_bar(area, content_area, buf, content_height);
+ }
+
+ fn render_header(&self, area: Rect, buf: &mut Buffer) {
+ Span::from("/ ".repeat(area.width as usize / 2))
+ .dim()
+ .render_ref(area, buf);
+ let header = format!("/ {}", self.title);
+ header.dim().render_ref(area, buf);
+ }
+
+ fn render_content(&self, area: Rect, buf: &mut Buffer) {
+ let mut y = -(self.scroll_offset as isize);
+ let mut drawn_bottom = area.y;
+ for renderable in &self.renderables {
+ let top = y;
+ let height = renderable.desired_height(area.width) as isize;
+ y += height;
+ let bottom = y;
+ if bottom < area.y as isize {
+ continue;
+ }
+ if top > area.y as isize + area.height as isize {
+ break;
+ }
+ if top < 0 {
+ let drawn = render_offset_content(area, buf, &**renderable, (-top) as u16);
+ drawn_bottom = drawn_bottom.max(area.y + drawn);
+ } else {
+ let draw_height = (height as u16).min(area.height.saturating_sub(top as u16));
+ let draw_area = Rect::new(area.x, area.y + top as u16, area.width, draw_height);
+ renderable.render(draw_area, buf);
+ drawn_bottom = drawn_bottom.max(draw_area.y.saturating_add(draw_area.height));
+ }
+ }
+
+ for y in drawn_bottom..area.bottom() {
+ if area.width == 0 {
+ break;
+ }
+ buf[(area.x, y)] = Cell::from('~');
+ for x in area.x + 1..area.right() {
+ buf[(x, y)] = Cell::from(' ');
+ }
+ }
+ }
+
+ fn render_bottom_bar(
+ &self,
+ full_area: Rect,
+ content_area: Rect,
+ buf: &mut Buffer,
+ total_len: usize,
+ ) {
+ let sep_y = content_area.bottom();
+ let sep_rect = Rect::new(full_area.x, sep_y, full_area.width, 1);
+
+ Span::from("─".repeat(sep_rect.width as usize))
+ .dim()
+ .render_ref(sep_rect, buf);
+ let percent = if total_len == 0 {
+ 100
+ } else {
+ let max_scroll = total_len.saturating_sub(content_area.height as usize);
+ if max_scroll == 0 {
+ 100
+ } else {
+ (((self.scroll_offset.min(max_scroll)) as f32 / max_scroll as f32) * 100.0).round()
+ as u8
+ }
+ };
+ let pct_text = format!(" {percent}% ");
+ let pct_w = pct_text.chars().count() as u16;
+ let pct_x = sep_rect.x + sep_rect.width - pct_w - 1;
+ Span::from(pct_text)
+ .dim()
+ .render_ref(Rect::new(pct_x, sep_rect.y, pct_w, 1), buf);
+ }
+
+ fn handle_key_event(&mut self, tui: &mut tui::Tui, key_event: KeyEvent) -> Result<()> {
+ match key_event {
+ e if KEY_UP.is_press(e) || KEY_K.is_press(e) => {
+ self.scroll_offset = self.scroll_offset.saturating_sub(1);
+ }
+ e if KEY_DOWN.is_press(e) || KEY_J.is_press(e) => {
+ self.scroll_offset = self.scroll_offset.saturating_add(1);
+ }
+ e if KEY_PAGE_UP.is_press(e)
+ || KEY_SHIFT_SPACE.is_press(e)
+ || KEY_CTRL_B.is_press(e) =>
+ {
+ let page_height = self.page_height(tui.terminal.viewport_area);
+ self.scroll_offset = self.scroll_offset.saturating_sub(page_height);
+ }
+ e if KEY_PAGE_DOWN.is_press(e) || KEY_SPACE.is_press(e) || KEY_CTRL_F.is_press(e) => {
+ let page_height = self.page_height(tui.terminal.viewport_area);
+ self.scroll_offset = self.scroll_offset.saturating_add(page_height);
+ }
+ e if KEY_CTRL_D.is_press(e) => {
+ let area = self.content_area(tui.terminal.viewport_area);
+ let half_page = (area.height as usize).saturating_add(1) / 2;
+ self.scroll_offset = self.scroll_offset.saturating_add(half_page);
+ }
+ e if KEY_CTRL_U.is_press(e) => {
+ let area = self.content_area(tui.terminal.viewport_area);
+ let half_page = (area.height as usize).saturating_add(1) / 2;
+ self.scroll_offset = self.scroll_offset.saturating_sub(half_page);
+ }
+ e if KEY_HOME.is_press(e) => {
+ self.scroll_offset = 0;
+ }
+ e if KEY_END.is_press(e) => {
+ self.scroll_offset = usize::MAX;
+ }
+ _ => {
+ return Ok(());
+ }
+ }
+ tui.frame_requester()
+ .schedule_frame_in(Duration::from_millis(16));
+ Ok(())
+ }
+
+ /// Returns the height of one page in content rows.
+ ///
+ /// Prefers the last rendered content height (excluding header/footer chrome);
+ /// if no render has occurred yet, falls back to the content area height
+ /// computed from the given viewport.
+ fn page_height(&self, viewport_area: Rect) -> usize {
+ self.last_content_height
+ .unwrap_or_else(|| self.content_area(viewport_area).height as usize)
+ }
+
+ fn update_last_content_height(&mut self, height: u16) {
+ self.last_content_height = Some(height as usize);
+ }
+
+ fn content_area(&self, area: Rect) -> Rect {
+ let mut area = area;
+ area.y = area.y.saturating_add(1);
+ area.height = area.height.saturating_sub(2);
+ area
+ }
+}
+
+impl PagerView {
+ fn is_scrolled_to_bottom(&self) -> bool {
+ if self.scroll_offset == usize::MAX {
+ return true;
+ }
+ let Some(height) = self.last_content_height else {
+ return false;
+ };
+ if self.renderables.is_empty() {
+ return true;
+ }
+ let Some(total_height) = self.last_rendered_height else {
+ return false;
+ };
+ if total_height <= height {
+ return true;
+ }
+ let max_scroll = total_height.saturating_sub(height);
+ self.scroll_offset >= max_scroll
+ }
+
+ /// Request that the given text chunk index be scrolled into view on next render.
+ fn scroll_chunk_into_view(&mut self, chunk_index: usize) {
+ self.pending_scroll_chunk = Some(chunk_index);
+ }
+
+ fn ensure_chunk_visible(&mut self, idx: usize, area: Rect) {
+ if area.height == 0 || idx >= self.renderables.len() {
+ return;
+ }
+ let first = self
+ .renderables
+ .iter()
+ .take(idx)
+ .map(|r| r.desired_height(area.width) as usize)
+ .sum();
+ let last = first + self.renderables[idx].desired_height(area.width) as usize;
+ let current_top = self.scroll_offset;
+ let current_bottom = current_top.saturating_add(area.height.saturating_sub(1) as usize);
+ if first < current_top {
+ self.scroll_offset = first;
+ } else if last > current_bottom {
+ self.scroll_offset = last.saturating_sub(area.height.saturating_sub(1) as usize);
+ }
+ }
+}
+
+/// A renderable that caches its desired height.
+struct CachedRenderable {
+ renderable: Box<dyn Renderable>,
+ height: std::cell::Cell<Option<u16>>,
+ last_width: std::cell::Cell<Option<u16>>,
+}
+
+impl CachedRenderable {
+ fn new(renderable: impl Into<Box<dyn Renderable>>) -> Self {
+ Self {
+ renderable: renderable.into(),
+ height: std::cell::Cell::new(None),
+ last_width: std::cell::Cell::new(None),
+ }
+ }
+}
+
+impl Renderable for CachedRenderable {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ self.renderable.render(area, buf);
+ }
+ fn desired_height(&self, width: u16) -> u16 {
+ if self.last_width.get() != Some(width) {
+ let height = self.renderable.desired_height(width);
+ self.height.set(Some(height));
+ self.last_width.set(Some(width));
+ }
+ self.height.get().unwrap_or(0)
+ }
+}
+
+struct CellRenderable {
+ cell: Arc<dyn HistoryCell>,
+ style: Style,
+}
+
+impl Renderable for CellRenderable {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ let p =
+ Paragraph::new(Text::from(self.cell.transcript_lines(area.width))).style(self.style);
+ p.render(area, buf);
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ self.cell.desired_transcript_height(width)
+ }
+}
+
+pub(crate) struct TranscriptOverlay {
+ view: PagerView,
+ cells: Vec<Arc<dyn HistoryCell>>,
+ highlight_cell: Option<usize>,
+ is_done: bool,
+}
+
+impl TranscriptOverlay {
+ pub(crate) fn new(transcript_cells: Vec<Arc<dyn HistoryCell>>) -> Self {
+ Self {
+ view: PagerView::new(
+ Self::render_cells(&transcript_cells, None),
+ "T R A N S C R I P T".to_string(),
+ usize::MAX,
+ ),
+ cells: transcript_cells,
+ highlight_cell: None,
+ is_done: false,
+ }
+ }
+
+ fn render_cells(
+ cells: &[Arc<dyn HistoryCell>],
+ highlight_cell: Option<usize>,
+ ) -> Vec<Box<dyn Renderable>> {
+ cells
+ .iter()
+ .enumerate()
+ .flat_map(|(i, c)| {
+ let mut v: Vec<Box<dyn Renderable>> = Vec::new();
+ let mut cell_renderable = if c.as_any().is::<UserHistoryCell>() {
+ Box::new(CachedRenderable::new(CellRenderable {
+ cell: c.clone(),
+ style: if highlight_cell == Some(i) {
+ user_message_style().reversed()
+ } else {
+ user_message_style()
+ },
+ })) as Box<dyn Renderable>
+ } else {
+ Box::new(CachedRenderable::new(CellRenderable {
+ cell: c.clone(),
+ style: Style::default(),
+ })) as Box<dyn Renderable>
+ };
+ if !c.is_stream_continuation() && i > 0 {
+ cell_renderable = Box::new(InsetRenderable::new(
+ cell_renderable,
+ Insets::tlbr(1, 0, 0, 0),
+ ));
+ }
+ v.push(cell_renderable);
+ v
+ })
+ .collect()
+ }
+
+ pub(crate) fn insert_cell(&mut self, cell: Arc<dyn HistoryCell>) {
+ let follow_bottom = self.view.is_scrolled_to_bottom();
+ self.cells.push(cell);
+ self.view.renderables = Self::render_cells(&self.cells, self.highlight_cell);
+ if follow_bottom {
+ self.view.scroll_offset = usize::MAX;
+ }
+ }
+
+ pub(crate) fn set_highlight_cell(&mut self, cell: Option<usize>) {
+ self.highlight_cell = cell;
+ self.view.renderables = Self::render_cells(&self.cells, self.highlight_cell);
+ if let Some(idx) = self.highlight_cell {
+ self.view.scroll_chunk_into_view(idx);
+ }
+ }
+
+ fn render_hints(&self, area: Rect, buf: &mut Buffer) {
+ let line1 = Rect::new(area.x, area.y, area.width, 1);
+ let line2 = Rect::new(area.x, area.y.saturating_add(1), area.width, 1);
+ render_key_hints(line1, buf, PAGER_KEY_HINTS);
+
+ let mut pairs: Vec<(&[KeyBinding], &str)> =
+ vec![(&[KEY_Q], "to quit"), (&[KEY_ESC], "to edit prev")];
+ if self.highlight_cell.is_some() {
+ pairs.push((&[KEY_ENTER], "to edit message"));
+ }
+ render_key_hints(line2, buf, &pairs);
+ }
+
+ pub(crate) fn render(&mut self, area: Rect, buf: &mut Buffer) {
+ let top_h = area.height.saturating_sub(3);
+ let top = Rect::new(area.x, area.y, area.width, top_h);
+ let bottom = Rect::new(area.x, area.y + top_h, area.width, 3);
+ self.view.render(top, buf);
+ self.render_hints(bottom, buf);
+ }
+}
+
+impl TranscriptOverlay {
+ pub(crate) fn handle_event(&mut self, tui: &mut tui::Tui, event: TuiEvent) -> Result<()> {
+ match event {
+ TuiEvent::Key(key_event) => match key_event {
+ e if KEY_Q.is_press(e) || KEY_CTRL_C.is_press(e) || KEY_CTRL_T.is_press(e) => {
+ self.is_done = true;
+ Ok(())
+ }
+ other => self.view.handle_key_event(tui, other),
+ },
+ TuiEvent::Draw => {
+ tui.draw(u16::MAX, |frame| {
+ self.render(frame.area(), frame.buffer);
+ })?;
+ Ok(())
+ }
+ _ => Ok(()),
+ }
+ }
+ pub(crate) fn is_done(&self) -> bool {
+ self.is_done
+ }
+}
+
+pub(crate) struct StaticOverlay {
+ view: PagerView,
+ is_done: bool,
+}
+
+impl StaticOverlay {
+ pub(crate) fn with_title(lines: Vec<Line<'static>>, title: String) -> Self {
+ let paragraph = Paragraph::new(Text::from(lines)).wrap(Wrap { trim: false });
+ Self::with_renderables(vec![Box::new(CachedRenderable::new(paragraph))], title)
+ }
+
+ pub(crate) fn with_renderables(renderables: Vec<Box<dyn Renderable>>, title: String) -> Self {
+ Self {
+ view: PagerView::new(renderables, title, 0),
+ is_done: false,
+ }
+ }
+
+ fn render_hints(&self, area: Rect, buf: &mut Buffer) {
+ let line1 = Rect::new(area.x, area.y, area.width, 1);
+ let line2 = Rect::new(area.x, area.y.saturating_add(1), area.width, 1);
+ render_key_hints(line1, buf, PAGER_KEY_HINTS);
+ let pairs: Vec<(&[KeyBinding], &str)> = vec![(&[KEY_Q], "to quit")];
+ render_key_hints(line2, buf, &pairs);
+ }
+
+ pub(crate) fn render(&mut self, area: Rect, buf: &mut Buffer) {
+ let top_h = area.height.saturating_sub(3);
+ let top = Rect::new(area.x, area.y, area.width, top_h);
+ let bottom = Rect::new(area.x, area.y + top_h, area.width, 3);
+ self.view.render(top, buf);
+ self.render_hints(bottom, buf);
+ }
+}
+
+impl StaticOverlay {
+ pub(crate) fn handle_event(&mut self, tui: &mut tui::Tui, event: TuiEvent) -> Result<()> {
+ match event {
+ TuiEvent::Key(key_event) => match key_event {
+ e if KEY_Q.is_press(e) || KEY_CTRL_C.is_press(e) => {
+ self.is_done = true;
+ Ok(())
+ }
+ other => self.view.handle_key_event(tui, other),
+ },
+ TuiEvent::Draw => {
+ tui.draw(u16::MAX, |frame| {
+ self.render(frame.area(), frame.buffer);
+ })?;
+ Ok(())
+ }
+ _ => Ok(()),
+ }
+ }
+ pub(crate) fn is_done(&self) -> bool {
+ self.is_done
+ }
+}
+
+fn render_offset_content(
+ area: Rect,
+ buf: &mut Buffer,
+ renderable: &dyn Renderable,
+ scroll_offset: u16,
+) -> u16 {
+ let height = renderable.desired_height(area.width);
+ let mut tall_buf = Buffer::empty(Rect::new(
+ 0,
+ 0,
+ area.width,
+ height.min(area.height + scroll_offset),
+ ));
+ renderable.render(*tall_buf.area(), &mut tall_buf);
+ let copy_height = area
+ .height
+ .min(tall_buf.area().height.saturating_sub(scroll_offset));
+ for y in 0..copy_height {
+ let src_y = y + scroll_offset;
+ for x in 0..area.width {
+ buf[(area.x + x, area.y + y)] = tall_buf[(x, src_y)].clone();
+ }
+ }
+
+ copy_height
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use codex_core::protocol::ExecCommandSource;
+ use codex_core::protocol::ReviewDecision;
+ use insta::assert_snapshot;
+ use std::collections::HashMap;
+ use std::path::PathBuf;
+ use std::sync::Arc;
+ use std::time::Duration;
+
+ use crate::exec_cell::CommandOutput;
+ use crate::history_cell;
+ use crate::history_cell::HistoryCell;
+ use crate::history_cell::new_patch_event;
+ use codex_core::protocol::FileChange;
+ use codex_protocol::parse_command::ParsedCommand;
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+ use ratatui::text::Text;
+
+ #[derive(Debug)]
+ struct TestCell {
+ lines: Vec<Line<'static>>,
+ }
+
+ impl crate::history_cell::HistoryCell for TestCell {
+ fn display_lines(&self, _width: u16) -> Vec<Line<'static>> {
+ self.lines.clone()
+ }
+
+ fn transcript_lines(&self, _width: u16) -> Vec<Line<'static>> {
+ self.lines.clone()
+ }
+ }
+
+ fn paragraph_block(label: &str, lines: usize) -> Box<dyn Renderable> {
+ let text = Text::from(
+ (0..lines)
+ .map(|i| Line::from(format!("{label}{i}")))
+ .collect::<Vec<_>>(),
+ );
+ Box::new(Paragraph::new(text)) as Box<dyn Renderable>
+ }
+
+ #[test]
+ fn edit_prev_hint_is_visible() {
+ let mut overlay = TranscriptOverlay::new(vec![Arc::new(TestCell {
+ lines: vec![Line::from("hello")],
+ })]);
+
+ // Render into a small buffer and assert the backtrack hint is present
+ let area = Rect::new(0, 0, 40, 10);
+ let mut buf = Buffer::empty(area);
+ overlay.render(area, &mut buf);
+
+ // Flatten buffer to a string and check for the hint text
+ let mut s = String::new();
+ for y in area.y..area.bottom() {
+ for x in area.x..area.right() {
+ s.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
+ }
+ s.push('\n');
+ }
+ assert!(
+ s.contains("edit prev"),
+ "expected 'edit prev' hint in overlay footer, got: {s:?}"
+ );
+ }
+
+ #[test]
+ fn transcript_overlay_snapshot_basic() {
+ // Prepare a transcript overlay with a few lines
+ let mut overlay = TranscriptOverlay::new(vec![
+ Arc::new(TestCell {
+ lines: vec![Line::from("alpha")],
+ }),
+ Arc::new(TestCell {
+ lines: vec![Line::from("beta")],
+ }),
+ Arc::new(TestCell {
+ lines: vec![Line::from("gamma")],
+ }),
+ ]);
+ let mut term = Terminal::new(TestBackend::new(40, 10)).expect("term");
+ term.draw(|f| overlay.render(f.area(), f.buffer_mut()))
+ .expect("draw");
+ assert_snapshot!(term.backend());
+ }
+
+ fn buffer_to_text(buf: &Buffer, area: Rect) -> String {
+ let mut out = String::new();
+ for y in area.y..area.bottom() {
+ for x in area.x..area.right() {
+ let symbol = buf[(x, y)].symbol();
+ if symbol.is_empty() {
+ out.push(' ');
+ } else {
+ out.push(symbol.chars().next().unwrap_or(' '));
+ }
+ }
+ // Trim trailing spaces for stability.
+ while out.ends_with(' ') {
+ out.pop();
+ }
+ out.push('\n');
+ }
+ out
+ }
+
+ #[test]
+ fn transcript_overlay_apply_patch_scroll_vt100_clears_previous_page() {
+ let cwd = PathBuf::from("/repo");
+ let mut cells: Vec<Arc<dyn HistoryCell>> = Vec::new();
+
+ let mut approval_changes = HashMap::new();
+ approval_changes.insert(
+ PathBuf::from("foo.txt"),
+ FileChange::Add {
+ content: "hello\nworld\n".to_string(),
+ },
+ );
+ let approval_cell: Arc<dyn HistoryCell> = Arc::new(new_patch_event(approval_changes, &cwd));
+ cells.push(approval_cell);
+
+ let mut apply_changes = HashMap::new();
+ apply_changes.insert(
+ PathBuf::from("foo.txt"),
+ FileChange::Add {
+ content: "hello\nworld\n".to_string(),
+ },
+ );
+ let apply_begin_cell: Arc<dyn HistoryCell> = Arc::new(new_patch_event(apply_changes, &cwd));
+ cells.push(apply_begin_cell);
+
+ let apply_end_cell: Arc<dyn HistoryCell> =
+ history_cell::new_approval_decision_cell(vec!["ls".into()], ReviewDecision::Approved)
+ .into();
+ cells.push(apply_end_cell);
+
+ let mut exec_cell = crate::exec_cell::new_active_exec_command(
+ "exec-1".into(),
+ vec!["bash".into(), "-lc".into(), "ls".into()],
+ vec![ParsedCommand::Unknown { cmd: "ls".into() }],
+ ExecCommandSource::Agent,
+ None,
+ true,
+ );
+ exec_cell.complete_call(
+ "exec-1",
+ CommandOutput {
+ exit_code: 0,
+ aggregated_output: "src\nREADME.md\n".into(),
+ formatted_output: "src\nREADME.md\n".into(),
+ },
+ Duration::from_millis(420),
+ );
+ let exec_cell: Arc<dyn HistoryCell> = Arc::new(exec_cell);
+ cells.push(exec_cell);
+
+ let mut overlay = TranscriptOverlay::new(cells);
+ let area = Rect::new(0, 0, 80, 12);
+ let mut buf = Buffer::empty(area);
+
+ overlay.render(area, &mut buf);
+ overlay.view.scroll_offset = 0;
+ overlay.render(area, &mut buf);
+
+ let snapshot = buffer_to_text(&buf, area);
+ assert_snapshot!("transcript_overlay_apply_patch_scroll_vt100", snapshot);
+ }
+
+ #[test]
+ fn transcript_overlay_keeps_scroll_pinned_at_bottom() {
+ let mut overlay = TranscriptOverlay::new(
+ (0..20)
+ .map(|i| {
+ Arc::new(TestCell {
+ lines: vec![Line::from(format!("line{i}"))],
+ }) as Arc<dyn HistoryCell>
+ })
+ .collect(),
+ );
+ let mut term = Terminal::new(TestBackend::new(40, 12)).expect("term");
+ term.draw(|f| overlay.render(f.area(), f.buffer_mut()))
+ .expect("draw");
+
+ assert!(
+ overlay.view.is_scrolled_to_bottom(),
+ "expected initial render to leave view at bottom"
+ );
+
+ overlay.insert_cell(Arc::new(TestCell {
+ lines: vec!["tail".into()],
+ }));
+
+ assert_eq!(overlay.view.scroll_offset, usize::MAX);
+ }
+
+ #[test]
+ fn transcript_overlay_preserves_manual_scroll_position() {
+ let mut overlay = TranscriptOverlay::new(
+ (0..20)
+ .map(|i| {
+ Arc::new(TestCell {
+ lines: vec![Line::from(format!("line{i}"))],
+ }) as Arc<dyn HistoryCell>
+ })
+ .collect(),
+ );
+ let mut term = Terminal::new(TestBackend::new(40, 12)).expect("term");
+ term.draw(|f| overlay.render(f.area(), f.buffer_mut()))
+ .expect("draw");
+
+ overlay.view.scroll_offset = 0;
+
+ overlay.insert_cell(Arc::new(TestCell {
+ lines: vec!["tail".into()],
+ }));
+
+ assert_eq!(overlay.view.scroll_offset, 0);
+ }
+
+ #[test]
+ fn static_overlay_snapshot_basic() {
+ // Prepare a static overlay with a few lines and a title
+ let mut overlay = StaticOverlay::with_title(
+ vec!["one".into(), "two".into(), "three".into()],
+ "S T A T I C".to_string(),
+ );
+ let mut term = Terminal::new(TestBackend::new(40, 10)).expect("term");
+ term.draw(|f| overlay.render(f.area(), f.buffer_mut()))
+ .expect("draw");
+ assert_snapshot!(term.backend());
+ }
+
+ /// Render transcript overlay and return visible line numbers (`line-NN`) in order.
+ fn transcript_line_numbers(overlay: &mut TranscriptOverlay, area: Rect) -> Vec<usize> {
+ let mut buf = Buffer::empty(area);
+ overlay.render(area, &mut buf);
+
+ let top_h = area.height.saturating_sub(3);
+ let top = Rect::new(area.x, area.y, area.width, top_h);
+ let content_area = overlay.view.content_area(top);
+
+ let mut nums = Vec::new();
+ for y in content_area.y..content_area.bottom() {
+ let mut line = String::new();
+ for x in content_area.x..content_area.right() {
+ line.push(buf[(x, y)].symbol().chars().next().unwrap_or(' '));
+ }
+ if let Some(n) = line
+ .split_whitespace()
+ .find_map(|w| w.strip_prefix("line-"))
+ .and_then(|s| s.parse().ok())
+ {
+ nums.push(n);
+ }
+ }
+ nums
+ }
+
+ #[test]
+ fn transcript_overlay_paging_is_continuous_and_round_trips() {
+ let mut overlay = TranscriptOverlay::new(
+ (0..50)
+ .map(|i| {
+ Arc::new(TestCell {
+ lines: vec![Line::from(format!("line-{i:02}"))],
+ }) as Arc<dyn HistoryCell>
+ })
+ .collect(),
+ );
+ let area = Rect::new(0, 0, 40, 15);
+
+ // Prime layout so last_content_height is populated and paging uses the real content height.
+ let mut buf = Buffer::empty(area);
+ overlay.view.scroll_offset = 0;
+ overlay.render(area, &mut buf);
+ let page_height = overlay.view.page_height(area);
+
+ // Scenario 1: starting from the top, PageDown should show the next page of content.
+ overlay.view.scroll_offset = 0;
+ let page1 = transcript_line_numbers(&mut overlay, area);
+ let page1_len = page1.len();
+ let expected_page1: Vec<usize> = (0..page1_len).collect();
+ assert_eq!(
+ page1, expected_page1,
+ "first page should start at line-00 and show a full page of content"
+ );
+
+ overlay.view.scroll_offset = overlay.view.scroll_offset.saturating_add(page_height);
+ let page2 = transcript_line_numbers(&mut overlay, area);
+ assert_eq!(
+ page2.len(),
+ page1_len,
+ "second page should have the same number of visible lines as the first page"
+ );
+ let expected_page2_first = *page1.last().unwrap() + 1;
+ assert_eq!(
+ page2[0], expected_page2_first,
+ "second page after PageDown should immediately follow the first page"
+ );
+
+ // Scenario 2: from an interior offset (start=3), PageDown then PageUp should round-trip.
+ let interior_offset = 3usize;
+ overlay.view.scroll_offset = interior_offset;
+ let before = transcript_line_numbers(&mut overlay, area);
+ overlay.view.scroll_offset = overlay.view.scroll_offset.saturating_add(page_height);
+ let _ = transcript_line_numbers(&mut overlay, area);
+ overlay.view.scroll_offset = overlay.view.scroll_offset.saturating_sub(page_height);
+ let after = transcript_line_numbers(&mut overlay, area);
+ assert_eq!(
+ before, after,
+ "PageDown+PageUp from interior offset ({interior_offset}) should round-trip"
+ );
+
+ // Scenario 3: from the top of the second page, PageUp then PageDown should round-trip.
+ overlay.view.scroll_offset = page_height;
+ let before2 = transcript_line_numbers(&mut overlay, area);
+ overlay.view.scroll_offset = overlay.view.scroll_offset.saturating_sub(page_height);
+ let _ = transcript_line_numbers(&mut overlay, area);
+ overlay.view.scroll_offset = overlay.view.scroll_offset.saturating_add(page_height);
+ let after2 = transcript_line_numbers(&mut overlay, area);
+ assert_eq!(
+ before2, after2,
+ "PageUp+PageDown from the top of the second page should round-trip"
+ );
+ }
+
+ #[test]
+ fn static_overlay_wraps_long_lines() {
+ let mut overlay = StaticOverlay::with_title(
+ vec!["a very long line that should wrap when rendered within a narrow pager overlay width".into()],
+ "S T A T I C".to_string(),
+ );
+ let mut term = Terminal::new(TestBackend::new(24, 8)).expect("term");
+ term.draw(|f| overlay.render(f.area(), f.buffer_mut()))
+ .expect("draw");
+ assert_snapshot!(term.backend());
+ }
+
+ #[test]
+ fn pager_view_content_height_counts_renderables() {
+ let pv = PagerView::new(
+ vec![paragraph_block("a", 2), paragraph_block("b", 3)],
+ "T".to_string(),
+ 0,
+ );
+
+ assert_eq!(pv.content_height(80), 5);
+ }
+
+ #[test]
+ fn pager_view_ensure_chunk_visible_scrolls_down_when_needed() {
+ let mut pv = PagerView::new(
+ vec![
+ paragraph_block("a", 1),
+ paragraph_block("b", 3),
+ paragraph_block("c", 3),
+ ],
+ "T".to_string(),
+ 0,
+ );
+ let area = Rect::new(0, 0, 20, 8);
+
+ pv.scroll_offset = 0;
+ let content_area = pv.content_area(area);
+ pv.ensure_chunk_visible(2, content_area);
+
+ let mut buf = Buffer::empty(area);
+ pv.render(area, &mut buf);
+ let rendered = buffer_to_text(&buf, area);
+
+ assert!(
+ rendered.contains("c0"),
+ "expected chunk top in view: {rendered:?}"
+ );
+ assert!(
+ rendered.contains("c1"),
+ "expected chunk middle in view: {rendered:?}"
+ );
+ assert!(
+ rendered.contains("c2"),
+ "expected chunk bottom in view: {rendered:?}"
+ );
+ }
+
+ #[test]
+ fn pager_view_ensure_chunk_visible_scrolls_up_when_needed() {
+ let mut pv = PagerView::new(
+ vec![
+ paragraph_block("a", 2),
+ paragraph_block("b", 3),
+ paragraph_block("c", 3),
+ ],
+ "T".to_string(),
+ 0,
+ );
+ let area = Rect::new(0, 0, 20, 3);
+
+ pv.scroll_offset = 6;
+ pv.ensure_chunk_visible(0, area);
+
+ assert_eq!(pv.scroll_offset, 0);
+ }
+
+ #[test]
+ fn pager_view_is_scrolled_to_bottom_accounts_for_wrapped_height() {
+ let mut pv = PagerView::new(vec![paragraph_block("a", 10)], "T".to_string(), 0);
+ let area = Rect::new(0, 0, 20, 8);
+ let mut buf = Buffer::empty(area);
+
+ pv.render(area, &mut buf);
+
+ assert!(
+ !pv.is_scrolled_to_bottom(),
+ "expected view to report not at bottom when offset < max"
+ );
+
+ pv.scroll_offset = usize::MAX;
+ pv.render(area, &mut buf);
+
+ assert!(
+ pv.is_scrolled_to_bottom(),
+ "expected view to report at bottom after scrolling to end"
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/public_widgets/composer_input.rs b/codex-rs/tui2/src/public_widgets/composer_input.rs
new file mode 100644
index 0000000000..2a80c087ee
--- /dev/null
+++ b/codex-rs/tui2/src/public_widgets/composer_input.rs
@@ -0,0 +1,128 @@
+//! Public wrapper around the internal ChatComposer for simple, reusable text input.
+//!
+//! This exposes a minimal interface suitable for other crates (e.g.,
+//! codex-cloud-tasks) to reuse the mature composer behavior: multi-line input,
+//! paste heuristics, Enter-to-submit, and Shift+Enter for newline.
+
+use crossterm::event::KeyEvent;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use std::time::Duration;
+
+use crate::app_event::AppEvent;
+use crate::app_event_sender::AppEventSender;
+use crate::bottom_pane::ChatComposer;
+use crate::bottom_pane::InputResult;
+use crate::render::renderable::Renderable;
+
+/// Action returned from feeding a key event into the ComposerInput.
+pub enum ComposerAction {
+ /// The user submitted the current text (typically via Enter). Contains the submitted text.
+ Submitted(String),
+ /// No submission occurred; UI may need to redraw if `needs_redraw()` returned true.
+ None,
+}
+
+/// A minimal, public wrapper for the internal `ChatComposer` that behaves as a
+/// reusable text input field with submit semantics.
+pub struct ComposerInput {
+ inner: ChatComposer,
+ _tx: tokio::sync::mpsc::UnboundedSender<AppEvent>,
+ rx: tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
+}
+
+impl ComposerInput {
+ /// Create a new composer input with a neutral placeholder.
+ pub fn new() -> Self {
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
+ let sender = AppEventSender::new(tx.clone());
+ // `enhanced_keys_supported=true` enables Shift+Enter newline hint/behavior.
+ let inner = ChatComposer::new(true, sender, true, "Compose new task".to_string(), false);
+ Self { inner, _tx: tx, rx }
+ }
+
+ /// Returns true if the input is empty.
+ pub fn is_empty(&self) -> bool {
+ self.inner.is_empty()
+ }
+
+ /// Clear the input text.
+ pub fn clear(&mut self) {
+ self.inner.set_text_content(String::new());
+ }
+
+ /// Feed a key event into the composer and return a high-level action.
+ pub fn input(&mut self, key: KeyEvent) -> ComposerAction {
+ let action = match self.inner.handle_key_event(key).0 {
+ InputResult::Submitted(text) => ComposerAction::Submitted(text),
+ _ => ComposerAction::None,
+ };
+ self.drain_app_events();
+ action
+ }
+
+ pub fn handle_paste(&mut self, pasted: String) -> bool {
+ let handled = self.inner.handle_paste(pasted);
+ self.drain_app_events();
+ handled
+ }
+
+ /// Override the footer hint items displayed under the composer.
+ /// Each tuple is rendered as "<key> <label>", with keys styled.
+ pub fn set_hint_items(&mut self, items: Vec<(impl Into<String>, impl Into<String>)>) {
+ let mapped: Vec<(String, String)> = items
+ .into_iter()
+ .map(|(k, v)| (k.into(), v.into()))
+ .collect();
+ self.inner.set_footer_hint_override(Some(mapped));
+ }
+
+ /// Clear any previously set custom hint items and restore the default hints.
+ pub fn clear_hint_items(&mut self) {
+ self.inner.set_footer_hint_override(None);
+ }
+
+ /// Desired height (in rows) for a given width.
+ pub fn desired_height(&self, width: u16) -> u16 {
+ self.inner.desired_height(width)
+ }
+
+ /// Compute the on-screen cursor position for the given area.
+ pub fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ self.inner.cursor_pos(area)
+ }
+
+ /// Render the input into the provided buffer at `area`.
+ pub fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ self.inner.render(area, buf);
+ }
+
+ /// Return true if a paste-burst detection is currently active.
+ pub fn is_in_paste_burst(&self) -> bool {
+ self.inner.is_in_paste_burst()
+ }
+
+ /// Flush a pending paste-burst if the inter-key timeout has elapsed.
+ /// Returns true if text changed and a redraw is warranted.
+ pub fn flush_paste_burst_if_due(&mut self) -> bool {
+ let flushed = self.inner.flush_paste_burst_if_due();
+ self.drain_app_events();
+ flushed
+ }
+
+ /// Recommended delay to schedule the next micro-flush frame while a
+ /// paste-burst is active.
+ pub fn recommended_flush_delay() -> Duration {
+ crate::bottom_pane::ChatComposer::recommended_paste_flush_delay()
+ }
+
+ fn drain_app_events(&mut self) {
+ while self.rx.try_recv().is_ok() {}
+ }
+}
+
+impl Default for ComposerInput {
+ fn default() -> Self {
+ Self::new()
+ }
+}
diff --git a/codex-rs/tui2/src/public_widgets/mod.rs b/codex-rs/tui2/src/public_widgets/mod.rs
new file mode 100644
index 0000000000..c752189f3b
--- /dev/null
+++ b/codex-rs/tui2/src/public_widgets/mod.rs
@@ -0,0 +1 @@
+pub mod composer_input;
diff --git a/codex-rs/tui2/src/render/highlight.rs b/codex-rs/tui2/src/render/highlight.rs
new file mode 100644
index 0000000000..e6d200cc3d
--- /dev/null
+++ b/codex-rs/tui2/src/render/highlight.rs
@@ -0,0 +1,236 @@
+use ratatui::style::Style;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use std::sync::OnceLock;
+use tree_sitter_highlight::Highlight;
+use tree_sitter_highlight::HighlightConfiguration;
+use tree_sitter_highlight::HighlightEvent;
+use tree_sitter_highlight::Highlighter;
+
+// Ref: https://github.com/tree-sitter/tree-sitter-bash/blob/master/queries/highlights.scm
+#[derive(Copy, Clone)]
+enum BashHighlight {
+ Comment,
+ Constant,
+ Embedded,
+ Function,
+ Keyword,
+ Number,
+ Operator,
+ Property,
+ String,
+}
+
+impl BashHighlight {
+ const ALL: [Self; 9] = [
+ Self::Comment,
+ Self::Constant,
+ Self::Embedded,
+ Self::Function,
+ Self::Keyword,
+ Self::Number,
+ Self::Operator,
+ Self::Property,
+ Self::String,
+ ];
+
+ const fn as_str(self) -> &'static str {
+ match self {
+ Self::Comment => "comment",
+ Self::Constant => "constant",
+ Self::Embedded => "embedded",
+ Self::Function => "function",
+ Self::Keyword => "keyword",
+ Self::Number => "number",
+ Self::Operator => "operator",
+ Self::Property => "property",
+ Self::String => "string",
+ }
+ }
+
+ fn style(self) -> Style {
+ match self {
+ Self::Comment | Self::Operator | Self::String => Style::default().dim(),
+ _ => Style::default(),
+ }
+ }
+}
+
+static HIGHLIGHT_CONFIG: OnceLock<HighlightConfiguration> = OnceLock::new();
+
+fn highlight_names() -> &'static [&'static str] {
+ static NAMES: OnceLock<[&'static str; BashHighlight::ALL.len()]> = OnceLock::new();
+ NAMES
+ .get_or_init(|| BashHighlight::ALL.map(BashHighlight::as_str))
+ .as_slice()
+}
+
+fn highlight_config() -> &'static HighlightConfiguration {
+ HIGHLIGHT_CONFIG.get_or_init(|| {
+ let language = tree_sitter_bash::LANGUAGE.into();
+ #[expect(clippy::expect_used)]
+ let mut config = HighlightConfiguration::new(
+ language,
+ "bash",
+ tree_sitter_bash::HIGHLIGHT_QUERY,
+ "",
+ "",
+ )
+ .expect("load bash highlight query");
+ config.configure(highlight_names());
+ config
+ })
+}
+
+fn highlight_for(highlight: Highlight) -> BashHighlight {
+ BashHighlight::ALL[highlight.0]
+}
+
+fn push_segment(lines: &mut Vec<Line<'static>>, segment: &str, style: Option<Style>) {
+ for (i, part) in segment.split('\n').enumerate() {
+ if i > 0 {
+ lines.push(Line::from(""));
+ }
+ if part.is_empty() {
+ continue;
+ }
+ let span = match style {
+ Some(style) => Span::styled(part.to_string(), style),
+ None => part.to_string().into(),
+ };
+ if let Some(last) = lines.last_mut() {
+ last.spans.push(span);
+ }
+ }
+}
+
+/// Convert a bash script into per-line styled content using tree-sitter's
+/// bash highlight query. The highlighter is streamed so multi-line content is
+/// split into `Line`s while preserving style boundaries.
+pub(crate) fn highlight_bash_to_lines(script: &str) -> Vec<Line<'static>> {
+ let mut highlighter = Highlighter::new();
+ let iterator =
+ match highlighter.highlight(highlight_config(), script.as_bytes(), None, |_| None) {
+ Ok(iter) => iter,
+ Err(_) => return vec![script.to_string().into()],
+ };
+
+ let mut lines: Vec<Line<'static>> = vec![Line::from("")];
+ let mut highlight_stack: Vec<Highlight> = Vec::new();
+
+ for event in iterator {
+ match event {
+ Ok(HighlightEvent::HighlightStart(highlight)) => highlight_stack.push(highlight),
+ Ok(HighlightEvent::HighlightEnd) => {
+ highlight_stack.pop();
+ }
+ Ok(HighlightEvent::Source { start, end }) => {
+ if start == end {
+ continue;
+ }
+ let style = highlight_stack.last().map(|h| highlight_for(*h).style());
+ push_segment(&mut lines, &script[start..end], style);
+ }
+ Err(_) => return vec![script.to_string().into()],
+ }
+ }
+
+ if lines.is_empty() {
+ vec![Line::from("")]
+ } else {
+ lines
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use pretty_assertions::assert_eq;
+ use ratatui::style::Modifier;
+
+ fn reconstructed(lines: &[Line<'static>]) -> String {
+ lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|sp| sp.content.clone())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+ }
+
+ fn dimmed_tokens(lines: &[Line<'static>]) -> Vec<String> {
+ lines
+ .iter()
+ .flat_map(|l| l.spans.iter())
+ .filter(|sp| sp.style.add_modifier.contains(Modifier::DIM))
+ .map(|sp| sp.content.clone().into_owned())
+ .map(|token| token.trim().to_string())
+ .filter(|token| !token.is_empty())
+ .collect()
+ }
+
+ #[test]
+ fn dims_expected_bash_operators() {
+ let s = "echo foo && bar || baz | qux & (echo hi)";
+ let lines = highlight_bash_to_lines(s);
+ assert_eq!(reconstructed(&lines), s);
+
+ let dimmed = dimmed_tokens(&lines);
+ assert!(dimmed.contains(&"&&".to_string()));
+ assert!(dimmed.contains(&"|".to_string()));
+ assert!(!dimmed.contains(&"echo".to_string()));
+ }
+
+ #[test]
+ fn dims_redirects_and_strings() {
+ let s = "echo \"hi\" > out.txt; echo 'ok'";
+ let lines = highlight_bash_to_lines(s);
+ assert_eq!(reconstructed(&lines), s);
+
+ let dimmed = dimmed_tokens(&lines);
+ assert!(dimmed.contains(&">".to_string()));
+ assert!(dimmed.contains(&"\"hi\"".to_string()));
+ assert!(dimmed.contains(&"'ok'".to_string()));
+ }
+
+ #[test]
+ fn highlights_command_and_strings() {
+ let s = "echo \"hi\"";
+ let lines = highlight_bash_to_lines(s);
+ let mut echo_style = None;
+ let mut string_style = None;
+ for span in &lines[0].spans {
+ let text = span.content.as_ref();
+ if text == "echo" {
+ echo_style = Some(span.style);
+ }
+ if text == "\"hi\"" {
+ string_style = Some(span.style);
+ }
+ }
+ let echo_style = echo_style.expect("echo span missing");
+ let string_style = string_style.expect("string span missing");
+ assert!(echo_style.fg.is_none());
+ assert!(!echo_style.add_modifier.contains(Modifier::DIM));
+ assert!(string_style.add_modifier.contains(Modifier::DIM));
+ }
+
+ #[test]
+ fn highlights_heredoc_body_as_string() {
+ let s = "cat <<EOF\nheredoc body\nEOF";
+ let lines = highlight_bash_to_lines(s);
+ let body_line = &lines[1];
+ let mut body_style = None;
+ for span in &body_line.spans {
+ if span.content.as_ref() == "heredoc body" {
+ body_style = Some(span.style);
+ }
+ }
+ let body_style = body_style.expect("missing heredoc span");
+ assert!(body_style.add_modifier.contains(Modifier::DIM));
+ }
+}
diff --git a/codex-rs/tui2/src/render/line_utils.rs b/codex-rs/tui2/src/render/line_utils.rs
new file mode 100644
index 0000000000..175b79b2a8
--- /dev/null
+++ b/codex-rs/tui2/src/render/line_utils.rs
@@ -0,0 +1,59 @@
+use ratatui::text::Line;
+use ratatui::text::Span;
+
+/// Clone a borrowed ratatui `Line` into an owned `'static` line.
+pub fn line_to_static(line: &Line<'_>) -> Line<'static> {
+ Line {
+ style: line.style,
+ alignment: line.alignment,
+ spans: line
+ .spans
+ .iter()
+ .map(|s| Span {
+ style: s.style,
+ content: std::borrow::Cow::Owned(s.content.to_string()),
+ })
+ .collect(),
+ }
+}
+
+/// Append owned copies of borrowed lines to `out`.
+pub fn push_owned_lines<'a>(src: &[Line<'a>], out: &mut Vec<Line<'static>>) {
+ for l in src {
+ out.push(line_to_static(l));
+ }
+}
+
+/// Consider a line blank if it has no spans or only spans whose contents are
+/// empty or consist solely of spaces (no tabs/newlines).
+pub fn is_blank_line_spaces_only(line: &Line<'_>) -> bool {
+ if line.spans.is_empty() {
+ return true;
+ }
+ line.spans
+ .iter()
+ .all(|s| s.content.is_empty() || s.content.chars().all(|c| c == ' '))
+}
+
+/// Prefix each line with `initial_prefix` for the first line and
+/// `subsequent_prefix` for following lines. Returns a new Vec of owned lines.
+pub fn prefix_lines(
+ lines: Vec<Line<'static>>,
+ initial_prefix: Span<'static>,
+ subsequent_prefix: Span<'static>,
+) -> Vec<Line<'static>> {
+ lines
+ .into_iter()
+ .enumerate()
+ .map(|(i, l)| {
+ let mut spans = Vec::with_capacity(l.spans.len() + 1);
+ spans.push(if i == 0 {
+ initial_prefix.clone()
+ } else {
+ subsequent_prefix.clone()
+ });
+ spans.extend(l.spans);
+ Line::from(spans).style(l.style)
+ })
+ .collect()
+}
diff --git a/codex-rs/tui2/src/render/mod.rs b/codex-rs/tui2/src/render/mod.rs
new file mode 100644
index 0000000000..a2e4920586
--- /dev/null
+++ b/codex-rs/tui2/src/render/mod.rs
@@ -0,0 +1,50 @@
+use ratatui::layout::Rect;
+
+pub mod highlight;
+pub mod line_utils;
+pub mod renderable;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Insets {
+ left: u16,
+ top: u16,
+ right: u16,
+ bottom: u16,
+}
+
+impl Insets {
+ pub fn tlbr(top: u16, left: u16, bottom: u16, right: u16) -> Self {
+ Self {
+ top,
+ left,
+ bottom,
+ right,
+ }
+ }
+
+ pub fn vh(v: u16, h: u16) -> Self {
+ Self {
+ top: v,
+ left: h,
+ bottom: v,
+ right: h,
+ }
+ }
+}
+
+pub trait RectExt {
+ fn inset(&self, insets: Insets) -> Rect;
+}
+
+impl RectExt for Rect {
+ fn inset(&self, insets: Insets) -> Rect {
+ let horizontal = insets.left.saturating_add(insets.right);
+ let vertical = insets.top.saturating_add(insets.bottom);
+ Rect {
+ x: self.x.saturating_add(insets.left),
+ y: self.y.saturating_add(insets.top),
+ width: self.width.saturating_sub(horizontal),
+ height: self.height.saturating_sub(vertical),
+ }
+ }
+}
diff --git a/codex-rs/tui2/src/render/renderable.rs b/codex-rs/tui2/src/render/renderable.rs
new file mode 100644
index 0000000000..8581468c0a
--- /dev/null
+++ b/codex-rs/tui2/src/render/renderable.rs
@@ -0,0 +1,431 @@
+use std::sync::Arc;
+
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::WidgetRef;
+
+use crate::render::Insets;
+use crate::render::RectExt as _;
+
+pub trait Renderable {
+ fn render(&self, area: Rect, buf: &mut Buffer);
+ fn desired_height(&self, width: u16) -> u16;
+ fn cursor_pos(&self, _area: Rect) -> Option<(u16, u16)> {
+ None
+ }
+}
+
+pub enum RenderableItem<'a> {
+ Owned(Box<dyn Renderable + 'a>),
+ Borrowed(&'a dyn Renderable),
+}
+
+impl<'a> Renderable for RenderableItem<'a> {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ match self {
+ RenderableItem::Owned(child) => child.render(area, buf),
+ RenderableItem::Borrowed(child) => child.render(area, buf),
+ }
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ match self {
+ RenderableItem::Owned(child) => child.desired_height(width),
+ RenderableItem::Borrowed(child) => child.desired_height(width),
+ }
+ }
+
+ fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ match self {
+ RenderableItem::Owned(child) => child.cursor_pos(area),
+ RenderableItem::Borrowed(child) => child.cursor_pos(area),
+ }
+ }
+}
+
+impl<'a> From<Box<dyn Renderable + 'a>> for RenderableItem<'a> {
+ fn from(value: Box<dyn Renderable + 'a>) -> Self {
+ RenderableItem::Owned(value)
+ }
+}
+
+impl<'a, R> From<R> for Box<dyn Renderable + 'a>
+where
+ R: Renderable + 'a,
+{
+ fn from(value: R) -> Self {
+ Box::new(value)
+ }
+}
+
+impl Renderable for () {
+ fn render(&self, _area: Rect, _buf: &mut Buffer) {}
+ fn desired_height(&self, _width: u16) -> u16 {
+ 0
+ }
+}
+
+impl Renderable for &str {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ self.render_ref(area, buf);
+ }
+ fn desired_height(&self, _width: u16) -> u16 {
+ 1
+ }
+}
+
+impl Renderable for String {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ self.render_ref(area, buf);
+ }
+ fn desired_height(&self, _width: u16) -> u16 {
+ 1
+ }
+}
+
+impl<'a> Renderable for Span<'a> {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ self.render_ref(area, buf);
+ }
+ fn desired_height(&self, _width: u16) -> u16 {
+ 1
+ }
+}
+
+impl<'a> Renderable for Line<'a> {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ WidgetRef::render_ref(self, area, buf);
+ }
+ fn desired_height(&self, _width: u16) -> u16 {
+ 1
+ }
+}
+
+impl<'a> Renderable for Paragraph<'a> {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ self.render_ref(area, buf);
+ }
+ fn desired_height(&self, width: u16) -> u16 {
+ self.line_count(width) as u16
+ }
+}
+
+impl<R: Renderable> Renderable for Option<R> {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ if let Some(renderable) = self {
+ renderable.render(area, buf);
+ }
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ if let Some(renderable) = self {
+ renderable.desired_height(width)
+ } else {
+ 0
+ }
+ }
+}
+
+impl<R: Renderable> Renderable for Arc<R> {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ self.as_ref().render(area, buf);
+ }
+ fn desired_height(&self, width: u16) -> u16 {
+ self.as_ref().desired_height(width)
+ }
+}
+
+pub struct ColumnRenderable<'a> {
+ children: Vec<RenderableItem<'a>>,
+}
+
+impl Renderable for ColumnRenderable<'_> {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ let mut y = area.y;
+ for child in &self.children {
+ let child_area = Rect::new(area.x, y, area.width, child.desired_height(area.width))
+ .intersection(area);
+ if !child_area.is_empty() {
+ child.render(child_area, buf);
+ }
+ y += child_area.height;
+ }
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ self.children
+ .iter()
+ .map(|child| child.desired_height(width))
+ .sum()
+ }
+
+ /// Returns the cursor position of the first child that has a cursor position, offset by the
+ /// child's position in the column.
+ ///
+ /// It is generally assumed that either zero or one child will have a cursor position.
+ fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ let mut y = area.y;
+ for child in &self.children {
+ let child_area = Rect::new(area.x, y, area.width, child.desired_height(area.width))
+ .intersection(area);
+ if !child_area.is_empty()
+ && let Some((px, py)) = child.cursor_pos(child_area)
+ {
+ return Some((px, py));
+ }
+ y += child_area.height;
+ }
+ None
+ }
+}
+
+impl<'a> ColumnRenderable<'a> {
+ pub fn new() -> Self {
+ Self { children: vec![] }
+ }
+
+ pub fn with<I, T>(children: I) -> Self
+ where
+ I: IntoIterator<Item = T>,
+ T: Into<RenderableItem<'a>>,
+ {
+ Self {
+ children: children.into_iter().map(Into::into).collect(),
+ }
+ }
+
+ pub fn push(&mut self, child: impl Into<Box<dyn Renderable + 'a>>) {
+ self.children.push(RenderableItem::Owned(child.into()));
+ }
+
+ #[allow(dead_code)]
+ pub fn push_ref<R>(&mut self, child: &'a R)
+ where
+ R: Renderable + 'a,
+ {
+ self.children
+ .push(RenderableItem::Borrowed(child as &'a dyn Renderable));
+ }
+}
+
+pub struct FlexChild<'a> {
+ flex: i32,
+ child: RenderableItem<'a>,
+}
+
+pub struct FlexRenderable<'a> {
+ children: Vec<FlexChild<'a>>,
+}
+
+/// Lays out children in a column, with the ability to specify a flex factor for each child.
+///
+/// Children with flex factor > 0 will be allocated the remaining space after the non-flex children,
+/// proportional to the flex factor.
+impl<'a> FlexRenderable<'a> {
+ pub fn new() -> Self {
+ Self { children: vec![] }
+ }
+
+ pub fn push(&mut self, flex: i32, child: impl Into<RenderableItem<'a>>) {
+ self.children.push(FlexChild {
+ flex,
+ child: child.into(),
+ });
+ }
+
+ /// Loosely inspired by Flutter's Flex widget.
+ ///
+ /// Ref https://github.com/flutter/flutter/blob/3fd81edbf1e015221e143c92b2664f4371bdc04a/packages/flutter/lib/src/rendering/flex.dart#L1205-L1209
+ fn allocate(&self, area: Rect) -> Vec<Rect> {
+ let mut allocated_rects = Vec::with_capacity(self.children.len());
+ let mut child_sizes = vec![0; self.children.len()];
+ let mut allocated_size = 0;
+ let mut total_flex = 0;
+
+ // 1. Allocate space to non-flex children.
+ let max_size = area.height;
+ let mut last_flex_child_idx = 0;
+ for (i, FlexChild { flex, child }) in self.children.iter().enumerate() {
+ if *flex > 0 {
+ total_flex += flex;
+ last_flex_child_idx = i;
+ } else {
+ child_sizes[i] = child
+ .desired_height(area.width)
+ .min(max_size.saturating_sub(allocated_size));
+ allocated_size += child_sizes[i];
+ }
+ }
+ let free_space = max_size.saturating_sub(allocated_size);
+ // 2. Allocate space to flex children, proportional to their flex factor.
+ let mut allocated_flex_space = 0;
+ if total_flex > 0 {
+ let space_per_flex = free_space / total_flex as u16;
+ for (i, FlexChild { flex, child }) in self.children.iter().enumerate() {
+ if *flex > 0 {
+ // Last flex child gets all the remaining space, to prevent a rounding error
+ // from not allocating all the space.
+ let max_child_extent = if i == last_flex_child_idx {
+ free_space - allocated_flex_space
+ } else {
+ space_per_flex * *flex as u16
+ };
+ let child_size = child.desired_height(area.width).min(max_child_extent);
+ child_sizes[i] = child_size;
+ allocated_size += child_size;
+ allocated_flex_space += child_size;
+ }
+ }
+ }
+
+ let mut y = area.y;
+ for size in child_sizes {
+ let child_area = Rect::new(area.x, y, area.width, size);
+ allocated_rects.push(child_area);
+ y += child_area.height;
+ }
+ allocated_rects
+ }
+}
+
+impl<'a> Renderable for FlexRenderable<'a> {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ self.allocate(area)
+ .into_iter()
+ .zip(self.children.iter())
+ .for_each(|(rect, child)| {
+ child.child.render(rect, buf);
+ });
+ }
+
+ fn desired_height(&self, width: u16) -> u16 {
+ self.allocate(Rect::new(0, 0, width, u16::MAX))
+ .last()
+ .map(|rect| rect.bottom())
+ .unwrap_or(0)
+ }
+
+ fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ self.allocate(area)
+ .into_iter()
+ .zip(self.children.iter())
+ .find_map(|(rect, child)| child.child.cursor_pos(rect))
+ }
+}
+
+pub struct RowRenderable<'a> {
+ children: Vec<(u16, RenderableItem<'a>)>,
+}
+
+impl Renderable for RowRenderable<'_> {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ let mut x = area.x;
+ for (width, child) in &self.children {
+ let available_width = area.width.saturating_sub(x - area.x);
+ let child_area = Rect::new(x, area.y, (*width).min(available_width), area.height);
+ if child_area.is_empty() {
+ break;
+ }
+ child.render(child_area, buf);
+ x = x.saturating_add(*width);
+ }
+ }
+ fn desired_height(&self, width: u16) -> u16 {
+ let mut max_height = 0;
+ let mut width_remaining = width;
+ for (child_width, child) in &self.children {
+ let w = (*child_width).min(width_remaining);
+ if w == 0 {
+ break;
+ }
+ let height = child.desired_height(w);
+ if height > max_height {
+ max_height = height;
+ }
+ width_remaining = width_remaining.saturating_sub(w);
+ }
+ max_height
+ }
+
+ fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ let mut x = area.x;
+ for (width, child) in &self.children {
+ let available_width = area.width.saturating_sub(x - area.x);
+ let child_area = Rect::new(x, area.y, (*width).min(available_width), area.height);
+ if !child_area.is_empty()
+ && let Some(pos) = child.cursor_pos(child_area)
+ {
+ return Some(pos);
+ }
+ x = x.saturating_add(*width);
+ }
+ None
+ }
+}
+
+impl<'a> RowRenderable<'a> {
+ pub fn new() -> Self {
+ Self { children: vec![] }
+ }
+
+ pub fn push(&mut self, width: u16, child: impl Into<Box<dyn Renderable>>) {
+ self.children
+ .push((width, RenderableItem::Owned(child.into())));
+ }
+
+ #[allow(dead_code)]
+ pub fn push_ref<R>(&mut self, width: u16, child: &'a R)
+ where
+ R: Renderable + 'a,
+ {
+ self.children
+ .push((width, RenderableItem::Borrowed(child as &'a dyn Renderable)));
+ }
+}
+
+pub struct InsetRenderable<'a> {
+ child: RenderableItem<'a>,
+ insets: Insets,
+}
+
+impl<'a> Renderable for InsetRenderable<'a> {
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ self.child.render(area.inset(self.insets), buf);
+ }
+ fn desired_height(&self, width: u16) -> u16 {
+ self.child
+ .desired_height(width - self.insets.left - self.insets.right)
+ + self.insets.top
+ + self.insets.bottom
+ }
+ fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
+ self.child.cursor_pos(area.inset(self.insets))
+ }
+}
+
+impl<'a> InsetRenderable<'a> {
+ pub fn new(child: impl Into<RenderableItem<'a>>, insets: Insets) -> Self {
+ Self {
+ child: child.into(),
+ insets,
+ }
+ }
+}
+
+pub trait RenderableExt<'a> {
+ fn inset(self, insets: Insets) -> RenderableItem<'a>;
+}
+
+impl<'a, R> RenderableExt<'a> for R
+where
+ R: Renderable + 'a,
+{
+ fn inset(self, insets: Insets) -> RenderableItem<'a> {
+ let child: RenderableItem<'a> =
+ RenderableItem::Owned(Box::new(self) as Box<dyn Renderable + 'a>);
+ RenderableItem::Owned(Box::new(InsetRenderable { child, insets }))
+ }
+}
diff --git a/codex-rs/tui2/src/resume_picker.rs b/codex-rs/tui2/src/resume_picker.rs
new file mode 100644
index 0000000000..f2c6a3269d
--- /dev/null
+++ b/codex-rs/tui2/src/resume_picker.rs
@@ -0,0 +1,1728 @@
+use std::collections::HashSet;
+use std::path::Path;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use chrono::DateTime;
+use chrono::Utc;
+use codex_core::ConversationItem;
+use codex_core::ConversationsPage;
+use codex_core::Cursor;
+use codex_core::INTERACTIVE_SESSION_SOURCES;
+use codex_core::RolloutRecorder;
+use codex_protocol::items::TurnItem;
+use color_eyre::eyre::Result;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use ratatui::layout::Constraint;
+use ratatui::layout::Layout;
+use ratatui::layout::Rect;
+use ratatui::style::Stylize as _;
+use ratatui::text::Line;
+use ratatui::text::Span;
+use tokio::sync::mpsc;
+use tokio_stream::StreamExt;
+use tokio_stream::wrappers::UnboundedReceiverStream;
+use unicode_width::UnicodeWidthStr;
+
+use crate::diff_render::display_path_for;
+use crate::key_hint;
+use crate::text_formatting::truncate_text;
+use crate::tui::FrameRequester;
+use crate::tui::Tui;
+use crate::tui::TuiEvent;
+use codex_protocol::models::ResponseItem;
+use codex_protocol::protocol::SessionMetaLine;
+
+const PAGE_SIZE: usize = 25;
+const LOAD_NEAR_THRESHOLD: usize = 5;
+
+#[derive(Debug, Clone)]
+pub enum ResumeSelection {
+ StartFresh,
+ Resume(PathBuf),
+ Exit,
+}
+
+#[derive(Clone)]
+struct PageLoadRequest {
+ codex_home: PathBuf,
+ cursor: Option<Cursor>,
+ request_token: usize,
+ search_token: Option<usize>,
+ default_provider: String,
+}
+
+type PageLoader = Arc<dyn Fn(PageLoadRequest) + Send + Sync>;
+
+enum BackgroundEvent {
+ PageLoaded {
+ request_token: usize,
+ search_token: Option<usize>,
+ page: std::io::Result<ConversationsPage>,
+ },
+}
+
+/// Interactive session picker that lists recorded rollout files with simple
+/// search and pagination. Shows the first user input as the preview, relative
+/// time (e.g., "5 seconds ago"), and the absolute path.
+pub async fn run_resume_picker(
+ tui: &mut Tui,
+ codex_home: &Path,
+ default_provider: &str,
+ show_all: bool,
+) -> Result<ResumeSelection> {
+ let alt = AltScreenGuard::enter(tui);
+ let (bg_tx, bg_rx) = mpsc::unbounded_channel();
+
+ let default_provider = default_provider.to_string();
+ let filter_cwd = if show_all {
+ None
+ } else {
+ std::env::current_dir().ok()
+ };
+
+ let loader_tx = bg_tx.clone();
+ let page_loader: PageLoader = Arc::new(move |request: PageLoadRequest| {
+ let tx = loader_tx.clone();
+ tokio::spawn(async move {
+ let provider_filter = vec![request.default_provider.clone()];
+ let page = RolloutRecorder::list_conversations(
+ &request.codex_home,
+ PAGE_SIZE,
+ request.cursor.as_ref(),
+ INTERACTIVE_SESSION_SOURCES,
+ Some(provider_filter.as_slice()),
+ request.default_provider.as_str(),
+ )
+ .await;
+ let _ = tx.send(BackgroundEvent::PageLoaded {
+ request_token: request.request_token,
+ search_token: request.search_token,
+ page,
+ });
+ });
+ });
+
+ let mut state = PickerState::new(
+ codex_home.to_path_buf(),
+ alt.tui.frame_requester(),
+ page_loader,
+ default_provider.clone(),
+ show_all,
+ filter_cwd,
+ );
+ state.start_initial_load();
+ state.request_frame();
+
+ let mut tui_events = alt.tui.event_stream().fuse();
+ let mut background_events = UnboundedReceiverStream::new(bg_rx).fuse();
+
+ loop {
+ tokio::select! {
+ Some(ev) = tui_events.next() => {
+ match ev {
+ TuiEvent::Key(key) => {
+ if matches!(key.kind, KeyEventKind::Release) {
+ continue;
+ }
+ if let Some(sel) = state.handle_key(key).await? {
+ return Ok(sel);
+ }
+ }
+ TuiEvent::Draw => {
+ if let Ok(size) = alt.tui.terminal.size() {
+ let list_height = size.height.saturating_sub(4) as usize;
+ state.update_view_rows(list_height);
+ state.ensure_minimum_rows_for_view(list_height);
+ }
+ draw_picker(alt.tui, &state)?;
+ }
+ _ => {}
+ }
+ }
+ Some(event) = background_events.next() => {
+ state.handle_background_event(event)?;
+ }
+ else => break,
+ }
+ }
+
+ // Fallback – treat as cancel/new
+ Ok(ResumeSelection::StartFresh)
+}
+
+/// RAII guard that ensures we leave the alt-screen on scope exit.
+struct AltScreenGuard<'a> {
+ tui: &'a mut Tui,
+}
+
+impl<'a> AltScreenGuard<'a> {
+ fn enter(tui: &'a mut Tui) -> Self {
+ let _ = tui.enter_alt_screen();
+ Self { tui }
+ }
+}
+
+impl Drop for AltScreenGuard<'_> {
+ fn drop(&mut self) {
+ let _ = self.tui.leave_alt_screen();
+ }
+}
+
+struct PickerState {
+ codex_home: PathBuf,
+ requester: FrameRequester,
+ pagination: PaginationState,
+ all_rows: Vec<Row>,
+ filtered_rows: Vec<Row>,
+ seen_paths: HashSet<PathBuf>,
+ selected: usize,
+ scroll_top: usize,
+ query: String,
+ search_state: SearchState,
+ next_request_token: usize,
+ next_search_token: usize,
+ page_loader: PageLoader,
+ view_rows: Option<usize>,
+ default_provider: String,
+ show_all: bool,
+ filter_cwd: Option<PathBuf>,
+}
+
+struct PaginationState {
+ next_cursor: Option<Cursor>,
+ num_scanned_files: usize,
+ reached_scan_cap: bool,
+ loading: LoadingState,
+}
+
+#[derive(Clone, Copy, Debug)]
+enum LoadingState {
+ Idle,
+ Pending(PendingLoad),
+}
+
+#[derive(Clone, Copy, Debug)]
+struct PendingLoad {
+ request_token: usize,
+ search_token: Option<usize>,
+}
+
+#[derive(Clone, Copy, Debug)]
+enum SearchState {
+ Idle,
+ Active { token: usize },
+}
+
+enum LoadTrigger {
+ Scroll,
+ Search { token: usize },
+}
+
+impl LoadingState {
+ fn is_pending(&self) -> bool {
+ matches!(self, LoadingState::Pending(_))
+ }
+}
+
+impl SearchState {
+ fn active_token(&self) -> Option<usize> {
+ match self {
+ SearchState::Idle => None,
+ SearchState::Active { token } => Some(*token),
+ }
+ }
+
+ fn is_active(&self) -> bool {
+ self.active_token().is_some()
+ }
+}
+
+#[derive(Clone)]
+struct Row {
+ path: PathBuf,
+ preview: String,
+ created_at: Option<DateTime<Utc>>,
+ updated_at: Option<DateTime<Utc>>,
+ cwd: Option<PathBuf>,
+ git_branch: Option<String>,
+}
+
+impl PickerState {
+ fn new(
+ codex_home: PathBuf,
+ requester: FrameRequester,
+ page_loader: PageLoader,
+ default_provider: String,
+ show_all: bool,
+ filter_cwd: Option<PathBuf>,
+ ) -> Self {
+ Self {
+ codex_home,
+ requester,
+ pagination: PaginationState {
+ next_cursor: None,
+ num_scanned_files: 0,
+ reached_scan_cap: false,
+ loading: LoadingState::Idle,
+ },
+ all_rows: Vec::new(),
+ filtered_rows: Vec::new(),
+ seen_paths: HashSet::new(),
+ selected: 0,
+ scroll_top: 0,
+ query: String::new(),
+ search_state: SearchState::Idle,
+ next_request_token: 0,
+ next_search_token: 0,
+ page_loader,
+ view_rows: None,
+ default_provider,
+ show_all,
+ filter_cwd,
+ }
+ }
+
+ fn request_frame(&self) {
+ self.requester.schedule_frame();
+ }
+
+ async fn handle_key(&mut self, key: KeyEvent) -> Result<Option<ResumeSelection>> {
+ match key.code {
+ KeyCode::Esc => return Ok(Some(ResumeSelection::StartFresh)),
+ KeyCode::Char('c')
+ if key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL) =>
+ {
+ return Ok(Some(ResumeSelection::Exit));
+ }
+ KeyCode::Enter => {
+ if let Some(row) = self.filtered_rows.get(self.selected) {
+ return Ok(Some(ResumeSelection::Resume(row.path.clone())));
+ }
+ }
+ KeyCode::Up => {
+ if self.selected > 0 {
+ self.selected -= 1;
+ self.ensure_selected_visible();
+ }
+ self.request_frame();
+ }
+ KeyCode::Down => {
+ if self.selected + 1 < self.filtered_rows.len() {
+ self.selected += 1;
+ self.ensure_selected_visible();
+ }
+ self.maybe_load_more_for_scroll();
+ self.request_frame();
+ }
+ KeyCode::PageUp => {
+ let step = self.view_rows.unwrap_or(10).max(1);
+ if self.selected > 0 {
+ self.selected = self.selected.saturating_sub(step);
+ self.ensure_selected_visible();
+ self.request_frame();
+ }
+ }
+ KeyCode::PageDown => {
+ if !self.filtered_rows.is_empty() {
+ let step = self.view_rows.unwrap_or(10).max(1);
+ let max_index = self.filtered_rows.len().saturating_sub(1);
+ self.selected = (self.selected + step).min(max_index);
+ self.ensure_selected_visible();
+ self.maybe_load_more_for_scroll();
+ self.request_frame();
+ }
+ }
+ KeyCode::Backspace => {
+ let mut new_query = self.query.clone();
+ new_query.pop();
+ self.set_query(new_query);
+ }
+ KeyCode::Char(c) => {
+ // basic text input for search
+ if !key
+ .modifiers
+ .contains(crossterm::event::KeyModifiers::CONTROL)
+ && !key.modifiers.contains(crossterm::event::KeyModifiers::ALT)
+ {
+ let mut new_query = self.query.clone();
+ new_query.push(c);
+ self.set_query(new_query);
+ }
+ }
+ _ => {}
+ }
+ Ok(None)
+ }
+
+ fn start_initial_load(&mut self) {
+ self.reset_pagination();
+ self.all_rows.clear();
+ self.filtered_rows.clear();
+ self.seen_paths.clear();
+ self.search_state = SearchState::Idle;
+ self.selected = 0;
+
+ let request_token = self.allocate_request_token();
+ self.pagination.loading = LoadingState::Pending(PendingLoad {
+ request_token,
+ search_token: None,
+ });
+ self.request_frame();
+
+ (self.page_loader)(PageLoadRequest {
+ codex_home: self.codex_home.clone(),
+ cursor: None,
+ request_token,
+ search_token: None,
+ default_provider: self.default_provider.clone(),
+ });
+ }
+
+ fn handle_background_event(&mut self, event: BackgroundEvent) -> Result<()> {
+ match event {
+ BackgroundEvent::PageLoaded {
+ request_token,
+ search_token,
+ page,
+ } => {
+ let pending = match self.pagination.loading {
+ LoadingState::Pending(pending) => pending,
+ LoadingState::Idle => return Ok(()),
+ };
+ if pending.request_token != request_token {
+ return Ok(());
+ }
+ self.pagination.loading = LoadingState::Idle;
+ let page = page.map_err(color_eyre::Report::from)?;
+ self.ingest_page(page);
+ let completed_token = pending.search_token.or(search_token);
+ self.continue_search_if_token_matches(completed_token);
+ }
+ }
+ Ok(())
+ }
+
+ fn reset_pagination(&mut self) {
+ self.pagination.next_cursor = None;
+ self.pagination.num_scanned_files = 0;
+ self.pagination.reached_scan_cap = false;
+ self.pagination.loading = LoadingState::Idle;
+ }
+
+ fn ingest_page(&mut self, page: ConversationsPage) {
+ if let Some(cursor) = page.next_cursor.clone() {
+ self.pagination.next_cursor = Some(cursor);
+ } else {
+ self.pagination.next_cursor = None;
+ }
+ self.pagination.num_scanned_files = self
+ .pagination
+ .num_scanned_files
+ .saturating_add(page.num_scanned_files);
+ if page.reached_scan_cap {
+ self.pagination.reached_scan_cap = true;
+ }
+
+ let rows = rows_from_items(page.items);
+ for row in rows {
+ if self.seen_paths.insert(row.path.clone()) {
+ self.all_rows.push(row);
+ }
+ }
+
+ self.apply_filter();
+ }
+
+ fn apply_filter(&mut self) {
+ let base_iter = self
+ .all_rows
+ .iter()
+ .filter(|row| self.row_matches_filter(row));
+ if self.query.is_empty() {
+ self.filtered_rows = base_iter.cloned().collect();
+ } else {
+ let q = self.query.to_lowercase();
+ self.filtered_rows = base_iter
+ .filter(|r| r.preview.to_lowercase().contains(&q))
+ .cloned()
+ .collect();
+ }
+ if self.selected >= self.filtered_rows.len() {
+ self.selected = self.filtered_rows.len().saturating_sub(1);
+ }
+ if self.filtered_rows.is_empty() {
+ self.scroll_top = 0;
+ }
+ self.ensure_selected_visible();
+ self.request_frame();
+ }
+
+ fn row_matches_filter(&self, row: &Row) -> bool {
+ if self.show_all {
+ return true;
+ }
+ let Some(filter_cwd) = self.filter_cwd.as_ref() else {
+ return true;
+ };
+ let Some(row_cwd) = row.cwd.as_ref() else {
+ return false;
+ };
+ paths_match(row_cwd, filter_cwd)
+ }
+
+ fn set_query(&mut self, new_query: String) {
+ if self.query == new_query {
+ return;
+ }
+ self.query = new_query;
+ self.selected = 0;
+ self.apply_filter();
+ if self.query.is_empty() {
+ self.search_state = SearchState::Idle;
+ return;
+ }
+ if !self.filtered_rows.is_empty() {
+ self.search_state = SearchState::Idle;
+ return;
+ }
+ if self.pagination.reached_scan_cap || self.pagination.next_cursor.is_none() {
+ self.search_state = SearchState::Idle;
+ return;
+ }
+ let token = self.allocate_search_token();
+ self.search_state = SearchState::Active { token };
+ self.load_more_if_needed(LoadTrigger::Search { token });
+ }
+
+ fn continue_search_if_needed(&mut self) {
+ let Some(token) = self.search_state.active_token() else {
+ return;
+ };
+ if !self.filtered_rows.is_empty() {
+ self.search_state = SearchState::Idle;
+ return;
+ }
+ if self.pagination.reached_scan_cap || self.pagination.next_cursor.is_none() {
+ self.search_state = SearchState::Idle;
+ return;
+ }
+ self.load_more_if_needed(LoadTrigger::Search { token });
+ }
+
+ fn continue_search_if_token_matches(&mut self, completed_token: Option<usize>) {
+ let Some(active) = self.search_state.active_token() else {
+ return;
+ };
+ if let Some(token) = completed_token
+ && token != active
+ {
+ return;
+ }
+ self.continue_search_if_needed();
+ }
+
+ fn ensure_selected_visible(&mut self) {
+ if self.filtered_rows.is_empty() {
+ self.scroll_top = 0;
+ return;
+ }
+ let capacity = self.view_rows.unwrap_or(self.filtered_rows.len()).max(1);
+
+ if self.selected < self.scroll_top {
+ self.scroll_top = self.selected;
+ } else {
+ let last_visible = self.scroll_top.saturating_add(capacity - 1);
+ if self.selected > last_visible {
+ self.scroll_top = self.selected.saturating_sub(capacity - 1);
+ }
+ }
+
+ let max_start = self.filtered_rows.len().saturating_sub(capacity);
+ if self.scroll_top > max_start {
+ self.scroll_top = max_start;
+ }
+ }
+
+ fn ensure_minimum_rows_for_view(&mut self, minimum_rows: usize) {
+ if minimum_rows == 0 {
+ return;
+ }
+ if self.filtered_rows.len() >= minimum_rows {
+ return;
+ }
+ if self.pagination.loading.is_pending() || self.pagination.next_cursor.is_none() {
+ return;
+ }
+ if let Some(token) = self.search_state.active_token() {
+ self.load_more_if_needed(LoadTrigger::Search { token });
+ } else {
+ self.load_more_if_needed(LoadTrigger::Scroll);
+ }
+ }
+
+ fn update_view_rows(&mut self, rows: usize) {
+ self.view_rows = if rows == 0 { None } else { Some(rows) };
+ self.ensure_selected_visible();
+ }
+
+ fn maybe_load_more_for_scroll(&mut self) {
+ if self.pagination.loading.is_pending() {
+ return;
+ }
+ if self.pagination.next_cursor.is_none() {
+ return;
+ }
+ if self.filtered_rows.is_empty() {
+ return;
+ }
+ let remaining = self.filtered_rows.len().saturating_sub(self.selected + 1);
+ if remaining <= LOAD_NEAR_THRESHOLD {
+ self.load_more_if_needed(LoadTrigger::Scroll);
+ }
+ }
+
+ fn load_more_if_needed(&mut self, trigger: LoadTrigger) {
+ if self.pagination.loading.is_pending() {
+ return;
+ }
+ let Some(cursor) = self.pagination.next_cursor.clone() else {
+ return;
+ };
+ let request_token = self.allocate_request_token();
+ let search_token = match trigger {
+ LoadTrigger::Scroll => None,
+ LoadTrigger::Search { token } => Some(token),
+ };
+ self.pagination.loading = LoadingState::Pending(PendingLoad {
+ request_token,
+ search_token,
+ });
+ self.request_frame();
+
+ (self.page_loader)(PageLoadRequest {
+ codex_home: self.codex_home.clone(),
+ cursor: Some(cursor),
+ request_token,
+ search_token,
+ default_provider: self.default_provider.clone(),
+ });
+ }
+
+ fn allocate_request_token(&mut self) -> usize {
+ let token = self.next_request_token;
+ self.next_request_token = self.next_request_token.wrapping_add(1);
+ token
+ }
+
+ fn allocate_search_token(&mut self) -> usize {
+ let token = self.next_search_token;
+ self.next_search_token = self.next_search_token.wrapping_add(1);
+ token
+ }
+}
+
+fn rows_from_items(items: Vec<ConversationItem>) -> Vec<Row> {
+ items.into_iter().map(|item| head_to_row(&item)).collect()
+}
+
+fn head_to_row(item: &ConversationItem) -> Row {
+ let created_at = item
+ .created_at
+ .as_deref()
+ .and_then(parse_timestamp_str)
+ .or_else(|| item.head.first().and_then(extract_timestamp));
+ let updated_at = item
+ .updated_at
+ .as_deref()
+ .and_then(parse_timestamp_str)
+ .or(created_at);
+
+ let (cwd, git_branch) = extract_session_meta_from_head(&item.head);
+ let preview = preview_from_head(&item.head)
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .unwrap_or_else(|| String::from("(no message yet)"));
+
+ Row {
+ path: item.path.clone(),
+ preview,
+ created_at,
+ updated_at,
+ cwd,
+ git_branch,
+ }
+}
+
+fn extract_session_meta_from_head(head: &[serde_json::Value]) -> (Option<PathBuf>, Option<String>) {
+ for value in head {
+ if let Ok(meta_line) = serde_json::from_value::<SessionMetaLine>(value.clone()) {
+ let cwd = Some(meta_line.meta.cwd);
+ let git_branch = meta_line.git.and_then(|git| git.branch);
+ return (cwd, git_branch);
+ }
+ }
+ (None, None)
+}
+
+fn paths_match(a: &Path, b: &Path) -> bool {
+ if let (Ok(ca), Ok(cb)) = (a.canonicalize(), b.canonicalize()) {
+ return ca == cb;
+ }
+ a == b
+}
+
+fn parse_timestamp_str(ts: &str) -> Option<DateTime<Utc>> {
+ chrono::DateTime::parse_from_rfc3339(ts)
+ .map(|dt| dt.with_timezone(&Utc))
+ .ok()
+}
+
+fn extract_timestamp(value: &serde_json::Value) -> Option<DateTime<Utc>> {
+ value
+ .get("timestamp")
+ .and_then(|v| v.as_str())
+ .and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok())
+ .map(|dt| dt.with_timezone(&Utc))
+}
+
+fn preview_from_head(head: &[serde_json::Value]) -> Option<String> {
+ head.iter()
+ .filter_map(|value| serde_json::from_value::<ResponseItem>(value.clone()).ok())
+ .find_map(|item| match codex_core::parse_turn_item(&item) {
+ Some(TurnItem::UserMessage(user)) => Some(user.message()),
+ _ => None,
+ })
+}
+
+fn draw_picker(tui: &mut Tui, state: &PickerState) -> std::io::Result<()> {
+ // Render full-screen overlay
+ let height = tui.terminal.size()?.height;
+ tui.draw(height, |frame| {
+ let area = frame.area();
+ let [header, search, columns, list, hint] = Layout::vertical([
+ Constraint::Length(1),
+ Constraint::Length(1),
+ Constraint::Length(1),
+ Constraint::Min(area.height.saturating_sub(4)),
+ Constraint::Length(1),
+ ])
+ .areas(area);
+
+ // Header
+ frame.render_widget_ref(
+ Line::from(vec!["Resume a previous session".bold().cyan()]),
+ header,
+ );
+
+ // Search line
+ let q = if state.query.is_empty() {
+ "Type to search".dim().to_string()
+ } else {
+ format!("Search: {}", state.query)
+ };
+ frame.render_widget_ref(Line::from(q), search);
+
+ let metrics = calculate_column_metrics(&state.filtered_rows, state.show_all);
+
+ // Column headers and list
+ render_column_headers(frame, columns, &metrics);
+ render_list(frame, list, state, &metrics);
+
+ // Hint line
+ let hint_line: Line = vec![
+ key_hint::plain(KeyCode::Enter).into(),
+ " to resume ".dim(),
+ " ".dim(),
+ key_hint::plain(KeyCode::Esc).into(),
+ " to start new ".dim(),
+ " ".dim(),
+ key_hint::ctrl(KeyCode::Char('c')).into(),
+ " to quit ".dim(),
+ " ".dim(),
+ key_hint::plain(KeyCode::Up).into(),
+ "/".dim(),
+ key_hint::plain(KeyCode::Down).into(),
+ " to browse".dim(),
+ ]
+ .into();
+ frame.render_widget_ref(hint_line, hint);
+ })
+}
+
+fn render_list(
+ frame: &mut crate::custom_terminal::Frame,
+ area: Rect,
+ state: &PickerState,
+ metrics: &ColumnMetrics,
+) {
+ if area.height == 0 {
+ return;
+ }
+
+ let rows = &state.filtered_rows;
+ if rows.is_empty() {
+ let message = render_empty_state_line(state);
+ frame.render_widget_ref(message, area);
+ return;
+ }
+
+ let capacity = area.height as usize;
+ let start = state.scroll_top.min(rows.len().saturating_sub(1));
+ let end = rows.len().min(start + capacity);
+ let labels = &metrics.labels;
+ let mut y = area.y;
+
+ let max_updated_width = metrics.max_updated_width;
+ let max_branch_width = metrics.max_branch_width;
+ let max_cwd_width = metrics.max_cwd_width;
+
+ for (idx, (row, (updated_label, branch_label, cwd_label))) in rows[start..end]
+ .iter()
+ .zip(labels[start..end].iter())
+ .enumerate()
+ {
+ let is_sel = start + idx == state.selected;
+ let marker = if is_sel { "> ".bold() } else { " ".into() };
+ let marker_width = 2usize;
+ let updated_span = if max_updated_width == 0 {
+ None
+ } else {
+ Some(Span::from(format!("{updated_label:<max_updated_width$}")).dim())
+ };
+ let branch_span = if max_branch_width == 0 {
+ None
+ } else if branch_label.is_empty() {
+ Some(
+ Span::from(format!(
+ "{empty:<width$}",
+ empty = "-",
+ width = max_branch_width
+ ))
+ .dim(),
+ )
+ } else {
+ Some(Span::from(format!("{branch_label:<max_branch_width$}")).cyan())
+ };
+ let cwd_span = if max_cwd_width == 0 {
+ None
+ } else if cwd_label.is_empty() {
+ Some(
+ Span::from(format!(
+ "{empty:<width$}",
+ empty = "-",
+ width = max_cwd_width
+ ))
+ .dim(),
+ )
+ } else {
+ Some(Span::from(format!("{cwd_label:<max_cwd_width$}")).dim())
+ };
+
+ let mut preview_width = area.width as usize;
+ preview_width = preview_width.saturating_sub(marker_width);
+ if max_updated_width > 0 {
+ preview_width = preview_width.saturating_sub(max_updated_width + 2);
+ }
+ if max_branch_width > 0 {
+ preview_width = preview_width.saturating_sub(max_branch_width + 2);
+ }
+ if max_cwd_width > 0 {
+ preview_width = preview_width.saturating_sub(max_cwd_width + 2);
+ }
+ let add_leading_gap = max_updated_width == 0 && max_branch_width == 0 && max_cwd_width == 0;
+ if add_leading_gap {
+ preview_width = preview_width.saturating_sub(2);
+ }
+ let preview = truncate_text(&row.preview, preview_width);
+ let mut spans: Vec<Span> = vec![marker];
+ if let Some(updated) = updated_span {
+ spans.push(updated);
+ spans.push(" ".into());
+ }
+ if let Some(branch) = branch_span {
+ spans.push(branch);
+ spans.push(" ".into());
+ }
+ if let Some(cwd) = cwd_span {
+ spans.push(cwd);
+ spans.push(" ".into());
+ }
+ if add_leading_gap {
+ spans.push(" ".into());
+ }
+ spans.push(preview.into());
+
+ let line: Line = spans.into();
+ let rect = Rect::new(area.x, y, area.width, 1);
+ frame.render_widget_ref(line, rect);
+ y = y.saturating_add(1);
+ }
+
+ if state.pagination.loading.is_pending() && y < area.y.saturating_add(area.height) {
+ let loading_line: Line = vec![" ".into(), "Loading older sessions…".italic().dim()].into();
+ let rect = Rect::new(area.x, y, area.width, 1);
+ frame.render_widget_ref(loading_line, rect);
+ }
+}
+
+fn render_empty_state_line(state: &PickerState) -> Line<'static> {
+ if !state.query.is_empty() {
+ if state.search_state.is_active()
+ || (state.pagination.loading.is_pending() && state.pagination.next_cursor.is_some())
+ {
+ return vec!["Searching…".italic().dim()].into();
+ }
+ if state.pagination.reached_scan_cap {
+ let msg = format!(
+ "Search scanned first {} sessions; more may exist",
+ state.pagination.num_scanned_files
+ );
+ return vec![Span::from(msg).italic().dim()].into();
+ }
+ return vec!["No results for your search".italic().dim()].into();
+ }
+
+ if state.all_rows.is_empty() && state.pagination.num_scanned_files == 0 {
+ return vec!["No sessions yet".italic().dim()].into();
+ }
+
+ if state.pagination.loading.is_pending() {
+ return vec!["Loading older sessions…".italic().dim()].into();
+ }
+
+ vec!["No sessions yet".italic().dim()].into()
+}
+
+fn human_time_ago(ts: DateTime<Utc>) -> String {
+ let now = Utc::now();
+ let delta = now - ts;
+ let secs = delta.num_seconds();
+ if secs < 60 {
+ let n = secs.max(0);
+ if n == 1 {
+ format!("{n} second ago")
+ } else {
+ format!("{n} seconds ago")
+ }
+ } else if secs < 60 * 60 {
+ let m = secs / 60;
+ if m == 1 {
+ format!("{m} minute ago")
+ } else {
+ format!("{m} minutes ago")
+ }
+ } else if secs < 60 * 60 * 24 {
+ let h = secs / 3600;
+ if h == 1 {
+ format!("{h} hour ago")
+ } else {
+ format!("{h} hours ago")
+ }
+ } else {
+ let d = secs / (60 * 60 * 24);
+ if d == 1 {
+ format!("{d} day ago")
+ } else {
+ format!("{d} days ago")
+ }
+ }
+}
+
+fn format_updated_label(row: &Row) -> String {
+ match (row.updated_at, row.created_at) {
+ (Some(updated), _) => human_time_ago(updated),
+ (None, Some(created)) => human_time_ago(created),
+ (None, None) => "-".to_string(),
+ }
+}
+
+fn render_column_headers(
+ frame: &mut crate::custom_terminal::Frame,
+ area: Rect,
+ metrics: &ColumnMetrics,
+) {
+ if area.height == 0 {
+ return;
+ }
+
+ let mut spans: Vec<Span> = vec![" ".into()];
+ if metrics.max_updated_width > 0 {
+ let label = format!(
+ "{text:<width$}",
+ text = "Updated",
+ width = metrics.max_updated_width
+ );
+ spans.push(Span::from(label).bold());
+ spans.push(" ".into());
+ }
+ if metrics.max_branch_width > 0 {
+ let label = format!(
+ "{text:<width$}",
+ text = "Branch",
+ width = metrics.max_branch_width
+ );
+ spans.push(Span::from(label).bold());
+ spans.push(" ".into());
+ }
+ if metrics.max_cwd_width > 0 {
+ let label = format!(
+ "{text:<width$}",
+ text = "CWD",
+ width = metrics.max_cwd_width
+ );
+ spans.push(Span::from(label).bold());
+ spans.push(" ".into());
+ }
+ spans.push("Conversation".bold());
+ frame.render_widget_ref(Line::from(spans), area);
+}
+
+struct ColumnMetrics {
+ max_updated_width: usize,
+ max_branch_width: usize,
+ max_cwd_width: usize,
+ labels: Vec<(String, String, String)>,
+}
+
+fn calculate_column_metrics(rows: &[Row], include_cwd: bool) -> ColumnMetrics {
+ fn right_elide(s: &str, max: usize) -> String {
+ if s.chars().count() <= max {
+ return s.to_string();
+ }
+ if max <= 1 {
+ return "…".to_string();
+ }
+ let tail_len = max - 1;
+ let tail: String = s
+ .chars()
+ .rev()
+ .take(tail_len)
+ .collect::<String>()
+ .chars()
+ .rev()
+ .collect();
+ format!("…{tail}")
+ }
+
+ let mut labels: Vec<(String, String, String)> = Vec::with_capacity(rows.len());
+ let mut max_updated_width = UnicodeWidthStr::width("Updated");
+ let mut max_branch_width = UnicodeWidthStr::width("Branch");
+ let mut max_cwd_width = if include_cwd {
+ UnicodeWidthStr::width("CWD")
+ } else {
+ 0
+ };
+
+ for row in rows {
+ let updated = format_updated_label(row);
+ let branch_raw = row.git_branch.clone().unwrap_or_default();
+ let branch = right_elide(&branch_raw, 24);
+ let cwd = if include_cwd {
+ let cwd_raw = row
+ .cwd
+ .as_ref()
+ .map(|p| display_path_for(p, std::path::Path::new("/")))
+ .unwrap_or_default();
+ right_elide(&cwd_raw, 24)
+ } else {
+ String::new()
+ };
+ max_updated_width = max_updated_width.max(UnicodeWidthStr::width(updated.as_str()));
+ max_branch_width = max_branch_width.max(UnicodeWidthStr::width(branch.as_str()));
+ max_cwd_width = max_cwd_width.max(UnicodeWidthStr::width(cwd.as_str()));
+ labels.push((updated, branch, cwd));
+ }
+
+ ColumnMetrics {
+ max_updated_width,
+ max_branch_width,
+ max_cwd_width,
+ labels,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono::Duration;
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+ use insta::assert_snapshot;
+ use serde_json::json;
+ use std::future::Future;
+ use std::path::PathBuf;
+ use std::sync::Arc;
+ use std::sync::Mutex;
+
+ fn head_with_ts_and_user_text(ts: &str, texts: &[&str]) -> Vec<serde_json::Value> {
+ vec![
+ json!({ "timestamp": ts }),
+ json!({
+ "type": "message",
+ "role": "user",
+ "content": texts
+ .iter()
+ .map(|t| json!({ "type": "input_text", "text": *t }))
+ .collect::<Vec<_>>()
+ }),
+ ]
+ }
+
+ fn make_item(path: &str, ts: &str, preview: &str) -> ConversationItem {
+ ConversationItem {
+ path: PathBuf::from(path),
+ head: head_with_ts_and_user_text(ts, &[preview]),
+ created_at: Some(ts.to_string()),
+ updated_at: Some(ts.to_string()),
+ }
+ }
+
+ fn cursor_from_str(repr: &str) -> Cursor {
+ serde_json::from_str::<Cursor>(&format!("\"{repr}\""))
+ .expect("cursor format should deserialize")
+ }
+
+ fn page(
+ items: Vec<ConversationItem>,
+ next_cursor: Option<Cursor>,
+ num_scanned_files: usize,
+ reached_scan_cap: bool,
+ ) -> ConversationsPage {
+ ConversationsPage {
+ items,
+ next_cursor,
+ num_scanned_files,
+ reached_scan_cap,
+ }
+ }
+
+ fn block_on_future<F: Future<Output = T>, T>(future: F) -> T {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(future)
+ }
+
+ #[test]
+ fn preview_uses_first_message_input_text() {
+ let head = vec![
+ json!({ "timestamp": "2025-01-01T00:00:00Z" }),
+ json!({
+ "type": "message",
+ "role": "user",
+ "content": [
+ { "type": "input_text", "text": "# AGENTS.md instructions for project\n\n<INSTRUCTIONS>\nhi\n</INSTRUCTIONS>" },
+ ]
+ }),
+ json!({
+ "type": "message",
+ "role": "user",
+ "content": [
+ { "type": "input_text", "text": "<environment_context>...</environment_context>" },
+ ]
+ }),
+ json!({
+ "type": "message",
+ "role": "user",
+ "content": [
+ { "type": "input_text", "text": "real question" },
+ { "type": "input_image", "image_url": "ignored" }
+ ]
+ }),
+ json!({
+ "type": "message",
+ "role": "user",
+ "content": [ { "type": "input_text", "text": "later text" } ]
+ }),
+ ];
+ let preview = preview_from_head(&head);
+ assert_eq!(preview.as_deref(), Some("real question"));
+ }
+
+ #[test]
+ fn rows_from_items_preserves_backend_order() {
+ // Construct two items with different timestamps and real user text.
+ let a = ConversationItem {
+ path: PathBuf::from("/tmp/a.jsonl"),
+ head: head_with_ts_and_user_text("2025-01-01T00:00:00Z", &["A"]),
+ created_at: Some("2025-01-01T00:00:00Z".into()),
+ updated_at: Some("2025-01-01T00:00:00Z".into()),
+ };
+ let b = ConversationItem {
+ path: PathBuf::from("/tmp/b.jsonl"),
+ head: head_with_ts_and_user_text("2025-01-02T00:00:00Z", &["B"]),
+ created_at: Some("2025-01-02T00:00:00Z".into()),
+ updated_at: Some("2025-01-02T00:00:00Z".into()),
+ };
+ let rows = rows_from_items(vec![a, b]);
+ assert_eq!(rows.len(), 2);
+ // Preserve the given order even if timestamps differ; backend already provides newest-first.
+ assert!(rows[0].preview.contains('A'));
+ assert!(rows[1].preview.contains('B'));
+ }
+
+ #[test]
+ fn row_uses_tail_timestamp_for_updated_at() {
+ let head = head_with_ts_and_user_text("2025-01-01T00:00:00Z", &["Hello"]);
+ let item = ConversationItem {
+ path: PathBuf::from("/tmp/a.jsonl"),
+ head,
+ created_at: Some("2025-01-01T00:00:00Z".into()),
+ updated_at: Some("2025-01-01T01:00:00Z".into()),
+ };
+
+ let row = head_to_row(&item);
+ let expected_created = chrono::DateTime::parse_from_rfc3339("2025-01-01T00:00:00Z")
+ .unwrap()
+ .with_timezone(&Utc);
+ let expected_updated = chrono::DateTime::parse_from_rfc3339("2025-01-01T01:00:00Z")
+ .unwrap()
+ .with_timezone(&Utc);
+
+ assert_eq!(row.created_at, Some(expected_created));
+ assert_eq!(row.updated_at, Some(expected_updated));
+ }
+
+ #[test]
+ fn resume_table_snapshot() {
+ use crate::custom_terminal::Terminal;
+ use crate::test_backend::VT100Backend;
+ use ratatui::layout::Constraint;
+ use ratatui::layout::Layout;
+
+ let loader: PageLoader = Arc::new(|_| {});
+ let mut state = PickerState::new(
+ PathBuf::from("/tmp"),
+ FrameRequester::test_dummy(),
+ loader,
+ String::from("openai"),
+ true,
+ None,
+ );
+
+ let now = Utc::now();
+ let rows = vec![
+ Row {
+ path: PathBuf::from("/tmp/a.jsonl"),
+ preview: String::from("Fix resume picker timestamps"),
+ created_at: Some(now - Duration::minutes(16)),
+ updated_at: Some(now - Duration::seconds(42)),
+ cwd: None,
+ git_branch: None,
+ },
+ Row {
+ path: PathBuf::from("/tmp/b.jsonl"),
+ preview: String::from("Investigate lazy pagination cap"),
+ created_at: Some(now - Duration::hours(1)),
+ updated_at: Some(now - Duration::minutes(35)),
+ cwd: None,
+ git_branch: None,
+ },
+ Row {
+ path: PathBuf::from("/tmp/c.jsonl"),
+ preview: String::from("Explain the codebase"),
+ created_at: Some(now - Duration::hours(2)),
+ updated_at: Some(now - Duration::hours(2)),
+ cwd: None,
+ git_branch: None,
+ },
+ ];
+ state.all_rows = rows.clone();
+ state.filtered_rows = rows;
+ state.view_rows = Some(3);
+ state.selected = 1;
+ state.scroll_top = 0;
+ state.update_view_rows(3);
+
+ let metrics = calculate_column_metrics(&state.filtered_rows, state.show_all);
+
+ let width: u16 = 80;
+ let height: u16 = 6;
+ let backend = VT100Backend::new(width, height);
+ let mut terminal = Terminal::with_options(backend).expect("terminal");
+ terminal.set_viewport_area(Rect::new(0, 0, width, height));
+
+ {
+ let mut frame = terminal.get_frame();
+ let area = frame.area();
+ let segments =
+ Layout::vertical([Constraint::Length(1), Constraint::Min(1)]).split(area);
+ render_column_headers(&mut frame, segments[0], &metrics);
+ render_list(&mut frame, segments[1], &state, &metrics);
+ }
+ terminal.flush().expect("flush");
+
+ let snapshot = terminal.backend().to_string();
+ assert_snapshot!("resume_picker_table", snapshot);
+ }
+
+ #[test]
+ fn resume_picker_screen_snapshot() {
+ use crate::custom_terminal::Terminal;
+ use crate::test_backend::VT100Backend;
+ use uuid::Uuid;
+
+ // Create real rollout files so the snapshot uses the actual listing pipeline.
+ let tempdir = tempfile::tempdir().expect("tempdir");
+ let sessions_root = tempdir.path().join("sessions");
+ std::fs::create_dir_all(&sessions_root).expect("mkdir sessions root");
+
+ let now = Utc::now();
+
+ // Helper to write a rollout file with minimal meta + one user message.
+ let write_rollout = |ts: DateTime<Utc>, cwd: &str, branch: &str, preview: &str| {
+ let dir = sessions_root
+ .join(ts.format("%Y").to_string())
+ .join(ts.format("%m").to_string())
+ .join(ts.format("%d").to_string());
+ std::fs::create_dir_all(&dir).expect("mkdir date dirs");
+ let filename = format!(
+ "rollout-{}-{}.jsonl",
+ ts.format("%Y-%m-%dT%H-%M-%S"),
+ Uuid::new_v4()
+ );
+ let path = dir.join(filename);
+ let meta = serde_json::json!({
+ "timestamp": ts.to_rfc3339(),
+ "item": {
+ "SessionMeta": {
+ "meta": {
+ "id": Uuid::new_v4(),
+ "timestamp": ts.to_rfc3339(),
+ "cwd": cwd,
+ "originator": "user",
+ "cli_version": "0.0.0",
+ "instructions": null,
+ "source": "Cli",
+ "model_provider": "openai",
+ }
+ }
+ }
+ });
+ let user = serde_json::json!({
+ "timestamp": ts.to_rfc3339(),
+ "item": {
+ "EventMsg": {
+ "UserMessage": {
+ "message": preview,
+ "images": null
+ }
+ }
+ }
+ });
+ let branch_meta = serde_json::json!({
+ "timestamp": ts.to_rfc3339(),
+ "item": {
+ "EventMsg": {
+ "SessionMeta": {
+ "meta": {
+ "git_branch": branch
+ }
+ }
+ }
+ }
+ });
+ std::fs::write(&path, format!("{meta}\n{user}\n{branch_meta}\n"))
+ .expect("write rollout");
+ };
+
+ write_rollout(
+ now - Duration::seconds(42),
+ "/tmp/project",
+ "feature/resume",
+ "Fix resume picker timestamps",
+ );
+ write_rollout(
+ now - Duration::minutes(35),
+ "/tmp/other",
+ "main",
+ "Investigate lazy pagination cap",
+ );
+
+ let loader: PageLoader = Arc::new(|_| {});
+ let mut state = PickerState::new(
+ PathBuf::from("/tmp"),
+ FrameRequester::test_dummy(),
+ loader,
+ String::from("openai"),
+ true,
+ None,
+ );
+
+ let page = block_on_future(RolloutRecorder::list_conversations(
+ &state.codex_home,
+ PAGE_SIZE,
+ None,
+ INTERACTIVE_SESSION_SOURCES,
+ Some(&[String::from("openai")]),
+ "openai",
+ ))
+ .expect("list conversations");
+
+ let rows = rows_from_items(page.items);
+ state.all_rows = rows.clone();
+ state.filtered_rows = rows;
+ state.view_rows = Some(4);
+ state.selected = 0;
+ state.scroll_top = 0;
+ state.update_view_rows(4);
+
+ let metrics = calculate_column_metrics(&state.filtered_rows, state.show_all);
+
+ let width: u16 = 80;
+ let height: u16 = 9;
+ let backend = VT100Backend::new(width, height);
+ let mut terminal = Terminal::with_options(backend).expect("terminal");
+ terminal.set_viewport_area(Rect::new(0, 0, width, height));
+
+ {
+ let mut frame = terminal.get_frame();
+ let area = frame.area();
+ let [header, search, columns, list, hint] = Layout::vertical([
+ Constraint::Length(1),
+ Constraint::Length(1),
+ Constraint::Length(1),
+ Constraint::Min(area.height.saturating_sub(4)),
+ Constraint::Length(1),
+ ])
+ .areas(area);
+
+ frame.render_widget_ref(
+ Line::from(vec!["Resume a previous session".bold().cyan()]),
+ header,
+ );
+
+ frame.render_widget_ref(Line::from("Type to search".dim()), search);
+
+ render_column_headers(&mut frame, columns, &metrics);
+ render_list(&mut frame, list, &state, &metrics);
+
+ let hint_line: Line = vec![
+ key_hint::plain(KeyCode::Enter).into(),
+ " to resume ".dim(),
+ " ".dim(),
+ key_hint::plain(KeyCode::Esc).into(),
+ " to start new ".dim(),
+ " ".dim(),
+ key_hint::ctrl(KeyCode::Char('c')).into(),
+ " to quit ".dim(),
+ ]
+ .into();
+ frame.render_widget_ref(hint_line, hint);
+ }
+ terminal.flush().expect("flush");
+
+ let snapshot = terminal.backend().to_string();
+ assert_snapshot!("resume_picker_screen", snapshot);
+ }
+
+ #[test]
+ fn pageless_scrolling_deduplicates_and_keeps_order() {
+ let loader: PageLoader = Arc::new(|_| {});
+ let mut state = PickerState::new(
+ PathBuf::from("/tmp"),
+ FrameRequester::test_dummy(),
+ loader,
+ String::from("openai"),
+ true,
+ None,
+ );
+
+ state.reset_pagination();
+ state.ingest_page(page(
+ vec![
+ make_item("/tmp/a.jsonl", "2025-01-03T00:00:00Z", "third"),
+ make_item("/tmp/b.jsonl", "2025-01-02T00:00:00Z", "second"),
+ ],
+ Some(cursor_from_str(
+ "2025-01-02T00-00-00|00000000-0000-0000-0000-000000000000",
+ )),
+ 2,
+ false,
+ ));
+
+ state.ingest_page(page(
+ vec![
+ make_item("/tmp/a.jsonl", "2025-01-03T00:00:00Z", "duplicate"),
+ make_item("/tmp/c.jsonl", "2025-01-01T00:00:00Z", "first"),
+ ],
+ Some(cursor_from_str(
+ "2025-01-01T00-00-00|00000000-0000-0000-0000-000000000001",
+ )),
+ 2,
+ false,
+ ));
+
+ state.ingest_page(page(
+ vec![make_item(
+ "/tmp/d.jsonl",
+ "2024-12-31T23:00:00Z",
+ "very old",
+ )],
+ None,
+ 1,
+ false,
+ ));
+
+ let previews: Vec<_> = state
+ .filtered_rows
+ .iter()
+ .map(|row| row.preview.as_str())
+ .collect();
+ assert_eq!(previews, vec!["third", "second", "first", "very old"]);
+
+ let unique_paths = state
+ .filtered_rows
+ .iter()
+ .map(|row| row.path.clone())
+ .collect::<std::collections::HashSet<_>>();
+ assert_eq!(unique_paths.len(), 4);
+ }
+
+ #[test]
+ fn ensure_minimum_rows_prefetches_when_underfilled() {
+ let recorded_requests: Arc<Mutex<Vec<PageLoadRequest>>> = Arc::new(Mutex::new(Vec::new()));
+ let request_sink = recorded_requests.clone();
+ let loader: PageLoader = Arc::new(move |req: PageLoadRequest| {
+ request_sink.lock().unwrap().push(req);
+ });
+
+ let mut state = PickerState::new(
+ PathBuf::from("/tmp"),
+ FrameRequester::test_dummy(),
+ loader,
+ String::from("openai"),
+ true,
+ None,
+ );
+ state.reset_pagination();
+ state.ingest_page(page(
+ vec![
+ make_item("/tmp/a.jsonl", "2025-01-01T00:00:00Z", "one"),
+ make_item("/tmp/b.jsonl", "2025-01-02T00:00:00Z", "two"),
+ ],
+ Some(cursor_from_str(
+ "2025-01-03T00-00-00|00000000-0000-0000-0000-000000000000",
+ )),
+ 2,
+ false,
+ ));
+
+ assert!(recorded_requests.lock().unwrap().is_empty());
+ state.ensure_minimum_rows_for_view(10);
+ let guard = recorded_requests.lock().unwrap();
+ assert_eq!(guard.len(), 1);
+ assert!(guard[0].search_token.is_none());
+ }
+
+ #[test]
+ fn page_navigation_uses_view_rows() {
+ let loader: PageLoader = Arc::new(|_| {});
+ let mut state = PickerState::new(
+ PathBuf::from("/tmp"),
+ FrameRequester::test_dummy(),
+ loader,
+ String::from("openai"),
+ true,
+ None,
+ );
+
+ let mut items = Vec::new();
+ for idx in 0..20 {
+ let ts = format!("2025-01-{:02}T00:00:00Z", idx + 1);
+ let preview = format!("item-{idx}");
+ let path = format!("/tmp/item-{idx}.jsonl");
+ items.push(make_item(&path, &ts, &preview));
+ }
+
+ state.reset_pagination();
+ state.ingest_page(page(items, None, 20, false));
+ state.update_view_rows(5);
+
+ assert_eq!(state.selected, 0);
+ block_on_future(async {
+ state
+ .handle_key(KeyEvent::new(KeyCode::PageDown, KeyModifiers::NONE))
+ .await
+ .unwrap();
+ });
+ assert_eq!(state.selected, 5);
+
+ block_on_future(async {
+ state
+ .handle_key(KeyEvent::new(KeyCode::PageDown, KeyModifiers::NONE))
+ .await
+ .unwrap();
+ });
+ assert_eq!(state.selected, 10);
+
+ block_on_future(async {
+ state
+ .handle_key(KeyEvent::new(KeyCode::PageUp, KeyModifiers::NONE))
+ .await
+ .unwrap();
+ });
+ assert_eq!(state.selected, 5);
+ }
+
+ #[test]
+ fn up_at_bottom_does_not_scroll_when_visible() {
+ let loader: PageLoader = Arc::new(|_| {});
+ let mut state = PickerState::new(
+ PathBuf::from("/tmp"),
+ FrameRequester::test_dummy(),
+ loader,
+ String::from("openai"),
+ true,
+ None,
+ );
+
+ let mut items = Vec::new();
+ for idx in 0..10 {
+ let ts = format!("2025-02-{:02}T00:00:00Z", idx + 1);
+ let preview = format!("item-{idx}");
+ let path = format!("/tmp/item-{idx}.jsonl");
+ items.push(make_item(&path, &ts, &preview));
+ }
+
+ state.reset_pagination();
+ state.ingest_page(page(items, None, 10, false));
+ state.update_view_rows(5);
+
+ state.selected = state.filtered_rows.len().saturating_sub(1);
+ state.ensure_selected_visible();
+
+ let initial_top = state.scroll_top;
+ assert_eq!(initial_top, state.filtered_rows.len().saturating_sub(5));
+
+ block_on_future(async {
+ state
+ .handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE))
+ .await
+ .unwrap();
+ });
+
+ assert_eq!(state.scroll_top, initial_top);
+ assert_eq!(state.selected, state.filtered_rows.len().saturating_sub(2));
+ }
+
+ #[test]
+ fn set_query_loads_until_match_and_respects_scan_cap() {
+ let recorded_requests: Arc<Mutex<Vec<PageLoadRequest>>> = Arc::new(Mutex::new(Vec::new()));
+ let request_sink = recorded_requests.clone();
+ let loader: PageLoader = Arc::new(move |req: PageLoadRequest| {
+ request_sink.lock().unwrap().push(req);
+ });
+
+ let mut state = PickerState::new(
+ PathBuf::from("/tmp"),
+ FrameRequester::test_dummy(),
+ loader,
+ String::from("openai"),
+ true,
+ None,
+ );
+ state.reset_pagination();
+ state.ingest_page(page(
+ vec![make_item(
+ "/tmp/start.jsonl",
+ "2025-01-01T00:00:00Z",
+ "alpha",
+ )],
+ Some(cursor_from_str(
+ "2025-01-02T00-00-00|00000000-0000-0000-0000-000000000000",
+ )),
+ 1,
+ false,
+ ));
+ recorded_requests.lock().unwrap().clear();
+
+ state.set_query("target".to_string());
+ let first_request = {
+ let guard = recorded_requests.lock().unwrap();
+ assert_eq!(guard.len(), 1);
+ guard[0].clone()
+ };
+
+ state
+ .handle_background_event(BackgroundEvent::PageLoaded {
+ request_token: first_request.request_token,
+ search_token: first_request.search_token,
+ page: Ok(page(
+ vec![make_item("/tmp/beta.jsonl", "2025-01-02T00:00:00Z", "beta")],
+ Some(cursor_from_str(
+ "2025-01-03T00-00-00|00000000-0000-0000-0000-000000000001",
+ )),
+ 5,
+ false,
+ )),
+ })
+ .unwrap();
+
+ let second_request = {
+ let guard = recorded_requests.lock().unwrap();
+ assert_eq!(guard.len(), 2);
+ guard[1].clone()
+ };
+ assert!(state.search_state.is_active());
+ assert!(state.filtered_rows.is_empty());
+
+ state
+ .handle_background_event(BackgroundEvent::PageLoaded {
+ request_token: second_request.request_token,
+ search_token: second_request.search_token,
+ page: Ok(page(
+ vec![make_item(
+ "/tmp/match.jsonl",
+ "2025-01-03T00:00:00Z",
+ "target log",
+ )],
+ Some(cursor_from_str(
+ "2025-01-04T00-00-00|00000000-0000-0000-0000-000000000002",
+ )),
+ 7,
+ false,
+ )),
+ })
+ .unwrap();
+
+ assert!(!state.filtered_rows.is_empty());
+ assert!(!state.search_state.is_active());
+
+ recorded_requests.lock().unwrap().clear();
+ state.set_query("missing".to_string());
+ let active_request = {
+ let guard = recorded_requests.lock().unwrap();
+ assert_eq!(guard.len(), 1);
+ guard[0].clone()
+ };
+
+ state
+ .handle_background_event(BackgroundEvent::PageLoaded {
+ request_token: second_request.request_token,
+ search_token: second_request.search_token,
+ page: Ok(page(Vec::new(), None, 0, false)),
+ })
+ .unwrap();
+ assert_eq!(recorded_requests.lock().unwrap().len(), 1);
+
+ state
+ .handle_background_event(BackgroundEvent::PageLoaded {
+ request_token: active_request.request_token,
+ search_token: active_request.search_token,
+ page: Ok(page(Vec::new(), None, 3, true)),
+ })
+ .unwrap();
+
+ assert!(state.filtered_rows.is_empty());
+ assert!(!state.search_state.is_active());
+ assert!(state.pagination.reached_scan_cap);
+ }
+}
diff --git a/codex-rs/tui2/src/selection_list.rs b/codex-rs/tui2/src/selection_list.rs
new file mode 100644
index 0000000000..4816735437
--- /dev/null
+++ b/codex-rs/tui2/src/selection_list.rs
@@ -0,0 +1,35 @@
+use crate::render::renderable::Renderable;
+use crate::render::renderable::RowRenderable;
+use ratatui::style::Style;
+use ratatui::style::Styled as _;
+use ratatui::style::Stylize as _;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::Wrap;
+use unicode_width::UnicodeWidthStr;
+
+pub(crate) fn selection_option_row(
+ index: usize,
+ label: String,
+ is_selected: bool,
+) -> Box<dyn Renderable> {
+ let prefix = if is_selected {
+ format!("› {}. ", index + 1)
+ } else {
+ format!(" {}. ", index + 1)
+ };
+ let style = if is_selected {
+ Style::default().cyan()
+ } else {
+ Style::default()
+ };
+ let prefix_width = UnicodeWidthStr::width(prefix.as_str()) as u16;
+ let mut row = RowRenderable::new();
+ row.push(prefix_width, prefix.set_style(style));
+ row.push(
+ u16::MAX,
+ Paragraph::new(label)
+ .style(style)
+ .wrap(Wrap { trim: false }),
+ );
+ row.into()
+}
diff --git a/codex-rs/tui2/src/session_log.rs b/codex-rs/tui2/src/session_log.rs
new file mode 100644
index 0000000000..b2858e8f21
--- /dev/null
+++ b/codex-rs/tui2/src/session_log.rs
@@ -0,0 +1,210 @@
+use std::fs::File;
+use std::fs::OpenOptions;
+use std::io::Write;
+use std::path::PathBuf;
+use std::sync::LazyLock;
+use std::sync::Mutex;
+use std::sync::OnceLock;
+
+use codex_core::config::Config;
+use codex_core::protocol::Op;
+use serde::Serialize;
+use serde_json::json;
+
+use crate::app_event::AppEvent;
+
+static LOGGER: LazyLock<SessionLogger> = LazyLock::new(SessionLogger::new);
+
+struct SessionLogger {
+ file: OnceLock<Mutex<File>>,
+}
+
+impl SessionLogger {
+ fn new() -> Self {
+ Self {
+ file: OnceLock::new(),
+ }
+ }
+
+ fn open(&self, path: PathBuf) -> std::io::Result<()> {
+ let mut opts = OpenOptions::new();
+ opts.create(true).truncate(true).write(true);
+
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::OpenOptionsExt;
+ opts.mode(0o600);
+ }
+
+ let file = opts.open(path)?;
+ self.file.get_or_init(|| Mutex::new(file));
+ Ok(())
+ }
+
+ fn write_json_line(&self, value: serde_json::Value) {
+ let Some(mutex) = self.file.get() else {
+ return;
+ };
+ let mut guard = match mutex.lock() {
+ Ok(g) => g,
+ Err(poisoned) => poisoned.into_inner(),
+ };
+ match serde_json::to_string(&value) {
+ Ok(serialized) => {
+ if let Err(e) = guard.write_all(serialized.as_bytes()) {
+ tracing::warn!("session log write error: {}", e);
+ return;
+ }
+ if let Err(e) = guard.write_all(b"\n") {
+ tracing::warn!("session log write error: {}", e);
+ return;
+ }
+ if let Err(e) = guard.flush() {
+ tracing::warn!("session log flush error: {}", e);
+ }
+ }
+ Err(e) => tracing::warn!("session log serialize error: {}", e),
+ }
+ }
+
+ fn is_enabled(&self) -> bool {
+ self.file.get().is_some()
+ }
+}
+
+fn now_ts() -> String {
+ // RFC3339 for readability; consumers can parse as needed.
+ chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
+}
+
+pub(crate) fn maybe_init(config: &Config) {
+ let enabled = std::env::var("CODEX_TUI_RECORD_SESSION")
+ .map(|v| matches!(v.as_str(), "1" | "true" | "TRUE" | "yes" | "YES"))
+ .unwrap_or(false);
+ if !enabled {
+ return;
+ }
+
+ let path = if let Ok(path) = std::env::var("CODEX_TUI_SESSION_LOG_PATH") {
+ PathBuf::from(path)
+ } else {
+ let mut p = match codex_core::config::log_dir(config) {
+ Ok(dir) => dir,
+ Err(_) => std::env::temp_dir(),
+ };
+ let filename = format!(
+ "session-{}.jsonl",
+ chrono::Utc::now().format("%Y%m%dT%H%M%SZ")
+ );
+ p.push(filename);
+ p
+ };
+
+ if let Err(e) = LOGGER.open(path.clone()) {
+ tracing::error!("failed to open session log {:?}: {}", path, e);
+ return;
+ }
+
+ // Write a header record so we can attach context.
+ let header = json!({
+ "ts": now_ts(),
+ "dir": "meta",
+ "kind": "session_start",
+ "cwd": config.cwd,
+ "model": config.model,
+ "model_provider_id": config.model_provider_id,
+ "model_provider_name": config.model_provider.name,
+ });
+ LOGGER.write_json_line(header);
+}
+
+pub(crate) fn log_inbound_app_event(event: &AppEvent) {
+ // Log only if enabled
+ if !LOGGER.is_enabled() {
+ return;
+ }
+
+ match event {
+ AppEvent::CodexEvent(ev) => {
+ write_record("to_tui", "codex_event", ev);
+ }
+ AppEvent::NewSession => {
+ let value = json!({
+ "ts": now_ts(),
+ "dir": "to_tui",
+ "kind": "new_session",
+ });
+ LOGGER.write_json_line(value);
+ }
+ AppEvent::InsertHistoryCell(cell) => {
+ let value = json!({
+ "ts": now_ts(),
+ "dir": "to_tui",
+ "kind": "insert_history_cell",
+ "lines": cell.transcript_lines(u16::MAX).len(),
+ });
+ LOGGER.write_json_line(value);
+ }
+ AppEvent::StartFileSearch(query) => {
+ let value = json!({
+ "ts": now_ts(),
+ "dir": "to_tui",
+ "kind": "file_search_start",
+ "query": query,
+ });
+ LOGGER.write_json_line(value);
+ }
+ AppEvent::FileSearchResult { query, matches } => {
+ let value = json!({
+ "ts": now_ts(),
+ "dir": "to_tui",
+ "kind": "file_search_result",
+ "query": query,
+ "matches": matches.len(),
+ });
+ LOGGER.write_json_line(value);
+ }
+ // Noise or control flow – record variant only
+ other => {
+ let value = json!({
+ "ts": now_ts(),
+ "dir": "to_tui",
+ "kind": "app_event",
+ "variant": format!("{other:?}").split('(').next().unwrap_or("app_event"),
+ });
+ LOGGER.write_json_line(value);
+ }
+ }
+}
+
+pub(crate) fn log_outbound_op(op: &Op) {
+ if !LOGGER.is_enabled() {
+ return;
+ }
+ write_record("from_tui", "op", op);
+}
+
+pub(crate) fn log_session_end() {
+ if !LOGGER.is_enabled() {
+ return;
+ }
+ let value = json!({
+ "ts": now_ts(),
+ "dir": "meta",
+ "kind": "session_end",
+ });
+ LOGGER.write_json_line(value);
+}
+
+fn write_record<T>(dir: &str, kind: &str, obj: &T)
+where
+ T: Serialize,
+{
+ let value = json!({
+ "ts": now_ts(),
+ "dir": dir,
+ "kind": kind,
+ "payload": obj,
+ });
+ LOGGER.write_json_line(value);
+}
diff --git a/codex-rs/tui2/src/shimmer.rs b/codex-rs/tui2/src/shimmer.rs
new file mode 100644
index 0000000000..ba081e7c49
--- /dev/null
+++ b/codex-rs/tui2/src/shimmer.rs
@@ -0,0 +1,80 @@
+use std::sync::OnceLock;
+use std::time::Duration;
+use std::time::Instant;
+
+use ratatui::style::Color;
+use ratatui::style::Modifier;
+use ratatui::style::Style;
+use ratatui::text::Span;
+
+use crate::color::blend;
+use crate::terminal_palette::default_bg;
+use crate::terminal_palette::default_fg;
+
+static PROCESS_START: OnceLock<Instant> = OnceLock::new();
+
+fn elapsed_since_start() -> Duration {
+ let start = PROCESS_START.get_or_init(Instant::now);
+ start.elapsed()
+}
+
+pub(crate) fn shimmer_spans(text: &str) -> Vec<Span<'static>> {
+ let chars: Vec<char> = text.chars().collect();
+ if chars.is_empty() {
+ return Vec::new();
+ }
+ // Use time-based sweep synchronized to process start.
+ let padding = 10usize;
+ let period = chars.len() + padding * 2;
+ let sweep_seconds = 2.0f32;
+ let pos_f =
+ (elapsed_since_start().as_secs_f32() % sweep_seconds) / sweep_seconds * (period as f32);
+ let pos = pos_f as usize;
+ let has_true_color = supports_color::on_cached(supports_color::Stream::Stdout)
+ .map(|level| level.has_16m)
+ .unwrap_or(false);
+ let band_half_width = 5.0;
+
+ let mut spans: Vec<Span<'static>> = Vec::with_capacity(chars.len());
+ let base_color = default_fg().unwrap_or((128, 128, 128));
+ let highlight_color = default_bg().unwrap_or((255, 255, 255));
+ for (i, ch) in chars.iter().enumerate() {
+ let i_pos = i as isize + padding as isize;
+ let pos = pos as isize;
+ let dist = (i_pos - pos).abs() as f32;
+
+ let t = if dist <= band_half_width {
+ let x = std::f32::consts::PI * (dist / band_half_width);
+ 0.5 * (1.0 + x.cos())
+ } else {
+ 0.0
+ };
+ let style = if has_true_color {
+ let highlight = t.clamp(0.0, 1.0);
+ let (r, g, b) = blend(highlight_color, base_color, highlight * 0.9);
+ // Allow custom RGB colors, as the implementation is thoughtfully
+ // adjusting the level of the default foreground color.
+ #[allow(clippy::disallowed_methods)]
+ {
+ Style::default()
+ .fg(Color::Rgb(r, g, b))
+ .add_modifier(Modifier::BOLD)
+ }
+ } else {
+ color_for_level(t)
+ };
+ spans.push(Span::styled(ch.to_string(), style));
+ }
+ spans
+}
+
+fn color_for_level(intensity: f32) -> Style {
+ // Tune fallback styling so the shimmer band reads even without RGB support.
+ if intensity < 0.2 {
+ Style::default().add_modifier(Modifier::DIM)
+ } else if intensity < 0.6 {
+ Style::default()
+ } else {
+ Style::default().add_modifier(Modifier::BOLD)
+ }
+}
diff --git a/codex-rs/tui2/src/skill_error_prompt.rs b/codex-rs/tui2/src/skill_error_prompt.rs
new file mode 100644
index 0000000000..33d3b5dce1
--- /dev/null
+++ b/codex-rs/tui2/src/skill_error_prompt.rs
@@ -0,0 +1,164 @@
+use crate::tui::FrameRequester;
+use crate::tui::Tui;
+use crate::tui::TuiEvent;
+use codex_core::skills::SkillError;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use crossterm::event::KeyModifiers;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::prelude::Stylize as _;
+use ratatui::text::Line;
+use ratatui::widgets::Block;
+use ratatui::widgets::Borders;
+use ratatui::widgets::Clear;
+use ratatui::widgets::Paragraph;
+use ratatui::widgets::Widget;
+use ratatui::widgets::WidgetRef;
+use ratatui::widgets::Wrap;
+use tokio_stream::StreamExt;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum SkillErrorPromptOutcome {
+ Continue,
+ Exit,
+}
+
+pub(crate) async fn run_skill_error_prompt(
+ tui: &mut Tui,
+ errors: &[SkillError],
+) -> SkillErrorPromptOutcome {
+ struct AltScreenGuard<'a> {
+ tui: &'a mut Tui,
+ }
+ impl<'a> AltScreenGuard<'a> {
+ fn enter(tui: &'a mut Tui) -> Self {
+ let _ = tui.enter_alt_screen();
+ Self { tui }
+ }
+ }
+ impl Drop for AltScreenGuard<'_> {
+ fn drop(&mut self) {
+ let _ = self.tui.leave_alt_screen();
+ }
+ }
+
+ let alt = AltScreenGuard::enter(tui);
+ let mut screen = SkillErrorScreen::new(alt.tui.frame_requester(), errors);
+
+ let _ = alt.tui.draw(u16::MAX, |frame| {
+ frame.render_widget_ref(&screen, frame.area());
+ });
+
+ let events = alt.tui.event_stream();
+ tokio::pin!(events);
+
+ while !screen.is_done() {
+ if let Some(event) = events.next().await {
+ match event {
+ TuiEvent::Key(key_event) => screen.handle_key(key_event),
+ TuiEvent::Paste(_) => {}
+ TuiEvent::Draw => {
+ let _ = alt.tui.draw(u16::MAX, |frame| {
+ frame.render_widget_ref(&screen, frame.area());
+ });
+ }
+ }
+ } else {
+ screen.confirm_continue();
+ break;
+ }
+ }
+
+ screen.outcome()
+}
+
+struct SkillErrorScreen {
+ request_frame: FrameRequester,
+ lines: Vec<Line<'static>>,
+ done: bool,
+ exit: bool,
+}
+
+impl SkillErrorScreen {
+ fn new(request_frame: FrameRequester, errors: &[SkillError]) -> Self {
+ let mut lines: Vec<Line<'static>> = Vec::new();
+ lines.push(Line::from("Skill validation errors detected".bold()));
+ lines.push(Line::from(
+ "Fix these SKILL.md files and restart. Invalid skills are ignored until resolved. Press enter or esc to continue, Ctrl+C or Ctrl+D to exit.",
+ ));
+ lines.push(Line::from(""));
+
+ for error in errors {
+ let message = format!("- {}: {}", error.path.display(), error.message);
+ lines.push(Line::from(message));
+ }
+
+ Self {
+ request_frame,
+ lines,
+ done: false,
+ exit: false,
+ }
+ }
+
+ fn is_done(&self) -> bool {
+ self.done
+ }
+
+ fn confirm_continue(&mut self) {
+ self.done = true;
+ self.exit = false;
+ self.request_frame.schedule_frame();
+ }
+
+ fn confirm_exit(&mut self) {
+ self.done = true;
+ self.exit = true;
+ self.request_frame.schedule_frame();
+ }
+
+ fn outcome(&self) -> SkillErrorPromptOutcome {
+ if self.exit {
+ SkillErrorPromptOutcome::Exit
+ } else {
+ SkillErrorPromptOutcome::Continue
+ }
+ }
+
+ fn handle_key(&mut self, key_event: KeyEvent) {
+ if key_event.kind == KeyEventKind::Release {
+ return;
+ }
+
+ if key_event
+ .modifiers
+ .intersects(KeyModifiers::CONTROL | KeyModifiers::META)
+ && matches!(key_event.code, KeyCode::Char('c') | KeyCode::Char('d'))
+ {
+ self.confirm_exit();
+ return;
+ }
+
+ match key_event.code {
+ KeyCode::Enter | KeyCode::Esc | KeyCode::Char(' ') | KeyCode::Char('q') => {
+ self.confirm_continue();
+ }
+ _ => {}
+ }
+ }
+}
+
+impl WidgetRef for &SkillErrorScreen {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ Clear.render(area, buf);
+ let block = Block::default()
+ .title("Skill errors".bold())
+ .borders(Borders::ALL);
+ Paragraph::new(self.lines.clone())
+ .block(block)
+ .wrap(Wrap { trim: true })
+ .render(area, buf);
+ }
+}
diff --git a/codex-rs/tui2/src/slash_command.rs b/codex-rs/tui2/src/slash_command.rs
new file mode 100644
index 0000000000..e0c676812c
--- /dev/null
+++ b/codex-rs/tui2/src/slash_command.rs
@@ -0,0 +1,106 @@
+use strum::IntoEnumIterator;
+use strum_macros::AsRefStr;
+use strum_macros::EnumIter;
+use strum_macros::EnumString;
+use strum_macros::IntoStaticStr;
+
+/// Commands that can be invoked by starting a message with a leading slash.
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Hash, EnumString, EnumIter, AsRefStr, IntoStaticStr,
+)]
+#[strum(serialize_all = "kebab-case")]
+pub enum SlashCommand {
+ // DO NOT ALPHA-SORT! Enum order is presentation order in the popup, so
+ // more frequently used commands should be listed first.
+ Model,
+ Approvals,
+ Skills,
+ Review,
+ New,
+ Resume,
+ Init,
+ Compact,
+ Undo,
+ Diff,
+ Mention,
+ Status,
+ Mcp,
+ Logout,
+ Quit,
+ Exit,
+ Feedback,
+ Rollout,
+ TestApproval,
+}
+
+impl SlashCommand {
+ /// User-visible description shown in the popup.
+ pub fn description(self) -> &'static str {
+ match self {
+ SlashCommand::Feedback => "send logs to maintainers",
+ SlashCommand::New => "start a new chat during a conversation",
+ SlashCommand::Init => "create an AGENTS.md file with instructions for Codex",
+ SlashCommand::Compact => "summarize conversation to prevent hitting the context limit",
+ SlashCommand::Review => "review my current changes and find issues",
+ SlashCommand::Resume => "resume a saved chat",
+ SlashCommand::Undo => "ask Codex to undo a turn",
+ SlashCommand::Quit | SlashCommand::Exit => "exit Codex",
+ SlashCommand::Diff => "show git diff (including untracked files)",
+ SlashCommand::Mention => "mention a file",
+ SlashCommand::Skills => "use skills to improve how Codex performs specific tasks",
+ SlashCommand::Status => "show current session configuration and token usage",
+ SlashCommand::Model => "choose what model and reasoning effort to use",
+ SlashCommand::Approvals => "choose what Codex can do without approval",
+ SlashCommand::Mcp => "list configured MCP tools",
+ SlashCommand::Logout => "log out of Codex",
+ SlashCommand::Rollout => "print the rollout file path",
+ SlashCommand::TestApproval => "test approval request",
+ }
+ }
+
+ /// Command string without the leading '/'. Provided for compatibility with
+ /// existing code that expects a method named `command()`.
+ pub fn command(self) -> &'static str {
+ self.into()
+ }
+
+ /// Whether this command can be run while a task is in progress.
+ pub fn available_during_task(self) -> bool {
+ match self {
+ SlashCommand::New
+ | SlashCommand::Resume
+ | SlashCommand::Init
+ | SlashCommand::Compact
+ | SlashCommand::Undo
+ | SlashCommand::Model
+ | SlashCommand::Approvals
+ | SlashCommand::Review
+ | SlashCommand::Logout => false,
+ SlashCommand::Diff
+ | SlashCommand::Mention
+ | SlashCommand::Skills
+ | SlashCommand::Status
+ | SlashCommand::Mcp
+ | SlashCommand::Feedback
+ | SlashCommand::Quit
+ | SlashCommand::Exit => true,
+ SlashCommand::Rollout => true,
+ SlashCommand::TestApproval => true,
+ }
+ }
+
+ fn is_visible(self) -> bool {
+ match self {
+ SlashCommand::Rollout | SlashCommand::TestApproval => cfg!(debug_assertions),
+ _ => true,
+ }
+ }
+}
+
+/// Return all built-in commands in a Vec paired with their command string.
+pub fn built_in_slash_commands() -> Vec<(&'static str, SlashCommand)> {
+ SlashCommand::iter()
+ .filter(|command| command.is_visible())
+ .map(|c| (c.command(), c))
+ .collect()
+}
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_add_block.snap b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_add_block.snap
new file mode 100644
index 0000000000..bb2d4a161d
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_add_block.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Added new_file.txt (+2 -0) "
+" 1 +alpha "
+" 2 +beta "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_delete_block.snap b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_delete_block.snap
new file mode 100644
index 0000000000..3e5afa27c0
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_delete_block.snap
@@ -0,0 +1,16 @@
+---
+source: tui2/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Deleted tmp_delete_example.txt (+0 -3) "
+" 1 -first "
+" 2 -second "
+" 3 -third "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_multiple_files_block.snap b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_multiple_files_block.snap
new file mode 100644
index 0000000000..32432db778
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_multiple_files_block.snap
@@ -0,0 +1,18 @@
+---
+source: tui2/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Edited 2 files (+2 -1) "
+" └ a.txt (+1 -1) "
+" 1 -one "
+" 1 +one changed "
+" "
+" └ b.txt (+1 -0) "
+" 1 +new "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block.snap b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block.snap
new file mode 100644
index 0000000000..ca7ed957b2
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block.snap
@@ -0,0 +1,16 @@
+---
+source: tui2/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Edited example.txt (+1 -1) "
+" 1 line one "
+" 2 -line two "
+" 2 +line two changed "
+" 3 line three "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_line_numbers_three_digits_text.snap b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_line_numbers_three_digits_text.snap
new file mode 100644
index 0000000000..5938269d56
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_line_numbers_three_digits_text.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/diff_render.rs
+expression: text
+---
+• Edited hundreds.txt (+1 -1)
+ 97 line 97
+ 98 line 98
+ 99 line 99
+ 100 -line 100
+ 100 +line 100 changed
+ 101 line 101
+ 102 line 102
+ 103 line 103
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_relativizes_path.snap b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_relativizes_path.snap
new file mode 100644
index 0000000000..ce00f8b782
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_relativizes_path.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Edited abs_old.rs → abs_new.rs (+1 -1) "
+" 1 -X "
+" 1 +X changed "
+" 2 Y "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_wraps_long_lines.snap b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_wraps_long_lines.snap
new file mode 100644
index 0000000000..fddd6eb22a
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_wraps_long_lines.snap
@@ -0,0 +1,16 @@
+---
+source: tui2/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Edited long_example.txt (+1 -1) "
+" 1 line 1 "
+" 2 -short "
+" 2 +short this_is_a_very_long_modified_line_that_should_wrap_across_m "
+" ultiple_terminal_columns_and_continue_even_further_beyond_eighty_ "
+" columns_to_force_multiple_wraps "
+" 3 line 3 "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_wraps_long_lines_text.snap b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_wraps_long_lines_text.snap
new file mode 100644
index 0000000000..5c680baf84
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_block_wraps_long_lines_text.snap
@@ -0,0 +1,15 @@
+---
+source: tui2/src/diff_render.rs
+expression: text
+---
+• Edited wrap_demo.txt (+2 -2)
+ 1 1
+ 2 -2
+ 2 +added long line which
+ wraps and_if_there_i
+ s_a_long_token_it_wil
+ l_be_broken
+ 3 3
+ 4 -4
+ 4 +4 context line which
+ also wraps across
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_with_rename_block.snap b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_with_rename_block.snap
new file mode 100644
index 0000000000..bcd5612a6c
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__apply_update_with_rename_block.snap
@@ -0,0 +1,16 @@
+---
+source: tui2/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Edited old_name.rs → new_name.rs (+1 -1) "
+" 1 A "
+" 2 -B "
+" 2 +B changed "
+" 3 C "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__wrap_behavior_insert.snap b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__wrap_behavior_insert.snap
new file mode 100644
index 0000000000..87b7dc15de
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__diff_render__tests__wrap_behavior_insert.snap
@@ -0,0 +1,12 @@
+---
+source: tui2/src/diff_render.rs
+expression: terminal.backend()
+---
+"1 +this is a very long line that should wrap across multiple terminal columns an "
+" d continue "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__active_mcp_tool_call_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__active_mcp_tool_call_snapshot.snap
new file mode 100644
index 0000000000..808e6c179d
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__active_mcp_tool_call_snapshot.snap
@@ -0,0 +1,5 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Calling search.find_docs({"query":"ratatui styling","limit":3})
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__coalesced_reads_dedupe_names.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__coalesced_reads_dedupe_names.snap
new file mode 100644
index 0000000000..aa1f74c0c5
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__coalesced_reads_dedupe_names.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Explored
+ └ Read auth.rs, shimmer.rs
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__coalesces_reads_across_multiple_calls.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__coalesces_reads_across_multiple_calls.snap
new file mode 100644
index 0000000000..7491039bdf
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__coalesces_reads_across_multiple_calls.snap
@@ -0,0 +1,7 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Explored
+ └ Search shimmer_spans
+ Read shimmer.rs, status_indicator_widget.rs
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__coalesces_sequential_reads_within_one_call.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__coalesces_sequential_reads_within_one_call.snap
new file mode 100644
index 0000000000..ec07610d41
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__coalesces_sequential_reads_within_one_call.snap
@@ -0,0 +1,8 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Explored
+ └ Search shimmer_spans
+ Read shimmer.rs
+ Read status_indicator_widget.rs
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_error_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_error_snapshot.snap
new file mode 100644
index 0000000000..504ce206b0
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_error_snapshot.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Called search.find_docs({"query":"ratatui styling","limit":3})
+ └ Error: network timeout
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_multiple_outputs_inline_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_multiple_outputs_inline_snapshot.snap
new file mode 100644
index 0000000000..c21d18f4c1
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_multiple_outputs_inline_snapshot.snap
@@ -0,0 +1,7 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Called metrics.summary({"metric":"trace.latency","window":"15m"})
+ └ Latency summary: p50=120ms, p95=480ms.
+ No anomalies detected.
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_multiple_outputs_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_multiple_outputs_snapshot.snap
new file mode 100644
index 0000000000..4750a9f0f9
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_multiple_outputs_snapshot.snap
@@ -0,0 +1,10 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Called
+ └ search.find_docs({"query":"ratatui
+ styling","limit":3})
+ Found styling guidance in styles.md and
+ additional notes in CONTRIBUTING.md.
+ link: file:///docs/styles.md
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_success_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_success_snapshot.snap
new file mode 100644
index 0000000000..0d9330edb2
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_success_snapshot.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Called search.find_docs({"query":"ratatui styling","limit":3})
+ └ Found styling guidance in styles.md
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_wrapped_outputs_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_wrapped_outputs_snapshot.snap
new file mode 100644
index 0000000000..a3ce24f145
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__completed_mcp_tool_call_wrapped_outputs_snapshot.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Called
+ └ metrics.get_nearby_metric({"query":"
+ very_long_query_that_needs_wrapp
+ ing_to_display_properly_in_the_h
+ istory","limit":1})
+ Line one of the response, which is
+ quite long and needs wrapping.
+ Line two continues the response with
+ more detail.
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__mcp_tools_output_masks_sensitive_values.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__mcp_tools_output_masks_sensitive_values.snap
new file mode 100644
index 0000000000..31191bd156
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__mcp_tools_output_masks_sensitive_values.snap
@@ -0,0 +1,26 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+/mcp
+
+🔌 MCP Tools
+
+ • docs
+ • Status: enabled
+ • Auth: Unsupported
+ • Command: docs-server
+ • Env: TOKEN=*****, APP_TOKEN=*****
+ • Tools: list
+ • Resources: (none)
+ • Resource templates: (none)
+
+ • http
+ • Status: enabled
+ • Auth: Unsupported
+ • URL: https://example.com/mcp
+ • HTTP headers: Authorization=*****
+ • Env HTTP headers: X-API-Key=API_KEY_ENV
+ • Tools: ping
+ • Resources: (none)
+ • Resource templates: (none)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__multiline_command_both_lines_wrap_with_correct_prefixes.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__multiline_command_both_lines_wrap_with_correct_prefixes.snap
new file mode 100644
index 0000000000..714b9de361
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__multiline_command_both_lines_wrap_with_correct_prefixes.snap
@@ -0,0 +1,9 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Ran first_token_is_long_en
+ │ ough_to_wrap
+ │ second_token_is_also_lon
+ │ … +1 lines
+ └ (no output)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__multiline_command_without_wrap_uses_branch_then_eight_spaces.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__multiline_command_without_wrap_uses_branch_then_eight_spaces.snap
new file mode 100644
index 0000000000..caeb2aa6e9
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__multiline_command_without_wrap_uses_branch_then_eight_spaces.snap
@@ -0,0 +1,7 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Ran echo one
+ │ echo two
+ └ (no output)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__multiline_command_wraps_with_extra_indent_on_subsequent_lines.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__multiline_command_wraps_with_extra_indent_on_subsequent_lines.snap
new file mode 100644
index 0000000000..b5a87ddb96
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__multiline_command_wraps_with_extra_indent_on_subsequent_lines.snap
@@ -0,0 +1,8 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Ran set -o pipefail
+ │ cargo test
+ │ --all-features --quiet
+ └ (no output)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__plan_update_with_note_and_wrapping_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__plan_update_with_note_and_wrapping_snapshot.snap
new file mode 100644
index 0000000000..18912a0af5
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__plan_update_with_note_and_wrapping_snapshot.snap
@@ -0,0 +1,20 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Updated Plan
+ └ I’ll update Grafana call
+ error handling by adding
+ retries and clearer
+ messages when the backend is
+ unreachable.
+ ✔ Investigate existing error
+ paths and logging around
+ HTTP timeouts
+ □ Harden Grafana client
+ error handling with retry/
+ backoff and user‑friendly
+ messages
+ □ Add tests for transient
+ failure scenarios and
+ surfacing to the UI
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__plan_update_without_note_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__plan_update_without_note_snapshot.snap
new file mode 100644
index 0000000000..95feb11e74
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__plan_update_without_note_snapshot.snap
@@ -0,0 +1,7 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Updated Plan
+ └ □ Define error taxonomy
+ □ Implement mapping to user messages
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__ran_cell_multiline_with_stderr_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__ran_cell_multiline_with_stderr_snapshot.snap
new file mode 100644
index 0000000000..4725251422
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__ran_cell_multiline_with_stderr_snapshot.snap
@@ -0,0 +1,12 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Ran echo
+ │ this_is_a_very_long_si
+ │ ngle_token_that_will_w
+ │ … +2 lines
+ └ error: first line on
+ stderr
+ error: second line on
+ stderr
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__single_line_command_compact_when_fits.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__single_line_command_compact_when_fits.snap
new file mode 100644
index 0000000000..fcc30de8a0
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__single_line_command_compact_when_fits.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Ran echo ok
+ └ (no output)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__single_line_command_wraps_with_four_space_continuation.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__single_line_command_wraps_with_four_space_continuation.snap
new file mode 100644
index 0000000000..8797697b64
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__single_line_command_wraps_with_four_space_continuation.snap
@@ -0,0 +1,8 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Ran a_very_long_token_
+ │ without_spaces_to_
+ │ force_wrapping
+ └ (no output)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__stderr_tail_more_than_five_lines_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__stderr_tail_more_than_five_lines_snapshot.snap
new file mode 100644
index 0000000000..a42084f59e
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__stderr_tail_more_than_five_lines_snapshot.snap
@@ -0,0 +1,10 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+• Ran seq 1 10 1>&2 && false
+ └ 1
+ 2
+ … +6 lines
+ 9
+ 10
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__user_history_cell_wraps_and_prefixes_each_line_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__user_history_cell_wraps_and_prefixes_each_line_snapshot.snap
new file mode 100644
index 0000000000..234ed71171
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__history_cell__tests__user_history_cell_wraps_and_prefixes_each_line_snapshot.snap
@@ -0,0 +1,8 @@
+---
+source: tui2/src/history_cell.rs
+expression: rendered
+---
+› one two
+ three
+ four five
+ six seven
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__markdown_render__markdown_render_tests__markdown_render_complex_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui2__markdown_render__markdown_render_tests__markdown_render_complex_snapshot.snap
new file mode 100644
index 0000000000..1cc5ae501d
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__markdown_render__markdown_render_tests__markdown_render_complex_snapshot.snap
@@ -0,0 +1,62 @@
+---
+source: tui2/src/markdown_render_tests.rs
+expression: rendered
+---
+# H1: Markdown Streaming Test
+
+Intro paragraph with bold text, italic text, and inline code x=1.
+Combined bold-italic both and escaped asterisks *literal*.
+Auto-link: https://example.com (https://example.com) and reference link [ref][r1].
+Link with title: hover me (https://example.com) and mailto mailto:[email protected] (mailto:[email protected]).
+Image: alt text
+
+> Blockquote level 1
+>
+> > Blockquote level 2 with inline code
+
+- Unordered list item 1
+ - Nested bullet with italics inner
+- Unordered list item 2 with strikethrough
+
+1. Ordered item one
+2. Ordered item two with sublist:
+ 1. Alt-numbered subitem
+
+- [ ] Task: unchecked
+- [x] Task: checked with link home (https://example.org)
+
+———
+
+Table below (alignment test):
+| Left | Center | Right |
+|:-----|:------:|------:|
+| a | b | c |
+Inline HTML: <sup>sup</sup> and <sub>sub</sub>.
+HTML block:
+<div style="border:1px solid #ccc;padding:2px">inline block</div>
+Escapes: \_underscores\_, backslash \\, ticks ``code with `backtick` inside``.
+Emoji shortcodes: :sparkles: :tada: (if supported).
+Hard break test (line ends with two spaces)
+Next line should be close to previous.
+Footnote reference here[^1] and another[^longnote].
+Horizontal rule with asterisks:
+***
+Fenced code block (JSON):
+```json
+{ "a": 1, "b": [true, false] }
+```
+Fenced code with tildes and triple backticks inside:
+~~~markdown
+To close ``` you need tildes.
+~~~
+Indented code block:
+ for i in range(3): print(i)
+Definition-like list:
+Term
+: Definition with `code`.
+Character entities: &amp; &lt; &gt; &quot; &#39;
+[^1]: This is the first footnote.
+[^longnote]: A longer footnote with a link to [Rust](https://www.rust-lang.org/).
+Escaped pipe in text: a \| b \| c.
+URL with parentheses: [link](https://example.com/path_(with)_parens).
+[r1]: https://example.com/ref "Reference link title"
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt.snap b/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt.snap
new file mode 100644
index 0000000000..dd3ae058dc
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt.snap
@@ -0,0 +1,19 @@
+---
+source: tui2/src/model_migration.rs
+expression: terminal.backend()
+---
+> Codex just got an upgrade. Introducing gpt-5.1-codex-max
+
+ Codex is now powered by gpt-5.1-codex-max, our latest
+ frontier agentic coding model. It is smarter and faster
+ than its predecessors and capable of long-running
+ project-scale work.
+
+ Learn more at https://openai.com/index/gpt-5-1-codex-max/.
+
+ Choose how you'd like Codex to proceed.
+
+› 1. Try new model
+ 2. Use existing model
+
+ Use ↑/↓ to move, press enter to confirm
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt_gpt5_codex.snap b/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt_gpt5_codex.snap
new file mode 100644
index 0000000000..dbf2e2e4ea
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt_gpt5_codex.snap
@@ -0,0 +1,15 @@
+---
+source: tui2/src/model_migration.rs
+expression: terminal.backend()
+---
+> Introducing our gpt-5.1 models
+
+ We've upgraded our family of models supported in Codex to
+ gpt-5.1, gpt-5.1-codex and gpt-5.1-codex-mini.
+
+ You can continue using legacy models by specifying them
+ directly with the -m option or in your config.toml.
+
+ Learn more at https://openai.com/index/gpt-5-1/.
+
+ Press enter to continue
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt_gpt5_codex_mini.snap b/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt_gpt5_codex_mini.snap
new file mode 100644
index 0000000000..dbf2e2e4ea
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt_gpt5_codex_mini.snap
@@ -0,0 +1,15 @@
+---
+source: tui2/src/model_migration.rs
+expression: terminal.backend()
+---
+> Introducing our gpt-5.1 models
+
+ We've upgraded our family of models supported in Codex to
+ gpt-5.1, gpt-5.1-codex and gpt-5.1-codex-mini.
+
+ You can continue using legacy models by specifying them
+ directly with the -m option or in your config.toml.
+
+ Learn more at https://openai.com/index/gpt-5-1/.
+
+ Press enter to continue
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt_gpt5_family.snap b/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt_gpt5_family.snap
new file mode 100644
index 0000000000..dbf2e2e4ea
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__model_migration__tests__model_migration_prompt_gpt5_family.snap
@@ -0,0 +1,15 @@
+---
+source: tui2/src/model_migration.rs
+expression: terminal.backend()
+---
+> Introducing our gpt-5.1 models
+
+ We've upgraded our family of models supported in Codex to
+ gpt-5.1, gpt-5.1-codex and gpt-5.1-codex-mini.
+
+ You can continue using legacy models by specifying them
+ directly with the -m option or in your config.toml.
+
+ Learn more at https://openai.com/index/gpt-5-1/.
+
+ Press enter to continue
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__static_overlay_snapshot_basic.snap b/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__static_overlay_snapshot_basic.snap
new file mode 100644
index 0000000000..aea41abff1
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__static_overlay_snapshot_basic.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/pager_overlay.rs
+expression: term.backend()
+---
+"/ S T A T I C / / / / / / / / / / / / / "
+"one "
+"two "
+"three "
+"~ "
+"~ "
+"───────────────────────────────── 100% ─"
+" ↑/↓ to scroll pgup/pgdn to page hom"
+" q to quit "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__static_overlay_wraps_long_lines.snap b/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__static_overlay_wraps_long_lines.snap
new file mode 100644
index 0000000000..8c4cda9ac5
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__static_overlay_wraps_long_lines.snap
@@ -0,0 +1,12 @@
+---
+source: tui2/src/pager_overlay.rs
+expression: term.backend()
+---
+"/ S T A T I C / / / / / "
+"a very long line that "
+"should wrap when "
+"rendered within a narrow"
+"─────────────────── 0% ─"
+" ↑/↓ to scroll pgup/pg"
+" q to quit "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap b/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap
new file mode 100644
index 0000000000..b931e2ab21
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap
@@ -0,0 +1,15 @@
+---
+source: tui2/src/pager_overlay.rs
+expression: snapshot
+---
+/ T R A N S C R I P T / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
+• Added foo.txt (+2 -0)
+ 1 +hello
+ 2 +world
+
+• Added foo.txt (+2 -0)
+ 1 +hello
+ 2 +world
+─────────────────────────────────────────────────────────────────────────── 0% ─
+ ↑/↓ to scroll pgup/pgdn to page home/end to jump
+ q to quit esc to edit prev
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__transcript_overlay_snapshot_basic.snap b/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__transcript_overlay_snapshot_basic.snap
new file mode 100644
index 0000000000..59c79a365d
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__pager_overlay__tests__transcript_overlay_snapshot_basic.snap
@@ -0,0 +1,14 @@
+---
+source: tui2/src/pager_overlay.rs
+expression: term.backend()
+---
+"/ T R A N S C R I P T / / / / / / / / / "
+"alpha "
+" "
+"beta "
+" "
+"gamma "
+"───────────────────────────────── 100% ─"
+" ↑/↓ to scroll pgup/pgdn to page hom"
+" q to quit esc to edit prev "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__resume_picker__tests__resume_picker_screen.snap b/codex-rs/tui2/src/snapshots/codex_tui2__resume_picker__tests__resume_picker_screen.snap
new file mode 100644
index 0000000000..25f8d5afaa
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__resume_picker__tests__resume_picker_screen.snap
@@ -0,0 +1,13 @@
+---
+source: tui2/src/resume_picker.rs
+expression: snapshot
+---
+Resume a previous session
+Type to search
+ Updated Branch CWD Conversation
+No sessions yet
+
+
+
+
+enter to resume esc to start new ctrl + c to quit
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__resume_picker__tests__resume_picker_table.snap b/codex-rs/tui2/src/snapshots/codex_tui2__resume_picker__tests__resume_picker_table.snap
new file mode 100644
index 0000000000..313c199767
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__resume_picker__tests__resume_picker_table.snap
@@ -0,0 +1,8 @@
+---
+source: tui2/src/resume_picker.rs
+expression: snapshot
+---
+ Updated Branch CWD Conversation
+ 42 seconds ago - - Fix resume picker timestamps
+> 35 minutes ago - - Investigate lazy pagination cap
+ 2 hours ago - - Explain the codebase
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__status_indicator_widget__tests__renders_truncated.snap b/codex-rs/tui2/src/snapshots/codex_tui2__status_indicator_widget__tests__renders_truncated.snap
new file mode 100644
index 0000000000..6b4f661ff1
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__status_indicator_widget__tests__renders_truncated.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/status_indicator_widget.rs
+expression: terminal.backend()
+---
+"• Working (0s • esc "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui2__status_indicator_widget__tests__renders_with_working_header.snap b/codex-rs/tui2/src/snapshots/codex_tui2__status_indicator_widget__tests__renders_with_working_header.snap
new file mode 100644
index 0000000000..99e0c344ef
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui2__status_indicator_widget__tests__renders_with_working_header.snap
@@ -0,0 +1,6 @@
+---
+source: tui2/src/status_indicator_widget.rs
+expression: terminal.backend()
+---
+"• Working (0s • esc to interrupt) "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__add_details.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__add_details.snap
new file mode 100644
index 0000000000..1ff570945b
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__add_details.snap
@@ -0,0 +1,15 @@
+---
+source: tui/src/diff_render.rs
+assertion_line: 765
+expression: terminal.backend()
+---
+"• Proposed Change README.md (+2 -0) "
+" 1 +first line "
+" 2 +second line "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_add_block.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_add_block.snap
new file mode 100644
index 0000000000..cd5aaf5fa0
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_add_block.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Added new_file.txt (+2 -0) "
+" 1 +alpha "
+" 2 +beta "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_delete_block.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_delete_block.snap
new file mode 100644
index 0000000000..edfdb2c05f
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_delete_block.snap
@@ -0,0 +1,16 @@
+---
+source: tui/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Deleted tmp_delete_example.txt (+0 -3) "
+" 1 -first "
+" 2 -second "
+" 3 -third "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_multiple_files_block.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_multiple_files_block.snap
new file mode 100644
index 0000000000..62fc671d11
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_multiple_files_block.snap
@@ -0,0 +1,18 @@
+---
+source: tui/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Edited 2 files (+2 -1) "
+" └ a.txt (+1 -1) "
+" 1 -one "
+" 1 +one changed "
+" "
+" └ b.txt (+1 -0) "
+" 1 +new "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block.snap
new file mode 100644
index 0000000000..8cc31efdde
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block.snap
@@ -0,0 +1,16 @@
+---
+source: tui/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Edited example.txt (+1 -1) "
+" 1 line one "
+" 2 -line two "
+" 2 +line two changed "
+" 3 line three "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_line_numbers_three_digits_text.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_line_numbers_three_digits_text.snap
new file mode 100644
index 0000000000..56058ee70e
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_line_numbers_three_digits_text.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/diff_render.rs
+expression: text
+---
+• Edited hundreds.txt (+1 -1)
+ 97 line 97
+ 98 line 98
+ 99 line 99
+ 100 -line 100
+ 100 +line 100 changed
+ 101 line 101
+ 102 line 102
+ 103 line 103
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_relativizes_path.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_relativizes_path.snap
new file mode 100644
index 0000000000..a50f7700cf
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_relativizes_path.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Edited abs_old.rs → abs_new.rs (+1 -1) "
+" 1 -X "
+" 1 +X changed "
+" 2 Y "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_wraps_long_lines.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_wraps_long_lines.snap
new file mode 100644
index 0000000000..72b9528e5c
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_wraps_long_lines.snap
@@ -0,0 +1,16 @@
+---
+source: tui/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Edited long_example.txt (+1 -1) "
+" 1 line 1 "
+" 2 -short "
+" 2 +short this_is_a_very_long_modified_line_that_should_wrap_across_m "
+" ultiple_terminal_columns_and_continue_even_further_beyond_eighty_ "
+" columns_to_force_multiple_wraps "
+" 3 line 3 "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_wraps_long_lines_text.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_wraps_long_lines_text.snap
new file mode 100644
index 0000000000..17c92c1b5d
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_block_wraps_long_lines_text.snap
@@ -0,0 +1,15 @@
+---
+source: tui/src/diff_render.rs
+expression: text
+---
+• Edited wrap_demo.txt (+2 -2)
+ 1 1
+ 2 -2
+ 2 +added long line which
+ wraps and_if_there_i
+ s_a_long_token_it_wil
+ l_be_broken
+ 3 3
+ 4 -4
+ 4 +4 context line which
+ also wraps across
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_with_rename_block.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_with_rename_block.snap
new file mode 100644
index 0000000000..29b321011c
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__apply_update_with_rename_block.snap
@@ -0,0 +1,16 @@
+---
+source: tui/src/diff_render.rs
+expression: terminal.backend()
+---
+"• Edited old_name.rs → new_name.rs (+1 -1) "
+" 1 A "
+" 2 -B "
+" 2 +B changed "
+" 3 C "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__blank_context_line.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__blank_context_line.snap
new file mode 100644
index 0000000000..a662041e8d
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__blank_context_line.snap
@@ -0,0 +1,15 @@
+---
+source: tui/src/diff_render.rs
+assertion_line: 765
+expression: terminal.backend()
+---
+"• Proposed Change example.txt (+1 -1) "
+" 1 "
+" 2 -Y "
+" 2 +Y changed "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__single_line_replacement_counts.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__single_line_replacement_counts.snap
new file mode 100644
index 0000000000..d4a7bd8bf3
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__single_line_replacement_counts.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/diff_render.rs
+assertion_line: 765
+expression: terminal.backend()
+---
+"• Proposed Change README.md (+1 -1) "
+" 1 -# Codex CLI (Rust Implementation) "
+" 1 +# Codex CLI (Rust Implementation) banana "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__update_details_with_rename.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__update_details_with_rename.snap
new file mode 100644
index 0000000000..6e5c34ba24
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__update_details_with_rename.snap
@@ -0,0 +1,17 @@
+---
+source: tui/src/diff_render.rs
+assertion_line: 765
+expression: terminal.backend()
+---
+"• Proposed Change src/lib.rs → src/lib_new.rs (+1 -1) "
+" 1 line one "
+" 2 -line two "
+" 2 +line two changed "
+" 3 line three "
+" "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__vertical_ellipsis_between_hunks.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__vertical_ellipsis_between_hunks.snap
new file mode 100644
index 0000000000..bc7743886d
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__vertical_ellipsis_between_hunks.snap
@@ -0,0 +1,21 @@
+---
+source: tui/src/diff_render.rs
+assertion_line: 765
+expression: terminal.backend()
+---
+"• Proposed Change example.txt (+2 -2) "
+" 1 line 1 "
+" 2 -line 2 "
+" 2 +line two changed "
+" 3 line 3 "
+" 4 line 4 "
+" 5 line 5 "
+" ⋮ "
+" 6 line 6 "
+" 7 line 7 "
+" 8 line 8 "
+" 9 -line 9 "
+" 9 +line nine changed "
+" 10 line 10 "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__wrap_behavior_insert.snap b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__wrap_behavior_insert.snap
new file mode 100644
index 0000000000..7532977cea
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__diff_render__tests__wrap_behavior_insert.snap
@@ -0,0 +1,12 @@
+---
+source: tui/src/diff_render.rs
+expression: terminal.backend()
+---
+"1 +this is a very long line that should wrap across multiple terminal columns an "
+" d continue "
+" "
+" "
+" "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__active_mcp_tool_call_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__active_mcp_tool_call_snapshot.snap
new file mode 100644
index 0000000000..7360fd138f
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__active_mcp_tool_call_snapshot.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/history_cell.rs
+assertion_line: 1740
+expression: rendered
+---
+• Calling search.find_docs({"query":"ratatui styling","limit":3})
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__coalesced_reads_dedupe_names.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__coalesced_reads_dedupe_names.snap
new file mode 100644
index 0000000000..2044d41a1a
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__coalesced_reads_dedupe_names.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Explored
+ └ Read auth.rs, shimmer.rs
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__coalesces_reads_across_multiple_calls.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__coalesces_reads_across_multiple_calls.snap
new file mode 100644
index 0000000000..fcfa31eede
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__coalesces_reads_across_multiple_calls.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Explored
+ └ Search shimmer_spans
+ Read shimmer.rs, status_indicator_widget.rs
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__coalesces_sequential_reads_within_one_call.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__coalesces_sequential_reads_within_one_call.snap
new file mode 100644
index 0000000000..533a489ee6
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__coalesces_sequential_reads_within_one_call.snap
@@ -0,0 +1,8 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Explored
+ └ Search shimmer_spans
+ Read shimmer.rs
+ Read status_indicator_widget.rs
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_error_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_error_snapshot.snap
new file mode 100644
index 0000000000..776f792075
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_error_snapshot.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/history_cell.rs
+assertion_line: 1817
+expression: rendered
+---
+• Called search.find_docs({"query":"ratatui styling","limit":3})
+ └ Error: network timeout
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_multiple_outputs_inline_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_multiple_outputs_inline_snapshot.snap
new file mode 100644
index 0000000000..6e6bccb315
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_multiple_outputs_inline_snapshot.snap
@@ -0,0 +1,8 @@
+---
+source: tui/src/history_cell.rs
+assertion_line: 1934
+expression: rendered
+---
+• Called metrics.summary({"metric":"trace.latency","window":"15m"})
+ └ Latency summary: p50=120ms, p95=480ms.
+ No anomalies detected.
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_multiple_outputs_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_multiple_outputs_snapshot.snap
new file mode 100644
index 0000000000..6f7fd0e835
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_multiple_outputs_snapshot.snap
@@ -0,0 +1,11 @@
+---
+source: tui/src/history_cell.rs
+assertion_line: 1850
+expression: rendered
+---
+• Called
+ └ search.find_docs({"query":"ratatui
+ styling","limit":3})
+ Found styling guidance in styles.md and
+ additional notes in CONTRIBUTING.md.
+ link: file:///docs/styles.md
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_success_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_success_snapshot.snap
new file mode 100644
index 0000000000..3c601c22ec
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_success_snapshot.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/history_cell.rs
+assertion_line: 1795
+expression: rendered
+---
+• Called search.find_docs({"query":"ratatui styling","limit":3})
+ └ Found styling guidance in styles.md
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_wrapped_outputs_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_wrapped_outputs_snapshot.snap
new file mode 100644
index 0000000000..7d9c16132b
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__completed_mcp_tool_call_wrapped_outputs_snapshot.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/history_cell.rs
+assertion_line: 1891
+expression: rendered
+---
+• Called
+ └ metrics.get_nearby_metric({"query":"
+ very_long_query_that_needs_wrapp
+ ing_to_display_properly_in_the_h
+ istory","limit":1})
+ Line one of the response, which is
+ quite long and needs wrapping.
+ Line two continues the response with
+ more detail.
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__mcp_tools_output_masks_sensitive_values.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__mcp_tools_output_masks_sensitive_values.snap
new file mode 100644
index 0000000000..b9c0dfdee5
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__mcp_tools_output_masks_sensitive_values.snap
@@ -0,0 +1,27 @@
+---
+source: tui/src/history_cell.rs
+assertion_line: 1540
+expression: rendered
+---
+/mcp
+
+🔌 MCP Tools
+
+ • docs
+ • Status: enabled
+ • Auth: Unsupported
+ • Command: docs-server
+ • Env: TOKEN=*****, APP_TOKEN=*****
+ • Tools: list
+ • Resources: (none)
+ • Resource templates: (none)
+
+ • http
+ • Status: enabled
+ • Auth: Unsupported
+ • URL: https://example.com/mcp
+ • HTTP headers: Authorization=*****
+ • Env HTTP headers: X-API-Key=API_KEY_ENV
+ • Tools: ping
+ • Resources: (none)
+ • Resource templates: (none)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__multiline_command_both_lines_wrap_with_correct_prefixes.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__multiline_command_both_lines_wrap_with_correct_prefixes.snap
new file mode 100644
index 0000000000..b5d4fac168
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__multiline_command_both_lines_wrap_with_correct_prefixes.snap
@@ -0,0 +1,9 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Ran first_token_is_long_en
+ │ ough_to_wrap
+ │ second_token_is_also_lon
+ │ … +1 lines
+ └ (no output)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__multiline_command_without_wrap_uses_branch_then_eight_spaces.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__multiline_command_without_wrap_uses_branch_then_eight_spaces.snap
new file mode 100644
index 0000000000..10d87ad9dc
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__multiline_command_without_wrap_uses_branch_then_eight_spaces.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Ran echo one
+ │ echo two
+ └ (no output)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__multiline_command_wraps_with_extra_indent_on_subsequent_lines.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__multiline_command_wraps_with_extra_indent_on_subsequent_lines.snap
new file mode 100644
index 0000000000..e8458cfdc1
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__multiline_command_wraps_with_extra_indent_on_subsequent_lines.snap
@@ -0,0 +1,8 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Ran set -o pipefail
+ │ cargo test
+ │ --all-features --quiet
+ └ (no output)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__plan_update_with_note_and_wrapping_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__plan_update_with_note_and_wrapping_snapshot.snap
new file mode 100644
index 0000000000..27649a11d6
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__plan_update_with_note_and_wrapping_snapshot.snap
@@ -0,0 +1,20 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Updated Plan
+ └ I’ll update Grafana call
+ error handling by adding
+ retries and clearer
+ messages when the backend is
+ unreachable.
+ ✔ Investigate existing error
+ paths and logging around
+ HTTP timeouts
+ □ Harden Grafana client
+ error handling with retry/
+ backoff and user‑friendly
+ messages
+ □ Add tests for transient
+ failure scenarios and
+ surfacing to the UI
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__plan_update_without_note_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__plan_update_without_note_snapshot.snap
new file mode 100644
index 0000000000..e3ac8844f8
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__plan_update_without_note_snapshot.snap
@@ -0,0 +1,7 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Updated Plan
+ └ □ Define error taxonomy
+ □ Implement mapping to user messages
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__ran_cell_multiline_with_stderr_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__ran_cell_multiline_with_stderr_snapshot.snap
new file mode 100644
index 0000000000..0c7b5ee840
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__ran_cell_multiline_with_stderr_snapshot.snap
@@ -0,0 +1,12 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Ran echo
+ │ this_is_a_very_long_si
+ │ ngle_token_that_will_w
+ │ … +2 lines
+ └ error: first line on
+ stderr
+ error: second line on
+ stderr
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__single_line_command_compact_when_fits.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__single_line_command_compact_when_fits.snap
new file mode 100644
index 0000000000..23827df922
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__single_line_command_compact_when_fits.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Ran echo ok
+ └ (no output)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__single_line_command_wraps_with_four_space_continuation.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__single_line_command_wraps_with_four_space_continuation.snap
new file mode 100644
index 0000000000..244fd1d7e4
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__single_line_command_wraps_with_four_space_continuation.snap
@@ -0,0 +1,8 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Ran a_very_long_token_
+ │ without_spaces_to_
+ │ force_wrapping
+ └ (no output)
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__stderr_tail_more_than_five_lines_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__stderr_tail_more_than_five_lines_snapshot.snap
new file mode 100644
index 0000000000..ae7ee15187
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__stderr_tail_more_than_five_lines_snapshot.snap
@@ -0,0 +1,10 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+• Ran seq 1 10 1>&2 && false
+ └ 1
+ 2
+ … +6 lines
+ 9
+ 10
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__user_history_cell_wraps_and_prefixes_each_line_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__user_history_cell_wraps_and_prefixes_each_line_snapshot.snap
new file mode 100644
index 0000000000..9870dddb06
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__history_cell__tests__user_history_cell_wraps_and_prefixes_each_line_snapshot.snap
@@ -0,0 +1,8 @@
+---
+source: tui/src/history_cell.rs
+expression: rendered
+---
+› one two
+ three
+ four five
+ six seven
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__markdown_render__markdown_render_tests__markdown_render_complex_snapshot.snap b/codex-rs/tui2/src/snapshots/codex_tui__markdown_render__markdown_render_tests__markdown_render_complex_snapshot.snap
new file mode 100644
index 0000000000..cc752dd66d
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__markdown_render__markdown_render_tests__markdown_render_complex_snapshot.snap
@@ -0,0 +1,62 @@
+---
+source: tui/src/markdown_render_tests.rs
+expression: rendered
+---
+# H1: Markdown Streaming Test
+
+Intro paragraph with bold text, italic text, and inline code x=1.
+Combined bold-italic both and escaped asterisks *literal*.
+Auto-link: https://example.com (https://example.com) and reference link [ref][r1].
+Link with title: hover me (https://example.com) and mailto mailto:[email protected] (mailto:[email protected]).
+Image: alt text
+
+> Blockquote level 1
+>
+> > Blockquote level 2 with inline code
+
+- Unordered list item 1
+ - Nested bullet with italics inner
+- Unordered list item 2 with strikethrough
+
+1. Ordered item one
+2. Ordered item two with sublist:
+ 1. Alt-numbered subitem
+
+- [ ] Task: unchecked
+- [x] Task: checked with link home (https://example.org)
+
+———
+
+Table below (alignment test):
+| Left | Center | Right |
+|:-----|:------:|------:|
+| a | b | c |
+Inline HTML: <sup>sup</sup> and <sub>sub</sub>.
+HTML block:
+<div style="border:1px solid #ccc;padding:2px">inline block</div>
+Escapes: \_underscores\_, backslash \\, ticks ``code with `backtick` inside``.
+Emoji shortcodes: :sparkles: :tada: (if supported).
+Hard break test (line ends with two spaces)
+Next line should be close to previous.
+Footnote reference here[^1] and another[^longnote].
+Horizontal rule with asterisks:
+***
+Fenced code block (JSON):
+```json
+{ "a": 1, "b": [true, false] }
+```
+Fenced code with tildes and triple backticks inside:
+~~~markdown
+To close ``` you need tildes.
+~~~
+Indented code block:
+ for i in range(3): print(i)
+Definition-like list:
+Term
+: Definition with `code`.
+Character entities: &amp; &lt; &gt; &quot; &#39;
+[^1]: This is the first footnote.
+[^longnote]: A longer footnote with a link to [Rust](https://www.rust-lang.org/).
+Escaped pipe in text: a \| b \| c.
+URL with parentheses: [link](https://example.com/path_(with)_parens).
+[r1]: https://example.com/ref "Reference link title"
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt.snap b/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt.snap
new file mode 100644
index 0000000000..1f95142169
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt.snap
@@ -0,0 +1,19 @@
+---
+source: tui/src/model_migration.rs
+expression: terminal.backend()
+---
+> Codex just got an upgrade. Introducing gpt-5.1-codex-max
+
+ Codex is now powered by gpt-5.1-codex-max, our latest
+ frontier agentic coding model. It is smarter and faster
+ than its predecessors and capable of long-running
+ project-scale work.
+
+ Learn more at https://openai.com/index/gpt-5-1-codex-max/.
+
+ Choose how you'd like Codex to proceed.
+
+› 1. Try new model
+ 2. Use existing model
+
+ Use ↑/↓ to move, press enter to confirm
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex.snap b/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex.snap
new file mode 100644
index 0000000000..52718e5793
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex.snap
@@ -0,0 +1,15 @@
+---
+source: tui/src/model_migration.rs
+expression: terminal.backend()
+---
+> Introducing our gpt-5.1 models
+
+ We've upgraded our family of models supported in Codex to
+ gpt-5.1, gpt-5.1-codex and gpt-5.1-codex-mini.
+
+ You can continue using legacy models by specifying them
+ directly with the -m option or in your config.toml.
+
+ Learn more at https://openai.com/index/gpt-5-1/.
+
+ Press enter to continue
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex_mini.snap b/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex_mini.snap
new file mode 100644
index 0000000000..52718e5793
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_codex_mini.snap
@@ -0,0 +1,15 @@
+---
+source: tui/src/model_migration.rs
+expression: terminal.backend()
+---
+> Introducing our gpt-5.1 models
+
+ We've upgraded our family of models supported in Codex to
+ gpt-5.1, gpt-5.1-codex and gpt-5.1-codex-mini.
+
+ You can continue using legacy models by specifying them
+ directly with the -m option or in your config.toml.
+
+ Learn more at https://openai.com/index/gpt-5-1/.
+
+ Press enter to continue
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_family.snap b/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_family.snap
new file mode 100644
index 0000000000..52718e5793
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__model_migration__tests__model_migration_prompt_gpt5_family.snap
@@ -0,0 +1,15 @@
+---
+source: tui/src/model_migration.rs
+expression: terminal.backend()
+---
+> Introducing our gpt-5.1 models
+
+ We've upgraded our family of models supported in Codex to
+ gpt-5.1, gpt-5.1-codex and gpt-5.1-codex-mini.
+
+ You can continue using legacy models by specifying them
+ directly with the -m option or in your config.toml.
+
+ Learn more at https://openai.com/index/gpt-5-1/.
+
+ Press enter to continue
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_snapshot_basic.snap b/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_snapshot_basic.snap
new file mode 100644
index 0000000000..bc7818aff9
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_snapshot_basic.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/pager_overlay.rs
+expression: term.backend()
+---
+"/ S T A T I C / / / / / / / / / / / / / "
+"one "
+"two "
+"three "
+"~ "
+"~ "
+"───────────────────────────────── 100% ─"
+" ↑/↓ to scroll pgup/pgdn to page hom"
+" q to quit "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_wraps_long_lines.snap b/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_wraps_long_lines.snap
new file mode 100644
index 0000000000..2dfab2aa7d
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__static_overlay_wraps_long_lines.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/pager_overlay.rs
+assertion_line: 798
+expression: term.backend()
+---
+"/ S T A T I C / / / / / "
+"a very long line that "
+"should wrap when "
+"rendered within a narrow"
+"─────────────────── 0% ─"
+" ↑/↓ to scroll pgup/pg"
+" q to quit "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap b/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap
new file mode 100644
index 0000000000..1f086e81e4
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap
@@ -0,0 +1,15 @@
+---
+source: tui/src/pager_overlay.rs
+expression: snapshot
+---
+/ T R A N S C R I P T / / / / / / / / / / / / / / / / / / / / / / / / / / / / /
+• Added foo.txt (+2 -0)
+ 1 +hello
+ 2 +world
+
+• Added foo.txt (+2 -0)
+ 1 +hello
+ 2 +world
+─────────────────────────────────────────────────────────────────────────── 0% ─
+ ↑/↓ to scroll pgup/pgdn to page home/end to jump
+ q to quit esc to edit prev
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_snapshot_basic.snap b/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_snapshot_basic.snap
new file mode 100644
index 0000000000..61fcf7d2ea
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_snapshot_basic.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/pager_overlay.rs
+expression: term.backend()
+---
+"/ T R A N S C R I P T / / / / / / / / / "
+"alpha "
+" "
+"beta "
+" "
+"gamma "
+"───────────────────────────────── 100% ─"
+" ↑/↓ to scroll pgup/pgdn to page hom"
+" q to quit esc to edit prev "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__resume_picker__tests__resume_picker_screen.snap b/codex-rs/tui2/src/snapshots/codex_tui__resume_picker__tests__resume_picker_screen.snap
new file mode 100644
index 0000000000..79a169a06d
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__resume_picker__tests__resume_picker_screen.snap
@@ -0,0 +1,14 @@
+---
+source: tui/src/resume_picker.rs
+assertion_line: 1438
+expression: snapshot
+---
+Resume a previous session
+Type to search
+ Updated Branch CWD Conversation
+No sessions yet
+
+
+
+
+enter to resume esc to start new ctrl + c to quit
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__resume_picker__tests__resume_picker_table.snap b/codex-rs/tui2/src/snapshots/codex_tui__resume_picker__tests__resume_picker_table.snap
new file mode 100644
index 0000000000..c029043219
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__resume_picker__tests__resume_picker_table.snap
@@ -0,0 +1,8 @@
+---
+source: tui/src/resume_picker.rs
+expression: snapshot
+---
+ Updated Branch CWD Conversation
+ 42 seconds ago - - Fix resume picker timestamps
+> 35 minutes ago - - Investigate lazy pagination cap
+ 2 hours ago - - Explain the codebase
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_truncated.snap b/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_truncated.snap
new file mode 100644
index 0000000000..ba179808bd
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_truncated.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/status_indicator_widget.rs
+expression: terminal.backend()
+---
+"• Working (0s • esc "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages.snap b/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages.snap
new file mode 100644
index 0000000000..a46fbcc043
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages.snap
@@ -0,0 +1,12 @@
+---
+source: tui/src/status_indicator_widget.rs
+expression: terminal.backend()
+---
+"• Working (0s • esc to interrupt) "
+" "
+" ↳ first "
+" ↳ second "
+" alt + ↑ edit "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages@macos.snap b/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages@macos.snap
new file mode 100644
index 0000000000..5974455c89
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages@macos.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/status_indicator_widget.rs
+assertion_line: 289
+expression: terminal.backend()
+---
+"• Working (0s • esc to interrupt) "
+" "
+" ↳ first "
+" ↳ second "
+" ⌥ + ↑ edit "
+" "
+" "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_working_header.snap b/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_working_header.snap
new file mode 100644
index 0000000000..2b80830f81
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_working_header.snap
@@ -0,0 +1,6 @@
+---
+source: tui/src/status_indicator_widget.rs
+expression: terminal.backend()
+---
+"• Working (0s • esc to interrupt) "
+" "
diff --git a/codex-rs/tui2/src/snapshots/codex_tui__update_prompt__tests__update_prompt_modal.snap b/codex-rs/tui2/src/snapshots/codex_tui__update_prompt__tests__update_prompt_modal.snap
new file mode 100644
index 0000000000..24d8831c95
--- /dev/null
+++ b/codex-rs/tui2/src/snapshots/codex_tui__update_prompt__tests__update_prompt_modal.snap
@@ -0,0 +1,13 @@
+---
+source: tui/src/update_prompt.rs
+expression: terminal.backend()
+---
+ ✨ Update available! 0.0.0 -> 9.9.9
+
+ Release notes: https://github.com/openai/codex/releases/latest
+
+› 1. Update now (runs `npm install -g @openai/codex@latest`)
+ 2. Skip
+ 3. Skip until next version
+
+ Press enter to continue
diff --git a/codex-rs/tui2/src/status/account.rs b/codex-rs/tui2/src/status/account.rs
new file mode 100644
index 0000000000..23255f4379
--- /dev/null
+++ b/codex-rs/tui2/src/status/account.rs
@@ -0,0 +1,8 @@
+#[derive(Debug, Clone)]
+pub(crate) enum StatusAccountDisplay {
+ ChatGpt {
+ email: Option<String>,
+ plan: Option<String>,
+ },
+ ApiKey,
+}
diff --git a/codex-rs/tui2/src/status/card.rs b/codex-rs/tui2/src/status/card.rs
new file mode 100644
index 0000000000..aac981c764
--- /dev/null
+++ b/codex-rs/tui2/src/status/card.rs
@@ -0,0 +1,409 @@
+use crate::history_cell::CompositeHistoryCell;
+use crate::history_cell::HistoryCell;
+use crate::history_cell::PlainHistoryCell;
+use crate::history_cell::with_border_with_inner_width;
+use crate::version::CODEX_CLI_VERSION;
+use chrono::DateTime;
+use chrono::Local;
+use codex_common::create_config_summary_entries;
+use codex_core::config::Config;
+use codex_core::openai_models::model_family::ModelFamily;
+use codex_core::protocol::SandboxPolicy;
+use codex_core::protocol::TokenUsage;
+use codex_protocol::ConversationId;
+use codex_protocol::account::PlanType;
+use ratatui::prelude::*;
+use ratatui::style::Stylize;
+use std::collections::BTreeSet;
+use std::path::PathBuf;
+
+use super::account::StatusAccountDisplay;
+use super::format::FieldFormatter;
+use super::format::line_display_width;
+use super::format::push_label;
+use super::format::truncate_line_to_width;
+use super::helpers::compose_account_display;
+use super::helpers::compose_agents_summary;
+use super::helpers::compose_model_display;
+use super::helpers::format_directory_display;
+use super::helpers::format_tokens_compact;
+use super::rate_limits::RateLimitSnapshotDisplay;
+use super::rate_limits::StatusRateLimitData;
+use super::rate_limits::StatusRateLimitRow;
+use super::rate_limits::StatusRateLimitValue;
+use super::rate_limits::compose_rate_limit_data;
+use super::rate_limits::format_status_limit_summary;
+use super::rate_limits::render_status_limit_progress_bar;
+use crate::wrapping::RtOptions;
+use crate::wrapping::word_wrap_lines;
+use codex_core::AuthManager;
+
+#[derive(Debug, Clone)]
+struct StatusContextWindowData {
+ percent_remaining: i64,
+ tokens_in_context: i64,
+ window: i64,
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct StatusTokenUsageData {
+ total: i64,
+ input: i64,
+ output: i64,
+ context_window: Option<StatusContextWindowData>,
+}
+
+#[derive(Debug)]
+struct StatusHistoryCell {
+ model_name: String,
+ model_details: Vec<String>,
+ directory: PathBuf,
+ approval: String,
+ sandbox: String,
+ agents_summary: String,
+ account: Option<StatusAccountDisplay>,
+ session_id: Option<String>,
+ token_usage: StatusTokenUsageData,
+ rate_limits: StatusRateLimitData,
+}
+
+#[allow(clippy::too_many_arguments)]
+pub(crate) fn new_status_output(
+ config: &Config,
+ auth_manager: &AuthManager,
+ model_family: &ModelFamily,
+ total_usage: &TokenUsage,
+ context_usage: Option<&TokenUsage>,
+ session_id: &Option<ConversationId>,
+ rate_limits: Option<&RateLimitSnapshotDisplay>,
+ plan_type: Option<PlanType>,
+ now: DateTime<Local>,
+ model_name: &str,
+) -> CompositeHistoryCell {
+ let command = PlainHistoryCell::new(vec!["/status".magenta().into()]);
+ let card = StatusHistoryCell::new(
+ config,
+ auth_manager,
+ model_family,
+ total_usage,
+ context_usage,
+ session_id,
+ rate_limits,
+ plan_type,
+ now,
+ model_name,
+ );
+
+ CompositeHistoryCell::new(vec![Box::new(command), Box::new(card)])
+}
+
+impl StatusHistoryCell {
+ #[allow(clippy::too_many_arguments)]
+ fn new(
+ config: &Config,
+ auth_manager: &AuthManager,
+ model_family: &ModelFamily,
+ total_usage: &TokenUsage,
+ context_usage: Option<&TokenUsage>,
+ session_id: &Option<ConversationId>,
+ rate_limits: Option<&RateLimitSnapshotDisplay>,
+ plan_type: Option<PlanType>,
+ now: DateTime<Local>,
+ model_name: &str,
+ ) -> Self {
+ let config_entries = create_config_summary_entries(config, model_name);
+ let (model_name, model_details) = compose_model_display(model_name, &config_entries);
+ let approval = config_entries
+ .iter()
+ .find(|(k, _)| *k == "approval")
+ .map(|(_, v)| v.clone())
+ .unwrap_or_else(|| "<unknown>".to_string());
+ let sandbox = match &config.sandbox_policy {
+ SandboxPolicy::DangerFullAccess => "danger-full-access".to_string(),
+ SandboxPolicy::ReadOnly => "read-only".to_string(),
+ SandboxPolicy::WorkspaceWrite { .. } => "workspace-write".to_string(),
+ };
+ let agents_summary = compose_agents_summary(config);
+ let account = compose_account_display(auth_manager, plan_type);
+ let session_id = session_id.as_ref().map(std::string::ToString::to_string);
+ let context_window = model_family.context_window.and_then(|window| {
+ context_usage.map(|usage| StatusContextWindowData {
+ percent_remaining: usage.percent_of_context_window_remaining(window),
+ tokens_in_context: usage.tokens_in_context_window(),
+ window,
+ })
+ });
+
+ let token_usage = StatusTokenUsageData {
+ total: total_usage.blended_total(),
+ input: total_usage.non_cached_input(),
+ output: total_usage.output_tokens,
+ context_window,
+ };
+ let rate_limits = compose_rate_limit_data(rate_limits, now);
+
+ Self {
+ model_name,
+ model_details,
+ directory: config.cwd.clone(),
+ approval,
+ sandbox,
+ agents_summary,
+ account,
+ session_id,
+ token_usage,
+ rate_limits,
+ }
+ }
+
+ fn token_usage_spans(&self) -> Vec<Span<'static>> {
+ let total_fmt = format_tokens_compact(self.token_usage.total);
+ let input_fmt = format_tokens_compact(self.token_usage.input);
+ let output_fmt = format_tokens_compact(self.token_usage.output);
+
+ vec![
+ Span::from(total_fmt),
+ Span::from(" total "),
+ Span::from(" (").dim(),
+ Span::from(input_fmt).dim(),
+ Span::from(" input").dim(),
+ Span::from(" + ").dim(),
+ Span::from(output_fmt).dim(),
+ Span::from(" output").dim(),
+ Span::from(")").dim(),
+ ]
+ }
+
+ fn context_window_spans(&self) -> Option<Vec<Span<'static>>> {
+ let context = self.token_usage.context_window.as_ref()?;
+ let percent = context.percent_remaining;
+ let used_fmt = format_tokens_compact(context.tokens_in_context);
+ let window_fmt = format_tokens_compact(context.window);
+
+ Some(vec![
+ Span::from(format!("{percent}% left")),
+ Span::from(" (").dim(),
+ Span::from(used_fmt).dim(),
+ Span::from(" used / ").dim(),
+ Span::from(window_fmt).dim(),
+ Span::from(")").dim(),
+ ])
+ }
+
+ fn rate_limit_lines(
+ &self,
+ available_inner_width: usize,
+ formatter: &FieldFormatter,
+ ) -> Vec<Line<'static>> {
+ match &self.rate_limits {
+ StatusRateLimitData::Available(rows_data) => {
+ if rows_data.is_empty() {
+ return vec![
+ formatter.line("Limits", vec![Span::from("data not available yet").dim()]),
+ ];
+ }
+
+ self.rate_limit_row_lines(rows_data, available_inner_width, formatter)
+ }
+ StatusRateLimitData::Stale(rows_data) => {
+ let mut lines =
+ self.rate_limit_row_lines(rows_data, available_inner_width, formatter);
+ lines.push(formatter.line(
+ "Warning",
+ vec![Span::from("limits may be stale - start new turn to refresh.").dim()],
+ ));
+ lines
+ }
+ StatusRateLimitData::Missing => {
+ vec![formatter.line("Limits", vec![Span::from("data not available yet").dim()])]
+ }
+ }
+ }
+
+ fn rate_limit_row_lines(
+ &self,
+ rows: &[StatusRateLimitRow],
+ available_inner_width: usize,
+ formatter: &FieldFormatter,
+ ) -> Vec<Line<'static>> {
+ let mut lines = Vec::with_capacity(rows.len().saturating_mul(2));
+
+ for row in rows {
+ match &row.value {
+ StatusRateLimitValue::Window {
+ percent_used,
+ resets_at,
+ } => {
+ let percent_remaining = (100.0 - percent_used).clamp(0.0, 100.0);
+ let value_spans = vec![
+ Span::from(render_status_limit_progress_bar(percent_remaining)),
+ Span::from(" "),
+ Span::from(format_status_limit_summary(percent_remaining)),
+ ];
+ let base_spans = formatter.full_spans(row.label.as_str(), value_spans);
+ let base_line = Line::from(base_spans.clone());
+
+ if let Some(resets_at) = resets_at.as_ref() {
+ let resets_span = Span::from(format!("(resets {resets_at})")).dim();
+ let mut inline_spans = base_spans.clone();
+ inline_spans.push(Span::from(" ").dim());
+ inline_spans.push(resets_span.clone());
+
+ if line_display_width(&Line::from(inline_spans.clone()))
+ <= available_inner_width
+ {
+ lines.push(Line::from(inline_spans));
+ } else {
+ lines.push(base_line);
+ lines.push(formatter.continuation(vec![resets_span]));
+ }
+ } else {
+ lines.push(base_line);
+ }
+ }
+ StatusRateLimitValue::Text(text) => {
+ let label = row.label.clone();
+ let spans =
+ formatter.full_spans(label.as_str(), vec![Span::from(text.clone())]);
+ lines.push(Line::from(spans));
+ }
+ }
+ }
+
+ lines
+ }
+
+ fn collect_rate_limit_labels(&self, seen: &mut BTreeSet<String>, labels: &mut Vec<String>) {
+ match &self.rate_limits {
+ StatusRateLimitData::Available(rows) => {
+ if rows.is_empty() {
+ push_label(labels, seen, "Limits");
+ } else {
+ for row in rows {
+ push_label(labels, seen, row.label.as_str());
+ }
+ }
+ }
+ StatusRateLimitData::Stale(rows) => {
+ for row in rows {
+ push_label(labels, seen, row.label.as_str());
+ }
+ push_label(labels, seen, "Warning");
+ }
+ StatusRateLimitData::Missing => push_label(labels, seen, "Limits"),
+ }
+ }
+}
+
+impl HistoryCell for StatusHistoryCell {
+ fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
+ let mut lines: Vec<Line<'static>> = Vec::new();
+ lines.push(Line::from(vec![
+ Span::from(format!("{}>_ ", FieldFormatter::INDENT)).dim(),
+ Span::from("OpenAI Codex").bold(),
+ Span::from(" ").dim(),
+ Span::from(format!("(v{CODEX_CLI_VERSION})")).dim(),
+ ]));
+ lines.push(Line::from(Vec::<Span<'static>>::new()));
+
+ let available_inner_width = usize::from(width.saturating_sub(4));
+ if available_inner_width == 0 {
+ return Vec::new();
+ }
+
+ let account_value = self.account.as_ref().map(|account| match account {
+ StatusAccountDisplay::ChatGpt { email, plan } => match (email, plan) {
+ (Some(email), Some(plan)) => format!("{email} ({plan})"),
+ (Some(email), None) => email.clone(),
+ (None, Some(plan)) => plan.clone(),
+ (None, None) => "ChatGPT".to_string(),
+ },
+ StatusAccountDisplay::ApiKey => {
+ "API key configured (run codex login to use ChatGPT)".to_string()
+ }
+ });
+
+ let mut labels: Vec<String> =
+ vec!["Model", "Directory", "Approval", "Sandbox", "Agents.md"]
+ .into_iter()
+ .map(str::to_string)
+ .collect();
+ let mut seen: BTreeSet<String> = labels.iter().cloned().collect();
+
+ if account_value.is_some() {
+ push_label(&mut labels, &mut seen, "Account");
+ }
+ if self.session_id.is_some() {
+ push_label(&mut labels, &mut seen, "Session");
+ }
+ push_label(&mut labels, &mut seen, "Token usage");
+ if self.token_usage.context_window.is_some() {
+ push_label(&mut labels, &mut seen, "Context window");
+ }
+ self.collect_rate_limit_labels(&mut seen, &mut labels);
+
+ let formatter = FieldFormatter::from_labels(labels.iter().map(String::as_str));
+ let value_width = formatter.value_width(available_inner_width);
+
+ let note_first_line = Line::from(vec![
+ Span::from("Visit ").cyan(),
+ "https://chatgpt.com/codex/settings/usage"
+ .cyan()
+ .underlined(),
+ Span::from(" for up-to-date").cyan(),
+ ]);
+ let note_second_line = Line::from(vec![
+ Span::from("information on rate limits and credits").cyan(),
+ ]);
+ let note_lines = word_wrap_lines(
+ [note_first_line, note_second_line],
+ RtOptions::new(available_inner_width),
+ );
+ lines.extend(note_lines);
+ lines.push(Line::from(Vec::<Span<'static>>::new()));
+
+ let mut model_spans = vec![Span::from(self.model_name.clone())];
+ if !self.model_details.is_empty() {
+ model_spans.push(Span::from(" (").dim());
+ model_spans.push(Span::from(self.model_details.join(", ")).dim());
+ model_spans.push(Span::from(")").dim());
+ }
+
+ let directory_value = format_directory_display(&self.directory, Some(value_width));
+
+ lines.push(formatter.line("Model", model_spans));
+ lines.push(formatter.line("Directory", vec![Span::from(directory_value)]));
+ lines.push(formatter.line("Approval", vec![Span::from(self.approval.clone())]));
+ lines.push(formatter.line("Sandbox", vec![Span::from(self.sandbox.clone())]));
+ lines.push(formatter.line("Agents.md", vec![Span::from(self.agents_summary.clone())]));
+
+ if let Some(account_value) = account_value {
+ lines.push(formatter.line("Account", vec![Span::from(account_value)]));
+ }
+
+ if let Some(session) = self.session_id.as_ref() {
+ lines.push(formatter.line("Session", vec![Span::from(session.clone())]));
+ }
+
+ lines.push(Line::from(Vec::<Span<'static>>::new()));
+ // Hide token usage only for ChatGPT subscribers
+ if !matches!(self.account, Some(StatusAccountDisplay::ChatGpt { .. })) {
+ lines.push(formatter.line("Token usage", self.token_usage_spans()));
+ }
+
+ if let Some(spans) = self.context_window_spans() {
+ lines.push(formatter.line("Context window", spans));
+ }
+
+ lines.extend(self.rate_limit_lines(available_inner_width, &formatter));
+
+ let content_width = lines.iter().map(line_display_width).max().unwrap_or(0);
+ let inner_width = content_width.min(available_inner_width);
+ let truncated_lines: Vec<Line<'static>> = lines
+ .into_iter()
+ .map(|line| truncate_line_to_width(line, inner_width))
+ .collect();
+
+ with_border_with_inner_width(truncated_lines, inner_width)
+ }
+}
diff --git a/codex-rs/tui2/src/status/format.rs b/codex-rs/tui2/src/status/format.rs
new file mode 100644
index 0000000000..fda729040a
--- /dev/null
+++ b/codex-rs/tui2/src/status/format.rs
@@ -0,0 +1,147 @@
+use ratatui::prelude::*;
+use ratatui::style::Stylize;
+use std::collections::BTreeSet;
+use unicode_width::UnicodeWidthChar;
+use unicode_width::UnicodeWidthStr;
+
+#[derive(Debug, Clone)]
+pub(crate) struct FieldFormatter {
+ indent: &'static str,
+ label_width: usize,
+ value_offset: usize,
+ value_indent: String,
+}
+
+impl FieldFormatter {
+ pub(crate) const INDENT: &'static str = " ";
+
+ pub(crate) fn from_labels<S>(labels: impl IntoIterator<Item = S>) -> Self
+ where
+ S: AsRef<str>,
+ {
+ let label_width = labels
+ .into_iter()
+ .map(|label| UnicodeWidthStr::width(label.as_ref()))
+ .max()
+ .unwrap_or(0);
+ let indent_width = UnicodeWidthStr::width(Self::INDENT);
+ let value_offset = indent_width + label_width + 1 + 3;
+
+ Self {
+ indent: Self::INDENT,
+ label_width,
+ value_offset,
+ value_indent: " ".repeat(value_offset),
+ }
+ }
+
+ pub(crate) fn line(
+ &self,
+ label: &'static str,
+ value_spans: Vec<Span<'static>>,
+ ) -> Line<'static> {
+ Line::from(self.full_spans(label, value_spans))
+ }
+
+ pub(crate) fn continuation(&self, mut spans: Vec<Span<'static>>) -> Line<'static> {
+ let mut all_spans = Vec::with_capacity(spans.len() + 1);
+ all_spans.push(Span::from(self.value_indent.clone()).dim());
+ all_spans.append(&mut spans);
+ Line::from(all_spans)
+ }
+
+ pub(crate) fn value_width(&self, available_inner_width: usize) -> usize {
+ available_inner_width.saturating_sub(self.value_offset)
+ }
+
+ pub(crate) fn full_spans(
+ &self,
+ label: &str,
+ mut value_spans: Vec<Span<'static>>,
+ ) -> Vec<Span<'static>> {
+ let mut spans = Vec::with_capacity(value_spans.len() + 1);
+ spans.push(self.label_span(label));
+ spans.append(&mut value_spans);
+ spans
+ }
+
+ fn label_span(&self, label: &str) -> Span<'static> {
+ let mut buf = String::with_capacity(self.value_offset);
+ buf.push_str(self.indent);
+
+ buf.push_str(label);
+ buf.push(':');
+
+ let label_width = UnicodeWidthStr::width(label);
+ let padding = 3 + self.label_width.saturating_sub(label_width);
+ for _ in 0..padding {
+ buf.push(' ');
+ }
+
+ Span::from(buf).dim()
+ }
+}
+
+pub(crate) fn push_label(labels: &mut Vec<String>, seen: &mut BTreeSet<String>, label: &str) {
+ if seen.contains(label) {
+ return;
+ }
+
+ let owned = label.to_string();
+ seen.insert(owned.clone());
+ labels.push(owned);
+}
+
+pub(crate) fn line_display_width(line: &Line<'static>) -> usize {
+ line.iter()
+ .map(|span| UnicodeWidthStr::width(span.content.as_ref()))
+ .sum()
+}
+
+pub(crate) fn truncate_line_to_width(line: Line<'static>, max_width: usize) -> Line<'static> {
+ if max_width == 0 {
+ return Line::from(Vec::<Span<'static>>::new());
+ }
+
+ let mut used = 0usize;
+ let mut spans_out: Vec<Span<'static>> = Vec::new();
+
+ for span in line.spans {
+ let text = span.content.into_owned();
+ let style = span.style;
+ let span_width = UnicodeWidthStr::width(text.as_str());
+
+ if span_width == 0 {
+ spans_out.push(Span::styled(text, style));
+ continue;
+ }
+
+ if used >= max_width {
+ break;
+ }
+
+ if used + span_width <= max_width {
+ used += span_width;
+ spans_out.push(Span::styled(text, style));
+ continue;
+ }
+
+ let mut truncated = String::new();
+ for ch in text.chars() {
+ let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0);
+ if used + ch_width > max_width {
+ break;
+ }
+ truncated.push(ch);
+ used += ch_width;
+ }
+
+ if !truncated.is_empty() {
+ spans_out.push(Span::styled(truncated, style));
+ }
+
+ break;
+ }
+
+ Line::from(spans_out)
+}
diff --git a/codex-rs/tui2/src/status/helpers.rs b/codex-rs/tui2/src/status/helpers.rs
new file mode 100644
index 0000000000..8ba7ec3775
--- /dev/null
+++ b/codex-rs/tui2/src/status/helpers.rs
@@ -0,0 +1,189 @@
+use crate::exec_command::relativize_to_home;
+use crate::text_formatting;
+use chrono::DateTime;
+use chrono::Local;
+use codex_app_server_protocol::AuthMode;
+use codex_core::AuthManager;
+use codex_core::config::Config;
+use codex_core::project_doc::discover_project_doc_paths;
+use codex_protocol::account::PlanType;
+use std::path::Path;
+use unicode_width::UnicodeWidthStr;
+
+use super::account::StatusAccountDisplay;
+
+fn normalize_agents_display_path(path: &Path) -> String {
+ dunce::simplified(path).display().to_string()
+}
+
+pub(crate) fn compose_model_display(
+ model_name: &str,
+ entries: &[(&str, String)],
+) -> (String, Vec<String>) {
+ let mut details: Vec<String> = Vec::new();
+ if let Some((_, effort)) = entries.iter().find(|(k, _)| *k == "reasoning effort") {
+ details.push(format!("reasoning {}", effort.to_ascii_lowercase()));
+ }
+ if let Some((_, summary)) = entries.iter().find(|(k, _)| *k == "reasoning summaries") {
+ let summary = summary.trim();
+ if summary.eq_ignore_ascii_case("none") || summary.eq_ignore_ascii_case("off") {
+ details.push("summaries off".to_string());
+ } else if !summary.is_empty() {
+ details.push(format!("summaries {}", summary.to_ascii_lowercase()));
+ }
+ }
+
+ (model_name.to_string(), details)
+}
+
+pub(crate) fn compose_agents_summary(config: &Config) -> String {
+ match discover_project_doc_paths(config) {
+ Ok(paths) => {
+ let mut rels: Vec<String> = Vec::new();
+ for p in paths {
+ let file_name = p
+ .file_name()
+ .map(|name| name.to_string_lossy().to_string())
+ .unwrap_or_else(|| "<unknown>".to_string());
+ let display = if let Some(parent) = p.parent() {
+ if parent == config.cwd {
+ file_name.clone()
+ } else {
+ let mut cur = config.cwd.as_path();
+ let mut ups = 0usize;
+ let mut reached = false;
+ while let Some(c) = cur.parent() {
+ if cur == parent {
+ reached = true;
+ break;
+ }
+ cur = c;
+ ups += 1;
+ }
+ if reached {
+ let up = format!("..{}", std::path::MAIN_SEPARATOR);
+ format!("{}{}", up.repeat(ups), file_name)
+ } else if let Ok(stripped) = p.strip_prefix(&config.cwd) {
+ normalize_agents_display_path(stripped)
+ } else {
+ normalize_agents_display_path(&p)
+ }
+ }
+ } else {
+ normalize_agents_display_path(&p)
+ };
+ rels.push(display);
+ }
+ if rels.is_empty() {
+ "<none>".to_string()
+ } else {
+ rels.join(", ")
+ }
+ }
+ Err(_) => "<none>".to_string(),
+ }
+}
+
+pub(crate) fn compose_account_display(
+ auth_manager: &AuthManager,
+ plan: Option<PlanType>,
+) -> Option<StatusAccountDisplay> {
+ let auth = auth_manager.auth()?;
+
+ match auth.mode {
+ AuthMode::ChatGPT => {
+ let email = auth.get_account_email();
+ let plan = plan
+ .map(|plan_type| title_case(format!("{plan_type:?}").as_str()))
+ .or_else(|| Some("Unknown".to_string()));
+ Some(StatusAccountDisplay::ChatGpt { email, plan })
+ }
+ AuthMode::ApiKey => Some(StatusAccountDisplay::ApiKey),
+ }
+}
+
+pub(crate) fn format_tokens_compact(value: i64) -> String {
+ let value = value.max(0);
+ if value == 0 {
+ return "0".to_string();
+ }
+ if value < 1_000 {
+ return value.to_string();
+ }
+
+ let value_f64 = value as f64;
+ let (scaled, suffix) = if value >= 1_000_000_000_000 {
+ (value_f64 / 1_000_000_000_000.0, "T")
+ } else if value >= 1_000_000_000 {
+ (value_f64 / 1_000_000_000.0, "B")
+ } else if value >= 1_000_000 {
+ (value_f64 / 1_000_000.0, "M")
+ } else {
+ (value_f64 / 1_000.0, "K")
+ };
+
+ let decimals = if scaled < 10.0 {
+ 2
+ } else if scaled < 100.0 {
+ 1
+ } else {
+ 0
+ };
+
+ let mut formatted = format!("{scaled:.decimals$}");
+ if formatted.contains('.') {
+ while formatted.ends_with('0') {
+ formatted.pop();
+ }
+ if formatted.ends_with('.') {
+ formatted.pop();
+ }
+ }
+
+ format!("{formatted}{suffix}")
+}
+
+pub(crate) fn format_directory_display(directory: &Path, max_width: Option<usize>) -> String {
+ let formatted = if let Some(rel) = relativize_to_home(directory) {
+ if rel.as_os_str().is_empty() {
+ "~".to_string()
+ } else {
+ format!("~{}{}", std::path::MAIN_SEPARATOR, rel.display())
+ }
+ } else {
+ directory.display().to_string()
+ };
+
+ if let Some(max_width) = max_width {
+ if max_width == 0 {
+ return String::new();
+ }
+ if UnicodeWidthStr::width(formatted.as_str()) > max_width {
+ return text_formatting::center_truncate_path(&formatted, max_width);
+ }
+ }
+
+ formatted
+}
+
+pub(crate) fn format_reset_timestamp(dt: DateTime<Local>, captured_at: DateTime<Local>) -> String {
+ let time = dt.format("%H:%M").to_string();
+ if dt.date_naive() == captured_at.date_naive() {
+ time
+ } else {
+ format!("{time} on {}", dt.format("%-d %b"))
+ }
+}
+
+pub(crate) fn title_case(s: &str) -> String {
+ if s.is_empty() {
+ return String::new();
+ }
+ let mut chars = s.chars();
+ let first = match chars.next() {
+ Some(c) => c,
+ None => return String::new(),
+ };
+ let rest: String = chars.as_str().to_ascii_lowercase();
+ first.to_uppercase().collect::<String>() + &rest
+}
diff --git a/codex-rs/tui2/src/status/mod.rs b/codex-rs/tui2/src/status/mod.rs
new file mode 100644
index 0000000000..89c8daefdc
--- /dev/null
+++ b/codex-rs/tui2/src/status/mod.rs
@@ -0,0 +1,13 @@
+mod account;
+mod card;
+mod format;
+mod helpers;
+mod rate_limits;
+
+pub(crate) use card::new_status_output;
+pub(crate) use helpers::format_tokens_compact;
+pub(crate) use rate_limits::RateLimitSnapshotDisplay;
+pub(crate) use rate_limits::rate_limit_snapshot_display;
+
+#[cfg(test)]
+mod tests;
diff --git a/codex-rs/tui2/src/status/rate_limits.rs b/codex-rs/tui2/src/status/rate_limits.rs
new file mode 100644
index 0000000000..e8dc689a62
--- /dev/null
+++ b/codex-rs/tui2/src/status/rate_limits.rs
@@ -0,0 +1,235 @@
+use crate::chatwidget::get_limits_duration;
+
+use super::helpers::format_reset_timestamp;
+use chrono::DateTime;
+use chrono::Duration as ChronoDuration;
+use chrono::Local;
+use chrono::Utc;
+use codex_core::protocol::CreditsSnapshot as CoreCreditsSnapshot;
+use codex_core::protocol::RateLimitSnapshot;
+use codex_core::protocol::RateLimitWindow;
+
+const STATUS_LIMIT_BAR_SEGMENTS: usize = 20;
+const STATUS_LIMIT_BAR_FILLED: &str = "█";
+const STATUS_LIMIT_BAR_EMPTY: &str = "░";
+
+#[derive(Debug, Clone)]
+pub(crate) struct StatusRateLimitRow {
+ pub label: String,
+ pub value: StatusRateLimitValue,
+}
+
+#[derive(Debug, Clone)]
+pub(crate) enum StatusRateLimitValue {
+ Window {
+ percent_used: f64,
+ resets_at: Option<String>,
+ },
+ Text(String),
+}
+
+#[derive(Debug, Clone)]
+pub(crate) enum StatusRateLimitData {
+ Available(Vec<StatusRateLimitRow>),
+ Stale(Vec<StatusRateLimitRow>),
+ Missing,
+}
+
+pub(crate) const RATE_LIMIT_STALE_THRESHOLD_MINUTES: i64 = 15;
+
+#[derive(Debug, Clone)]
+pub(crate) struct RateLimitWindowDisplay {
+ pub used_percent: f64,
+ pub resets_at: Option<String>,
+ pub window_minutes: Option<i64>,
+}
+
+impl RateLimitWindowDisplay {
+ fn from_window(window: &RateLimitWindow, captured_at: DateTime<Local>) -> Self {
+ let resets_at = window
+ .resets_at
+ .and_then(|seconds| DateTime::<Utc>::from_timestamp(seconds, 0))
+ .map(|dt| dt.with_timezone(&Local))
+ .map(|dt| format_reset_timestamp(dt, captured_at));
+
+ Self {
+ used_percent: window.used_percent,
+ resets_at,
+ window_minutes: window.window_minutes,
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct RateLimitSnapshotDisplay {
+ pub captured_at: DateTime<Local>,
+ pub primary: Option<RateLimitWindowDisplay>,
+ pub secondary: Option<RateLimitWindowDisplay>,
+ pub credits: Option<CreditsSnapshotDisplay>,
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct CreditsSnapshotDisplay {
+ pub has_credits: bool,
+ pub unlimited: bool,
+ pub balance: Option<String>,
+}
+
+pub(crate) fn rate_limit_snapshot_display(
+ snapshot: &RateLimitSnapshot,
+ captured_at: DateTime<Local>,
+) -> RateLimitSnapshotDisplay {
+ RateLimitSnapshotDisplay {
+ captured_at,
+ primary: snapshot
+ .primary
+ .as_ref()
+ .map(|window| RateLimitWindowDisplay::from_window(window, captured_at)),
+ secondary: snapshot
+ .secondary
+ .as_ref()
+ .map(|window| RateLimitWindowDisplay::from_window(window, captured_at)),
+ credits: snapshot.credits.as_ref().map(CreditsSnapshotDisplay::from),
+ }
+}
+
+impl From<&CoreCreditsSnapshot> for CreditsSnapshotDisplay {
+ fn from(value: &CoreCreditsSnapshot) -> Self {
+ Self {
+ has_credits: value.has_credits,
+ unlimited: value.unlimited,
+ balance: value.balance.clone(),
+ }
+ }
+}
+
+pub(crate) fn compose_rate_limit_data(
+ snapshot: Option<&RateLimitSnapshotDisplay>,
+ now: DateTime<Local>,
+) -> StatusRateLimitData {
+ match snapshot {
+ Some(snapshot) => {
+ let mut rows = Vec::with_capacity(3);
+
+ if let Some(primary) = snapshot.primary.as_ref() {
+ let label: String = primary
+ .window_minutes
+ .map(get_limits_duration)
+ .unwrap_or_else(|| "5h".to_string());
+ let label = capitalize_first(&label);
+ rows.push(StatusRateLimitRow {
+ label: format!("{label} limit"),
+ value: StatusRateLimitValue::Window {
+ percent_used: primary.used_percent,
+ resets_at: primary.resets_at.clone(),
+ },
+ });
+ }
+
+ if let Some(secondary) = snapshot.secondary.as_ref() {
+ let label: String = secondary
+ .window_minutes
+ .map(get_limits_duration)
+ .unwrap_or_else(|| "weekly".to_string());
+ let label = capitalize_first(&label);
+ rows.push(StatusRateLimitRow {
+ label: format!("{label} limit"),
+ value: StatusRateLimitValue::Window {
+ percent_used: secondary.used_percent,
+ resets_at: secondary.resets_at.clone(),
+ },
+ });
+ }
+
+ if let Some(credits) = snapshot.credits.as_ref()
+ && let Some(row) = credit_status_row(credits)
+ {
+ rows.push(row);
+ }
+
+ let is_stale = now.signed_duration_since(snapshot.captured_at)
+ > ChronoDuration::minutes(RATE_LIMIT_STALE_THRESHOLD_MINUTES);
+
+ if rows.is_empty() {
+ StatusRateLimitData::Available(vec![])
+ } else if is_stale {
+ StatusRateLimitData::Stale(rows)
+ } else {
+ StatusRateLimitData::Available(rows)
+ }
+ }
+ None => StatusRateLimitData::Missing,
+ }
+}
+
+pub(crate) fn render_status_limit_progress_bar(percent_remaining: f64) -> String {
+ let ratio = (percent_remaining / 100.0).clamp(0.0, 1.0);
+ let filled = (ratio * STATUS_LIMIT_BAR_SEGMENTS as f64).round() as usize;
+ let filled = filled.min(STATUS_LIMIT_BAR_SEGMENTS);
+ let empty = STATUS_LIMIT_BAR_SEGMENTS.saturating_sub(filled);
+ format!(
+ "[{}{}]",
+ STATUS_LIMIT_BAR_FILLED.repeat(filled),
+ STATUS_LIMIT_BAR_EMPTY.repeat(empty)
+ )
+}
+
+pub(crate) fn format_status_limit_summary(percent_remaining: f64) -> String {
+ format!("{percent_remaining:.0}% left")
+}
+
+/// Builds a single `StatusRateLimitRow` for credits when the snapshot indicates
+/// that the account has credit tracking enabled. When credits are unlimited we
+/// show that fact explicitly; otherwise we render the rounded balance in
+/// credits. Accounts with credits = 0 skip this section entirely.
+fn credit_status_row(credits: &CreditsSnapshotDisplay) -> Option<StatusRateLimitRow> {
+ if !credits.has_credits {
+ return None;
+ }
+ if credits.unlimited {
+ return Some(StatusRateLimitRow {
+ label: "Credits".to_string(),
+ value: StatusRateLimitValue::Text("Unlimited".to_string()),
+ });
+ }
+ let balance = credits.balance.as_ref()?;
+ let display_balance = format_credit_balance(balance)?;
+ Some(StatusRateLimitRow {
+ label: "Credits".to_string(),
+ value: StatusRateLimitValue::Text(format!("{display_balance} credits")),
+ })
+}
+
+fn format_credit_balance(raw: &str) -> Option<String> {
+ let trimmed = raw.trim();
+ if trimmed.is_empty() {
+ return None;
+ }
+
+ if let Ok(int_value) = trimmed.parse::<i64>()
+ && int_value > 0
+ {
+ return Some(int_value.to_string());
+ }
+
+ if let Ok(value) = trimmed.parse::<f64>()
+ && value > 0.0
+ {
+ let rounded = value.round() as i64;
+ return Some(rounded.to_string());
+ }
+
+ None
+}
+
+fn capitalize_first(label: &str) -> String {
+ let mut chars = label.chars();
+ match chars.next() {
+ Some(first) => {
+ let mut capitalized = first.to_uppercase().collect::<String>();
+ capitalized.push_str(chars.as_str());
+ capitalized
+ }
+ None => String::new(),
+ }
+}
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap
new file mode 100644
index 0000000000..5c80556146
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap
@@ -0,0 +1,24 @@
+---
+source: tui2/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭─────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 1.05K total (700 input + 350 output) │
+│ Context window: 100% left (1.45K used / 272K) │
+│ 5h limit: [████████░░░░░░░░░░░░] 40% left (resets 11:32) │
+│ Weekly limit: [█████████████░░░░░░░] 65% left (resets 11:52) │
+│ Warning: limits may be stale - start new turn to refresh. │
+╰─────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_includes_credits_and_limits.snap b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_includes_credits_and_limits.snap
new file mode 100644
index 0000000000..7a91483739
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_includes_credits_and_limits.snap
@@ -0,0 +1,24 @@
+---
+source: tui2/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭───────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 2K total (1.4K input + 600 output) │
+│ Context window: 100% left (2.2K used / 272K) │
+│ 5h limit: [███████████░░░░░░░░░] 55% left (resets 09:25) │
+│ Weekly limit: [██████████████░░░░░░] 70% left (resets 09:55) │
+│ Credits: 38 credits │
+╰───────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_includes_monthly_limit.snap b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_includes_monthly_limit.snap
new file mode 100644
index 0000000000..6170111115
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_includes_monthly_limit.snap
@@ -0,0 +1,22 @@
+---
+source: tui2/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭────────────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 1.2K total (800 input + 400 output) │
+│ Context window: 100% left (1.2K used / 272K) │
+│ Monthly limit: [██████████████████░░] 88% left (resets 07:08 on 7 May) │
+╰────────────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_includes_reasoning_details.snap b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_includes_reasoning_details.snap
new file mode 100644
index 0000000000..1e88139cc4
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_includes_reasoning_details.snap
@@ -0,0 +1,23 @@
+---
+source: tui2/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭───────────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning high, summaries detailed) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: workspace-write │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 1.9K total (1K input + 900 output) │
+│ Context window: 100% left (2.25K used / 272K) │
+│ 5h limit: [██████░░░░░░░░░░░░░░] 28% left (resets 03:14) │
+│ Weekly limit: [███████████░░░░░░░░░] 55% left (resets 03:24) │
+╰───────────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_shows_empty_limits_message.snap b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_shows_empty_limits_message.snap
new file mode 100644
index 0000000000..ac824827e3
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_shows_empty_limits_message.snap
@@ -0,0 +1,22 @@
+---
+source: tui2/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭───────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 750 total (500 input + 250 output) │
+│ Context window: 100% left (750 used / 272K) │
+│ Limits: data not available yet │
+╰───────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_shows_missing_limits_message.snap b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_shows_missing_limits_message.snap
new file mode 100644
index 0000000000..ac824827e3
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_shows_missing_limits_message.snap
@@ -0,0 +1,22 @@
+---
+source: tui2/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭───────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 750 total (500 input + 250 output) │
+│ Context window: 100% left (750 used / 272K) │
+│ Limits: data not available yet │
+╰───────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_shows_stale_limits_message.snap b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_shows_stale_limits_message.snap
new file mode 100644
index 0000000000..ffdb825bac
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_shows_stale_limits_message.snap
@@ -0,0 +1,24 @@
+---
+source: tui2/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭───────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 1.9K total (1K input + 900 output) │
+│ Context window: 100% left (2.25K used / 272K) │
+│ 5h limit: [██████░░░░░░░░░░░░░░] 28% left (resets 03:14) │
+│ Weekly limit: [████████████░░░░░░░░] 60% left (resets 03:34) │
+│ Warning: limits may be stale - start new turn to refresh. │
+╰───────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_truncates_in_narrow_terminal.snap b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_truncates_in_narrow_terminal.snap
new file mode 100644
index 0000000000..1762b1b715
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui2__status__tests__status_snapshot_truncates_in_narrow_terminal.snap
@@ -0,0 +1,22 @@
+---
+source: tui2/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning high, summaries de │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 1.9K total (1K input + 900 output) │
+│ Context window: 100% left (2.25K used / 272K) │
+│ 5h limit: [██████░░░░░░░░░░░░░░] 28% left (resets 03:14) │
+╰────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap
new file mode 100644
index 0000000000..dbb634bab1
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_cached_limits_hide_credits_without_flag.snap
@@ -0,0 +1,24 @@
+---
+source: tui/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭─────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 1.05K total (700 input + 350 output) │
+│ Context window: 100% left (1.45K used / 272K) │
+│ 5h limit: [████████░░░░░░░░░░░░] 40% left (resets 11:32) │
+│ Weekly limit: [█████████████░░░░░░░] 65% left (resets 11:52) │
+│ Warning: limits may be stale - start new turn to refresh. │
+╰─────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_credits_and_limits.snap b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_credits_and_limits.snap
new file mode 100644
index 0000000000..1707a4c5fb
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_credits_and_limits.snap
@@ -0,0 +1,24 @@
+---
+source: tui/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭───────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 2K total (1.4K input + 600 output) │
+│ Context window: 100% left (2.2K used / 272K) │
+│ 5h limit: [███████████░░░░░░░░░] 55% left (resets 09:25) │
+│ Weekly limit: [██████████████░░░░░░] 70% left (resets 09:55) │
+│ Credits: 38 credits │
+╰───────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap
new file mode 100644
index 0000000000..3ecc4fa8ed
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_monthly_limit.snap
@@ -0,0 +1,22 @@
+---
+source: tui/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭────────────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 1.2K total (800 input + 400 output) │
+│ Context window: 100% left (1.2K used / 272K) │
+│ Monthly limit: [██████████████████░░] 88% left (resets 07:08 on 7 May) │
+╰────────────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap
new file mode 100644
index 0000000000..c22577407e
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_includes_reasoning_details.snap
@@ -0,0 +1,23 @@
+---
+source: tui/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭───────────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning high, summaries detailed) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: workspace-write │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 1.9K total (1K input + 900 output) │
+│ Context window: 100% left (2.25K used / 272K) │
+│ 5h limit: [██████░░░░░░░░░░░░░░] 28% left (resets 03:14) │
+│ Weekly limit: [███████████░░░░░░░░░] 55% left (resets 03:24) │
+╰───────────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_empty_limits_message.snap b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_empty_limits_message.snap
new file mode 100644
index 0000000000..f0e6b73445
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_empty_limits_message.snap
@@ -0,0 +1,22 @@
+---
+source: tui/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭───────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 750 total (500 input + 250 output) │
+│ Context window: 100% left (750 used / 272K) │
+│ Limits: data not available yet │
+╰───────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap
new file mode 100644
index 0000000000..f0e6b73445
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap
@@ -0,0 +1,22 @@
+---
+source: tui/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭───────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 750 total (500 input + 250 output) │
+│ Context window: 100% left (750 used / 272K) │
+│ Limits: data not available yet │
+╰───────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap
new file mode 100644
index 0000000000..a12be950bc
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap
@@ -0,0 +1,24 @@
+---
+source: tui/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭───────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning none, summaries auto) │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 1.9K total (1K input + 900 output) │
+│ Context window: 100% left (2.25K used / 272K) │
+│ 5h limit: [██████░░░░░░░░░░░░░░] 28% left (resets 03:14) │
+│ Weekly limit: [████████████░░░░░░░░] 60% left (resets 03:34) │
+│ Warning: limits may be stale - start new turn to refresh. │
+╰───────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap
new file mode 100644
index 0000000000..02ba1adec9
--- /dev/null
+++ b/codex-rs/tui2/src/status/snapshots/codex_tui__status__tests__status_snapshot_truncates_in_narrow_terminal.snap
@@ -0,0 +1,22 @@
+---
+source: tui/src/status/tests.rs
+expression: sanitized
+---
+/status
+
+╭────────────────────────────────────────────────────────────────────╮
+│ >_ OpenAI Codex (v0.0.0) │
+│ │
+│ Visit https://chatgpt.com/codex/settings/usage for up-to-date │
+│ information on rate limits and credits │
+│ │
+│ Model: gpt-5.1-codex-max (reasoning high, summaries de │
+│ Directory: [[workspace]] │
+│ Approval: on-request │
+│ Sandbox: read-only │
+│ Agents.md: <none> │
+│ │
+│ Token usage: 1.9K total (1K input + 900 output) │
+│ Context window: 100% left (2.25K used / 272K) │
+│ 5h limit: [██████░░░░░░░░░░░░░░] 28% left (resets 03:14) │
+╰────────────────────────────────────────────────────────────────────╯
diff --git a/codex-rs/tui2/src/status/tests.rs b/codex-rs/tui2/src/status/tests.rs
new file mode 100644
index 0000000000..53c728526a
--- /dev/null
+++ b/codex-rs/tui2/src/status/tests.rs
@@ -0,0 +1,832 @@
+use super::new_status_output;
+use super::rate_limit_snapshot_display;
+use crate::history_cell::HistoryCell;
+use chrono::Duration as ChronoDuration;
+use chrono::TimeZone;
+use chrono::Utc;
+use codex_core::AuthManager;
+use codex_core::config::Config;
+use codex_core::config::ConfigOverrides;
+use codex_core::config::ConfigToml;
+use codex_core::openai_models::model_family::ModelFamily;
+use codex_core::openai_models::models_manager::ModelsManager;
+use codex_core::protocol::CreditsSnapshot;
+use codex_core::protocol::RateLimitSnapshot;
+use codex_core::protocol::RateLimitWindow;
+use codex_core::protocol::SandboxPolicy;
+use codex_core::protocol::TokenUsage;
+use codex_protocol::config_types::ReasoningSummary;
+use codex_protocol::openai_models::ReasoningEffort;
+use insta::assert_snapshot;
+use ratatui::prelude::*;
+use std::path::PathBuf;
+use tempfile::TempDir;
+
+fn test_config(temp_home: &TempDir) -> Config {
+ Config::load_from_base_config_with_overrides(
+ ConfigToml::default(),
+ ConfigOverrides::default(),
+ temp_home.path().to_path_buf(),
+ )
+ .expect("load config")
+}
+
+fn test_auth_manager(config: &Config) -> AuthManager {
+ AuthManager::new(
+ config.codex_home.clone(),
+ false,
+ config.cli_auth_credentials_store_mode,
+ )
+}
+
+fn test_model_family(model_slug: &str, config: &Config) -> ModelFamily {
+ ModelsManager::construct_model_family_offline(model_slug, config)
+}
+
+fn render_lines(lines: &[Line<'static>]) -> Vec<String> {
+ lines
+ .iter()
+ .map(|line| {
+ line.spans
+ .iter()
+ .map(|span| span.content.as_ref())
+ .collect::<String>()
+ })
+ .collect()
+}
+
+fn sanitize_directory(lines: Vec<String>) -> Vec<String> {
+ lines
+ .into_iter()
+ .map(|line| {
+ if let (Some(dir_pos), Some(pipe_idx)) = (line.find("Directory: "), line.rfind('│')) {
+ let prefix = &line[..dir_pos + "Directory: ".len()];
+ let suffix = &line[pipe_idx..];
+ let content_width = pipe_idx.saturating_sub(dir_pos + "Directory: ".len());
+ let replacement = "[[workspace]]";
+ let mut rebuilt = prefix.to_string();
+ rebuilt.push_str(replacement);
+ if content_width > replacement.len() {
+ rebuilt.push_str(&" ".repeat(content_width - replacement.len()));
+ }
+ rebuilt.push_str(suffix);
+ rebuilt
+ } else {
+ line
+ }
+ })
+ .collect()
+}
+
+fn reset_at_from(captured_at: &chrono::DateTime<chrono::Local>, seconds: i64) -> i64 {
+ (*captured_at + ChronoDuration::seconds(seconds))
+ .with_timezone(&Utc)
+ .timestamp()
+}
+
+#[test]
+fn status_snapshot_includes_reasoning_details() {
+ let temp_home = TempDir::new().expect("temp home");
+ let mut config = test_config(&temp_home);
+ config.model = Some("gpt-5.1-codex-max".to_string());
+ config.model_provider_id = "openai".to_string();
+ config.model_reasoning_effort = Some(ReasoningEffort::High);
+ config.model_reasoning_summary = ReasoningSummary::Detailed;
+ config.sandbox_policy = SandboxPolicy::WorkspaceWrite {
+ writable_roots: Vec::new(),
+ network_access: false,
+ exclude_tmpdir_env_var: false,
+ exclude_slash_tmp: false,
+ };
+
+ config.cwd = PathBuf::from("/workspace/tests");
+
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage {
+ input_tokens: 1_200,
+ cached_input_tokens: 200,
+ output_tokens: 900,
+ reasoning_output_tokens: 150,
+ total_tokens: 2_250,
+ };
+
+ let captured_at = chrono::Local
+ .with_ymd_and_hms(2024, 1, 2, 3, 4, 5)
+ .single()
+ .expect("timestamp");
+ let snapshot = RateLimitSnapshot {
+ primary: Some(RateLimitWindow {
+ used_percent: 72.5,
+ window_minutes: Some(300),
+ resets_at: Some(reset_at_from(&captured_at, 600)),
+ }),
+ secondary: Some(RateLimitWindow {
+ used_percent: 45.0,
+ window_minutes: Some(10080),
+ resets_at: Some(reset_at_from(&captured_at, 1_200)),
+ }),
+ credits: None,
+ plan_type: None,
+ };
+ let rate_display = rate_limit_snapshot_display(&snapshot, captured_at);
+
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ Some(&rate_display),
+ None,
+ captured_at,
+ &model_slug,
+ );
+ let mut rendered_lines = render_lines(&composite.display_lines(80));
+ if cfg!(windows) {
+ for line in &mut rendered_lines {
+ *line = line.replace('\\', "/");
+ }
+ }
+ let sanitized = sanitize_directory(rendered_lines).join("\n");
+ assert_snapshot!(sanitized);
+}
+
+#[test]
+fn status_snapshot_includes_monthly_limit() {
+ let temp_home = TempDir::new().expect("temp home");
+ let mut config = test_config(&temp_home);
+ config.model = Some("gpt-5.1-codex-max".to_string());
+ config.model_provider_id = "openai".to_string();
+ config.cwd = PathBuf::from("/workspace/tests");
+
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage {
+ input_tokens: 800,
+ cached_input_tokens: 0,
+ output_tokens: 400,
+ reasoning_output_tokens: 0,
+ total_tokens: 1_200,
+ };
+
+ let captured_at = chrono::Local
+ .with_ymd_and_hms(2024, 5, 6, 7, 8, 9)
+ .single()
+ .expect("timestamp");
+ let snapshot = RateLimitSnapshot {
+ primary: Some(RateLimitWindow {
+ used_percent: 12.0,
+ window_minutes: Some(43_200),
+ resets_at: Some(reset_at_from(&captured_at, 86_400)),
+ }),
+ secondary: None,
+ credits: None,
+ plan_type: None,
+ };
+ let rate_display = rate_limit_snapshot_display(&snapshot, captured_at);
+
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ Some(&rate_display),
+ None,
+ captured_at,
+ &model_slug,
+ );
+ let mut rendered_lines = render_lines(&composite.display_lines(80));
+ if cfg!(windows) {
+ for line in &mut rendered_lines {
+ *line = line.replace('\\', "/");
+ }
+ }
+ let sanitized = sanitize_directory(rendered_lines).join("\n");
+ assert_snapshot!(sanitized);
+}
+
+#[test]
+fn status_snapshot_shows_unlimited_credits() {
+ let temp_home = TempDir::new().expect("temp home");
+ let config = test_config(&temp_home);
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage::default();
+ let captured_at = chrono::Local
+ .with_ymd_and_hms(2024, 2, 3, 4, 5, 6)
+ .single()
+ .expect("timestamp");
+ let snapshot = RateLimitSnapshot {
+ primary: None,
+ secondary: None,
+ credits: Some(CreditsSnapshot {
+ has_credits: true,
+ unlimited: true,
+ balance: None,
+ }),
+ plan_type: None,
+ };
+ let rate_display = rate_limit_snapshot_display(&snapshot, captured_at);
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ Some(&rate_display),
+ None,
+ captured_at,
+ &model_slug,
+ );
+ let rendered = render_lines(&composite.display_lines(120));
+ assert!(
+ rendered
+ .iter()
+ .any(|line| line.contains("Credits:") && line.contains("Unlimited")),
+ "expected Credits: Unlimited line, got {rendered:?}"
+ );
+}
+
+#[test]
+fn status_snapshot_shows_positive_credits() {
+ let temp_home = TempDir::new().expect("temp home");
+ let config = test_config(&temp_home);
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage::default();
+ let captured_at = chrono::Local
+ .with_ymd_and_hms(2024, 3, 4, 5, 6, 7)
+ .single()
+ .expect("timestamp");
+ let snapshot = RateLimitSnapshot {
+ primary: None,
+ secondary: None,
+ credits: Some(CreditsSnapshot {
+ has_credits: true,
+ unlimited: false,
+ balance: Some("12.5".to_string()),
+ }),
+ plan_type: None,
+ };
+ let rate_display = rate_limit_snapshot_display(&snapshot, captured_at);
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ Some(&rate_display),
+ None,
+ captured_at,
+ &model_slug,
+ );
+ let rendered = render_lines(&composite.display_lines(120));
+ assert!(
+ rendered
+ .iter()
+ .any(|line| line.contains("Credits:") && line.contains("13 credits")),
+ "expected Credits line with rounded credits, got {rendered:?}"
+ );
+}
+
+#[test]
+fn status_snapshot_hides_zero_credits() {
+ let temp_home = TempDir::new().expect("temp home");
+ let config = test_config(&temp_home);
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage::default();
+ let captured_at = chrono::Local
+ .with_ymd_and_hms(2024, 4, 5, 6, 7, 8)
+ .single()
+ .expect("timestamp");
+ let snapshot = RateLimitSnapshot {
+ primary: None,
+ secondary: None,
+ credits: Some(CreditsSnapshot {
+ has_credits: true,
+ unlimited: false,
+ balance: Some("0".to_string()),
+ }),
+ plan_type: None,
+ };
+ let rate_display = rate_limit_snapshot_display(&snapshot, captured_at);
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ Some(&rate_display),
+ None,
+ captured_at,
+ &model_slug,
+ );
+ let rendered = render_lines(&composite.display_lines(120));
+ assert!(
+ rendered.iter().all(|line| !line.contains("Credits:")),
+ "expected no Credits line, got {rendered:?}"
+ );
+}
+
+#[test]
+fn status_snapshot_hides_when_has_no_credits_flag() {
+ let temp_home = TempDir::new().expect("temp home");
+ let config = test_config(&temp_home);
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage::default();
+ let captured_at = chrono::Local
+ .with_ymd_and_hms(2024, 5, 6, 7, 8, 9)
+ .single()
+ .expect("timestamp");
+ let snapshot = RateLimitSnapshot {
+ primary: None,
+ secondary: None,
+ credits: Some(CreditsSnapshot {
+ has_credits: false,
+ unlimited: true,
+ balance: None,
+ }),
+ plan_type: None,
+ };
+ let rate_display = rate_limit_snapshot_display(&snapshot, captured_at);
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ Some(&rate_display),
+ None,
+ captured_at,
+ &model_slug,
+ );
+ let rendered = render_lines(&composite.display_lines(120));
+ assert!(
+ rendered.iter().all(|line| !line.contains("Credits:")),
+ "expected no Credits line when has_credits is false, got {rendered:?}"
+ );
+}
+
+#[test]
+fn status_card_token_usage_excludes_cached_tokens() {
+ let temp_home = TempDir::new().expect("temp home");
+ let mut config = test_config(&temp_home);
+ config.model = Some("gpt-5.1-codex-max".to_string());
+ config.cwd = PathBuf::from("/workspace/tests");
+
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage {
+ input_tokens: 1_200,
+ cached_input_tokens: 200,
+ output_tokens: 900,
+ reasoning_output_tokens: 0,
+ total_tokens: 2_100,
+ };
+
+ let now = chrono::Local
+ .with_ymd_and_hms(2024, 1, 1, 0, 0, 0)
+ .single()
+ .expect("timestamp");
+
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ None,
+ None,
+ now,
+ &model_slug,
+ );
+ let rendered = render_lines(&composite.display_lines(120));
+
+ assert!(
+ rendered.iter().all(|line| !line.contains("cached")),
+ "cached tokens should not be displayed, got: {rendered:?}"
+ );
+}
+
+#[test]
+fn status_snapshot_truncates_in_narrow_terminal() {
+ let temp_home = TempDir::new().expect("temp home");
+ let mut config = test_config(&temp_home);
+ config.model = Some("gpt-5.1-codex-max".to_string());
+ config.model_provider_id = "openai".to_string();
+ config.model_reasoning_effort = Some(ReasoningEffort::High);
+ config.model_reasoning_summary = ReasoningSummary::Detailed;
+ config.cwd = PathBuf::from("/workspace/tests");
+
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage {
+ input_tokens: 1_200,
+ cached_input_tokens: 200,
+ output_tokens: 900,
+ reasoning_output_tokens: 150,
+ total_tokens: 2_250,
+ };
+
+ let captured_at = chrono::Local
+ .with_ymd_and_hms(2024, 1, 2, 3, 4, 5)
+ .single()
+ .expect("timestamp");
+ let snapshot = RateLimitSnapshot {
+ primary: Some(RateLimitWindow {
+ used_percent: 72.5,
+ window_minutes: Some(300),
+ resets_at: Some(reset_at_from(&captured_at, 600)),
+ }),
+ secondary: None,
+ credits: None,
+ plan_type: None,
+ };
+ let rate_display = rate_limit_snapshot_display(&snapshot, captured_at);
+
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ Some(&rate_display),
+ None,
+ captured_at,
+ &model_slug,
+ );
+ let mut rendered_lines = render_lines(&composite.display_lines(70));
+ if cfg!(windows) {
+ for line in &mut rendered_lines {
+ *line = line.replace('\\', "/");
+ }
+ }
+ let sanitized = sanitize_directory(rendered_lines).join("\n");
+
+ assert_snapshot!(sanitized);
+}
+
+#[test]
+fn status_snapshot_shows_missing_limits_message() {
+ let temp_home = TempDir::new().expect("temp home");
+ let mut config = test_config(&temp_home);
+ config.model = Some("gpt-5.1-codex-max".to_string());
+ config.cwd = PathBuf::from("/workspace/tests");
+
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage {
+ input_tokens: 500,
+ cached_input_tokens: 0,
+ output_tokens: 250,
+ reasoning_output_tokens: 0,
+ total_tokens: 750,
+ };
+
+ let now = chrono::Local
+ .with_ymd_and_hms(2024, 2, 3, 4, 5, 6)
+ .single()
+ .expect("timestamp");
+
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ None,
+ None,
+ now,
+ &model_slug,
+ );
+ let mut rendered_lines = render_lines(&composite.display_lines(80));
+ if cfg!(windows) {
+ for line in &mut rendered_lines {
+ *line = line.replace('\\', "/");
+ }
+ }
+ let sanitized = sanitize_directory(rendered_lines).join("\n");
+ assert_snapshot!(sanitized);
+}
+
+#[test]
+fn status_snapshot_includes_credits_and_limits() {
+ let temp_home = TempDir::new().expect("temp home");
+ let mut config = test_config(&temp_home);
+ config.model = Some("gpt-5.1-codex".to_string());
+ config.cwd = PathBuf::from("/workspace/tests");
+
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage {
+ input_tokens: 1_500,
+ cached_input_tokens: 100,
+ output_tokens: 600,
+ reasoning_output_tokens: 0,
+ total_tokens: 2_200,
+ };
+
+ let captured_at = chrono::Local
+ .with_ymd_and_hms(2024, 7, 8, 9, 10, 11)
+ .single()
+ .expect("timestamp");
+ let snapshot = RateLimitSnapshot {
+ primary: Some(RateLimitWindow {
+ used_percent: 45.0,
+ window_minutes: Some(300),
+ resets_at: Some(reset_at_from(&captured_at, 900)),
+ }),
+ secondary: Some(RateLimitWindow {
+ used_percent: 30.0,
+ window_minutes: Some(10_080),
+ resets_at: Some(reset_at_from(&captured_at, 2_700)),
+ }),
+ credits: Some(CreditsSnapshot {
+ has_credits: true,
+ unlimited: false,
+ balance: Some("37.5".to_string()),
+ }),
+ plan_type: None,
+ };
+ let rate_display = rate_limit_snapshot_display(&snapshot, captured_at);
+
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ Some(&rate_display),
+ None,
+ captured_at,
+ &model_slug,
+ );
+ let mut rendered_lines = render_lines(&composite.display_lines(80));
+ if cfg!(windows) {
+ for line in &mut rendered_lines {
+ *line = line.replace('\\', "/");
+ }
+ }
+ let sanitized = sanitize_directory(rendered_lines).join("\n");
+ assert_snapshot!(sanitized);
+}
+
+#[test]
+fn status_snapshot_shows_empty_limits_message() {
+ let temp_home = TempDir::new().expect("temp home");
+ let mut config = test_config(&temp_home);
+ config.model = Some("gpt-5.1-codex-max".to_string());
+ config.cwd = PathBuf::from("/workspace/tests");
+
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage {
+ input_tokens: 500,
+ cached_input_tokens: 0,
+ output_tokens: 250,
+ reasoning_output_tokens: 0,
+ total_tokens: 750,
+ };
+
+ let snapshot = RateLimitSnapshot {
+ primary: None,
+ secondary: None,
+ credits: None,
+ plan_type: None,
+ };
+ let captured_at = chrono::Local
+ .with_ymd_and_hms(2024, 6, 7, 8, 9, 10)
+ .single()
+ .expect("timestamp");
+ let rate_display = rate_limit_snapshot_display(&snapshot, captured_at);
+
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ Some(&rate_display),
+ None,
+ captured_at,
+ &model_slug,
+ );
+ let mut rendered_lines = render_lines(&composite.display_lines(80));
+ if cfg!(windows) {
+ for line in &mut rendered_lines {
+ *line = line.replace('\\', "/");
+ }
+ }
+ let sanitized = sanitize_directory(rendered_lines).join("\n");
+ assert_snapshot!(sanitized);
+}
+
+#[test]
+fn status_snapshot_shows_stale_limits_message() {
+ let temp_home = TempDir::new().expect("temp home");
+ let mut config = test_config(&temp_home);
+ config.model = Some("gpt-5.1-codex-max".to_string());
+ config.cwd = PathBuf::from("/workspace/tests");
+
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage {
+ input_tokens: 1_200,
+ cached_input_tokens: 200,
+ output_tokens: 900,
+ reasoning_output_tokens: 150,
+ total_tokens: 2_250,
+ };
+
+ let captured_at = chrono::Local
+ .with_ymd_and_hms(2024, 1, 2, 3, 4, 5)
+ .single()
+ .expect("timestamp");
+ let snapshot = RateLimitSnapshot {
+ primary: Some(RateLimitWindow {
+ used_percent: 72.5,
+ window_minutes: Some(300),
+ resets_at: Some(reset_at_from(&captured_at, 600)),
+ }),
+ secondary: Some(RateLimitWindow {
+ used_percent: 40.0,
+ window_minutes: Some(10_080),
+ resets_at: Some(reset_at_from(&captured_at, 1_800)),
+ }),
+ credits: None,
+ plan_type: None,
+ };
+ let rate_display = rate_limit_snapshot_display(&snapshot, captured_at);
+ let now = captured_at + ChronoDuration::minutes(20);
+
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ Some(&rate_display),
+ None,
+ now,
+ &model_slug,
+ );
+ let mut rendered_lines = render_lines(&composite.display_lines(80));
+ if cfg!(windows) {
+ for line in &mut rendered_lines {
+ *line = line.replace('\\', "/");
+ }
+ }
+ let sanitized = sanitize_directory(rendered_lines).join("\n");
+ assert_snapshot!(sanitized);
+}
+
+#[test]
+fn status_snapshot_cached_limits_hide_credits_without_flag() {
+ let temp_home = TempDir::new().expect("temp home");
+ let mut config = test_config(&temp_home);
+ config.model = Some("gpt-5.1-codex".to_string());
+ config.cwd = PathBuf::from("/workspace/tests");
+
+ let auth_manager = test_auth_manager(&config);
+ let usage = TokenUsage {
+ input_tokens: 900,
+ cached_input_tokens: 200,
+ output_tokens: 350,
+ reasoning_output_tokens: 0,
+ total_tokens: 1_450,
+ };
+
+ let captured_at = chrono::Local
+ .with_ymd_and_hms(2024, 9, 10, 11, 12, 13)
+ .single()
+ .expect("timestamp");
+ let snapshot = RateLimitSnapshot {
+ primary: Some(RateLimitWindow {
+ used_percent: 60.0,
+ window_minutes: Some(300),
+ resets_at: Some(reset_at_from(&captured_at, 1_200)),
+ }),
+ secondary: Some(RateLimitWindow {
+ used_percent: 35.0,
+ window_minutes: Some(10_080),
+ resets_at: Some(reset_at_from(&captured_at, 2_400)),
+ }),
+ credits: Some(CreditsSnapshot {
+ has_credits: false,
+ unlimited: false,
+ balance: Some("80".to_string()),
+ }),
+ plan_type: None,
+ };
+ let rate_display = rate_limit_snapshot_display(&snapshot, captured_at);
+ let now = captured_at + ChronoDuration::minutes(20);
+
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &usage,
+ Some(&usage),
+ &None,
+ Some(&rate_display),
+ None,
+ now,
+ &model_slug,
+ );
+ let mut rendered_lines = render_lines(&composite.display_lines(80));
+ if cfg!(windows) {
+ for line in &mut rendered_lines {
+ *line = line.replace('\\', "/");
+ }
+ }
+ let sanitized = sanitize_directory(rendered_lines).join("\n");
+ assert_snapshot!(sanitized);
+}
+
+#[test]
+fn status_context_window_uses_last_usage() {
+ let temp_home = TempDir::new().expect("temp home");
+ let mut config = test_config(&temp_home);
+ config.model_context_window = Some(272_000);
+
+ let auth_manager = test_auth_manager(&config);
+ let total_usage = TokenUsage {
+ input_tokens: 12_800,
+ cached_input_tokens: 0,
+ output_tokens: 879,
+ reasoning_output_tokens: 0,
+ total_tokens: 102_000,
+ };
+ let last_usage = TokenUsage {
+ input_tokens: 12_800,
+ cached_input_tokens: 0,
+ output_tokens: 879,
+ reasoning_output_tokens: 0,
+ total_tokens: 13_679,
+ };
+
+ let now = chrono::Local
+ .with_ymd_and_hms(2024, 6, 1, 12, 0, 0)
+ .single()
+ .expect("timestamp");
+
+ let model_slug = ModelsManager::get_model_offline(config.model.as_deref());
+ let model_family = test_model_family(&model_slug, &config);
+ let composite = new_status_output(
+ &config,
+ &auth_manager,
+ &model_family,
+ &total_usage,
+ Some(&last_usage),
+ &None,
+ None,
+ None,
+ now,
+ &model_slug,
+ );
+ let rendered_lines = render_lines(&composite.display_lines(80));
+ let context_line = rendered_lines
+ .into_iter()
+ .find(|line| line.contains("Context window"))
+ .expect("context line");
+
+ assert!(
+ context_line.contains("13.7K used / 272K"),
+ "expected context line to reflect last usage tokens, got: {context_line}"
+ );
+ assert!(
+ !context_line.contains("102K"),
+ "context line should not use total aggregated tokens, got: {context_line}"
+ );
+}
diff --git a/codex-rs/tui2/src/status_indicator_widget.rs b/codex-rs/tui2/src/status_indicator_widget.rs
new file mode 100644
index 0000000000..642b9ca2b7
--- /dev/null
+++ b/codex-rs/tui2/src/status_indicator_widget.rs
@@ -0,0 +1,253 @@
+//! A live status indicator that shows the *latest* log line emitted by the
+//! application while the agent is processing a long‑running task.
+
+use std::time::Duration;
+use std::time::Instant;
+
+use codex_core::protocol::Op;
+use crossterm::event::KeyCode;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::style::Stylize;
+use ratatui::text::Line;
+use ratatui::widgets::WidgetRef;
+
+use crate::app_event::AppEvent;
+use crate::app_event_sender::AppEventSender;
+use crate::exec_cell::spinner;
+use crate::key_hint;
+use crate::render::renderable::Renderable;
+use crate::shimmer::shimmer_spans;
+use crate::tui::FrameRequester;
+
+pub(crate) struct StatusIndicatorWidget {
+ /// Animated header text (defaults to "Working").
+ header: String,
+ show_interrupt_hint: bool,
+
+ elapsed_running: Duration,
+ last_resume_at: Instant,
+ is_paused: bool,
+ app_event_tx: AppEventSender,
+ frame_requester: FrameRequester,
+ animations_enabled: bool,
+}
+
+// Format elapsed seconds into a compact human-friendly form used by the status line.
+// Examples: 0s, 59s, 1m 00s, 59m 59s, 1h 00m 00s, 2h 03m 09s
+pub fn fmt_elapsed_compact(elapsed_secs: u64) -> String {
+ if elapsed_secs < 60 {
+ return format!("{elapsed_secs}s");
+ }
+ if elapsed_secs < 3600 {
+ let minutes = elapsed_secs / 60;
+ let seconds = elapsed_secs % 60;
+ return format!("{minutes}m {seconds:02}s");
+ }
+ let hours = elapsed_secs / 3600;
+ let minutes = (elapsed_secs % 3600) / 60;
+ let seconds = elapsed_secs % 60;
+ format!("{hours}h {minutes:02}m {seconds:02}s")
+}
+
+impl StatusIndicatorWidget {
+ pub(crate) fn new(
+ app_event_tx: AppEventSender,
+ frame_requester: FrameRequester,
+ animations_enabled: bool,
+ ) -> Self {
+ Self {
+ header: String::from("Working"),
+ show_interrupt_hint: true,
+ elapsed_running: Duration::ZERO,
+ last_resume_at: Instant::now(),
+ is_paused: false,
+
+ app_event_tx,
+ frame_requester,
+ animations_enabled,
+ }
+ }
+
+ pub(crate) fn interrupt(&self) {
+ self.app_event_tx.send(AppEvent::CodexOp(Op::Interrupt));
+ }
+
+ /// Update the animated header label (left of the brackets).
+ pub(crate) fn update_header(&mut self, header: String) {
+ self.header = header;
+ }
+
+ #[cfg(test)]
+ pub(crate) fn header(&self) -> &str {
+ &self.header
+ }
+
+ pub(crate) fn set_interrupt_hint_visible(&mut self, visible: bool) {
+ self.show_interrupt_hint = visible;
+ }
+
+ #[cfg(test)]
+ pub(crate) fn interrupt_hint_visible(&self) -> bool {
+ self.show_interrupt_hint
+ }
+
+ pub(crate) fn pause_timer(&mut self) {
+ self.pause_timer_at(Instant::now());
+ }
+
+ pub(crate) fn resume_timer(&mut self) {
+ self.resume_timer_at(Instant::now());
+ }
+
+ pub(crate) fn pause_timer_at(&mut self, now: Instant) {
+ if self.is_paused {
+ return;
+ }
+ self.elapsed_running += now.saturating_duration_since(self.last_resume_at);
+ self.is_paused = true;
+ }
+
+ pub(crate) fn resume_timer_at(&mut self, now: Instant) {
+ if !self.is_paused {
+ return;
+ }
+ self.last_resume_at = now;
+ self.is_paused = false;
+ self.frame_requester.schedule_frame();
+ }
+
+ fn elapsed_duration_at(&self, now: Instant) -> Duration {
+ let mut elapsed = self.elapsed_running;
+ if !self.is_paused {
+ elapsed += now.saturating_duration_since(self.last_resume_at);
+ }
+ elapsed
+ }
+
+ fn elapsed_seconds_at(&self, now: Instant) -> u64 {
+ self.elapsed_duration_at(now).as_secs()
+ }
+
+ pub fn elapsed_seconds(&self) -> u64 {
+ self.elapsed_seconds_at(Instant::now())
+ }
+}
+
+impl Renderable for StatusIndicatorWidget {
+ fn desired_height(&self, _width: u16) -> u16 {
+ 1
+ }
+
+ fn render(&self, area: Rect, buf: &mut Buffer) {
+ if area.is_empty() {
+ return;
+ }
+
+ // Schedule next animation frame.
+ self.frame_requester
+ .schedule_frame_in(Duration::from_millis(32));
+ let now = Instant::now();
+ let elapsed_duration = self.elapsed_duration_at(now);
+ let pretty_elapsed = fmt_elapsed_compact(elapsed_duration.as_secs());
+
+ let mut spans = Vec::with_capacity(5);
+ spans.push(spinner(Some(self.last_resume_at), self.animations_enabled));
+ spans.push(" ".into());
+ if self.animations_enabled {
+ spans.extend(shimmer_spans(&self.header));
+ } else if !self.header.is_empty() {
+ spans.push(self.header.clone().into());
+ }
+ spans.push(" ".into());
+ if self.show_interrupt_hint {
+ spans.extend(vec![
+ format!("({pretty_elapsed} • ").dim(),
+ key_hint::plain(KeyCode::Esc).into(),
+ " to interrupt)".dim(),
+ ]);
+ } else {
+ spans.push(format!("({pretty_elapsed})").dim());
+ }
+
+ Line::from(spans).render_ref(area, buf);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::app_event::AppEvent;
+ use crate::app_event_sender::AppEventSender;
+ use ratatui::Terminal;
+ use ratatui::backend::TestBackend;
+ use std::time::Duration;
+ use std::time::Instant;
+ use tokio::sync::mpsc::unbounded_channel;
+
+ use pretty_assertions::assert_eq;
+
+ #[test]
+ fn fmt_elapsed_compact_formats_seconds_minutes_hours() {
+ assert_eq!(fmt_elapsed_compact(0), "0s");
+ assert_eq!(fmt_elapsed_compact(1), "1s");
+ assert_eq!(fmt_elapsed_compact(59), "59s");
+ assert_eq!(fmt_elapsed_compact(60), "1m 00s");
+ assert_eq!(fmt_elapsed_compact(61), "1m 01s");
+ assert_eq!(fmt_elapsed_compact(3 * 60 + 5), "3m 05s");
+ assert_eq!(fmt_elapsed_compact(59 * 60 + 59), "59m 59s");
+ assert_eq!(fmt_elapsed_compact(3600), "1h 00m 00s");
+ assert_eq!(fmt_elapsed_compact(3600 + 60 + 1), "1h 01m 01s");
+ assert_eq!(fmt_elapsed_compact(25 * 3600 + 2 * 60 + 3), "25h 02m 03s");
+ }
+
+ #[test]
+ fn renders_with_working_header() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let w = StatusIndicatorWidget::new(tx, crate::tui::FrameRequester::test_dummy(), true);
+
+ // Render into a fixed-size test terminal and snapshot the backend.
+ let mut terminal = Terminal::new(TestBackend::new(80, 2)).expect("terminal");
+ terminal
+ .draw(|f| w.render(f.area(), f.buffer_mut()))
+ .expect("draw");
+ insta::assert_snapshot!(terminal.backend());
+ }
+
+ #[test]
+ fn renders_truncated() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let w = StatusIndicatorWidget::new(tx, crate::tui::FrameRequester::test_dummy(), true);
+
+ // Render into a fixed-size test terminal and snapshot the backend.
+ let mut terminal = Terminal::new(TestBackend::new(20, 2)).expect("terminal");
+ terminal
+ .draw(|f| w.render(f.area(), f.buffer_mut()))
+ .expect("draw");
+ insta::assert_snapshot!(terminal.backend());
+ }
+
+ #[test]
+ fn timer_pauses_when_requested() {
+ let (tx_raw, _rx) = unbounded_channel::<AppEvent>();
+ let tx = AppEventSender::new(tx_raw);
+ let mut widget =
+ StatusIndicatorWidget::new(tx, crate::tui::FrameRequester::test_dummy(), true);
+
+ let baseline = Instant::now();
+ widget.last_resume_at = baseline;
+
+ let before_pause = widget.elapsed_seconds_at(baseline + Duration::from_secs(5));
+ assert_eq!(before_pause, 5);
+
+ widget.pause_timer_at(baseline + Duration::from_secs(5));
+ let paused_elapsed = widget.elapsed_seconds_at(baseline + Duration::from_secs(10));
+ assert_eq!(paused_elapsed, before_pause);
+
+ widget.resume_timer_at(baseline + Duration::from_secs(10));
+ let after_resume = widget.elapsed_seconds_at(baseline + Duration::from_secs(13));
+ assert_eq!(after_resume, before_pause + 3);
+ }
+}
diff --git a/codex-rs/tui2/src/streaming/controller.rs b/codex-rs/tui2/src/streaming/controller.rs
new file mode 100644
index 0000000000..e73ebd41e6
--- /dev/null
+++ b/codex-rs/tui2/src/streaming/controller.rs
@@ -0,0 +1,223 @@
+use crate::history_cell::HistoryCell;
+use crate::history_cell::{self};
+use ratatui::text::Line;
+
+use super::StreamState;
+
+/// Controller that manages newline-gated streaming, header emission, and
+/// commit animation across streams.
+pub(crate) struct StreamController {
+ state: StreamState,
+ finishing_after_drain: bool,
+ header_emitted: bool,
+}
+
+impl StreamController {
+ pub(crate) fn new(width: Option<usize>) -> Self {
+ Self {
+ state: StreamState::new(width),
+ finishing_after_drain: false,
+ header_emitted: false,
+ }
+ }
+
+ /// Push a delta; if it contains a newline, commit completed lines and start animation.
+ pub(crate) fn push(&mut self, delta: &str) -> bool {
+ let state = &mut self.state;
+ if !delta.is_empty() {
+ state.has_seen_delta = true;
+ }
+ state.collector.push_delta(delta);
+ if delta.contains('\n') {
+ let newly_completed = state.collector.commit_complete_lines();
+ if !newly_completed.is_empty() {
+ state.enqueue(newly_completed);
+ return true;
+ }
+ }
+ false
+ }
+
+ /// Finalize the active stream. Drain and emit now.
+ pub(crate) fn finalize(&mut self) -> Option<Box<dyn HistoryCell>> {
+ // Finalize collector first.
+ let remaining = {
+ let state = &mut self.state;
+ state.collector.finalize_and_drain()
+ };
+ // Collect all output first to avoid emitting headers when there is no content.
+ let mut out_lines = Vec::new();
+ {
+ let state = &mut self.state;
+ if !remaining.is_empty() {
+ state.enqueue(remaining);
+ }
+ let step = state.drain_all();
+ out_lines.extend(step);
+ }
+
+ // Cleanup
+ self.state.clear();
+ self.finishing_after_drain = false;
+ self.emit(out_lines)
+ }
+
+ /// Step animation: commit at most one queued line and handle end-of-drain cleanup.
+ pub(crate) fn on_commit_tick(&mut self) -> (Option<Box<dyn HistoryCell>>, bool) {
+ let step = self.state.step();
+ (self.emit(step), self.state.is_idle())
+ }
+
+ fn emit(&mut self, lines: Vec<Line<'static>>) -> Option<Box<dyn HistoryCell>> {
+ if lines.is_empty() {
+ return None;
+ }
+ Some(Box::new(history_cell::AgentMessageCell::new(lines, {
+ let header_emitted = self.header_emitted;
+ self.header_emitted = true;
+ !header_emitted
+ })))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn lines_to_plain_strings(lines: &[ratatui::text::Line<'_>]) -> Vec<String> {
+ lines
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.clone())
+ .collect::<Vec<_>>()
+ .join("")
+ })
+ .collect()
+ }
+
+ #[tokio::test]
+ async fn controller_loose_vs_tight_with_commit_ticks_matches_full() {
+ let mut ctrl = StreamController::new(None);
+ let mut lines = Vec::new();
+
+ // Exact deltas from the session log (section: Loose vs. tight list items)
+ let deltas = vec![
+ "\n\n",
+ "Loose",
+ " vs",
+ ".",
+ " tight",
+ " list",
+ " items",
+ ":\n",
+ "1",
+ ".",
+ " Tight",
+ " item",
+ "\n",
+ "2",
+ ".",
+ " Another",
+ " tight",
+ " item",
+ "\n\n",
+ "1",
+ ".",
+ " Loose",
+ " item",
+ " with",
+ " its",
+ " own",
+ " paragraph",
+ ".\n\n",
+ " ",
+ " This",
+ " paragraph",
+ " belongs",
+ " to",
+ " the",
+ " same",
+ " list",
+ " item",
+ ".\n\n",
+ "2",
+ ".",
+ " Second",
+ " loose",
+ " item",
+ " with",
+ " a",
+ " nested",
+ " list",
+ " after",
+ " a",
+ " blank",
+ " line",
+ ".\n\n",
+ " ",
+ " -",
+ " Nested",
+ " bullet",
+ " under",
+ " a",
+ " loose",
+ " item",
+ "\n",
+ " ",
+ " -",
+ " Another",
+ " nested",
+ " bullet",
+ "\n\n",
+ ];
+
+ // Simulate streaming with a commit tick attempt after each delta.
+ for d in deltas.iter() {
+ ctrl.push(d);
+ while let (Some(cell), idle) = ctrl.on_commit_tick() {
+ lines.extend(cell.transcript_lines(u16::MAX));
+ if idle {
+ break;
+ }
+ }
+ }
+ // Finalize and flush remaining lines now.
+ if let Some(cell) = ctrl.finalize() {
+ lines.extend(cell.transcript_lines(u16::MAX));
+ }
+
+ let streamed: Vec<_> = lines_to_plain_strings(&lines)
+ .into_iter()
+ // skip • and 2-space indentation
+ .map(|s| s.chars().skip(2).collect::<String>())
+ .collect();
+
+ // Full render of the same source
+ let source: String = deltas.iter().copied().collect();
+ let mut rendered: Vec<ratatui::text::Line<'static>> = Vec::new();
+ crate::markdown::append_markdown(&source, None, &mut rendered);
+ let rendered_strs = lines_to_plain_strings(&rendered);
+
+ assert_eq!(streamed, rendered_strs);
+
+ // Also assert exact expected plain strings for clarity.
+ let expected = vec![
+ "Loose vs. tight list items:".to_string(),
+ "".to_string(),
+ "1. Tight item".to_string(),
+ "2. Another tight item".to_string(),
+ "3. Loose item with its own paragraph.".to_string(),
+ "".to_string(),
+ " This paragraph belongs to the same list item.".to_string(),
+ "4. Second loose item with a nested list after a blank line.".to_string(),
+ " - Nested bullet under a loose item".to_string(),
+ " - Another nested bullet".to_string(),
+ ];
+ assert_eq!(
+ streamed, expected,
+ "expected exact rendered lines for loose/tight section"
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/streaming/mod.rs b/codex-rs/tui2/src/streaming/mod.rs
new file mode 100644
index 0000000000..fa00702834
--- /dev/null
+++ b/codex-rs/tui2/src/streaming/mod.rs
@@ -0,0 +1,39 @@
+use std::collections::VecDeque;
+
+use ratatui::text::Line;
+
+use crate::markdown_stream::MarkdownStreamCollector;
+pub(crate) mod controller;
+
+pub(crate) struct StreamState {
+ pub(crate) collector: MarkdownStreamCollector,
+ queued_lines: VecDeque<Line<'static>>,
+ pub(crate) has_seen_delta: bool,
+}
+
+impl StreamState {
+ pub(crate) fn new(width: Option<usize>) -> Self {
+ Self {
+ collector: MarkdownStreamCollector::new(width),
+ queued_lines: VecDeque::new(),
+ has_seen_delta: false,
+ }
+ }
+ pub(crate) fn clear(&mut self) {
+ self.collector.clear();
+ self.queued_lines.clear();
+ self.has_seen_delta = false;
+ }
+ pub(crate) fn step(&mut self) -> Vec<Line<'static>> {
+ self.queued_lines.pop_front().into_iter().collect()
+ }
+ pub(crate) fn drain_all(&mut self) -> Vec<Line<'static>> {
+ self.queued_lines.drain(..).collect()
+ }
+ pub(crate) fn is_idle(&self) -> bool {
+ self.queued_lines.is_empty()
+ }
+ pub(crate) fn enqueue(&mut self, lines: Vec<Line<'static>>) {
+ self.queued_lines.extend(lines);
+ }
+}
diff --git a/codex-rs/tui2/src/style.rs b/codex-rs/tui2/src/style.rs
new file mode 100644
index 0000000000..e50d59791e
--- /dev/null
+++ b/codex-rs/tui2/src/style.rs
@@ -0,0 +1,28 @@
+use crate::color::blend;
+use crate::color::is_light;
+use crate::terminal_palette::best_color;
+use crate::terminal_palette::default_bg;
+use ratatui::style::Color;
+use ratatui::style::Style;
+
+pub fn user_message_style() -> Style {
+ user_message_style_for(default_bg())
+}
+
+/// Returns the style for a user-authored message using the provided terminal background.
+pub fn user_message_style_for(terminal_bg: Option<(u8, u8, u8)>) -> Style {
+ match terminal_bg {
+ Some(bg) => Style::default().bg(user_message_bg(bg)),
+ None => Style::default(),
+ }
+}
+
+#[allow(clippy::disallowed_methods)]
+pub fn user_message_bg(terminal_bg: (u8, u8, u8)) -> Color {
+ let top = if is_light(terminal_bg) {
+ (0, 0, 0)
+ } else {
+ (255, 255, 255)
+ };
+ best_color(blend(top, terminal_bg, 0.1))
+}
diff --git a/codex-rs/tui2/src/terminal_palette.rs b/codex-rs/tui2/src/terminal_palette.rs
new file mode 100644
index 0000000000..5c6f32cd9e
--- /dev/null
+++ b/codex-rs/tui2/src/terminal_palette.rs
@@ -0,0 +1,401 @@
+use crate::color::perceptual_distance;
+use ratatui::style::Color;
+
+/// Returns the closest color to the target color that the terminal can display.
+pub fn best_color(target: (u8, u8, u8)) -> Color {
+ let Some(color_level) = supports_color::on_cached(supports_color::Stream::Stdout) else {
+ return Color::default();
+ };
+ if color_level.has_16m {
+ let (r, g, b) = target;
+ #[allow(clippy::disallowed_methods)]
+ Color::Rgb(r, g, b)
+ } else if color_level.has_256
+ && let Some((i, _)) = xterm_fixed_colors().min_by(|(_, a), (_, b)| {
+ perceptual_distance(*a, target)
+ .partial_cmp(&perceptual_distance(*b, target))
+ .unwrap_or(std::cmp::Ordering::Equal)
+ })
+ {
+ #[allow(clippy::disallowed_methods)]
+ Color::Indexed(i as u8)
+ } else {
+ #[allow(clippy::disallowed_methods)]
+ Color::default()
+ }
+}
+
+pub fn requery_default_colors() {
+ imp::requery_default_colors();
+}
+
+#[derive(Clone, Copy)]
+pub struct DefaultColors {
+ fg: (u8, u8, u8),
+ bg: (u8, u8, u8),
+}
+
+pub fn default_colors() -> Option<DefaultColors> {
+ imp::default_colors()
+}
+
+pub fn default_fg() -> Option<(u8, u8, u8)> {
+ default_colors().map(|c| c.fg)
+}
+
+pub fn default_bg() -> Option<(u8, u8, u8)> {
+ default_colors().map(|c| c.bg)
+}
+
+#[cfg(all(unix, not(test)))]
+mod imp {
+ use super::DefaultColors;
+ use crossterm::style::Color as CrosstermColor;
+ use crossterm::style::query_background_color;
+ use crossterm::style::query_foreground_color;
+ use std::sync::Mutex;
+ use std::sync::OnceLock;
+
+ struct Cache<T> {
+ attempted: bool,
+ value: Option<T>,
+ }
+
+ impl<T> Default for Cache<T> {
+ fn default() -> Self {
+ Self {
+ attempted: false,
+ value: None,
+ }
+ }
+ }
+
+ impl<T: Copy> Cache<T> {
+ fn get_or_init_with(&mut self, mut init: impl FnMut() -> Option<T>) -> Option<T> {
+ if !self.attempted {
+ self.value = init();
+ self.attempted = true;
+ }
+ self.value
+ }
+
+ fn refresh_with(&mut self, mut init: impl FnMut() -> Option<T>) -> Option<T> {
+ self.value = init();
+ self.attempted = true;
+ self.value
+ }
+ }
+
+ fn default_colors_cache() -> &'static Mutex<Cache<DefaultColors>> {
+ static CACHE: OnceLock<Mutex<Cache<DefaultColors>>> = OnceLock::new();
+ CACHE.get_or_init(|| Mutex::new(Cache::default()))
+ }
+
+ pub(super) fn default_colors() -> Option<DefaultColors> {
+ let cache = default_colors_cache();
+ let mut cache = cache.lock().ok()?;
+ cache.get_or_init_with(|| query_default_colors().unwrap_or_default())
+ }
+
+ pub(super) fn requery_default_colors() {
+ if let Ok(mut cache) = default_colors_cache().lock() {
+ // Don't try to refresh if the cache is already attempted and failed.
+ if cache.attempted && cache.value.is_none() {
+ return;
+ }
+ cache.refresh_with(|| query_default_colors().unwrap_or_default());
+ }
+ }
+
+ fn query_default_colors() -> std::io::Result<Option<DefaultColors>> {
+ let fg = query_foreground_color()?.and_then(color_to_tuple);
+ let bg = query_background_color()?.and_then(color_to_tuple);
+ Ok(fg.zip(bg).map(|(fg, bg)| DefaultColors { fg, bg }))
+ }
+
+ fn color_to_tuple(color: CrosstermColor) -> Option<(u8, u8, u8)> {
+ match color {
+ CrosstermColor::Rgb { r, g, b } => Some((r, g, b)),
+ _ => None,
+ }
+ }
+}
+
+#[cfg(not(all(unix, not(test))))]
+mod imp {
+ use super::DefaultColors;
+
+ pub(super) fn default_colors() -> Option<DefaultColors> {
+ None
+ }
+
+ pub(super) fn requery_default_colors() {}
+}
+
+/// The subset of Xterm colors that are usually consistent across terminals.
+fn xterm_fixed_colors() -> impl Iterator<Item = (usize, (u8, u8, u8))> {
+ XTERM_COLORS.into_iter().enumerate().skip(16)
+}
+
+// Xterm colors; derived from https://ss64.com/bash/syntax-colors.html
+pub const XTERM_COLORS: [(u8, u8, u8); 256] = [
+ // The first 16 colors vary based on terminal theme, so these are likely not the actual colors
+ // that are displayed when using these indices.
+ (0, 0, 0), // 0 Black (SYSTEM)
+ (128, 0, 0), // 1 Maroon (SYSTEM)
+ (0, 128, 0), // 2 Green (SYSTEM)
+ (128, 128, 0), // 3 Olive (SYSTEM)
+ (0, 0, 128), // 4 Navy (SYSTEM)
+ (128, 0, 128), // 5 Purple (SYSTEM)
+ (0, 128, 128), // 6 Teal (SYSTEM)
+ (192, 192, 192), // 7 Silver (SYSTEM)
+ (128, 128, 128), // 8 Grey (SYSTEM)
+ (255, 0, 0), // 9 Red (SYSTEM)
+ (0, 255, 0), // 10 Lime (SYSTEM)
+ (255, 255, 0), // 11 Yellow (SYSTEM)
+ (0, 0, 255), // 12 Blue (SYSTEM)
+ (255, 0, 255), // 13 Fuchsia (SYSTEM)
+ (0, 255, 255), // 14 Aqua (SYSTEM)
+ (255, 255, 255), // 15 White (SYSTEM)
+ // The rest of the colors are consistent in most terminals.
+ (0, 0, 0), // 16 Grey0
+ (0, 0, 95), // 17 NavyBlue
+ (0, 0, 135), // 18 DarkBlue
+ (0, 0, 175), // 19 Blue3
+ (0, 0, 215), // 20 Blue3
+ (0, 0, 255), // 21 Blue1
+ (0, 95, 0), // 22 DarkGreen
+ (0, 95, 95), // 23 DeepSkyBlue4
+ (0, 95, 135), // 24 DeepSkyBlue4
+ (0, 95, 175), // 25 DeepSkyBlue4
+ (0, 95, 215), // 26 DodgerBlue3
+ (0, 95, 255), // 27 DodgerBlue2
+ (0, 135, 0), // 28 Green4
+ (0, 135, 95), // 29 SpringGreen4
+ (0, 135, 135), // 30 Turquoise4
+ (0, 135, 175), // 31 DeepSkyBlue3
+ (0, 135, 215), // 32 DeepSkyBlue3
+ (0, 135, 255), // 33 DodgerBlue1
+ (0, 175, 0), // 34 Green3
+ (0, 175, 95), // 35 SpringGreen3
+ (0, 175, 135), // 36 DarkCyan
+ (0, 175, 175), // 37 LightSeaGreen
+ (0, 175, 215), // 38 DeepSkyBlue2
+ (0, 175, 255), // 39 DeepSkyBlue1
+ (0, 215, 0), // 40 Green3
+ (0, 215, 95), // 41 SpringGreen3
+ (0, 215, 135), // 42 SpringGreen2
+ (0, 215, 175), // 43 Cyan3
+ (0, 215, 215), // 44 DarkTurquoise
+ (0, 215, 255), // 45 Turquoise2
+ (0, 255, 0), // 46 Green1
+ (0, 255, 95), // 47 SpringGreen2
+ (0, 255, 135), // 48 SpringGreen1
+ (0, 255, 175), // 49 MediumSpringGreen
+ (0, 255, 215), // 50 Cyan2
+ (0, 255, 255), // 51 Cyan1
+ (95, 0, 0), // 52 DarkRed
+ (95, 0, 95), // 53 DeepPink4
+ (95, 0, 135), // 54 Purple4
+ (95, 0, 175), // 55 Purple4
+ (95, 0, 215), // 56 Purple3
+ (95, 0, 255), // 57 BlueViolet
+ (95, 95, 0), // 58 Orange4
+ (95, 95, 95), // 59 Grey37
+ (95, 95, 135), // 60 MediumPurple4
+ (95, 95, 175), // 61 SlateBlue3
+ (95, 95, 215), // 62 SlateBlue3
+ (95, 95, 255), // 63 RoyalBlue1
+ (95, 135, 0), // 64 Chartreuse4
+ (95, 135, 95), // 65 DarkSeaGreen4
+ (95, 135, 135), // 66 PaleTurquoise4
+ (95, 135, 175), // 67 SteelBlue
+ (95, 135, 215), // 68 SteelBlue3
+ (95, 135, 255), // 69 CornflowerBlue
+ (95, 175, 0), // 70 Chartreuse3
+ (95, 175, 95), // 71 DarkSeaGreen4
+ (95, 175, 135), // 72 CadetBlue
+ (95, 175, 175), // 73 CadetBlue
+ (95, 175, 215), // 74 SkyBlue3
+ (95, 175, 255), // 75 SteelBlue1
+ (95, 215, 0), // 76 Chartreuse3
+ (95, 215, 95), // 77 PaleGreen3
+ (95, 215, 135), // 78 SeaGreen3
+ (95, 215, 175), // 79 Aquamarine3
+ (95, 215, 215), // 80 MediumTurquoise
+ (95, 215, 255), // 81 SteelBlue1
+ (95, 255, 0), // 82 Chartreuse2
+ (95, 255, 95), // 83 SeaGreen2
+ (95, 255, 135), // 84 SeaGreen1
+ (95, 255, 175), // 85 SeaGreen1
+ (95, 255, 215), // 86 Aquamarine1
+ (95, 255, 255), // 87 DarkSlateGray2
+ (135, 0, 0), // 88 DarkRed
+ (135, 0, 95), // 89 DeepPink4
+ (135, 0, 135), // 90 DarkMagenta
+ (135, 0, 175), // 91 DarkMagenta
+ (135, 0, 215), // 92 DarkViolet
+ (135, 0, 255), // 93 Purple
+ (135, 95, 0), // 94 Orange4
+ (135, 95, 95), // 95 LightPink4
+ (135, 95, 135), // 96 Plum4
+ (135, 95, 175), // 97 MediumPurple3
+ (135, 95, 215), // 98 MediumPurple3
+ (135, 95, 255), // 99 SlateBlue1
+ (135, 135, 0), // 100 Yellow4
+ (135, 135, 95), // 101 Wheat4
+ (135, 135, 135), // 102 Grey53
+ (135, 135, 175), // 103 LightSlateGrey
+ (135, 135, 215), // 104 MediumPurple
+ (135, 135, 255), // 105 LightSlateBlue
+ (135, 175, 0), // 106 Yellow4
+ (135, 175, 95), // 107 DarkOliveGreen3
+ (135, 175, 135), // 108 DarkSeaGreen
+ (135, 175, 175), // 109 LightSkyBlue3
+ (135, 175, 215), // 110 LightSkyBlue3
+ (135, 175, 255), // 111 SkyBlue2
+ (135, 215, 0), // 112 Chartreuse2
+ (135, 215, 95), // 113 DarkOliveGreen3
+ (135, 215, 135), // 114 PaleGreen3
+ (135, 215, 175), // 115 DarkSeaGreen3
+ (135, 215, 215), // 116 DarkSlateGray3
+ (135, 215, 255), // 117 SkyBlue1
+ (135, 255, 0), // 118 Chartreuse1
+ (135, 255, 95), // 119 LightGreen
+ (135, 255, 135), // 120 LightGreen
+ (135, 255, 175), // 121 PaleGreen1
+ (135, 255, 215), // 122 Aquamarine1
+ (135, 255, 255), // 123 DarkSlateGray1
+ (175, 0, 0), // 124 Red3
+ (175, 0, 95), // 125 DeepPink4
+ (175, 0, 135), // 126 MediumVioletRed
+ (175, 0, 175), // 127 Magenta3
+ (175, 0, 215), // 128 DarkViolet
+ (175, 0, 255), // 129 Purple
+ (175, 95, 0), // 130 DarkOrange3
+ (175, 95, 95), // 131 IndianRed
+ (175, 95, 135), // 132 HotPink3
+ (175, 95, 175), // 133 MediumOrchid3
+ (175, 95, 215), // 134 MediumOrchid
+ (175, 95, 255), // 135 MediumPurple2
+ (175, 135, 0), // 136 DarkGoldenrod
+ (175, 135, 95), // 137 LightSalmon3
+ (175, 135, 135), // 138 RosyBrown
+ (175, 135, 175), // 139 Grey63
+ (175, 135, 215), // 140 MediumPurple2
+ (175, 135, 255), // 141 MediumPurple1
+ (175, 175, 0), // 142 Gold3
+ (175, 175, 95), // 143 DarkKhaki
+ (175, 175, 135), // 144 NavajoWhite3
+ (175, 175, 175), // 145 Grey69
+ (175, 175, 215), // 146 LightSteelBlue3
+ (175, 175, 255), // 147 LightSteelBlue
+ (175, 215, 0), // 148 Yellow3
+ (175, 215, 95), // 149 DarkOliveGreen3
+ (175, 215, 135), // 150 DarkSeaGreen3
+ (175, 215, 175), // 151 DarkSeaGreen2
+ (175, 215, 215), // 152 LightCyan3
+ (175, 215, 255), // 153 LightSkyBlue1
+ (175, 255, 0), // 154 GreenYellow
+ (175, 255, 95), // 155 DarkOliveGreen2
+ (175, 255, 135), // 156 PaleGreen1
+ (175, 255, 175), // 157 DarkSeaGreen2
+ (175, 255, 215), // 158 DarkSeaGreen1
+ (175, 255, 255), // 159 PaleTurquoise1
+ (215, 0, 0), // 160 Red3
+ (215, 0, 95), // 161 DeepPink3
+ (215, 0, 135), // 162 DeepPink3
+ (215, 0, 175), // 163 Magenta3
+ (215, 0, 215), // 164 Magenta3
+ (215, 0, 255), // 165 Magenta2
+ (215, 95, 0), // 166 DarkOrange3
+ (215, 95, 95), // 167 IndianRed
+ (215, 95, 135), // 168 HotPink3
+ (215, 95, 175), // 169 HotPink2
+ (215, 95, 215), // 170 Orchid
+ (215, 95, 255), // 171 MediumOrchid1
+ (215, 135, 0), // 172 Orange3
+ (215, 135, 95), // 173 LightSalmon3
+ (215, 135, 135), // 174 LightPink3
+ (215, 135, 175), // 175 Pink3
+ (215, 135, 215), // 176 Plum3
+ (215, 135, 255), // 177 Violet
+ (215, 175, 0), // 178 Gold3
+ (215, 175, 95), // 179 LightGoldenrod3
+ (215, 175, 135), // 180 Tan
+ (215, 175, 175), // 181 MistyRose3
+ (215, 175, 215), // 182 Thistle3
+ (215, 175, 255), // 183 Plum2
+ (215, 215, 0), // 184 Yellow3
+ (215, 215, 95), // 185 Khaki3
+ (215, 215, 135), // 186 LightGoldenrod2
+ (215, 215, 175), // 187 LightYellow3
+ (215, 215, 215), // 188 Grey84
+ (215, 215, 255), // 189 LightSteelBlue1
+ (215, 255, 0), // 190 Yellow2
+ (215, 255, 95), // 191 DarkOliveGreen1
+ (215, 255, 135), // 192 DarkOliveGreen1
+ (215, 255, 175), // 193 DarkSeaGreen1
+ (215, 255, 215), // 194 Honeydew2
+ (215, 255, 255), // 195 LightCyan1
+ (255, 0, 0), // 196 Red1
+ (255, 0, 95), // 197 DeepPink2
+ (255, 0, 135), // 198 DeepPink1
+ (255, 0, 175), // 199 DeepPink1
+ (255, 0, 215), // 200 Magenta2
+ (255, 0, 255), // 201 Magenta1
+ (255, 95, 0), // 202 OrangeRed1
+ (255, 95, 95), // 203 IndianRed1
+ (255, 95, 135), // 204 IndianRed1
+ (255, 95, 175), // 205 HotPink
+ (255, 95, 215), // 206 HotPink
+ (255, 95, 255), // 207 MediumOrchid1
+ (255, 135, 0), // 208 DarkOrange
+ (255, 135, 95), // 209 Salmon1
+ (255, 135, 135), // 210 LightCoral
+ (255, 135, 175), // 211 PaleVioletRed1
+ (255, 135, 215), // 212 Orchid2
+ (255, 135, 255), // 213 Orchid1
+ (255, 175, 0), // 214 Orange1
+ (255, 175, 95), // 215 SandyBrown
+ (255, 175, 135), // 216 LightSalmon1
+ (255, 175, 175), // 217 LightPink1
+ (255, 175, 215), // 218 Pink1
+ (255, 175, 255), // 219 Plum1
+ (255, 215, 0), // 220 Gold1
+ (255, 215, 95), // 221 LightGoldenrod2
+ (255, 215, 135), // 222 LightGoldenrod2
+ (255, 215, 175), // 223 NavajoWhite1
+ (255, 215, 215), // 224 MistyRose1
+ (255, 215, 255), // 225 Thistle1
+ (255, 255, 0), // 226 Yellow1
+ (255, 255, 95), // 227 LightGoldenrod1
+ (255, 255, 135), // 228 Khaki1
+ (255, 255, 175), // 229 Wheat1
+ (255, 255, 215), // 230 Cornsilk1
+ (255, 255, 255), // 231 Grey100
+ (8, 8, 8), // 232 Grey3
+ (18, 18, 18), // 233 Grey7
+ (28, 28, 28), // 234 Grey11
+ (38, 38, 38), // 235 Grey15
+ (48, 48, 48), // 236 Grey19
+ (58, 58, 58), // 237 Grey23
+ (68, 68, 68), // 238 Grey27
+ (78, 78, 78), // 239 Grey30
+ (88, 88, 88), // 240 Grey35
+ (98, 98, 98), // 241 Grey39
+ (108, 108, 108), // 242 Grey42
+ (118, 118, 118), // 243 Grey46
+ (128, 128, 128), // 244 Grey50
+ (138, 138, 138), // 245 Grey54
+ (148, 148, 148), // 246 Grey58
+ (158, 158, 158), // 247 Grey62
+ (168, 168, 168), // 248 Grey66
+ (178, 178, 178), // 249 Grey70
+ (188, 188, 188), // 250 Grey74
+ (198, 198, 198), // 251 Grey78
+ (208, 208, 208), // 252 Grey82
+ (218, 218, 218), // 253 Grey85
+ (228, 228, 228), // 254 Grey89
+ (238, 238, 238), // 255 Grey93
+];
diff --git a/codex-rs/tui2/src/test_backend.rs b/codex-rs/tui2/src/test_backend.rs
new file mode 100644
index 0000000000..a5460af2e0
--- /dev/null
+++ b/codex-rs/tui2/src/test_backend.rs
@@ -0,0 +1,124 @@
+use std::fmt::{self};
+use std::io::Write;
+use std::io::{self};
+
+use ratatui::prelude::CrosstermBackend;
+
+use ratatui::backend::Backend;
+use ratatui::backend::ClearType;
+use ratatui::backend::WindowSize;
+use ratatui::buffer::Cell;
+use ratatui::layout::Position;
+use ratatui::layout::Size;
+
+/// This wraps a CrosstermBackend and a vt100::Parser to mock
+/// a "real" terminal.
+///
+/// Importantly, this wrapper avoids calling any crossterm methods
+/// which write to stdout regardless of the writer. This includes:
+/// - getting the terminal size
+/// - getting the cursor position
+pub struct VT100Backend {
+ crossterm_backend: CrosstermBackend<vt100::Parser>,
+}
+
+impl VT100Backend {
+ /// Creates a new `TestBackend` with the specified width and height.
+ pub fn new(width: u16, height: u16) -> Self {
+ Self {
+ crossterm_backend: CrosstermBackend::new(vt100::Parser::new(height, width, 0)),
+ }
+ }
+
+ pub fn vt100(&self) -> &vt100::Parser {
+ self.crossterm_backend.writer()
+ }
+}
+
+impl Write for VT100Backend {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ self.crossterm_backend.writer_mut().write(buf)
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.crossterm_backend.writer_mut().flush()
+ }
+}
+
+impl fmt::Display for VT100Backend {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.crossterm_backend.writer().screen().contents())
+ }
+}
+
+impl Backend for VT100Backend {
+ fn draw<'a, I>(&mut self, content: I) -> io::Result<()>
+ where
+ I: Iterator<Item = (u16, u16, &'a Cell)>,
+ {
+ self.crossterm_backend.draw(content)?;
+ Ok(())
+ }
+
+ fn hide_cursor(&mut self) -> io::Result<()> {
+ self.crossterm_backend.hide_cursor()?;
+ Ok(())
+ }
+
+ fn show_cursor(&mut self) -> io::Result<()> {
+ self.crossterm_backend.show_cursor()?;
+ Ok(())
+ }
+
+ fn get_cursor_position(&mut self) -> io::Result<Position> {
+ Ok(self.vt100().screen().cursor_position().into())
+ }
+
+ fn set_cursor_position<P: Into<Position>>(&mut self, position: P) -> io::Result<()> {
+ self.crossterm_backend.set_cursor_position(position)
+ }
+
+ fn clear(&mut self) -> io::Result<()> {
+ self.crossterm_backend.clear()
+ }
+
+ fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> {
+ self.crossterm_backend.clear_region(clear_type)
+ }
+
+ fn append_lines(&mut self, line_count: u16) -> io::Result<()> {
+ self.crossterm_backend.append_lines(line_count)
+ }
+
+ fn size(&self) -> io::Result<Size> {
+ let (rows, cols) = self.vt100().screen().size();
+ Ok(Size::new(cols, rows))
+ }
+
+ fn window_size(&mut self) -> io::Result<WindowSize> {
+ Ok(WindowSize {
+ columns_rows: self.vt100().screen().size().into(),
+ // Arbitrary size, we don't rely on this in testing.
+ pixels: Size {
+ width: 640,
+ height: 480,
+ },
+ })
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ self.crossterm_backend.writer_mut().flush()
+ }
+
+ fn scroll_region_up(&mut self, region: std::ops::Range<u16>, scroll_by: u16) -> io::Result<()> {
+ self.crossterm_backend.scroll_region_up(region, scroll_by)
+ }
+
+ fn scroll_region_down(
+ &mut self,
+ region: std::ops::Range<u16>,
+ scroll_by: u16,
+ ) -> io::Result<()> {
+ self.crossterm_backend.scroll_region_down(region, scroll_by)
+ }
+}
diff --git a/codex-rs/tui2/src/text_formatting.rs b/codex-rs/tui2/src/text_formatting.rs
new file mode 100644
index 0000000000..91d1c84f22
--- /dev/null
+++ b/codex-rs/tui2/src/text_formatting.rs
@@ -0,0 +1,525 @@
+use unicode_segmentation::UnicodeSegmentation;
+use unicode_width::UnicodeWidthChar;
+use unicode_width::UnicodeWidthStr;
+
+/// Truncate a tool result to fit within the given height and width. If the text is valid JSON, we format it in a compact way before truncating.
+/// This is a best-effort approach that may not work perfectly for text where 1 grapheme is rendered as multiple terminal cells.
+pub(crate) fn format_and_truncate_tool_result(
+ text: &str,
+ max_lines: usize,
+ line_width: usize,
+) -> String {
+ // Work out the maximum number of graphemes we can display for a result.
+ // It's not guaranteed that 1 grapheme = 1 cell, so we subtract 1 per line as a fudge factor.
+ // It also won't handle future terminal resizes properly, but it's an OK approximation for now.
+ let max_graphemes = (max_lines * line_width).saturating_sub(max_lines);
+
+ if let Some(formatted_json) = format_json_compact(text) {
+ truncate_text(&formatted_json, max_graphemes)
+ } else {
+ truncate_text(text, max_graphemes)
+ }
+}
+
+/// Format JSON text in a compact single-line format with spaces for better Ratatui wrapping.
+/// Ex: `{"a":"b",c:["d","e"]}` -> `{"a": "b", "c": ["d", "e"]}`
+/// Returns the formatted JSON string if the input is valid JSON, otherwise returns None.
+/// This is a little complicated, but it's necessary because Ratatui's wrapping is *very* limited
+/// and can only do line breaks at whitespace. If we use the default serde_json format, we get lines
+/// without spaces that Ratatui can't wrap nicely. If we use the serde_json pretty format as-is,
+/// it's much too sparse and uses too many terminal rows.
+/// Relevant issue: https://github.com/ratatui/ratatui/issues/293
+pub(crate) fn format_json_compact(text: &str) -> Option<String> {
+ let json = serde_json::from_str::<serde_json::Value>(text).ok()?;
+ let json_pretty = serde_json::to_string_pretty(&json).unwrap_or_else(|_| json.to_string());
+
+ // Convert multi-line pretty JSON to compact single-line format by removing newlines and excess whitespace
+ let mut result = String::new();
+ let mut chars = json_pretty.chars().peekable();
+ let mut in_string = false;
+ let mut escape_next = false;
+
+ // Iterate over the characters in the JSON string, adding spaces after : and , but only when not in a string
+ while let Some(ch) = chars.next() {
+ match ch {
+ '"' if !escape_next => {
+ in_string = !in_string;
+ result.push(ch);
+ }
+ '\\' if in_string => {
+ escape_next = !escape_next;
+ result.push(ch);
+ }
+ '\n' | '\r' if !in_string => {
+ // Skip newlines when not in a string
+ }
+ ' ' | '\t' if !in_string => {
+ // Add a space after : and , but only when not in a string
+ if let Some(&next_ch) = chars.peek()
+ && let Some(last_ch) = result.chars().last()
+ && (last_ch == ':' || last_ch == ',')
+ && !matches!(next_ch, '}' | ']')
+ {
+ result.push(' ');
+ }
+ }
+ _ => {
+ if escape_next && in_string {
+ escape_next = false;
+ }
+ result.push(ch);
+ }
+ }
+ }
+
+ Some(result)
+}
+
+/// Truncate `text` to `max_graphemes` graphemes. Using graphemes to avoid accidentally truncating in the middle of a multi-codepoint character.
+pub(crate) fn truncate_text(text: &str, max_graphemes: usize) -> String {
+ let mut graphemes = text.grapheme_indices(true);
+
+ // Check if there's a grapheme at position max_graphemes (meaning there are more than max_graphemes total)
+ if let Some((byte_index, _)) = graphemes.nth(max_graphemes) {
+ // There are more than max_graphemes, so we need to truncate
+ if max_graphemes >= 3 {
+ // Truncate to max_graphemes - 3 and add "..." to stay within limit
+ let mut truncate_graphemes = text.grapheme_indices(true);
+ if let Some((truncate_byte_index, _)) = truncate_graphemes.nth(max_graphemes - 3) {
+ let truncated = &text[..truncate_byte_index];
+ format!("{truncated}...")
+ } else {
+ text.to_string()
+ }
+ } else {
+ // max_graphemes < 3, so just return first max_graphemes without "..."
+ let truncated = &text[..byte_index];
+ truncated.to_string()
+ }
+ } else {
+ // There are max_graphemes or fewer graphemes, return original text
+ text.to_string()
+ }
+}
+
+/// Truncate a path-like string to the given display width, keeping leading and trailing segments
+/// where possible and inserting a single Unicode ellipsis between them. If an individual segment
+/// cannot fit, it is front-truncated with an ellipsis.
+pub(crate) fn center_truncate_path(path: &str, max_width: usize) -> String {
+ if max_width == 0 {
+ return String::new();
+ }
+ if UnicodeWidthStr::width(path) <= max_width {
+ return path.to_string();
+ }
+
+ let sep = std::path::MAIN_SEPARATOR;
+ let has_leading_sep = path.starts_with(sep);
+ let has_trailing_sep = path.ends_with(sep);
+ let mut raw_segments: Vec<&str> = path.split(sep).collect();
+ if has_leading_sep && !raw_segments.is_empty() && raw_segments[0].is_empty() {
+ raw_segments.remove(0);
+ }
+ if has_trailing_sep
+ && !raw_segments.is_empty()
+ && raw_segments.last().is_some_and(|last| last.is_empty())
+ {
+ raw_segments.pop();
+ }
+
+ if raw_segments.is_empty() {
+ if has_leading_sep {
+ let root = sep.to_string();
+ if UnicodeWidthStr::width(root.as_str()) <= max_width {
+ return root;
+ }
+ }
+ return "…".to_string();
+ }
+
+ struct Segment<'a> {
+ original: &'a str,
+ text: String,
+ truncatable: bool,
+ is_suffix: bool,
+ }
+
+ let assemble = |leading: bool, segments: &[Segment<'_>]| -> String {
+ let mut result = String::new();
+ if leading {
+ result.push(sep);
+ }
+ for segment in segments {
+ if !result.is_empty() && !result.ends_with(sep) {
+ result.push(sep);
+ }
+ result.push_str(segment.text.as_str());
+ }
+ result
+ };
+
+ let front_truncate = |original: &str, allowed_width: usize| -> String {
+ if allowed_width == 0 {
+ return String::new();
+ }
+ if UnicodeWidthStr::width(original) <= allowed_width {
+ return original.to_string();
+ }
+ if allowed_width == 1 {
+ return "…".to_string();
+ }
+
+ let mut kept: Vec<char> = Vec::new();
+ let mut used_width = 1; // reserve space for leading ellipsis
+ for ch in original.chars().rev() {
+ let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0);
+ if used_width + ch_width > allowed_width {
+ break;
+ }
+ used_width += ch_width;
+ kept.push(ch);
+ }
+ kept.reverse();
+ let mut truncated = String::from("…");
+ for ch in kept {
+ truncated.push(ch);
+ }
+ truncated
+ };
+
+ let mut combos: Vec<(usize, usize)> = Vec::new();
+ let segment_count = raw_segments.len();
+ for left in 1..=segment_count {
+ let min_right = if left == segment_count { 0 } else { 1 };
+ for right in min_right..=(segment_count - left) {
+ combos.push((left, right));
+ }
+ }
+ let desired_suffix = if segment_count > 1 {
+ std::cmp::min(2, segment_count - 1)
+ } else {
+ 0
+ };
+ let mut prioritized: Vec<(usize, usize)> = Vec::new();
+ let mut fallback: Vec<(usize, usize)> = Vec::new();
+ for combo in combos {
+ if combo.1 >= desired_suffix {
+ prioritized.push(combo);
+ } else {
+ fallback.push(combo);
+ }
+ }
+ let sort_combos = |items: &mut Vec<(usize, usize)>| {
+ items.sort_by(|(left_a, right_a), (left_b, right_b)| {
+ left_b
+ .cmp(left_a)
+ .then_with(|| right_b.cmp(right_a))
+ .then_with(|| (left_b + right_b).cmp(&(left_a + right_a)))
+ });
+ };
+ sort_combos(&mut prioritized);
+ sort_combos(&mut fallback);
+
+ let fit_segments =
+ |segments: &mut Vec<Segment<'_>>, allow_front_truncate: bool| -> Option<String> {
+ loop {
+ let candidate = assemble(has_leading_sep, segments);
+ let width = UnicodeWidthStr::width(candidate.as_str());
+ if width <= max_width {
+ return Some(candidate);
+ }
+
+ if !allow_front_truncate {
+ return None;
+ }
+
+ let mut indices: Vec<usize> = Vec::new();
+ for (idx, seg) in segments.iter().enumerate().rev() {
+ if seg.truncatable && seg.is_suffix {
+ indices.push(idx);
+ }
+ }
+ for (idx, seg) in segments.iter().enumerate().rev() {
+ if seg.truncatable && !seg.is_suffix {
+ indices.push(idx);
+ }
+ }
+
+ if indices.is_empty() {
+ return None;
+ }
+
+ let mut changed = false;
+ for idx in indices {
+ let original_width = UnicodeWidthStr::width(segments[idx].original);
+ if original_width <= max_width && segment_count > 2 {
+ continue;
+ }
+ let seg_width = UnicodeWidthStr::width(segments[idx].text.as_str());
+ let other_width = width.saturating_sub(seg_width);
+ let allowed_width = max_width.saturating_sub(other_width).max(1);
+ let new_text = front_truncate(segments[idx].original, allowed_width);
+ if new_text != segments[idx].text {
+ segments[idx].text = new_text;
+ changed = true;
+ break;
+ }
+ }
+
+ if !changed {
+ return None;
+ }
+ }
+ };
+
+ for (left_count, right_count) in prioritized.into_iter().chain(fallback.into_iter()) {
+ let mut segments: Vec<Segment<'_>> = raw_segments[..left_count]
+ .iter()
+ .map(|seg| Segment {
+ original: seg,
+ text: (*seg).to_string(),
+ truncatable: true,
+ is_suffix: false,
+ })
+ .collect();
+
+ let need_ellipsis = left_count + right_count < segment_count;
+ if need_ellipsis {
+ segments.push(Segment {
+ original: "…",
+ text: "…".to_string(),
+ truncatable: false,
+ is_suffix: false,
+ });
+ }
+
+ if right_count > 0 {
+ segments.extend(
+ raw_segments[segment_count - right_count..]
+ .iter()
+ .map(|seg| Segment {
+ original: seg,
+ text: (*seg).to_string(),
+ truncatable: true,
+ is_suffix: true,
+ }),
+ );
+ }
+
+ let allow_front_truncate = need_ellipsis || segment_count <= 2;
+ if let Some(candidate) = fit_segments(&mut segments, allow_front_truncate) {
+ return candidate;
+ }
+ }
+
+ front_truncate(path, max_width)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use pretty_assertions::assert_eq;
+
+ #[test]
+ fn test_truncate_text() {
+ let text = "Hello, world!";
+ let truncated = truncate_text(text, 8);
+ assert_eq!(truncated, "Hello...");
+ }
+
+ #[test]
+ fn test_truncate_empty_string() {
+ let text = "";
+ let truncated = truncate_text(text, 5);
+ assert_eq!(truncated, "");
+ }
+
+ #[test]
+ fn test_truncate_max_graphemes_zero() {
+ let text = "Hello";
+ let truncated = truncate_text(text, 0);
+ assert_eq!(truncated, "");
+ }
+
+ #[test]
+ fn test_truncate_max_graphemes_one() {
+ let text = "Hello";
+ let truncated = truncate_text(text, 1);
+ assert_eq!(truncated, "H");
+ }
+
+ #[test]
+ fn test_truncate_max_graphemes_two() {
+ let text = "Hello";
+ let truncated = truncate_text(text, 2);
+ assert_eq!(truncated, "He");
+ }
+
+ #[test]
+ fn test_truncate_max_graphemes_three_boundary() {
+ let text = "Hello";
+ let truncated = truncate_text(text, 3);
+ assert_eq!(truncated, "...");
+ }
+
+ #[test]
+ fn test_truncate_text_shorter_than_limit() {
+ let text = "Hi";
+ let truncated = truncate_text(text, 10);
+ assert_eq!(truncated, "Hi");
+ }
+
+ #[test]
+ fn test_truncate_text_exact_length() {
+ let text = "Hello";
+ let truncated = truncate_text(text, 5);
+ assert_eq!(truncated, "Hello");
+ }
+
+ #[test]
+ fn test_truncate_emoji() {
+ let text = "👋🌍🚀✨💫";
+ let truncated = truncate_text(text, 3);
+ assert_eq!(truncated, "...");
+
+ let truncated_longer = truncate_text(text, 4);
+ assert_eq!(truncated_longer, "👋...");
+ }
+
+ #[test]
+ fn test_truncate_unicode_combining_characters() {
+ let text = "é́ñ̃"; // Characters with combining marks
+ let truncated = truncate_text(text, 2);
+ assert_eq!(truncated, "é́ñ̃");
+ }
+
+ #[test]
+ fn test_truncate_very_long_text() {
+ let text = "a".repeat(1000);
+ let truncated = truncate_text(&text, 10);
+ assert_eq!(truncated, "aaaaaaa...");
+ assert_eq!(truncated.len(), 10); // 7 'a's + 3 dots
+ }
+
+ #[test]
+ fn test_format_json_compact_simple_object() {
+ let json = r#"{ "name": "John", "age": 30 }"#;
+ let result = format_json_compact(json).unwrap();
+ assert_eq!(result, r#"{"name": "John", "age": 30}"#);
+ }
+
+ #[test]
+ fn test_format_json_compact_nested_object() {
+ let json = r#"{ "user": { "name": "John", "details": { "age": 30, "city": "NYC" } } }"#;
+ let result = format_json_compact(json).unwrap();
+ assert_eq!(
+ result,
+ r#"{"user": {"name": "John", "details": {"age": 30, "city": "NYC"}}}"#
+ );
+ }
+
+ #[test]
+ fn test_center_truncate_doesnt_truncate_short_path() {
+ let sep = std::path::MAIN_SEPARATOR;
+ let path = format!("{sep}Users{sep}codex{sep}Public");
+ let truncated = center_truncate_path(&path, 40);
+
+ assert_eq!(truncated, path);
+ }
+
+ #[test]
+ fn test_center_truncate_truncates_long_path() {
+ let sep = std::path::MAIN_SEPARATOR;
+ let path = format!("~{sep}hello{sep}the{sep}fox{sep}is{sep}very{sep}fast");
+ let truncated = center_truncate_path(&path, 24);
+
+ assert_eq!(
+ truncated,
+ format!("~{sep}hello{sep}the{sep}…{sep}very{sep}fast")
+ );
+ }
+
+ #[test]
+ fn test_center_truncate_truncates_long_windows_path() {
+ let sep = std::path::MAIN_SEPARATOR;
+ let path = format!(
+ "C:{sep}Users{sep}codex{sep}Projects{sep}super{sep}long{sep}windows{sep}path{sep}file.txt"
+ );
+ let truncated = center_truncate_path(&path, 36);
+
+ let expected = format!("C:{sep}Users{sep}codex{sep}…{sep}path{sep}file.txt");
+
+ assert_eq!(truncated, expected);
+ }
+
+ #[test]
+ fn test_center_truncate_handles_long_segment() {
+ let sep = std::path::MAIN_SEPARATOR;
+ let path = format!("~{sep}supercalifragilisticexpialidocious");
+ let truncated = center_truncate_path(&path, 18);
+
+ assert_eq!(truncated, format!("~{sep}…cexpialidocious"));
+ }
+
+ #[test]
+ fn test_format_json_compact_array() {
+ let json = r#"[ 1, 2, { "key": "value" }, "string" ]"#;
+ let result = format_json_compact(json).unwrap();
+ assert_eq!(result, r#"[1, 2, {"key": "value"}, "string"]"#);
+ }
+
+ #[test]
+ fn test_format_json_compact_already_compact() {
+ let json = r#"{"compact":true}"#;
+ let result = format_json_compact(json).unwrap();
+ assert_eq!(result, r#"{"compact": true}"#);
+ }
+
+ #[test]
+ fn test_format_json_compact_with_whitespace() {
+ let json = r#"
+ {
+ "name": "John",
+ "hobbies": [
+ "reading",
+ "coding"
+ ]
+ }
+ "#;
+ let result = format_json_compact(json).unwrap();
+ assert_eq!(
+ result,
+ r#"{"name": "John", "hobbies": ["reading", "coding"]}"#
+ );
+ }
+
+ #[test]
+ fn test_format_json_compact_invalid_json() {
+ let invalid_json = r#"{"invalid": json syntax}"#;
+ let result = format_json_compact(invalid_json);
+ assert!(result.is_none());
+ }
+
+ #[test]
+ fn test_format_json_compact_empty_object() {
+ let json = r#"{}"#;
+ let result = format_json_compact(json).unwrap();
+ assert_eq!(result, "{}");
+ }
+
+ #[test]
+ fn test_format_json_compact_empty_array() {
+ let json = r#"[]"#;
+ let result = format_json_compact(json).unwrap();
+ assert_eq!(result, "[]");
+ }
+
+ #[test]
+ fn test_format_json_compact_primitive_values() {
+ assert_eq!(format_json_compact("42").unwrap(), "42");
+ assert_eq!(format_json_compact("true").unwrap(), "true");
+ assert_eq!(format_json_compact("false").unwrap(), "false");
+ assert_eq!(format_json_compact("null").unwrap(), "null");
+ assert_eq!(format_json_compact(r#""string""#).unwrap(), r#""string""#);
+ }
+}
diff --git a/codex-rs/tui2/src/tooltips.rs b/codex-rs/tui2/src/tooltips.rs
new file mode 100644
index 0000000000..eb419c2ea3
--- /dev/null
+++ b/codex-rs/tui2/src/tooltips.rs
@@ -0,0 +1,49 @@
+use lazy_static::lazy_static;
+use rand::Rng;
+
+const RAW_TOOLTIPS: &str = include_str!("../tooltips.txt");
+
+lazy_static! {
+ static ref TOOLTIPS: Vec<&'static str> = RAW_TOOLTIPS
+ .lines()
+ .map(str::trim)
+ .filter(|line| !line.is_empty() && !line.starts_with('#'))
+ .collect();
+}
+
+pub(crate) fn random_tooltip() -> Option<&'static str> {
+ let mut rng = rand::rng();
+ pick_tooltip(&mut rng)
+}
+
+fn pick_tooltip<R: Rng + ?Sized>(rng: &mut R) -> Option<&'static str> {
+ if TOOLTIPS.is_empty() {
+ None
+ } else {
+ TOOLTIPS.get(rng.random_range(0..TOOLTIPS.len())).copied()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use rand::SeedableRng;
+ use rand::rngs::StdRng;
+
+ #[test]
+ fn random_tooltip_returns_some_tip_when_available() {
+ let mut rng = StdRng::seed_from_u64(42);
+ assert!(pick_tooltip(&mut rng).is_some());
+ }
+
+ #[test]
+ fn random_tooltip_is_reproducible_with_seed() {
+ let expected = {
+ let mut rng = StdRng::seed_from_u64(7);
+ pick_tooltip(&mut rng)
+ };
+
+ let mut rng = StdRng::seed_from_u64(7);
+ assert_eq!(expected, pick_tooltip(&mut rng));
+ }
+}
diff --git a/codex-rs/tui2/src/tui.rs b/codex-rs/tui2/src/tui.rs
new file mode 100644
index 0000000000..5502b83356
--- /dev/null
+++ b/codex-rs/tui2/src/tui.rs
@@ -0,0 +1,441 @@
+use std::fmt;
+use std::io::IsTerminal;
+use std::io::Result;
+use std::io::Stdout;
+use std::io::stdin;
+use std::io::stdout;
+use std::panic;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::sync::atomic::AtomicBool;
+use std::sync::atomic::Ordering;
+
+use crossterm::Command;
+use crossterm::SynchronizedUpdate;
+use crossterm::event::DisableBracketedPaste;
+use crossterm::event::DisableFocusChange;
+use crossterm::event::EnableBracketedPaste;
+use crossterm::event::EnableFocusChange;
+use crossterm::event::Event;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyboardEnhancementFlags;
+use crossterm::event::PopKeyboardEnhancementFlags;
+use crossterm::event::PushKeyboardEnhancementFlags;
+use crossterm::terminal::EnterAlternateScreen;
+use crossterm::terminal::LeaveAlternateScreen;
+use crossterm::terminal::supports_keyboard_enhancement;
+use ratatui::backend::Backend;
+use ratatui::backend::CrosstermBackend;
+use ratatui::crossterm::execute;
+use ratatui::crossterm::terminal::disable_raw_mode;
+use ratatui::crossterm::terminal::enable_raw_mode;
+use ratatui::layout::Offset;
+use ratatui::layout::Rect;
+use ratatui::text::Line;
+use tokio::select;
+use tokio::sync::broadcast;
+use tokio_stream::Stream;
+
+pub use self::frame_requester::FrameRequester;
+use crate::custom_terminal;
+use crate::custom_terminal::Terminal as CustomTerminal;
+#[cfg(unix)]
+use crate::tui::job_control::SUSPEND_KEY;
+#[cfg(unix)]
+use crate::tui::job_control::SuspendContext;
+
+mod frame_requester;
+#[cfg(unix)]
+mod job_control;
+
+/// A type alias for the terminal type used in this application
+pub type Terminal = CustomTerminal<CrosstermBackend<Stdout>>;
+
+pub fn set_modes() -> Result<()> {
+ execute!(stdout(), EnableBracketedPaste)?;
+
+ enable_raw_mode()?;
+ // Enable keyboard enhancement flags so modifiers for keys like Enter are disambiguated.
+ // chat_composer.rs is using a keyboard event listener to enter for any modified keys
+ // to create a new line that require this.
+ // Some terminals (notably legacy Windows consoles) do not support
+ // keyboard enhancement flags. Attempt to enable them, but continue
+ // gracefully if unsupported.
+ let _ = execute!(
+ stdout(),
+ PushKeyboardEnhancementFlags(
+ KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
+ | KeyboardEnhancementFlags::REPORT_EVENT_TYPES
+ | KeyboardEnhancementFlags::REPORT_ALTERNATE_KEYS
+ )
+ );
+
+ let _ = execute!(stdout(), EnableFocusChange);
+ Ok(())
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct EnableAlternateScroll;
+
+impl Command for EnableAlternateScroll {
+ fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
+ write!(f, "\x1b[?1007h")
+ }
+
+ #[cfg(windows)]
+ fn execute_winapi(&self) -> Result<()> {
+ Err(std::io::Error::other(
+ "tried to execute EnableAlternateScroll using WinAPI; use ANSI instead",
+ ))
+ }
+
+ #[cfg(windows)]
+ fn is_ansi_code_supported(&self) -> bool {
+ true
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct DisableAlternateScroll;
+
+impl Command for DisableAlternateScroll {
+ fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
+ write!(f, "\x1b[?1007l")
+ }
+
+ #[cfg(windows)]
+ fn execute_winapi(&self) -> Result<()> {
+ Err(std::io::Error::other(
+ "tried to execute DisableAlternateScroll using WinAPI; use ANSI instead",
+ ))
+ }
+
+ #[cfg(windows)]
+ fn is_ansi_code_supported(&self) -> bool {
+ true
+ }
+}
+
+/// Restore the terminal to its original state.
+/// Inverse of `set_modes`.
+pub fn restore() -> Result<()> {
+ // Pop may fail on platforms that didn't support the push; ignore errors.
+ let _ = execute!(stdout(), PopKeyboardEnhancementFlags);
+ execute!(stdout(), DisableBracketedPaste)?;
+ let _ = execute!(stdout(), DisableFocusChange);
+ disable_raw_mode()?;
+ let _ = execute!(stdout(), crossterm::cursor::Show);
+ Ok(())
+}
+
+/// Initialize the terminal (inline viewport; history stays in normal scrollback)
+pub fn init() -> Result<Terminal> {
+ if !stdin().is_terminal() {
+ return Err(std::io::Error::other("stdin is not a terminal"));
+ }
+ if !stdout().is_terminal() {
+ return Err(std::io::Error::other("stdout is not a terminal"));
+ }
+ set_modes()?;
+
+ set_panic_hook();
+
+ let backend = CrosstermBackend::new(stdout());
+ let tui = CustomTerminal::with_options(backend)?;
+ Ok(tui)
+}
+
+fn set_panic_hook() {
+ let hook = panic::take_hook();
+ panic::set_hook(Box::new(move |panic_info| {
+ let _ = restore(); // ignore any errors as we are already failing
+ hook(panic_info);
+ }));
+}
+
+#[derive(Debug)]
+pub enum TuiEvent {
+ Key(KeyEvent),
+ Paste(String),
+ Draw,
+}
+
+pub struct Tui {
+ frame_requester: FrameRequester,
+ draw_tx: broadcast::Sender<()>,
+ pub(crate) terminal: Terminal,
+ pending_history_lines: Vec<Line<'static>>,
+ alt_saved_viewport: Option<ratatui::layout::Rect>,
+ #[cfg(unix)]
+ suspend_context: SuspendContext,
+ // True when overlay alt-screen UI is active
+ alt_screen_active: Arc<AtomicBool>,
+ // True when terminal/tab is focused; updated internally from crossterm events
+ terminal_focused: Arc<AtomicBool>,
+ enhanced_keys_supported: bool,
+}
+
+impl Tui {
+ pub fn new(terminal: Terminal) -> Self {
+ let (draw_tx, _) = broadcast::channel(1);
+ let frame_requester = FrameRequester::new(draw_tx.clone());
+
+ // Detect keyboard enhancement support before any EventStream is created so the
+ // crossterm poller can acquire its lock without contention.
+ let enhanced_keys_supported = supports_keyboard_enhancement().unwrap_or(false);
+ // Cache this to avoid contention with the event reader.
+ supports_color::on_cached(supports_color::Stream::Stdout);
+ let _ = crate::terminal_palette::default_colors();
+
+ Self {
+ frame_requester,
+ draw_tx,
+ terminal,
+ pending_history_lines: vec![],
+ alt_saved_viewport: None,
+ #[cfg(unix)]
+ suspend_context: SuspendContext::new(),
+ alt_screen_active: Arc::new(AtomicBool::new(false)),
+ terminal_focused: Arc::new(AtomicBool::new(true)),
+ enhanced_keys_supported,
+ }
+ }
+
+ pub fn frame_requester(&self) -> FrameRequester {
+ self.frame_requester.clone()
+ }
+
+ pub fn enhanced_keys_supported(&self) -> bool {
+ self.enhanced_keys_supported
+ }
+
+ /// Emit a desktop notification now if the terminal is unfocused.
+ /// Returns true if a notification was posted.
+ pub fn notify(&mut self, message: impl AsRef<str>) -> bool {
+ if !self.terminal_focused.load(Ordering::Relaxed) {
+ let _ = execute!(stdout(), PostNotification(message.as_ref().to_string()));
+ true
+ } else {
+ false
+ }
+ }
+
+ pub fn event_stream(&self) -> Pin<Box<dyn Stream<Item = TuiEvent> + Send + 'static>> {
+ use tokio_stream::StreamExt;
+
+ let mut crossterm_events = crossterm::event::EventStream::new();
+ let mut draw_rx = self.draw_tx.subscribe();
+
+ // State for tracking how we should resume from ^Z suspend.
+ #[cfg(unix)]
+ let suspend_context = self.suspend_context.clone();
+ #[cfg(unix)]
+ let alt_screen_active = self.alt_screen_active.clone();
+
+ let terminal_focused = self.terminal_focused.clone();
+ let event_stream = async_stream::stream! {
+ loop {
+ select! {
+ Some(Ok(event)) = crossterm_events.next() => {
+ match event {
+ Event::Key(key_event) => {
+ #[cfg(unix)]
+ if SUSPEND_KEY.is_press(key_event) {
+ let _ = suspend_context.suspend(&alt_screen_active);
+ // We continue here after resume.
+ yield TuiEvent::Draw;
+ continue;
+ }
+ yield TuiEvent::Key(key_event);
+ }
+ Event::Resize(_, _) => {
+ yield TuiEvent::Draw;
+ }
+ Event::Paste(pasted) => {
+ yield TuiEvent::Paste(pasted);
+ }
+ Event::FocusGained => {
+ terminal_focused.store(true, Ordering::Relaxed);
+ crate::terminal_palette::requery_default_colors();
+ yield TuiEvent::Draw;
+ }
+ Event::FocusLost => {
+ terminal_focused.store(false, Ordering::Relaxed);
+ }
+ _ => {}
+ }
+ }
+ result = draw_rx.recv() => {
+ match result {
+ Ok(_) => {
+ yield TuiEvent::Draw;
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
+ // We dropped one or more draw notifications; coalesce to a single draw.
+ yield TuiEvent::Draw;
+ }
+ Err(tokio::sync::broadcast::error::RecvError::Closed) => {
+ // Sender dropped; stop emitting draws from this source.
+ }
+ }
+ }
+ }
+ }
+ };
+ Box::pin(event_stream)
+ }
+
+ /// Enter alternate screen and expand the viewport to full terminal size, saving the current
+ /// inline viewport for restoration when leaving.
+ pub fn enter_alt_screen(&mut self) -> Result<()> {
+ let _ = execute!(self.terminal.backend_mut(), EnterAlternateScreen);
+ // Enable "alternate scroll" so terminals may translate wheel to arrows
+ let _ = execute!(self.terminal.backend_mut(), EnableAlternateScroll);
+ if let Ok(size) = self.terminal.size() {
+ self.alt_saved_viewport = Some(self.terminal.viewport_area);
+ self.terminal.set_viewport_area(ratatui::layout::Rect::new(
+ 0,
+ 0,
+ size.width,
+ size.height,
+ ));
+ let _ = self.terminal.clear();
+ }
+ self.alt_screen_active.store(true, Ordering::Relaxed);
+ Ok(())
+ }
+
+ /// Leave alternate screen and restore the previously saved inline viewport, if any.
+ pub fn leave_alt_screen(&mut self) -> Result<()> {
+ // Disable alternate scroll when leaving alt-screen
+ let _ = execute!(self.terminal.backend_mut(), DisableAlternateScroll);
+ let _ = execute!(self.terminal.backend_mut(), LeaveAlternateScreen);
+ if let Some(saved) = self.alt_saved_viewport.take() {
+ self.terminal.set_viewport_area(saved);
+ }
+ self.alt_screen_active.store(false, Ordering::Relaxed);
+ Ok(())
+ }
+
+ pub fn insert_history_lines(&mut self, lines: Vec<Line<'static>>) {
+ self.pending_history_lines.extend(lines);
+ self.frame_requester().schedule_frame();
+ }
+
+ pub fn draw(
+ &mut self,
+ height: u16,
+ draw_fn: impl FnOnce(&mut custom_terminal::Frame),
+ ) -> Result<()> {
+ // If we are resuming from ^Z, we need to prepare the resume action now so we can apply it
+ // in the synchronized update.
+ #[cfg(unix)]
+ let mut prepared_resume = self
+ .suspend_context
+ .prepare_resume_action(&mut self.terminal, &mut self.alt_saved_viewport);
+
+ // Precompute any viewport updates that need a cursor-position query before entering
+ // the synchronized update, to avoid racing with the event reader.
+ let mut pending_viewport_area = self.pending_viewport_area()?;
+
+ stdout().sync_update(|_| {
+ #[cfg(unix)]
+ if let Some(prepared) = prepared_resume.take() {
+ prepared.apply(&mut self.terminal)?;
+ }
+
+ let terminal = &mut self.terminal;
+ if let Some(new_area) = pending_viewport_area.take() {
+ terminal.set_viewport_area(new_area);
+ terminal.clear()?;
+ }
+
+ let size = terminal.size()?;
+
+ let mut area = terminal.viewport_area;
+ area.height = height.min(size.height);
+ area.width = size.width;
+ // If the viewport has expanded, scroll everything else up to make room.
+ if area.bottom() > size.height {
+ terminal
+ .backend_mut()
+ .scroll_region_up(0..area.top(), area.bottom() - size.height)?;
+ area.y = size.height - area.height;
+ }
+ if area != terminal.viewport_area {
+ // TODO(nornagon): probably this could be collapsed with the clear + set_viewport_area above.
+ terminal.clear()?;
+ terminal.set_viewport_area(area);
+ }
+
+ if !self.pending_history_lines.is_empty() {
+ crate::insert_history::insert_history_lines(
+ terminal,
+ self.pending_history_lines.clone(),
+ )?;
+ self.pending_history_lines.clear();
+ }
+
+ // Update the y position for suspending so Ctrl-Z can place the cursor correctly.
+ #[cfg(unix)]
+ {
+ let inline_area_bottom = if self.alt_screen_active.load(Ordering::Relaxed) {
+ self.alt_saved_viewport
+ .map(|r| r.bottom().saturating_sub(1))
+ .unwrap_or_else(|| area.bottom().saturating_sub(1))
+ } else {
+ area.bottom().saturating_sub(1)
+ };
+ self.suspend_context.set_cursor_y(inline_area_bottom);
+ }
+
+ terminal.draw(|frame| {
+ draw_fn(frame);
+ })
+ })?
+ }
+
+ fn pending_viewport_area(&mut self) -> Result<Option<Rect>> {
+ let terminal = &mut self.terminal;
+ let screen_size = terminal.size()?;
+ let last_known_screen_size = terminal.last_known_screen_size;
+ if screen_size != last_known_screen_size
+ && let Ok(cursor_pos) = terminal.get_cursor_position()
+ {
+ let last_known_cursor_pos = terminal.last_known_cursor_pos;
+ // If we resized AND the cursor moved, we adjust the viewport area to keep the
+ // cursor in the same position. This is a heuristic that seems to work well
+ // at least in iTerm2.
+ if cursor_pos.y != last_known_cursor_pos.y {
+ let offset = Offset {
+ x: 0,
+ y: cursor_pos.y as i32 - last_known_cursor_pos.y as i32,
+ };
+ return Ok(Some(terminal.viewport_area.offset(offset)));
+ }
+ }
+ Ok(None)
+ }
+}
+
+/// Command that emits an OSC 9 desktop notification with a message.
+#[derive(Debug, Clone)]
+pub struct PostNotification(pub String);
+
+impl Command for PostNotification {
+ fn write_ansi(&self, f: &mut impl fmt::Write) -> fmt::Result {
+ write!(f, "\x1b]9;{}\x07", self.0)
+ }
+
+ #[cfg(windows)]
+ fn execute_winapi(&self) -> Result<()> {
+ Err(std::io::Error::other(
+ "tried to execute PostNotification using WinAPI; use ANSI instead",
+ ))
+ }
+
+ #[cfg(windows)]
+ fn is_ansi_code_supported(&self) -> bool {
+ true
+ }
+}
diff --git a/codex-rs/tui2/src/tui/frame_requester.rs b/codex-rs/tui2/src/tui/frame_requester.rs
new file mode 100644
index 0000000000..4f7886aa22
--- /dev/null
+++ b/codex-rs/tui2/src/tui/frame_requester.rs
@@ -0,0 +1,249 @@
+//! Frame draw scheduling utilities for the TUI.
+//!
+//! This module exposes [`FrameRequester`], a lightweight handle that widgets and
+//! background tasks can clone to request future redraws of the TUI.
+//!
+//! Internally it spawns a [`FrameScheduler`] task that coalesces many requests
+//! into a single notification on a broadcast channel used by the main TUI event
+//! loop. This keeps animations and status updates smooth without redrawing more
+//! often than necessary.
+//!
+//! This follows the actor-style design from
+//! [“Actors with Tokio”](https://ryhl.io/blog/actors-with-tokio/), with a
+//! dedicated scheduler task and lightweight request handles.
+
+use std::time::Duration;
+use std::time::Instant;
+
+use tokio::sync::broadcast;
+use tokio::sync::mpsc;
+
+/// A requester for scheduling future frame draws on the TUI event loop.
+///
+/// This is the handler side of an actor/handler pair with `FrameScheduler`, which coalesces
+/// multiple frame requests into a single draw operation.
+///
+/// Clones of this type can be freely shared across tasks to make it possible to trigger frame draws
+/// from anywhere in the TUI code.
+#[derive(Clone, Debug)]
+pub struct FrameRequester {
+ frame_schedule_tx: mpsc::UnboundedSender<Instant>,
+}
+
+impl FrameRequester {
+ /// Create a new FrameRequester and spawn its associated FrameScheduler task.
+ ///
+ /// The provided `draw_tx` is used to notify the TUI event loop of scheduled draws.
+ pub fn new(draw_tx: broadcast::Sender<()>) -> Self {
+ let (tx, rx) = mpsc::unbounded_channel();
+ let scheduler = FrameScheduler::new(rx, draw_tx);
+ tokio::spawn(scheduler.run());
+ Self {
+ frame_schedule_tx: tx,
+ }
+ }
+
+ /// Schedule a frame draw as soon as possible.
+ pub fn schedule_frame(&self) {
+ let _ = self.frame_schedule_tx.send(Instant::now());
+ }
+
+ /// Schedule a frame draw to occur after the specified duration.
+ pub fn schedule_frame_in(&self, dur: Duration) {
+ let _ = self.frame_schedule_tx.send(Instant::now() + dur);
+ }
+}
+
+#[cfg(test)]
+impl FrameRequester {
+ /// Create a no-op frame requester for tests.
+ pub(crate) fn test_dummy() -> Self {
+ let (tx, _rx) = mpsc::unbounded_channel();
+ FrameRequester {
+ frame_schedule_tx: tx,
+ }
+ }
+}
+
+/// A scheduler for coalescing frame draw requests and notifying the TUI event loop.
+///
+/// This type is internal to `FrameRequester` and is spawned as a task to handle scheduling logic.
+struct FrameScheduler {
+ receiver: mpsc::UnboundedReceiver<Instant>,
+ draw_tx: broadcast::Sender<()>,
+}
+
+impl FrameScheduler {
+ /// Create a new FrameScheduler with the provided receiver and draw notification sender.
+ fn new(receiver: mpsc::UnboundedReceiver<Instant>, draw_tx: broadcast::Sender<()>) -> Self {
+ Self { receiver, draw_tx }
+ }
+
+ /// Run the scheduling loop, coalescing frame requests and notifying the TUI event loop.
+ ///
+ /// This method runs indefinitely until all senders are dropped. A single draw notification
+ /// is sent for multiple requests scheduled before the next draw deadline.
+ async fn run(mut self) {
+ const ONE_YEAR: Duration = Duration::from_secs(60 * 60 * 24 * 365);
+ let mut next_deadline: Option<Instant> = None;
+ loop {
+ let target = next_deadline.unwrap_or_else(|| Instant::now() + ONE_YEAR);
+ let deadline = tokio::time::sleep_until(target.into());
+ tokio::pin!(deadline);
+
+ tokio::select! {
+ draw_at = self.receiver.recv() => {
+ let Some(draw_at) = draw_at else {
+ // All senders dropped; exit the scheduler.
+ break
+ };
+ next_deadline = Some(next_deadline.map_or(draw_at, |cur| cur.min(draw_at)));
+
+ // Do not send a draw immediately here. By continuing the loop,
+ // we recompute the sleep target so the draw fires once via the
+ // sleep branch, coalescing multiple requests into a single draw.
+ continue;
+ }
+ _ = &mut deadline => {
+ if next_deadline.is_some() {
+ next_deadline = None;
+ let _ = self.draw_tx.send(());
+ }
+ }
+ }
+ }
+ }
+}
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tokio::time;
+ use tokio_util::time::FutureExt;
+
+ #[tokio::test(flavor = "current_thread", start_paused = true)]
+ async fn test_schedule_frame_immediate_triggers_once() {
+ let (draw_tx, mut draw_rx) = broadcast::channel(16);
+ let requester = FrameRequester::new(draw_tx);
+
+ requester.schedule_frame();
+
+ // Advance time minimally to let the scheduler process and hit the deadline == now.
+ time::advance(Duration::from_millis(1)).await;
+
+ // First draw should arrive.
+ let first = draw_rx
+ .recv()
+ .timeout(Duration::from_millis(50))
+ .await
+ .expect("timed out waiting for first draw");
+ assert!(first.is_ok(), "broadcast closed unexpectedly");
+
+ // No second draw should arrive.
+ let second = draw_rx.recv().timeout(Duration::from_millis(20)).await;
+ assert!(second.is_err(), "unexpected extra draw received");
+ }
+
+ #[tokio::test(flavor = "current_thread", start_paused = true)]
+ async fn test_schedule_frame_in_triggers_at_delay() {
+ let (draw_tx, mut draw_rx) = broadcast::channel(16);
+ let requester = FrameRequester::new(draw_tx);
+
+ requester.schedule_frame_in(Duration::from_millis(50));
+
+ // Advance less than the delay: no draw yet.
+ time::advance(Duration::from_millis(30)).await;
+ let early = draw_rx.recv().timeout(Duration::from_millis(10)).await;
+ assert!(early.is_err(), "draw fired too early");
+
+ // Advance past the deadline: one draw should fire.
+ time::advance(Duration::from_millis(25)).await;
+ let first = draw_rx
+ .recv()
+ .timeout(Duration::from_millis(50))
+ .await
+ .expect("timed out waiting for scheduled draw");
+ assert!(first.is_ok(), "broadcast closed unexpectedly");
+
+ // No second draw should arrive.
+ let second = draw_rx.recv().timeout(Duration::from_millis(20)).await;
+ assert!(second.is_err(), "unexpected extra draw received");
+ }
+
+ #[tokio::test(flavor = "current_thread", start_paused = true)]
+ async fn test_coalesces_multiple_requests_into_single_draw() {
+ let (draw_tx, mut draw_rx) = broadcast::channel(16);
+ let requester = FrameRequester::new(draw_tx);
+
+ // Schedule multiple immediate requests close together.
+ requester.schedule_frame();
+ requester.schedule_frame();
+ requester.schedule_frame();
+
+ // Allow the scheduler to process and hit the coalesced deadline.
+ time::advance(Duration::from_millis(1)).await;
+
+ // Expect only a single draw notification despite three requests.
+ let first = draw_rx
+ .recv()
+ .timeout(Duration::from_millis(50))
+ .await
+ .expect("timed out waiting for coalesced draw");
+ assert!(first.is_ok(), "broadcast closed unexpectedly");
+
+ // No additional draw should be sent for the same coalesced batch.
+ let second = draw_rx.recv().timeout(Duration::from_millis(20)).await;
+ assert!(second.is_err(), "unexpected extra draw received");
+ }
+
+ #[tokio::test(flavor = "current_thread", start_paused = true)]
+ async fn test_coalesces_mixed_immediate_and_delayed_requests() {
+ let (draw_tx, mut draw_rx) = broadcast::channel(16);
+ let requester = FrameRequester::new(draw_tx);
+
+ // Schedule a delayed draw and then an immediate one; should coalesce and fire at the earliest (immediate).
+ requester.schedule_frame_in(Duration::from_millis(100));
+ requester.schedule_frame();
+
+ time::advance(Duration::from_millis(1)).await;
+
+ let first = draw_rx
+ .recv()
+ .timeout(Duration::from_millis(50))
+ .await
+ .expect("timed out waiting for coalesced immediate draw");
+ assert!(first.is_ok(), "broadcast closed unexpectedly");
+
+ // The later delayed request should have been coalesced into the earlier one; no second draw.
+ let second = draw_rx.recv().timeout(Duration::from_millis(120)).await;
+ assert!(second.is_err(), "unexpected extra draw received");
+ }
+
+ #[tokio::test(flavor = "current_thread", start_paused = true)]
+ async fn test_multiple_delayed_requests_coalesce_to_earliest() {
+ let (draw_tx, mut draw_rx) = broadcast::channel(16);
+ let requester = FrameRequester::new(draw_tx);
+
+ // Schedule multiple delayed draws; they should coalesce to the earliest (10ms).
+ requester.schedule_frame_in(Duration::from_millis(100));
+ requester.schedule_frame_in(Duration::from_millis(20));
+ requester.schedule_frame_in(Duration::from_millis(120));
+
+ // Advance to just before the earliest deadline: no draw yet.
+ time::advance(Duration::from_millis(10)).await;
+ let early = draw_rx.recv().timeout(Duration::from_millis(10)).await;
+ assert!(early.is_err(), "draw fired too early");
+
+ // Advance past the earliest deadline: one draw should fire.
+ time::advance(Duration::from_millis(20)).await;
+ let first = draw_rx
+ .recv()
+ .timeout(Duration::from_millis(50))
+ .await
+ .expect("timed out waiting for earliest coalesced draw");
+ assert!(first.is_ok(), "broadcast closed unexpectedly");
+
+ // No additional draw should fire for the later delayed requests.
+ let second = draw_rx.recv().timeout(Duration::from_millis(120)).await;
+ assert!(second.is_err(), "unexpected extra draw received");
+ }
+}
diff --git a/codex-rs/tui2/src/tui/job_control.rs b/codex-rs/tui2/src/tui/job_control.rs
new file mode 100644
index 0000000000..3680419489
--- /dev/null
+++ b/codex-rs/tui2/src/tui/job_control.rs
@@ -0,0 +1,182 @@
+use std::io::Result;
+use std::io::stdout;
+use std::sync::Arc;
+use std::sync::Mutex;
+use std::sync::PoisonError;
+use std::sync::atomic::AtomicBool;
+use std::sync::atomic::AtomicU16;
+use std::sync::atomic::Ordering;
+
+use crossterm::cursor::MoveTo;
+use crossterm::cursor::Show;
+use crossterm::event::KeyCode;
+use crossterm::terminal::EnterAlternateScreen;
+use crossterm::terminal::LeaveAlternateScreen;
+use ratatui::crossterm::execute;
+use ratatui::layout::Position;
+use ratatui::layout::Rect;
+
+use crate::key_hint;
+
+use super::DisableAlternateScroll;
+use super::EnableAlternateScroll;
+use super::Terminal;
+
+pub const SUSPEND_KEY: key_hint::KeyBinding = key_hint::ctrl(KeyCode::Char('z'));
+
+/// Coordinates suspend/resume handling so the TUI can restore terminal context after SIGTSTP.
+///
+/// On suspend, it records which resume path to take (realign inline viewport vs. restore alt
+/// screen) and caches the inline cursor row so the cursor can be placed meaningfully before
+/// yielding.
+///
+/// After resume, `prepare_resume_action` consumes the pending intent and returns a
+/// `PreparedResumeAction` describing any viewport adjustments to apply inside the synchronized
+/// draw.
+///
+/// Callers keep `suspend_cursor_y` up to date during normal drawing so the suspend step always
+/// has the latest cursor position.
+///
+/// The type is `Clone`, using Arc/atomic internals so bookkeeping can be shared across tasks
+/// and moved into the boxed `'static` event stream without borrowing `self`.
+#[derive(Clone)]
+pub struct SuspendContext {
+ /// Resume intent captured at suspend time; cleared once applied after resume.
+ resume_pending: Arc<Mutex<Option<ResumeAction>>>,
+ /// Inline viewport cursor row used to place the cursor before yielding during suspend.
+ suspend_cursor_y: Arc<AtomicU16>,
+}
+
+impl SuspendContext {
+ pub(crate) fn new() -> Self {
+ Self {
+ resume_pending: Arc::new(Mutex::new(None)),
+ suspend_cursor_y: Arc::new(AtomicU16::new(0)),
+ }
+ }
+
+ /// Capture how to resume, stash cursor position, and temporarily yield during SIGTSTP.
+ ///
+ /// - If the alt screen is active, exit alt-scroll/alt-screen and record `RestoreAlt`;
+ /// otherwise record `RealignInline`.
+ /// - Update the cached inline cursor row so suspend can place the cursor meaningfully.
+ /// - Trigger SIGTSTP so the process can be resumed and continue drawing with the saved state.
+ pub(crate) fn suspend(&self, alt_screen_active: &Arc<AtomicBool>) -> Result<()> {
+ if alt_screen_active.load(Ordering::Relaxed) {
+ // Leave alt-screen so the terminal returns to the normal buffer while suspended; also turn off alt-scroll.
+ let _ = execute!(stdout(), DisableAlternateScroll);
+ let _ = execute!(stdout(), LeaveAlternateScreen);
+ self.set_resume_action(ResumeAction::RestoreAlt);
+ } else {
+ self.set_resume_action(ResumeAction::RealignInline);
+ }
+ let y = self.suspend_cursor_y.load(Ordering::Relaxed);
+ let _ = execute!(stdout(), MoveTo(0, y), Show);
+ suspend_process()
+ }
+
+ /// Consume the pending resume intent and precompute any viewport changes needed post-resume.
+ ///
+ /// Returns a `PreparedResumeAction` describing how to realign the viewport once drawing
+ /// resumes; returns `None` when there was no pending suspend intent.
+ pub(crate) fn prepare_resume_action(
+ &self,
+ terminal: &mut Terminal,
+ alt_saved_viewport: &mut Option<Rect>,
+ ) -> Option<PreparedResumeAction> {
+ let action = self.take_resume_action()?;
+ match action {
+ ResumeAction::RealignInline => {
+ let cursor_pos = terminal
+ .get_cursor_position()
+ .unwrap_or(terminal.last_known_cursor_pos);
+ let viewport = Rect::new(0, cursor_pos.y, 0, 0);
+ Some(PreparedResumeAction::RealignViewport(viewport))
+ }
+ ResumeAction::RestoreAlt => {
+ if let Ok(Position { y, .. }) = terminal.get_cursor_position()
+ && let Some(saved) = alt_saved_viewport.as_mut()
+ {
+ saved.y = y;
+ }
+ Some(PreparedResumeAction::RestoreAltScreen)
+ }
+ }
+ }
+
+ /// Set the cached inline cursor row so suspend can place the cursor meaningfully.
+ ///
+ /// Call during normal drawing when the inline viewport moves so suspend has a fresh cursor
+ /// position to restore before yielding.
+ pub(crate) fn set_cursor_y(&self, value: u16) {
+ self.suspend_cursor_y.store(value, Ordering::Relaxed);
+ }
+
+ /// Record a pending resume action to apply after SIGTSTP returns control.
+ fn set_resume_action(&self, value: ResumeAction) {
+ *self
+ .resume_pending
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner) = Some(value);
+ }
+
+ /// Take and clear any pending resume action captured at suspend time.
+ fn take_resume_action(&self) -> Option<ResumeAction> {
+ self.resume_pending
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .take()
+ }
+}
+
+/// Captures what should happen when returning from suspend.
+///
+/// Either realign the inline viewport to keep the cursor position, or re-enter the alt screen
+/// to restore the overlay UI.
+#[derive(Copy, Clone, Debug, Eq, PartialEq)]
+pub(crate) enum ResumeAction {
+ /// Shift the inline viewport to keep the cursor anchored after resume.
+ RealignInline,
+ /// Re-enter the alt screen and restore the overlay UI.
+ RestoreAlt,
+}
+
+/// Describes the viewport change to apply when resuming from suspend during the synchronized draw.
+///
+/// Either restore the alt screen (with viewport reset) or realign the inline viewport.
+#[derive(Clone, Debug)]
+pub(crate) enum PreparedResumeAction {
+ /// Re-enter the alt screen and reset the viewport to the terminal dimensions.
+ RestoreAltScreen,
+ /// Apply a viewport shift to keep the inline cursor position stable.
+ RealignViewport(Rect),
+}
+
+impl PreparedResumeAction {
+ pub(crate) fn apply(self, terminal: &mut Terminal) -> Result<()> {
+ match self {
+ PreparedResumeAction::RealignViewport(area) => {
+ terminal.set_viewport_area(area);
+ }
+ PreparedResumeAction::RestoreAltScreen => {
+ execute!(terminal.backend_mut(), EnterAlternateScreen)?;
+ // Enable "alternate scroll" so terminals may translate wheel to arrows
+ execute!(terminal.backend_mut(), EnableAlternateScroll)?;
+ if let Ok(size) = terminal.size() {
+ terminal.set_viewport_area(Rect::new(0, 0, size.width, size.height));
+ terminal.clear()?;
+ }
+ }
+ }
+ Ok(())
+ }
+}
+
+/// Deliver SIGTSTP after restoring terminal state, then re-applies terminal modes once resumed.
+fn suspend_process() -> Result<()> {
+ super::restore()?;
+ unsafe { libc::kill(0, libc::SIGTSTP) };
+ // After the process resumes, reapply terminal modes so drawing can continue.
+ super::set_modes()?;
+ Ok(())
+}
diff --git a/codex-rs/tui2/src/ui_consts.rs b/codex-rs/tui2/src/ui_consts.rs
new file mode 100644
index 0000000000..ebbe4ce366
--- /dev/null
+++ b/codex-rs/tui2/src/ui_consts.rs
@@ -0,0 +1,11 @@
+//! Shared UI constants for layout and alignment within the TUI.
+
+/// Width (in terminal columns) reserved for the left gutter/prefix used by
+/// live cells and aligned widgets.
+///
+/// Semantics:
+/// - Chat composer reserves this many columns for the left border + padding.
+/// - Status indicator lines begin with this many spaces for alignment.
+/// - User history lines account for this many columns (e.g., "▌ ") when wrapping.
+pub(crate) const LIVE_PREFIX_COLS: u16 = 2;
+pub(crate) const FOOTER_INDENT_COLS: usize = LIVE_PREFIX_COLS as usize;
diff --git a/codex-rs/tui2/src/update_action.rs b/codex-rs/tui2/src/update_action.rs
new file mode 100644
index 0000000000..e2cb7b6733
--- /dev/null
+++ b/codex-rs/tui2/src/update_action.rs
@@ -0,0 +1,115 @@
+/// Update action the CLI should perform after the TUI exits.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UpdateAction {
+ /// Update via `npm install -g @openai/codex@latest`.
+ NpmGlobalLatest,
+ /// Update via `bun install -g @openai/codex@latest`.
+ BunGlobalLatest,
+ /// Update via `brew upgrade codex`.
+ BrewUpgrade,
+}
+
+impl From<UpdateAction> for codex_tui::update_action::UpdateAction {
+ fn from(action: UpdateAction) -> Self {
+ match action {
+ UpdateAction::NpmGlobalLatest => {
+ codex_tui::update_action::UpdateAction::NpmGlobalLatest
+ }
+ UpdateAction::BunGlobalLatest => {
+ codex_tui::update_action::UpdateAction::BunGlobalLatest
+ }
+ UpdateAction::BrewUpgrade => codex_tui::update_action::UpdateAction::BrewUpgrade,
+ }
+ }
+}
+
+impl UpdateAction {
+ /// Returns the list of command-line arguments for invoking the update.
+ pub fn command_args(self) -> (&'static str, &'static [&'static str]) {
+ match self {
+ UpdateAction::NpmGlobalLatest => ("npm", &["install", "-g", "@openai/codex"]),
+ UpdateAction::BunGlobalLatest => ("bun", &["install", "-g", "@openai/codex"]),
+ UpdateAction::BrewUpgrade => ("brew", &["upgrade", "codex"]),
+ }
+ }
+
+ /// Returns string representation of the command-line arguments for invoking the update.
+ pub fn command_str(self) -> String {
+ let (command, args) = self.command_args();
+ shlex::try_join(std::iter::once(command).chain(args.iter().copied()))
+ .unwrap_or_else(|_| format!("{command} {}", args.join(" ")))
+ }
+}
+
+#[cfg(not(debug_assertions))]
+pub(crate) fn get_update_action() -> Option<UpdateAction> {
+ let exe = std::env::current_exe().unwrap_or_default();
+ let managed_by_npm = std::env::var_os("CODEX_MANAGED_BY_NPM").is_some();
+ let managed_by_bun = std::env::var_os("CODEX_MANAGED_BY_BUN").is_some();
+
+ detect_update_action(
+ cfg!(target_os = "macos"),
+ &exe,
+ managed_by_npm,
+ managed_by_bun,
+ )
+}
+
+#[cfg(any(not(debug_assertions), test))]
+fn detect_update_action(
+ is_macos: bool,
+ current_exe: &std::path::Path,
+ managed_by_npm: bool,
+ managed_by_bun: bool,
+) -> Option<UpdateAction> {
+ if managed_by_npm {
+ Some(UpdateAction::NpmGlobalLatest)
+ } else if managed_by_bun {
+ Some(UpdateAction::BunGlobalLatest)
+ } else if is_macos
+ && (current_exe.starts_with("/opt/homebrew") || current_exe.starts_with("/usr/local"))
+ {
+ Some(UpdateAction::BrewUpgrade)
+ } else {
+ None
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn detects_update_action_without_env_mutation() {
+ assert_eq!(
+ detect_update_action(false, std::path::Path::new("/any/path"), false, false),
+ None
+ );
+ assert_eq!(
+ detect_update_action(false, std::path::Path::new("/any/path"), true, false),
+ Some(UpdateAction::NpmGlobalLatest)
+ );
+ assert_eq!(
+ detect_update_action(false, std::path::Path::new("/any/path"), false, true),
+ Some(UpdateAction::BunGlobalLatest)
+ );
+ assert_eq!(
+ detect_update_action(
+ true,
+ std::path::Path::new("/opt/homebrew/bin/codex"),
+ false,
+ false
+ ),
+ Some(UpdateAction::BrewUpgrade)
+ );
+ assert_eq!(
+ detect_update_action(
+ true,
+ std::path::Path::new("/usr/local/bin/codex"),
+ false,
+ false
+ ),
+ Some(UpdateAction::BrewUpgrade)
+ );
+ }
+}
diff --git a/codex-rs/tui2/src/update_prompt.rs b/codex-rs/tui2/src/update_prompt.rs
new file mode 100644
index 0000000000..43ee0dbd40
--- /dev/null
+++ b/codex-rs/tui2/src/update_prompt.rs
@@ -0,0 +1,313 @@
+#![cfg(not(debug_assertions))]
+
+use crate::history_cell::padded_emoji;
+use crate::key_hint;
+use crate::render::Insets;
+use crate::render::renderable::ColumnRenderable;
+use crate::render::renderable::Renderable;
+use crate::render::renderable::RenderableExt as _;
+use crate::selection_list::selection_option_row;
+use crate::tui::FrameRequester;
+use crate::tui::Tui;
+use crate::tui::TuiEvent;
+use crate::update_action::UpdateAction;
+use crate::updates;
+use codex_core::config::Config;
+use color_eyre::Result;
+use crossterm::event::KeyCode;
+use crossterm::event::KeyEvent;
+use crossterm::event::KeyEventKind;
+use crossterm::event::KeyModifiers;
+use ratatui::buffer::Buffer;
+use ratatui::layout::Rect;
+use ratatui::prelude::Widget;
+use ratatui::style::Stylize as _;
+use ratatui::text::Line;
+use ratatui::widgets::Clear;
+use ratatui::widgets::WidgetRef;
+use tokio_stream::StreamExt;
+
+pub(crate) enum UpdatePromptOutcome {
+ Continue,
+ RunUpdate(UpdateAction),
+}
+
+pub(crate) async fn run_update_prompt_if_needed(
+ tui: &mut Tui,
+ config: &Config,
+) -> Result<UpdatePromptOutcome> {
+ let Some(latest_version) = updates::get_upgrade_version_for_popup(config) else {
+ return Ok(UpdatePromptOutcome::Continue);
+ };
+ let Some(update_action) = crate::update_action::get_update_action() else {
+ return Ok(UpdatePromptOutcome::Continue);
+ };
+
+ let mut screen =
+ UpdatePromptScreen::new(tui.frame_requester(), latest_version.clone(), update_action);
+ tui.draw(u16::MAX, |frame| {
+ frame.render_widget_ref(&screen, frame.area());
+ })?;
+
+ let events = tui.event_stream();
+ tokio::pin!(events);
+
+ while !screen.is_done() {
+ if let Some(event) = events.next().await {
+ match event {
+ TuiEvent::Key(key_event) => screen.handle_key(key_event),
+ TuiEvent::Paste(_) => {}
+ TuiEvent::Draw => {
+ tui.draw(u16::MAX, |frame| {
+ frame.render_widget_ref(&screen, frame.area());
+ })?;
+ }
+ }
+ } else {
+ break;
+ }
+ }
+
+ match screen.selection() {
+ Some(UpdateSelection::UpdateNow) => {
+ tui.terminal.clear()?;
+ Ok(UpdatePromptOutcome::RunUpdate(update_action))
+ }
+ Some(UpdateSelection::NotNow) | None => Ok(UpdatePromptOutcome::Continue),
+ Some(UpdateSelection::DontRemind) => {
+ if let Err(err) = updates::dismiss_version(config, screen.latest_version()).await {
+ tracing::error!("Failed to persist update dismissal: {err}");
+ }
+ Ok(UpdatePromptOutcome::Continue)
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum UpdateSelection {
+ UpdateNow,
+ NotNow,
+ DontRemind,
+}
+
+struct UpdatePromptScreen {
+ request_frame: FrameRequester,
+ latest_version: String,
+ current_version: String,
+ update_action: UpdateAction,
+ highlighted: UpdateSelection,
+ selection: Option<UpdateSelection>,
+}
+
+impl UpdatePromptScreen {
+ fn new(
+ request_frame: FrameRequester,
+ latest_version: String,
+ update_action: UpdateAction,
+ ) -> Self {
+ Self {
+ request_frame,
+ latest_version,
+ current_version: env!("CARGO_PKG_VERSION").to_string(),
+ update_action,
+ highlighted: UpdateSelection::UpdateNow,
+ selection: None,
+ }
+ }
+
+ fn handle_key(&mut self, key_event: KeyEvent) {
+ if key_event.kind == KeyEventKind::Release {
+ return;
+ }
+ if key_event.modifiers.contains(KeyModifiers::CONTROL)
+ && matches!(key_event.code, KeyCode::Char('c') | KeyCode::Char('d'))
+ {
+ self.select(UpdateSelection::NotNow);
+ return;
+ }
+ match key_event.code {
+ KeyCode::Up | KeyCode::Char('k') => self.set_highlight(self.highlighted.prev()),
+ KeyCode::Down | KeyCode::Char('j') => self.set_highlight(self.highlighted.next()),
+ KeyCode::Char('1') => self.select(UpdateSelection::UpdateNow),
+ KeyCode::Char('2') => self.select(UpdateSelection::NotNow),
+ KeyCode::Char('3') => self.select(UpdateSelection::DontRemind),
+ KeyCode::Enter => self.select(self.highlighted),
+ KeyCode::Esc => self.select(UpdateSelection::NotNow),
+ _ => {}
+ }
+ }
+
+ fn set_highlight(&mut self, highlight: UpdateSelection) {
+ if self.highlighted != highlight {
+ self.highlighted = highlight;
+ self.request_frame.schedule_frame();
+ }
+ }
+
+ fn select(&mut self, selection: UpdateSelection) {
+ self.highlighted = selection;
+ self.selection = Some(selection);
+ self.request_frame.schedule_frame();
+ }
+
+ fn is_done(&self) -> bool {
+ self.selection.is_some()
+ }
+
+ fn selection(&self) -> Option<UpdateSelection> {
+ self.selection
+ }
+
+ fn latest_version(&self) -> &str {
+ self.latest_version.as_str()
+ }
+}
+
+impl UpdateSelection {
+ fn next(self) -> Self {
+ match self {
+ UpdateSelection::UpdateNow => UpdateSelection::NotNow,
+ UpdateSelection::NotNow => UpdateSelection::DontRemind,
+ UpdateSelection::DontRemind => UpdateSelection::UpdateNow,
+ }
+ }
+
+ fn prev(self) -> Self {
+ match self {
+ UpdateSelection::UpdateNow => UpdateSelection::DontRemind,
+ UpdateSelection::NotNow => UpdateSelection::UpdateNow,
+ UpdateSelection::DontRemind => UpdateSelection::NotNow,
+ }
+ }
+}
+
+impl WidgetRef for &UpdatePromptScreen {
+ fn render_ref(&self, area: Rect, buf: &mut Buffer) {
+ Clear.render(area, buf);
+ let mut column = ColumnRenderable::new();
+
+ let update_command = self.update_action.command_str();
+
+ column.push("");
+ column.push(Line::from(vec![
+ padded_emoji(" ✨").bold().cyan(),
+ "Update available!".bold(),
+ " ".into(),
+ format!(
+ "{current} -> {latest}",
+ current = self.current_version,
+ latest = self.latest_version
+ )
+ .dim(),
+ ]));
+ column.push("");
+ column.push(
+ Line::from(vec![
+ "Release notes: ".dim(),
+ "https://github.com/openai/codex/releases/latest"
+ .dim()
+ .underlined(),
+ ])
+ .inset(Insets::tlbr(0, 2, 0, 0)),
+ );
+ column.push("");
+ column.push(selection_option_row(
+ 0,
+ format!("Update now (runs `{update_command}`)"),
+ self.highlighted == UpdateSelection::UpdateNow,
+ ));
+ column.push(selection_option_row(
+ 1,
+ "Skip".to_string(),
+ self.highlighted == UpdateSelection::NotNow,
+ ));
+ column.push(selection_option_row(
+ 2,
+ "Skip until next version".to_string(),
+ self.highlighted == UpdateSelection::DontRemind,
+ ));
+ column.push("");
+ column.push(
+ Line::from(vec![
+ "Press ".dim(),
+ key_hint::plain(KeyCode::Enter).into(),
+ " to continue".dim(),
+ ])
+ .inset(Insets::tlbr(0, 2, 0, 0)),
+ );
+ column.render(area, buf);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::test_backend::VT100Backend;
+ use crate::tui::FrameRequester;
+ use crossterm::event::KeyCode;
+ use crossterm::event::KeyEvent;
+ use crossterm::event::KeyModifiers;
+ use ratatui::Terminal;
+
+ fn new_prompt() -> UpdatePromptScreen {
+ UpdatePromptScreen::new(
+ FrameRequester::test_dummy(),
+ "9.9.9".into(),
+ UpdateAction::NpmGlobalLatest,
+ )
+ }
+
+ #[test]
+ fn update_prompt_snapshot() {
+ let screen = new_prompt();
+ let mut terminal = Terminal::new(VT100Backend::new(80, 12)).expect("terminal");
+ terminal
+ .draw(|frame| frame.render_widget_ref(&screen, frame.area()))
+ .expect("render update prompt");
+ insta::assert_snapshot!("update_prompt_modal", terminal.backend());
+ }
+
+ #[test]
+ fn update_prompt_confirm_selects_update() {
+ let mut screen = new_prompt();
+ screen.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ assert!(screen.is_done());
+ assert_eq!(screen.selection(), Some(UpdateSelection::UpdateNow));
+ }
+
+ #[test]
+ fn update_prompt_dismiss_option_leaves_prompt_in_normal_state() {
+ let mut screen = new_prompt();
+ screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
+ screen.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ assert!(screen.is_done());
+ assert_eq!(screen.selection(), Some(UpdateSelection::NotNow));
+ }
+
+ #[test]
+ fn update_prompt_dont_remind_selects_dismissal() {
+ let mut screen = new_prompt();
+ screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
+ screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
+ screen.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
+ assert!(screen.is_done());
+ assert_eq!(screen.selection(), Some(UpdateSelection::DontRemind));
+ }
+
+ #[test]
+ fn update_prompt_ctrl_c_skips_update() {
+ let mut screen = new_prompt();
+ screen.handle_key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL));
+ assert!(screen.is_done());
+ assert_eq!(screen.selection(), Some(UpdateSelection::NotNow));
+ }
+
+ #[test]
+ fn update_prompt_navigation_wraps_between_entries() {
+ let mut screen = new_prompt();
+ screen.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE));
+ assert_eq!(screen.highlighted, UpdateSelection::DontRemind);
+ screen.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE));
+ assert_eq!(screen.highlighted, UpdateSelection::UpdateNow);
+ }
+}
diff --git a/codex-rs/tui2/src/updates.rs b/codex-rs/tui2/src/updates.rs
new file mode 100644
index 0000000000..89fd6f32f6
--- /dev/null
+++ b/codex-rs/tui2/src/updates.rs
@@ -0,0 +1,237 @@
+#![cfg(not(debug_assertions))]
+
+use crate::update_action;
+use crate::update_action::UpdateAction;
+use chrono::DateTime;
+use chrono::Duration;
+use chrono::Utc;
+use codex_core::config::Config;
+use codex_core::default_client::create_client;
+use serde::Deserialize;
+use serde::Serialize;
+use std::path::Path;
+use std::path::PathBuf;
+
+use crate::version::CODEX_CLI_VERSION;
+
+pub fn get_upgrade_version(config: &Config) -> Option<String> {
+ if !config.check_for_update_on_startup {
+ return None;
+ }
+
+ let version_file = version_filepath(config);
+ let info = read_version_info(&version_file).ok();
+
+ if match &info {
+ None => true,
+ Some(info) => info.last_checked_at < Utc::now() - Duration::hours(20),
+ } {
+ // Refresh the cached latest version in the background so TUI startup
+ // isn’t blocked by a network call. The UI reads the previously cached
+ // value (if any) for this run; the next run shows the banner if needed.
+ tokio::spawn(async move {
+ check_for_update(&version_file)
+ .await
+ .inspect_err(|e| tracing::error!("Failed to update version: {e}"))
+ });
+ }
+
+ info.and_then(|info| {
+ if is_newer(&info.latest_version, CODEX_CLI_VERSION).unwrap_or(false) {
+ Some(info.latest_version)
+ } else {
+ None
+ }
+ })
+}
+
+#[derive(Serialize, Deserialize, Debug, Clone)]
+struct VersionInfo {
+ latest_version: String,
+ // ISO-8601 timestamp (RFC3339)
+ last_checked_at: DateTime<Utc>,
+ #[serde(default)]
+ dismissed_version: Option<String>,
+}
+
+const VERSION_FILENAME: &str = "version.json";
+// We use the latest version from the cask if installation is via homebrew - homebrew does not immediately pick up the latest release and can lag behind.
+const HOMEBREW_CASK_URL: &str =
+ "https://raw.githubusercontent.com/Homebrew/homebrew-cask/HEAD/Casks/c/codex.rb";
+const LATEST_RELEASE_URL: &str = "https://api.github.com/repos/openai/codex/releases/latest";
+
+#[derive(Deserialize, Debug, Clone)]
+struct ReleaseInfo {
+ tag_name: String,
+}
+
+fn version_filepath(config: &Config) -> PathBuf {
+ config.codex_home.join(VERSION_FILENAME)
+}
+
+fn read_version_info(version_file: &Path) -> anyhow::Result<VersionInfo> {
+ let contents = std::fs::read_to_string(version_file)?;
+ Ok(serde_json::from_str(&contents)?)
+}
+
+async fn check_for_update(version_file: &Path) -> anyhow::Result<()> {
+ let latest_version = match update_action::get_update_action() {
+ Some(UpdateAction::BrewUpgrade) => {
+ let cask_contents = create_client()
+ .get(HOMEBREW_CASK_URL)
+ .send()
+ .await?
+ .error_for_status()?
+ .text()
+ .await?;
+ extract_version_from_cask(&cask_contents)?
+ }
+ _ => {
+ let ReleaseInfo {
+ tag_name: latest_tag_name,
+ } = create_client()
+ .get(LATEST_RELEASE_URL)
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ReleaseInfo>()
+ .await?;
+ extract_version_from_latest_tag(&latest_tag_name)?
+ }
+ };
+
+ // Preserve any previously dismissed version if present.
+ let prev_info = read_version_info(version_file).ok();
+ let info = VersionInfo {
+ latest_version,
+ last_checked_at: Utc::now(),
+ dismissed_version: prev_info.and_then(|p| p.dismissed_version),
+ };
+
+ let json_line = format!("{}\n", serde_json::to_string(&info)?);
+ if let Some(parent) = version_file.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+ tokio::fs::write(version_file, json_line).await?;
+ Ok(())
+}
+
+fn is_newer(latest: &str, current: &str) -> Option<bool> {
+ match (parse_version(latest), parse_version(current)) {
+ (Some(l), Some(c)) => Some(l > c),
+ _ => None,
+ }
+}
+
+fn extract_version_from_cask(cask_contents: &str) -> anyhow::Result<String> {
+ cask_contents
+ .lines()
+ .find_map(|line| {
+ let line = line.trim();
+ line.strip_prefix("version \"")
+ .and_then(|rest| rest.strip_suffix('"'))
+ .map(ToString::to_string)
+ })
+ .ok_or_else(|| anyhow::anyhow!("Failed to find version in Homebrew cask file"))
+}
+
+fn extract_version_from_latest_tag(latest_tag_name: &str) -> anyhow::Result<String> {
+ latest_tag_name
+ .strip_prefix("rust-v")
+ .map(str::to_owned)
+ .ok_or_else(|| anyhow::anyhow!("Failed to parse latest tag name '{latest_tag_name}'"))
+}
+
+/// Returns the latest version to show in a popup, if it should be shown.
+/// This respects the user's dismissal choice for the current latest version.
+pub fn get_upgrade_version_for_popup(config: &Config) -> Option<String> {
+ if !config.check_for_update_on_startup {
+ return None;
+ }
+
+ let version_file = version_filepath(config);
+ let latest = get_upgrade_version(config)?;
+ // If the user dismissed this exact version previously, do not show the popup.
+ if let Ok(info) = read_version_info(&version_file)
+ && info.dismissed_version.as_deref() == Some(latest.as_str())
+ {
+ return None;
+ }
+ Some(latest)
+}
+
+/// Persist a dismissal for the current latest version so we don't show
+/// the update popup again for this version.
+pub async fn dismiss_version(config: &Config, version: &str) -> anyhow::Result<()> {
+ let version_file = version_filepath(config);
+ let mut info = match read_version_info(&version_file) {
+ Ok(info) => info,
+ Err(_) => return Ok(()),
+ };
+ info.dismissed_version = Some(version.to_string());
+ let json_line = format!("{}\n", serde_json::to_string(&info)?);
+ if let Some(parent) = version_file.parent() {
+ tokio::fs::create_dir_all(parent).await?;
+ }
+ tokio::fs::write(version_file, json_line).await?;
+ Ok(())
+}
+
+fn parse_version(v: &str) -> Option<(u64, u64, u64)> {
+ let mut iter = v.trim().split('.');
+ let maj = iter.next()?.parse::<u64>().ok()?;
+ let min = iter.next()?.parse::<u64>().ok()?;
+ let pat = iter.next()?.parse::<u64>().ok()?;
+ Some((maj, min, pat))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_version_from_cask_contents() {
+ let cask = r#"
+ cask "codex" do
+ version "0.55.0"
+ end
+ "#;
+ assert_eq!(
+ extract_version_from_cask(cask).expect("failed to parse version"),
+ "0.55.0"
+ );
+ }
+
+ #[test]
+ fn extracts_version_from_latest_tag() {
+ assert_eq!(
+ extract_version_from_latest_tag("rust-v1.5.0").expect("failed to parse version"),
+ "1.5.0"
+ );
+ }
+
+ #[test]
+ fn latest_tag_without_prefix_is_invalid() {
+ assert!(extract_version_from_latest_tag("v1.5.0").is_err());
+ }
+
+ #[test]
+ fn prerelease_version_is_not_considered_newer() {
+ assert_eq!(is_newer("0.11.0-beta.1", "0.11.0"), None);
+ assert_eq!(is_newer("1.0.0-rc.1", "1.0.0"), None);
+ }
+
+ #[test]
+ fn plain_semver_comparisons_work() {
+ assert_eq!(is_newer("0.11.1", "0.11.0"), Some(true));
+ assert_eq!(is_newer("0.11.0", "0.11.1"), Some(false));
+ assert_eq!(is_newer("1.0.0", "0.9.9"), Some(true));
+ assert_eq!(is_newer("0.9.9", "1.0.0"), Some(false));
+ }
+
+ #[test]
+ fn whitespace_is_ignored() {
+ assert_eq!(parse_version(" 1.2.3 \n"), Some((1, 2, 3)));
+ assert_eq!(is_newer(" 1.2.3 ", "1.2.2"), Some(true));
+ }
+}
diff --git a/codex-rs/tui2/src/version.rs b/codex-rs/tui2/src/version.rs
new file mode 100644
index 0000000000..8c8d108dc6
--- /dev/null
+++ b/codex-rs/tui2/src/version.rs
@@ -0,0 +1,2 @@
+/// The current Codex CLI version as embedded at compile time.
+pub const CODEX_CLI_VERSION: &str = env!("CARGO_PKG_VERSION");
diff --git a/codex-rs/tui2/src/wrapping.rs b/codex-rs/tui2/src/wrapping.rs
new file mode 100644
index 0000000000..561da78b4e
--- /dev/null
+++ b/codex-rs/tui2/src/wrapping.rs
@@ -0,0 +1,652 @@
+use ratatui::text::Line;
+use ratatui::text::Span;
+use std::borrow::Cow;
+use std::ops::Range;
+use textwrap::Options;
+use textwrap::wrap_algorithms::Penalties;
+
+use crate::render::line_utils::push_owned_lines;
+
+pub(crate) fn wrap_ranges<'a, O>(text: &str, width_or_options: O) -> Vec<Range<usize>>
+where
+ O: Into<Options<'a>>,
+{
+ let opts = width_or_options.into();
+ let mut lines: Vec<Range<usize>> = Vec::new();
+ for line in textwrap::wrap(text, opts).iter() {
+ match line {
+ std::borrow::Cow::Borrowed(slice) => {
+ let start = unsafe { slice.as_ptr().offset_from(text.as_ptr()) as usize };
+ let end = start + slice.len();
+ let trailing_spaces = text[end..].chars().take_while(|c| *c == ' ').count();
+ lines.push(start..end + trailing_spaces + 1);
+ }
+ std::borrow::Cow::Owned(_) => panic!("wrap_ranges: unexpected owned string"),
+ }
+ }
+ lines
+}
+
+/// Like `wrap_ranges` but returns ranges without trailing whitespace and
+/// without the sentinel extra byte. Suitable for general wrapping where
+/// trailing spaces should not be preserved.
+pub(crate) fn wrap_ranges_trim<'a, O>(text: &str, width_or_options: O) -> Vec<Range<usize>>
+where
+ O: Into<Options<'a>>,
+{
+ let opts = width_or_options.into();
+ let mut lines: Vec<Range<usize>> = Vec::new();
+ for line in textwrap::wrap(text, opts).iter() {
+ match line {
+ std::borrow::Cow::Borrowed(slice) => {
+ let start = unsafe { slice.as_ptr().offset_from(text.as_ptr()) as usize };
+ let end = start + slice.len();
+ lines.push(start..end);
+ }
+ std::borrow::Cow::Owned(_) => panic!("wrap_ranges_trim: unexpected owned string"),
+ }
+ }
+ lines
+}
+
+#[derive(Debug, Clone)]
+pub struct RtOptions<'a> {
+ /// The width in columns at which the text will be wrapped.
+ pub width: usize,
+ /// Line ending used for breaking lines.
+ pub line_ending: textwrap::LineEnding,
+ /// Indentation used for the first line of output. See the
+ /// [`Options::initial_indent`] method.
+ pub initial_indent: Line<'a>,
+ /// Indentation used for subsequent lines of output. See the
+ /// [`Options::subsequent_indent`] method.
+ pub subsequent_indent: Line<'a>,
+ /// Allow long words to be broken if they cannot fit on a line.
+ /// When set to `false`, some lines may be longer than
+ /// `self.width`. See the [`Options::break_words`] method.
+ pub break_words: bool,
+ /// Wrapping algorithm to use, see the implementations of the
+ /// [`WrapAlgorithm`] trait for details.
+ pub wrap_algorithm: textwrap::WrapAlgorithm,
+ /// The line breaking algorithm to use, see the [`WordSeparator`]
+ /// trait for an overview and possible implementations.
+ pub word_separator: textwrap::WordSeparator,
+ /// The method for splitting words. This can be used to prohibit
+ /// splitting words on hyphens, or it can be used to implement
+ /// language-aware machine hyphenation.
+ pub word_splitter: textwrap::WordSplitter,
+}
+impl From<usize> for RtOptions<'_> {
+ fn from(width: usize) -> Self {
+ RtOptions::new(width)
+ }
+}
+
+#[allow(dead_code)]
+impl<'a> RtOptions<'a> {
+ pub fn new(width: usize) -> Self {
+ RtOptions {
+ width,
+ line_ending: textwrap::LineEnding::LF,
+ initial_indent: Line::default(),
+ subsequent_indent: Line::default(),
+ break_words: true,
+ word_separator: textwrap::WordSeparator::new(),
+ wrap_algorithm: textwrap::WrapAlgorithm::OptimalFit(Penalties {
+ // ~infinite overflow penalty, we never want to overflow a line.
+ overflow_penalty: usize::MAX / 4,
+ ..Default::default()
+ }),
+ word_splitter: textwrap::WordSplitter::HyphenSplitter,
+ }
+ }
+
+ pub fn line_ending(self, line_ending: textwrap::LineEnding) -> Self {
+ RtOptions {
+ line_ending,
+ ..self
+ }
+ }
+
+ pub fn width(self, width: usize) -> Self {
+ RtOptions { width, ..self }
+ }
+
+ pub fn initial_indent(self, initial_indent: Line<'a>) -> Self {
+ RtOptions {
+ initial_indent,
+ ..self
+ }
+ }
+
+ pub fn subsequent_indent(self, subsequent_indent: Line<'a>) -> Self {
+ RtOptions {
+ subsequent_indent,
+ ..self
+ }
+ }
+
+ pub fn break_words(self, break_words: bool) -> Self {
+ RtOptions {
+ break_words,
+ ..self
+ }
+ }
+
+ pub fn word_separator(self, word_separator: textwrap::WordSeparator) -> RtOptions<'a> {
+ RtOptions {
+ word_separator,
+ ..self
+ }
+ }
+
+ pub fn wrap_algorithm(self, wrap_algorithm: textwrap::WrapAlgorithm) -> RtOptions<'a> {
+ RtOptions {
+ wrap_algorithm,
+ ..self
+ }
+ }
+
+ pub fn word_splitter(self, word_splitter: textwrap::WordSplitter) -> RtOptions<'a> {
+ RtOptions {
+ word_splitter,
+ ..self
+ }
+ }
+}
+
+#[must_use]
+pub(crate) fn word_wrap_line<'a, O>(line: &'a Line<'a>, width_or_options: O) -> Vec<Line<'a>>
+where
+ O: Into<RtOptions<'a>>,
+{
+ // Flatten the line and record span byte ranges.
+ let mut flat = String::new();
+ let mut span_bounds = Vec::new();
+ let mut acc = 0usize;
+ for s in &line.spans {
+ let text = s.content.as_ref();
+ let start = acc;
+ flat.push_str(text);
+ acc += text.len();
+ span_bounds.push((start..acc, s.style));
+ }
+
+ let rt_opts: RtOptions<'a> = width_or_options.into();
+ let opts = Options::new(rt_opts.width)
+ .line_ending(rt_opts.line_ending)
+ .break_words(rt_opts.break_words)
+ .wrap_algorithm(rt_opts.wrap_algorithm)
+ .word_separator(rt_opts.word_separator)
+ .word_splitter(rt_opts.word_splitter);
+
+ let mut out: Vec<Line<'a>> = Vec::new();
+
+ // Compute first line range with reduced width due to initial indent.
+ let initial_width_available = opts
+ .width
+ .saturating_sub(rt_opts.initial_indent.width())
+ .max(1);
+ let initial_wrapped = wrap_ranges_trim(&flat, opts.clone().width(initial_width_available));
+ let Some(first_line_range) = initial_wrapped.first() else {
+ return vec![rt_opts.initial_indent.clone()];
+ };
+
+ // Build first wrapped line with initial indent.
+ let mut first_line = rt_opts.initial_indent.clone().style(line.style);
+ {
+ let sliced = slice_line_spans(line, &span_bounds, first_line_range);
+ let mut spans = first_line.spans;
+ spans.append(
+ &mut sliced
+ .spans
+ .into_iter()
+ .map(|s| s.patch_style(line.style))
+ .collect(),
+ );
+ first_line.spans = spans;
+ out.push(first_line);
+ }
+
+ // Wrap the remainder using subsequent indent width and map back to original indices.
+ let base = first_line_range.end;
+ let skip_leading_spaces = flat[base..].chars().take_while(|c| *c == ' ').count();
+ let base = base + skip_leading_spaces;
+ let subsequent_width_available = opts
+ .width
+ .saturating_sub(rt_opts.subsequent_indent.width())
+ .max(1);
+ let remaining_wrapped = wrap_ranges_trim(&flat[base..], opts.width(subsequent_width_available));
+ for r in &remaining_wrapped {
+ if r.is_empty() {
+ continue;
+ }
+ let mut subsequent_line = rt_opts.subsequent_indent.clone().style(line.style);
+ let offset_range = (r.start + base)..(r.end + base);
+ let sliced = slice_line_spans(line, &span_bounds, &offset_range);
+ let mut spans = subsequent_line.spans;
+ spans.append(
+ &mut sliced
+ .spans
+ .into_iter()
+ .map(|s| s.patch_style(line.style))
+ .collect(),
+ );
+ subsequent_line.spans = spans;
+ out.push(subsequent_line);
+ }
+
+ out
+}
+
+/// Utilities to allow wrapping either borrowed or owned lines.
+#[derive(Debug)]
+enum LineInput<'a> {
+ Borrowed(&'a Line<'a>),
+ Owned(Line<'a>),
+}
+
+impl<'a> LineInput<'a> {
+ fn as_ref(&self) -> &Line<'a> {
+ match self {
+ LineInput::Borrowed(line) => line,
+ LineInput::Owned(line) => line,
+ }
+ }
+}
+
+/// This trait makes it easier to pass whatever we need into word_wrap_lines.
+trait IntoLineInput<'a> {
+ fn into_line_input(self) -> LineInput<'a>;
+}
+
+impl<'a> IntoLineInput<'a> for &'a Line<'a> {
+ fn into_line_input(self) -> LineInput<'a> {
+ LineInput::Borrowed(self)
+ }
+}
+
+impl<'a> IntoLineInput<'a> for &'a mut Line<'a> {
+ fn into_line_input(self) -> LineInput<'a> {
+ LineInput::Borrowed(self)
+ }
+}
+
+impl<'a> IntoLineInput<'a> for Line<'a> {
+ fn into_line_input(self) -> LineInput<'a> {
+ LineInput::Owned(self)
+ }
+}
+
+impl<'a> IntoLineInput<'a> for String {
+ fn into_line_input(self) -> LineInput<'a> {
+ LineInput::Owned(Line::from(self))
+ }
+}
+
+impl<'a> IntoLineInput<'a> for &'a str {
+ fn into_line_input(self) -> LineInput<'a> {
+ LineInput::Owned(Line::from(self))
+ }
+}
+
+impl<'a> IntoLineInput<'a> for Cow<'a, str> {
+ fn into_line_input(self) -> LineInput<'a> {
+ LineInput::Owned(Line::from(self))
+ }
+}
+
+impl<'a> IntoLineInput<'a> for Span<'a> {
+ fn into_line_input(self) -> LineInput<'a> {
+ LineInput::Owned(Line::from(self))
+ }
+}
+
+impl<'a> IntoLineInput<'a> for Vec<Span<'a>> {
+ fn into_line_input(self) -> LineInput<'a> {
+ LineInput::Owned(Line::from(self))
+ }
+}
+
+/// Wrap a sequence of lines, applying the initial indent only to the very first
+/// output line, and using the subsequent indent for all later wrapped pieces.
+#[allow(private_bounds)] // IntoLineInput isn't public, but it doesn't really need to be.
+pub(crate) fn word_wrap_lines<'a, I, O, L>(lines: I, width_or_options: O) -> Vec<Line<'static>>
+where
+ I: IntoIterator<Item = L>,
+ L: IntoLineInput<'a>,
+ O: Into<RtOptions<'a>>,
+{
+ let base_opts: RtOptions<'a> = width_or_options.into();
+ let mut out: Vec<Line<'static>> = Vec::new();
+
+ for (idx, line) in lines.into_iter().enumerate() {
+ let line_input = line.into_line_input();
+ let opts = if idx == 0 {
+ base_opts.clone()
+ } else {
+ let mut o = base_opts.clone();
+ let sub = o.subsequent_indent.clone();
+ o = o.initial_indent(sub);
+ o
+ };
+ let wrapped = word_wrap_line(line_input.as_ref(), opts);
+ push_owned_lines(&wrapped, &mut out);
+ }
+
+ out
+}
+
+#[allow(dead_code)]
+pub(crate) fn word_wrap_lines_borrowed<'a, I, O>(lines: I, width_or_options: O) -> Vec<Line<'a>>
+where
+ I: IntoIterator<Item = &'a Line<'a>>,
+ O: Into<RtOptions<'a>>,
+{
+ let base_opts: RtOptions<'a> = width_or_options.into();
+ let mut out: Vec<Line<'a>> = Vec::new();
+ let mut first = true;
+ for line in lines.into_iter() {
+ let opts = if first {
+ base_opts.clone()
+ } else {
+ base_opts
+ .clone()
+ .initial_indent(base_opts.subsequent_indent.clone())
+ };
+ out.extend(word_wrap_line(line, opts));
+ first = false;
+ }
+ out
+}
+
+fn slice_line_spans<'a>(
+ original: &'a Line<'a>,
+ span_bounds: &[(Range<usize>, ratatui::style::Style)],
+ range: &Range<usize>,
+) -> Line<'a> {
+ let start_byte = range.start;
+ let end_byte = range.end;
+ let mut acc: Vec<Span<'a>> = Vec::new();
+ for (i, (range, style)) in span_bounds.iter().enumerate() {
+ let s = range.start;
+ let e = range.end;
+ if e <= start_byte {
+ continue;
+ }
+ if s >= end_byte {
+ break;
+ }
+ let seg_start = start_byte.max(s);
+ let seg_end = end_byte.min(e);
+ if seg_end > seg_start {
+ let local_start = seg_start - s;
+ let local_end = seg_end - s;
+ let content = original.spans[i].content.as_ref();
+ let slice = &content[local_start..local_end];
+ acc.push(Span {
+ style: *style,
+ content: std::borrow::Cow::Borrowed(slice),
+ });
+ }
+ if e >= end_byte {
+ break;
+ }
+ }
+ Line {
+ style: original.style,
+ alignment: original.alignment,
+ spans: acc,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use itertools::Itertools as _;
+ use pretty_assertions::assert_eq;
+ use ratatui::style::Color;
+ use ratatui::style::Stylize;
+ use std::string::ToString;
+
+ fn concat_line(line: &Line) -> String {
+ line.spans
+ .iter()
+ .map(|s| s.content.as_ref())
+ .collect::<String>()
+ }
+
+ #[test]
+ fn trivial_unstyled_no_indents_wide_width() {
+ let line = Line::from("hello");
+ let out = word_wrap_line(&line, 10);
+ assert_eq!(out.len(), 1);
+ assert_eq!(concat_line(&out[0]), "hello");
+ }
+
+ #[test]
+ fn simple_unstyled_wrap_narrow_width() {
+ let line = Line::from("hello world");
+ let out = word_wrap_line(&line, 5);
+ assert_eq!(out.len(), 2);
+ assert_eq!(concat_line(&out[0]), "hello");
+ assert_eq!(concat_line(&out[1]), "world");
+ }
+
+ #[test]
+ fn simple_styled_wrap_preserves_styles() {
+ let line = Line::from(vec!["hello ".red(), "world".into()]);
+ let out = word_wrap_line(&line, 6);
+ assert_eq!(out.len(), 2);
+ // First line should carry the red style
+ assert_eq!(concat_line(&out[0]), "hello");
+ assert_eq!(out[0].spans.len(), 1);
+ assert_eq!(out[0].spans[0].style.fg, Some(Color::Red));
+ // Second line is unstyled
+ assert_eq!(concat_line(&out[1]), "world");
+ assert_eq!(out[1].spans.len(), 1);
+ assert_eq!(out[1].spans[0].style.fg, None);
+ }
+
+ #[test]
+ fn with_initial_and_subsequent_indents() {
+ let opts = RtOptions::new(8)
+ .initial_indent(Line::from("- "))
+ .subsequent_indent(Line::from(" "));
+ let line = Line::from("hello world foo");
+ let out = word_wrap_line(&line, opts);
+ // Expect three lines with proper prefixes
+ assert!(concat_line(&out[0]).starts_with("- "));
+ assert!(concat_line(&out[1]).starts_with(" "));
+ assert!(concat_line(&out[2]).starts_with(" "));
+ // And content roughly segmented
+ assert_eq!(concat_line(&out[0]), "- hello");
+ assert_eq!(concat_line(&out[1]), " world");
+ assert_eq!(concat_line(&out[2]), " foo");
+ }
+
+ #[test]
+ fn empty_initial_indent_subsequent_spaces() {
+ let opts = RtOptions::new(8)
+ .initial_indent(Line::from(""))
+ .subsequent_indent(Line::from(" "));
+ let line = Line::from("hello world foobar");
+ let out = word_wrap_line(&line, opts);
+ assert!(concat_line(&out[0]).starts_with("hello"));
+ for l in &out[1..] {
+ assert!(concat_line(l).starts_with(" "));
+ }
+ }
+
+ #[test]
+ fn empty_input_yields_single_empty_line() {
+ let line = Line::from("");
+ let out = word_wrap_line(&line, 10);
+ assert_eq!(out.len(), 1);
+ assert_eq!(concat_line(&out[0]), "");
+ }
+
+ #[test]
+ fn leading_spaces_preserved_on_first_line() {
+ let line = Line::from(" hello");
+ let out = word_wrap_line(&line, 8);
+ assert_eq!(out.len(), 1);
+ assert_eq!(concat_line(&out[0]), " hello");
+ }
+
+ #[test]
+ fn multiple_spaces_between_words_dont_start_next_line_with_spaces() {
+ let line = Line::from("hello world");
+ let out = word_wrap_line(&line, 8);
+ assert_eq!(out.len(), 2);
+ assert_eq!(concat_line(&out[0]), "hello");
+ assert_eq!(concat_line(&out[1]), "world");
+ }
+
+ #[test]
+ fn break_words_false_allows_overflow_for_long_word() {
+ let opts = RtOptions::new(5).break_words(false);
+ let line = Line::from("supercalifragilistic");
+ let out = word_wrap_line(&line, opts);
+ assert_eq!(out.len(), 1);
+ assert_eq!(concat_line(&out[0]), "supercalifragilistic");
+ }
+
+ #[test]
+ fn hyphen_splitter_breaks_at_hyphen() {
+ let line = Line::from("hello-world");
+ let out = word_wrap_line(&line, 7);
+ assert_eq!(out.len(), 2);
+ assert_eq!(concat_line(&out[0]), "hello-");
+ assert_eq!(concat_line(&out[1]), "world");
+ }
+
+ #[test]
+ fn indent_consumes_width_leaving_one_char_space() {
+ let opts = RtOptions::new(4)
+ .initial_indent(Line::from(">>>>"))
+ .subsequent_indent(Line::from("--"));
+ let line = Line::from("hello");
+ let out = word_wrap_line(&line, opts);
+ assert_eq!(out.len(), 3);
+ assert_eq!(concat_line(&out[0]), ">>>>h");
+ assert_eq!(concat_line(&out[1]), "--el");
+ assert_eq!(concat_line(&out[2]), "--lo");
+ }
+
+ #[test]
+ fn wide_unicode_wraps_by_display_width() {
+ let line = Line::from("😀😀😀");
+ let out = word_wrap_line(&line, 4);
+ assert_eq!(out.len(), 2);
+ assert_eq!(concat_line(&out[0]), "😀😀");
+ assert_eq!(concat_line(&out[1]), "😀");
+ }
+
+ #[test]
+ fn styled_split_within_span_preserves_style() {
+ use ratatui::style::Stylize;
+ let line = Line::from(vec!["abcd".red()]);
+ let out = word_wrap_line(&line, 2);
+ assert_eq!(out.len(), 2);
+ assert_eq!(out[0].spans.len(), 1);
+ assert_eq!(out[1].spans.len(), 1);
+ assert_eq!(out[0].spans[0].style.fg, Some(Color::Red));
+ assert_eq!(out[1].spans[0].style.fg, Some(Color::Red));
+ assert_eq!(concat_line(&out[0]), "ab");
+ assert_eq!(concat_line(&out[1]), "cd");
+ }
+
+ #[test]
+ fn wrap_lines_applies_initial_indent_only_once() {
+ let opts = RtOptions::new(8)
+ .initial_indent(Line::from("- "))
+ .subsequent_indent(Line::from(" "));
+
+ let lines = vec![Line::from("hello world"), Line::from("foo bar baz")];
+ let out = word_wrap_lines(lines, opts);
+
+ // Expect: first line prefixed with "- ", subsequent wrapped pieces with " "
+ // and for the second input line, there should be no "- " prefix on its first piece
+ let rendered: Vec<String> = out.iter().map(concat_line).collect();
+ assert!(rendered[0].starts_with("- "));
+ for r in rendered.iter().skip(1) {
+ assert!(r.starts_with(" "));
+ }
+ }
+
+ #[test]
+ fn wrap_lines_without_indents_is_concat_of_single_wraps() {
+ let lines = vec![Line::from("hello"), Line::from("world!")];
+ let out = word_wrap_lines(lines, 10);
+ let rendered: Vec<String> = out.iter().map(concat_line).collect();
+ assert_eq!(rendered, vec!["hello", "world!"]);
+ }
+
+ #[test]
+ fn wrap_lines_borrowed_applies_initial_indent_only_once() {
+ let opts = RtOptions::new(8)
+ .initial_indent(Line::from("- "))
+ .subsequent_indent(Line::from(" "));
+
+ let lines = [Line::from("hello world"), Line::from("foo bar baz")];
+ let out = word_wrap_lines_borrowed(lines.iter(), opts);
+
+ let rendered: Vec<String> = out.iter().map(concat_line).collect();
+ assert!(rendered.first().unwrap().starts_with("- "));
+ for r in rendered.iter().skip(1) {
+ assert!(r.starts_with(" "));
+ }
+ }
+
+ #[test]
+ fn wrap_lines_borrowed_without_indents_is_concat_of_single_wraps() {
+ let lines = [Line::from("hello"), Line::from("world!")];
+ let out = word_wrap_lines_borrowed(lines.iter(), 10);
+ let rendered: Vec<String> = out.iter().map(concat_line).collect();
+ assert_eq!(rendered, vec!["hello", "world!"]);
+ }
+
+ #[test]
+ fn wrap_lines_accepts_borrowed_iterators() {
+ let lines = [Line::from("hello world"), Line::from("foo bar baz")];
+ let out = word_wrap_lines(lines, 10);
+ let rendered: Vec<String> = out.iter().map(concat_line).collect();
+ assert_eq!(rendered, vec!["hello", "world", "foo bar", "baz"]);
+ }
+
+ #[test]
+ fn wrap_lines_accepts_str_slices() {
+ let lines = ["hello world", "goodnight moon"];
+ let out = word_wrap_lines(lines, 12);
+ let rendered: Vec<String> = out.iter().map(concat_line).collect();
+ assert_eq!(rendered, vec!["hello world", "goodnight", "moon"]);
+ }
+
+ #[test]
+ fn line_height_counts_double_width_emoji() {
+ let line = "😀😀😀".into(); // each emoji ~ width 2
+ assert_eq!(word_wrap_line(&line, 4).len(), 2);
+ assert_eq!(word_wrap_line(&line, 2).len(), 3);
+ assert_eq!(word_wrap_line(&line, 6).len(), 1);
+ }
+
+ #[test]
+ fn word_wrap_does_not_split_words_simple_english() {
+ let sample = "Years passed, and Willowmere thrived in peace and friendship. Mira’s herb garden flourished with both ordinary and enchanted plants, and travelers spoke of the kindness of the woman who tended them.";
+ let line = Line::from(sample);
+ let lines = [line];
+ // Force small width to exercise wrapping at spaces.
+ let wrapped = word_wrap_lines_borrowed(&lines, 40);
+ let joined: String = wrapped.iter().map(ToString::to_string).join("\n");
+ assert_eq!(
+ joined,
+ r#"Years passed, and Willowmere thrived
+in peace and friendship. Mira’s herb
+garden flourished with both ordinary and
+enchanted plants, and travelers spoke
+of the kindness of the woman who tended
+them."#
+ );
+ }
+}
diff --git a/codex-rs/tui2/tooltips.txt b/codex-rs/tui2/tooltips.txt
new file mode 100644
index 0000000000..f4291f3bfc
--- /dev/null
+++ b/codex-rs/tui2/tooltips.txt
@@ -0,0 +1,11 @@
+Use /compact when the conversation gets long to summarize history and free up context.
+Start a fresh idea with /new; the previous session stays available in history.
+If a turn went sideways, /undo asks Codex to revert the last changes.
+Use /feedback to send logs to the maintainers when something looks off.
+Switch models or reasoning effort quickly with /model.
+You can run any shell commands from codex using `!` (e.g. `!ls`)
+Type / to open the command popup; Tab autocompletes slash commands and saved prompts.
+You can define your own `/` commands with custom prompts. More info here: https://developers.openai.com/codex/guides/slash-commands#create-your-own-slash-commands-with-custom-prompts
+With the composer empty, press Esc to step back and edit your last message; Enter confirms.
+Paste an image with Ctrl+V to attach it to your next message.
+You can resume a previous conversation by running `codex resume`