diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 73c1117af1..71681aa57f 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -638,9 +638,11 @@ dependencies = [ "codex-protocol", "codex-protocol-ts", "codex-tui", + "owo-colors", "predicates", "pretty_assertions", "serde_json", + "supports-color", "tempfile", "tokio", "tracing", @@ -687,7 +689,7 @@ dependencies = [ "portable-pty", "predicates", "pretty_assertions", - "rand 0.9.2", + "rand", "regex-lite", "reqwest", "seccompiler", @@ -797,7 +799,8 @@ dependencies = [ "chrono", "codex-core", "codex-protocol", - "rand 0.8.5", + "core_test_support", + "rand", "reqwest", "serde", "serde_json", @@ -835,6 +838,7 @@ dependencies = [ "codex-core", "codex-login", "codex-protocol", + "core_test_support", "mcp-types", "mcp_test_support", "os_info", @@ -929,12 +933,11 @@ dependencies = [ "libc", "mcp-types", "once_cell", - "owo-colors", "path-clean", "pathdiff", "pretty_assertions", "pulldown-cmark", - "rand 0.9.2", + "rand", "ratatui", "regex-lite", "serde", @@ -3452,35 +3455,14 @@ dependencies = [ "nibble_vec", ] -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - [[package]] name = "rand" version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.3", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", + "rand_chacha", + "rand_core", ] [[package]] @@ -3490,16 +3472,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core 0.9.3", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.16", + "rand_core", ] [[package]] diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 1502e62f2f..7e0d562074 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -29,15 +29,167 @@ version = "0.0.0" # edition. edition = "2024" +[workspace.dependencies] +# Internal +codex-ansi-escape = { path = "ansi-escape" } +codex-apply-patch = { path = "apply-patch" } +codex-arg0 = { path = "arg0" } +codex-chatgpt = { path = "chatgpt" } +codex-common = { path = "common" } +codex-core = { path = "core" } +codex-exec = { path = "exec" } +codex-file-search = { path = "file-search" } +codex-linux-sandbox = { path = "linux-sandbox" } +codex-login = { path = "login" } +codex-mcp-client = { path = "mcp-client" } +codex-mcp-server = { path = "mcp-server" } +codex-ollama = { path = "ollama" } +codex-protocol = { path = "protocol" } +codex-protocol-ts = { path = "protocol-ts" } +codex-tui = { path = "tui" } +core_test_support = { path = "core/tests/common" } +mcp-types = { path = "mcp-types" } +mcp_test_support = { path = "mcp-server/tests/common" } + +# External +allocative = "0.3.3" +ansi-to-tui = "7.0.0" +anyhow = "1" +arboard = "3" +askama = "0.12" +assert_cmd = "2" +async-channel = "2.3.1" +async-stream = "0.3.6" +base64 = "0.22.1" +bytes = "1.10.1" +chrono = "0.4.40" +clap = "4" +clap_complete = "4" +color-eyre = "0.6.3" +crossterm = "0.28.1" +derive_more = "2" +diffy = "0.4.2" +dirs = "6" +dotenvy = "0.15.7" +env-flags = "0.1.1" +env_logger = "0.11.5" +eventsource-stream = "0.2.3" +futures = "0.3" +icu_decimal = "2.0.0" +icu_locale_core = "2.0.0" +ignore = "0.4.23" +image = { version = "^0.25.8", default-features = false } +insta = "1.43.2" +itertools = "0.14.0" +landlock = "0.4.1" +lazy_static = "1" +libc = "0.2.175" +log = "0.4" +maplit = "1.0.2" +mime_guess = "2.0.5" +multimap = "0.10.0" +nucleo-matcher = "0.3.1" +once_cell = "1" +openssl-sys = "*" +os_info = "3.12.0" +owo-colors = "4.2.0" +path-absolutize = "3.1.1" +path-clean = "1.0.1" +pathdiff = "0.2" +portable-pty = "0.9.0" +predicates = "3" +pretty_assertions = "1.4.1" +pulldown-cmark = "0.10" +rand = "0.9" +ratatui = "0.29.0" +regex-lite = "0.1.7" +reqwest = "0.12" +schemars = "0.8.22" +seccompiler = "0.5.0" +serde = "1" +serde_json = "1" +serde_with = "3.14" +sha1 = "0.10.6" +sha2 = "0.10" +shlex = "1.3.0" +similar = "2.7.0" +starlark = "0.13.0" +strum = "0.27.2" +strum_macros = "0.27.2" +supports-color = "3.0.2" +sys-locale = "0.3.2" +tempfile = "3.13.0" +textwrap = "0.16.2" +thiserror = "2.0.16" +time = "0.3" +tiny_http = "0.12" +tokio = "1" +tokio-stream = "0.1.17" +tokio-test = "0.4" +tokio-util = "0.7.16" +toml = "0.9.5" +toml_edit = "0.23.4" +tracing = "0.1.41" +tracing-appender = "0.2.3" +tracing-subscriber = "0.3.20" +tree-sitter = "0.25.9" +tree-sitter-bash = "0.25.0" +ts-rs = "11" +unicode-segmentation = "1.12.0" +unicode-width = "0.1" +url = "2" +urlencoding = "2.1" +uuid = "1" +vt100 = "0.16.2" +walkdir = "2.5.0" +webbrowser = "1.0" +which = "6" +wildmatch = "2.5.0" +wiremock = "0.6" + [workspace.lints] rust = {} [workspace.lints.clippy] expect_used = "deny" +identity_op = "deny" +manual_clamp = "deny" +manual_filter = "deny" +manual_find = "deny" +manual_flatten = "deny" +manual_map = "deny" +manual_memcpy = "deny" +manual_non_exhaustive = "deny" +manual_ok_or = "deny" +manual_range_contains = "deny" +manual_retain = "deny" +manual_strip = "deny" +manual_try_fold = "deny" +manual_unwrap_or = "deny" +needless_borrow = "deny" +needless_borrowed_reference = "deny" +needless_collect = "deny" +needless_late_init = "deny" +needless_option_as_deref = "deny" +needless_question_mark = "deny" +needless_update = "deny" redundant_clone = "deny" +redundant_closure = "deny" +redundant_closure_for_method_calls = "deny" +redundant_static_lifetimes = "deny" +trivially_copy_pass_by_ref = "deny" uninlined_format_args = "deny" +unnecessary_filter_map = "deny" +unnecessary_lazy_evaluations = "deny" +unnecessary_sort_by = "deny" +unnecessary_to_owned = "deny" unwrap_used = "deny" +# cargo-shear cannot see the platform-specific openssl-sys usage, so we +# silence the false positive here instead of deleting a real dependency. +[workspace.metadata.cargo-shear] +ignored = ["openssl-sys"] + [profile.release] lto = "fat" # Because we bundle some of these executables with the TypeScript CLI, we diff --git a/codex-rs/ansi-escape/Cargo.toml b/codex-rs/ansi-escape/Cargo.toml index ada675380d..4107a72754 100644 --- a/codex-rs/ansi-escape/Cargo.toml +++ b/codex-rs/ansi-escape/Cargo.toml @@ -8,9 +8,9 @@ name = "codex_ansi_escape" path = "src/lib.rs" [dependencies] -ansi-to-tui = "7.0.0" -ratatui = { version = "0.29.0", features = [ +ansi-to-tui = { workspace = true } +ratatui = { workspace = true, features = [ "unstable-rendered-line-info", "unstable-widget-ref", ] } -tracing = { version = "0.1.41", features = ["log"] } +tracing = { workspace = true, features = ["log"] } diff --git a/codex-rs/apply-patch/Cargo.toml b/codex-rs/apply-patch/Cargo.toml index 7b5919a323..d37404c15b 100644 --- a/codex-rs/apply-patch/Cargo.toml +++ b/codex-rs/apply-patch/Cargo.toml @@ -15,14 +15,14 @@ path = "src/main.rs" workspace = true [dependencies] -anyhow = "1" -similar = "2.7.0" -thiserror = "2.0.16" -tree-sitter = "0.25.9" -tree-sitter-bash = "0.25.0" -once_cell = "1" +anyhow = { workspace = true } +similar = { workspace = true } +thiserror = { workspace = true } +tree-sitter = { workspace = true } +tree-sitter-bash = { workspace = true } +once_cell = { workspace = true } [dev-dependencies] -assert_cmd = "2" -pretty_assertions = "1.4.1" -tempfile = "3.13.0" +assert_cmd = { workspace = true } +pretty_assertions = { workspace = true } +tempfile = { workspace = true } diff --git a/codex-rs/apply-patch/src/lib.rs b/codex-rs/apply-patch/src/lib.rs index 5bda31c4c2..189c1a07d0 100644 --- a/codex-rs/apply-patch/src/lib.rs +++ b/codex-rs/apply-patch/src/lib.rs @@ -648,21 +648,18 @@ fn derive_new_contents_from_chunks( } }; - let mut original_lines: Vec = original_contents - .split('\n') - .map(|s| s.to_string()) - .collect(); + let mut original_lines: Vec = original_contents.split('\n').map(String::from).collect(); // Drop the trailing empty element that results from the final newline so // that line counts match the behaviour of standard `diff`. - if original_lines.last().is_some_and(|s| s.is_empty()) { + if original_lines.last().is_some_and(String::is_empty) { original_lines.pop(); } let replacements = compute_replacements(&original_lines, path, chunks)?; let new_lines = apply_replacements(original_lines, &replacements); let mut new_lines = new_lines; - if !new_lines.last().is_some_and(|s| s.is_empty()) { + if !new_lines.last().is_some_and(String::is_empty) { new_lines.push(String::new()); } let new_contents = new_lines.join("\n"); @@ -706,7 +703,7 @@ fn compute_replacements( if chunk.old_lines.is_empty() { // Pure addition (no old lines). We'll add them at the end or just // before the final empty line if one exists. - let insertion_idx = if original_lines.last().is_some_and(|s| s.is_empty()) { + let insertion_idx = if original_lines.last().is_some_and(String::is_empty) { original_lines.len() - 1 } else { original_lines.len() @@ -732,11 +729,11 @@ fn compute_replacements( let mut new_slice: &[String] = &chunk.new_lines; - if found.is_none() && pattern.last().is_some_and(|s| s.is_empty()) { + if found.is_none() && pattern.last().is_some_and(String::is_empty) { // Retry without the trailing empty line which represents the final // newline in the file. pattern = &pattern[..pattern.len() - 1]; - if new_slice.last().is_some_and(|s| s.is_empty()) { + if new_slice.last().is_some_and(String::is_empty) { new_slice = &new_slice[..new_slice.len() - 1]; } @@ -848,6 +845,7 @@ mod tests { use super::*; use pretty_assertions::assert_eq; use std::fs; + use std::string::ToString; use tempfile::tempdir; /// Helper to construct a patch with the given body. @@ -856,7 +854,7 @@ mod tests { } fn strs_to_strings(strs: &[&str]) -> Vec { - strs.iter().map(|s| s.to_string()).collect() + strs.iter().map(ToString::to_string).collect() } // Test helpers to reduce repetition when building bash -lc heredoc scripts diff --git a/codex-rs/apply-patch/src/seek_sequence.rs b/codex-rs/apply-patch/src/seek_sequence.rs index 0144580f9b..b005b08c75 100644 --- a/codex-rs/apply-patch/src/seek_sequence.rs +++ b/codex-rs/apply-patch/src/seek_sequence.rs @@ -112,9 +112,10 @@ pub(crate) fn seek_sequence( #[cfg(test)] mod tests { use super::seek_sequence; + use std::string::ToString; fn to_vec(strings: &[&str]) -> Vec { - strings.iter().map(|s| s.to_string()).collect() + strings.iter().map(ToString::to_string).collect() } #[test] diff --git a/codex-rs/arg0/Cargo.toml b/codex-rs/arg0/Cargo.toml index a01120b798..10d09e4a4b 100644 --- a/codex-rs/arg0/Cargo.toml +++ b/codex-rs/arg0/Cargo.toml @@ -11,10 +11,10 @@ path = "src/lib.rs" workspace = true [dependencies] -anyhow = "1" -codex-apply-patch = { path = "../apply-patch" } -codex-core = { path = "../core" } -codex-linux-sandbox = { path = "../linux-sandbox" } -dotenvy = "0.15.7" -tempfile = "3" -tokio = { version = "1", features = ["rt-multi-thread"] } +anyhow = { workspace = true } +codex-apply-patch = { workspace = true } +codex-core = { workspace = true } +codex-linux-sandbox = { workspace = true } +dotenvy = { workspace = true } +tempfile = { workspace = true } +tokio = { workspace = true, features = ["rt-multi-thread"] } diff --git a/codex-rs/arg0/src/lib.rs b/codex-rs/arg0/src/lib.rs index d5df68e554..e70ff2df64 100644 --- a/codex-rs/arg0/src/lib.rs +++ b/codex-rs/arg0/src/lib.rs @@ -54,7 +54,7 @@ where let argv1 = args.next().unwrap_or_default(); if argv1 == CODEX_APPLY_PATCH_ARG1 { - let patch_arg = args.next().and_then(|s| s.to_str().map(|s| s.to_owned())); + let patch_arg = args.next().and_then(|s| s.to_str().map(str::to_owned)); let exit_code = match patch_arg { Some(patch_arg) => { let mut stdout = std::io::stdout(); diff --git a/codex-rs/chatgpt/Cargo.toml b/codex-rs/chatgpt/Cargo.toml index af5f910efe..97e14d7fe7 100644 --- a/codex-rs/chatgpt/Cargo.toml +++ b/codex-rs/chatgpt/Cargo.toml @@ -7,13 +7,13 @@ version = { workspace = true } workspace = true [dependencies] -anyhow = "1" -clap = { version = "4", features = ["derive"] } -codex-common = { path = "../common", features = ["cli"] } -codex-core = { path = "../core" } -serde = { version = "1", features = ["derive"] } -serde_json = "1" -tokio = { version = "1", features = ["full"] } +anyhow = { workspace = true } +clap = { workspace = true, features = ["derive"] } +codex-common = { workspace = true, features = ["cli"] } +codex-core = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +tokio = { workspace = true, features = ["full"] } [dev-dependencies] -tempfile = "3" +tempfile = { workspace = true } diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.toml index 291ef47748..c410e09a82 100644 --- a/codex-rs/cli/Cargo.toml +++ b/codex-rs/cli/Cargo.toml @@ -15,32 +15,34 @@ path = "src/lib.rs" workspace = true [dependencies] -anyhow = "1" -clap = { version = "4", features = ["derive"] } -clap_complete = "4" -codex-arg0 = { path = "../arg0" } -codex-chatgpt = { path = "../chatgpt" } -codex-common = { path = "../common", features = ["cli"] } -codex-core = { path = "../core" } -codex-exec = { path = "../exec" } -codex-login = { path = "../login" } -codex-mcp-server = { path = "../mcp-server" } -codex-protocol = { path = "../protocol" } -codex-tui = { path = "../tui" } -serde_json = "1" -tokio = { version = "1", features = [ +anyhow = { workspace = true } +clap = { workspace = true, features = ["derive"] } +clap_complete = { workspace = true } +codex-arg0 = { workspace = true } +codex-chatgpt = { workspace = true } +codex-common = { workspace = true, features = ["cli"] } +codex-core = { workspace = true } +codex-exec = { workspace = true } +codex-login = { workspace = true } +codex-mcp-server = { workspace = true } +codex-protocol = { workspace = true } +codex-protocol-ts = { workspace = true } +codex-tui = { workspace = true } +owo-colors = { workspace = true } +serde_json = { workspace = true } +supports-color = { workspace = true } +tokio = { workspace = true, features = [ "io-std", "macros", "process", "rt-multi-thread", "signal", ] } -tracing = "0.1.41" -tracing-subscriber = "0.3.20" -codex-protocol-ts = { path = "../protocol-ts" } +tracing = { workspace = true } +tracing-subscriber = { workspace = true } [dev-dependencies] -assert_cmd = "2" -predicates = "3" -pretty_assertions = "1" -tempfile = "3" +assert_cmd = { workspace = true } +predicates = { workspace = true } +pretty_assertions = { workspace = true } +tempfile = { workspace = true } diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index e66855fe73..df757b0cc5 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -14,8 +14,11 @@ use codex_cli::login::run_logout; use codex_cli::proto; use codex_common::CliConfigOverrides; use codex_exec::Cli as ExecCli; +use codex_tui::AppExitInfo; use codex_tui::Cli as TuiCli; +use owo_colors::OwoColorize; use std::path::PathBuf; +use supports_color::Stream; mod mcp_cmd; @@ -156,6 +159,41 @@ struct GenerateTsCommand { prettier: Option, } +fn format_exit_messages(exit_info: AppExitInfo, color_enabled: bool) -> Vec { + let AppExitInfo { + token_usage, + conversation_id, + } = exit_info; + + if token_usage.is_zero() { + return Vec::new(); + } + + let mut lines = vec![format!( + "{}", + codex_core::protocol::FinalOutput::from(token_usage) + )]; + + if let Some(session_id) = conversation_id { + let resume_cmd = format!("codex resume {session_id}"); + let command = if color_enabled { + resume_cmd.cyan().to_string() + } else { + resume_cmd + }; + lines.push(format!("To continue this session, run {command}.")); + } + + lines +} + +fn print_exit_messages(exit_info: AppExitInfo) { + let color_enabled = supports_color::on(Stream::Stdout).is_some(); + for line in format_exit_messages(exit_info, color_enabled) { + println!("{line}"); + } +} + fn main() -> anyhow::Result<()> { arg0_dispatch_or_else(|codex_linux_sandbox_exe| async move { cli_main(codex_linux_sandbox_exe).await?; @@ -176,13 +214,8 @@ async fn cli_main(codex_linux_sandbox_exe: Option) -> anyhow::Result<() &mut interactive.config_overrides, root_config_overrides.clone(), ); - let usage = codex_tui::run_main(interactive, codex_linux_sandbox_exe).await?; - if !usage.token_usage.is_zero() { - println!( - "{}", - codex_core::protocol::FinalOutput::from(usage.token_usage) - ); - } + let exit_info = codex_tui::run_main(interactive, codex_linux_sandbox_exe).await?; + print_exit_messages(exit_info); } Some(Subcommand::Exec(mut exec_cli)) => { prepend_config_flags( @@ -372,6 +405,8 @@ fn print_completion(cmd: CompletionCommand) { #[cfg(test)] mod tests { use super::*; + use codex_core::protocol::TokenUsage; + use codex_protocol::mcp_protocol::ConversationId; fn finalize_from_args(args: &[&str]) -> TuiCli { let cli = MultitoolCli::try_parse_from(args).expect("parse"); @@ -393,6 +428,52 @@ mod tests { finalize_resume_interactive(interactive, root_overrides, session_id, last, resume_cli) } + fn sample_exit_info(conversation: Option<&str>) -> AppExitInfo { + let token_usage = TokenUsage { + output_tokens: 2, + total_tokens: 2, + ..Default::default() + }; + AppExitInfo { + token_usage, + conversation_id: conversation + .map(ConversationId::from_string) + .map(Result::unwrap), + } + } + + #[test] + fn format_exit_messages_skips_zero_usage() { + let exit_info = AppExitInfo { + token_usage: TokenUsage::default(), + conversation_id: None, + }; + let lines = format_exit_messages(exit_info, false); + assert!(lines.is_empty()); + } + + #[test] + fn format_exit_messages_includes_resume_hint_without_color() { + let exit_info = sample_exit_info(Some("123e4567-e89b-12d3-a456-426614174000")); + let lines = format_exit_messages(exit_info, false); + assert_eq!( + lines, + vec![ + "Token usage: total=2 input=0 output=2".to_string(), + "To continue this session, run codex resume 123e4567-e89b-12d3-a456-426614174000." + .to_string(), + ] + ); + } + + #[test] + fn format_exit_messages_applies_color_when_enabled() { + let exit_info = sample_exit_info(Some("123e4567-e89b-12d3-a456-426614174000")); + let lines = format_exit_messages(exit_info, true); + assert_eq!(lines.len(), 2); + assert!(lines[1].contains("\u{1b}[36m")); + } + #[test] fn resume_model_flag_applies_when_no_root_flags() { let interactive = finalize_from_args(["codex", "resume", "-m", "gpt-5-test"].as_ref()); diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index 437511ad57..465de71aac 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -148,7 +148,8 @@ fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Result<( command: command_bin, args: command_args, env: env_map, - startup_timeout_ms: None, + startup_timeout_sec: None, + tool_timeout_sec: None, }; servers.insert(name.clone(), new_entry); @@ -210,7 +211,12 @@ fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> Resul "command": cfg.command, "args": cfg.args, "env": env, - "startup_timeout_ms": cfg.startup_timeout_ms, + "startup_timeout_sec": cfg + .startup_timeout_sec + .map(|timeout| timeout.as_secs_f64()), + "tool_timeout_sec": cfg + .tool_timeout_sec + .map(|timeout| timeout.as_secs_f64()), }) }) .collect(); @@ -305,7 +311,12 @@ fn run_get(config_overrides: &CliConfigOverrides, get_args: GetArgs) -> Result<( "command": server.command, "args": server.args, "env": env, - "startup_timeout_ms": server.startup_timeout_ms, + "startup_timeout_sec": server + .startup_timeout_sec + .map(|timeout| timeout.as_secs_f64()), + "tool_timeout_sec": server + .tool_timeout_sec + .map(|timeout| timeout.as_secs_f64()), }))?; println!("{output}"); return Ok(()); @@ -333,8 +344,11 @@ fn run_get(config_overrides: &CliConfigOverrides, get_args: GetArgs) -> Result<( } }; println!(" env: {env_display}"); - if let Some(timeout) = server.startup_timeout_ms { - println!(" startup_timeout_ms: {timeout}"); + if let Some(timeout) = server.startup_timeout_sec { + println!(" startup_timeout_sec: {}", timeout.as_secs_f64()); + } + if let Some(timeout) = server.tool_timeout_sec { + println!(" tool_timeout_sec: {}", timeout.as_secs_f64()); } println!(" remove: codex mcp remove {}", get_args.name); diff --git a/codex-rs/common/Cargo.toml b/codex-rs/common/Cargo.toml index b10600574c..3ce84a6f50 100644 --- a/codex-rs/common/Cargo.toml +++ b/codex-rs/common/Cargo.toml @@ -7,11 +7,11 @@ version = { workspace = true } workspace = true [dependencies] -clap = { version = "4", features = ["derive", "wrap_help"], optional = true } -codex-core = { path = "../core" } -codex-protocol = { path = "../protocol" } -serde = { version = "1", optional = true } -toml = { version = "0.9", optional = true } +clap = { workspace = true, features = ["derive", "wrap_help"], optional = true } +codex-core = { workspace = true } +codex-protocol = { workspace = true } +serde = { workspace = true, optional = true } +toml = { workspace = true, optional = true } [features] # Separate feature so that `clap` is not a mandatory dependency. diff --git a/codex-rs/common/src/model_presets.rs b/codex-rs/common/src/model_presets.rs index 065bb1e340..8eb5beacda 100644 --- a/codex-rs/common/src/model_presets.rs +++ b/codex-rs/common/src/model_presets.rs @@ -1,4 +1,3 @@ -use codex_core::config::GPT_5_CODEX_MEDIUM_MODEL; use codex_core::protocol_config_types::ReasoningEffort; use codex_protocol::mcp_protocol::AuthMode; @@ -69,13 +68,6 @@ const PRESETS: &[ModelPreset] = &[ }, ]; -pub fn builtin_model_presets(auth_mode: Option) -> Vec { - match auth_mode { - Some(AuthMode::ApiKey) => PRESETS - .iter() - .copied() - .filter(|p| p.model != GPT_5_CODEX_MEDIUM_MODEL) - .collect(), - _ => PRESETS.to_vec(), - } +pub fn builtin_model_presets(_auth_mode: Option) -> Vec { + PRESETS.to_vec() } diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 9973a00442..d9ded08283 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -12,81 +12,81 @@ path = "src/lib.rs" workspace = true [dependencies] -anyhow = "1" -askama = "0.12" -async-channel = "2.3.1" -base64 = "0.22" -bytes = "1.10.1" -chrono = { version = "0.4", features = ["serde"] } -codex-apply-patch = { path = "../apply-patch" } -codex-file-search = { path = "../file-search" } -codex-mcp-client = { path = "../mcp-client" } -codex-protocol = { path = "../protocol" } -dirs = "6" -env-flags = "0.1.1" -eventsource-stream = "0.2.3" -futures = "0.3" -libc = "0.2.175" -mcp-types = { path = "../mcp-types" } -os_info = "3.12.0" -portable-pty = "0.9.0" -rand = "0.9" -regex-lite = "0.1.7" -reqwest = { version = "0.12", features = ["json", "stream"] } -serde = { version = "1", features = ["derive"] } -serde_json = "1" -sha1 = "0.10.6" -shlex = "1.3.0" -similar = "2.7.0" -strum_macros = "0.27.2" -tempfile = "3" -thiserror = "2.0.16" -time = { version = "0.3", features = [ +anyhow = { workspace = true } +askama = { workspace = true } +async-channel = { workspace = true } +base64 = { workspace = true } +bytes = { workspace = true } +chrono = { workspace = true, features = ["serde"] } +codex-apply-patch = { workspace = true } +codex-file-search = { workspace = true } +codex-mcp-client = { workspace = true } +codex-protocol = { workspace = true } +dirs = { workspace = true } +env-flags = { workspace = true } +eventsource-stream = { workspace = true } +futures = { workspace = true } +libc = { workspace = true } +mcp-types = { workspace = true } +os_info = { workspace = true } +portable-pty = { workspace = true } +rand = { workspace = true } +regex-lite = { workspace = true } +reqwest = { workspace = true, features = ["json", "stream"] } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +sha1 = { workspace = true } +shlex = { workspace = true } +similar = { workspace = true } +strum_macros = { workspace = true } +tempfile = { workspace = true } +thiserror = { workspace = true } +time = { workspace = true, features = [ "formatting", "parsing", "local-offset", "macros", ] } -tokio = { version = "1", features = [ +tokio = { workspace = true, features = [ "io-std", "macros", "process", "rt-multi-thread", "signal", ] } -tokio-util = "0.7.16" -toml = "0.9.5" -toml_edit = "0.23.4" -tracing = { version = "0.1.41", features = ["log"] } -tree-sitter = "0.25.9" -tree-sitter-bash = "0.25.0" -uuid = { version = "1", features = ["serde", "v4"] } -which = "6" -wildmatch = "2.5.0" +tokio-util = { workspace = true } +toml = { workspace = true } +toml_edit = { workspace = true } +tracing = { workspace = true, features = ["log"] } +tree-sitter = { workspace = true } +tree-sitter-bash = { workspace = true } +uuid = { workspace = true, features = ["serde", "v4"] } +which = { workspace = true } +wildmatch = { workspace = true } [target.'cfg(target_os = "linux")'.dependencies] -landlock = "0.4.1" -seccompiler = "0.5.0" +landlock = { workspace = true } +seccompiler = { workspace = true } # Build OpenSSL from source for musl builds. [target.x86_64-unknown-linux-musl.dependencies] -openssl-sys = { version = "*", features = ["vendored"] } +openssl-sys = { workspace = true, features = ["vendored"] } # Build OpenSSL from source for musl builds. [target.aarch64-unknown-linux-musl.dependencies] -openssl-sys = { version = "*", features = ["vendored"] } +openssl-sys = { workspace = true, features = ["vendored"] } [dev-dependencies] -assert_cmd = "2" -core_test_support = { path = "tests/common" } -maplit = "1.0.2" -predicates = "3" -pretty_assertions = "1.4.1" -tempfile = "3" -tokio-test = "0.4" -walkdir = "2.5.0" -wiremock = "0.6" +assert_cmd = { workspace = true } +core_test_support = { workspace = true } +maplit = { workspace = true } +predicates = { workspace = true } +pretty_assertions = { workspace = true } +tempfile = { workspace = true } +tokio-test = { workspace = true } +walkdir = { workspace = true } +wiremock = { workspace = true } [package.metadata.cargo-shear] ignored = ["openssl-sys"] diff --git a/codex-rs/core/src/bash.rs b/codex-rs/core/src/bash.rs index 4bed3a9c16..f25b4f7f67 100644 --- a/codex-rs/core/src/bash.rs +++ b/codex-rs/core/src/bash.rs @@ -1,3 +1,4 @@ +use tree_sitter::Node; use tree_sitter::Parser; use tree_sitter::Tree; use tree_sitter_bash::LANGUAGE as BASH; @@ -74,7 +75,7 @@ pub fn try_parse_word_only_commands_sequence(tree: &Tree, src: &str) -> Option( if let Some(reasoning_val) = choice.get("delta").and_then(|d| d.get("reasoning")) { let mut maybe_text = reasoning_val .as_str() - .map(|s| s.to_string()) + .map(str::to_string) .filter(|s| !s.is_empty()); if maybe_text.is_none() && reasoning_val.is_object() { diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 57848d388b..72ca770abd 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -4,6 +4,7 @@ use std::sync::OnceLock; use std::time::Duration; use crate::AuthManager; +use crate::auth::CodexAuth; use bytes::Bytes; use codex_protocol::mcp_protocol::AuthMode; use codex_protocol::mcp_protocol::ConversationId; @@ -337,7 +338,7 @@ impl ModelClient { // token. let plan_type = error .plan_type - .or_else(|| auth.as_ref().and_then(|a| a.get_plan_type())); + .or_else(|| auth.as_ref().and_then(CodexAuth::get_plan_type)); let resets_in_seconds = error.resets_in_seconds; return Err(CodexErr::UsageLimitReached(UsageLimitReachedError { plan_type, @@ -486,18 +487,18 @@ fn attach_item_ids(payload_json: &mut Value, original_items: &[ResponseItem]) { fn parse_rate_limit_snapshot(headers: &HeaderMap) -> Option { let primary_used_percent = parse_header_f64(headers, "x-codex-primary-used-percent")?; - let weekly_used_percent = parse_header_f64(headers, "x-codex-protection-used-percent")?; - let primary_to_weekly_ratio_percent = - parse_header_f64(headers, "x-codex-primary-over-protection-limit-percent")?; + let secondary_used_percent = parse_header_f64(headers, "x-codex-secondary-used-percent")?; + let primary_to_secondary_ratio_percent = + parse_header_f64(headers, "x-codex-primary-over-secondary-limit-percent")?; let primary_window_minutes = parse_header_u64(headers, "x-codex-primary-window-minutes")?; - let weekly_window_minutes = parse_header_u64(headers, "x-codex-protection-window-minutes")?; + let secondary_window_minutes = parse_header_u64(headers, "x-codex-secondary-window-minutes")?; Some(RateLimitSnapshotEvent { primary_used_percent, - weekly_used_percent, - primary_to_weekly_ratio_percent, + secondary_used_percent, + primary_to_secondary_ratio_percent, primary_window_minutes, - weekly_window_minutes, + secondary_window_minutes, }) } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 05ef09377e..08b28bdef5 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -1008,10 +1008,9 @@ impl Session { server: &str, tool: &str, arguments: Option, - timeout: Option, ) -> anyhow::Result { self.mcp_connection_manager - .call_tool(server, tool, arguments, timeout) + .call_tool(server, tool, arguments) .await } @@ -1748,7 +1747,7 @@ async fn run_task( .unwrap_or(i64::MAX); let total_usage_tokens = total_token_usage .as_ref() - .map(|usage| usage.tokens_in_context_window()); + .map(TokenUsage::tokens_in_context_window); let token_limit_reached = total_usage_tokens .map(|tokens| (tokens as i64) >= limit) .unwrap_or(false); @@ -2596,12 +2595,7 @@ async fn handle_function_call( _ => { match sess.mcp_connection_manager.parse_tool_name(&name) { Some((server, tool_name)) => { - // TODO(mbolin): Determine appropriate timeout for tool call. - let timeout = None; - handle_mcp_tool_call( - sess, &sub_id, call_id, server, tool_name, arguments, timeout, - ) - .await + handle_mcp_tool_call(sess, &sub_id, call_id, server, tool_name, arguments).await } None => { // Unknown function: reply with structured failure so the model can adapt. diff --git a/codex-rs/core/src/codex/compact.rs b/codex-rs/core/src/codex/compact.rs index 05d57cd945..d1547a4818 100644 --- a/codex-rs/core/src/codex/compact.rs +++ b/codex-rs/core/src/codex/compact.rs @@ -18,6 +18,7 @@ use crate::protocol::InputMessageKind; use crate::protocol::TaskCompleteEvent; use crate::protocol::TaskStartedEvent; use crate::protocol::TurnContextItem; +use crate::truncate::truncate_middle; use crate::util::backoff; use askama::Template; use codex_protocol::models::ContentItem; @@ -28,6 +29,7 @@ use futures::prelude::*; pub(super) const COMPACT_TRIGGER_TEXT: &str = "Start Summarization"; const SUMMARIZATION_PROMPT: &str = include_str!("../../templates/compact/prompt.md"); +const COMPACT_USER_MESSAGE_MAX_TOKENS: usize = 20_000; #[derive(Template)] #[template(path = "compact/history_bridge.md", escape = "none")] @@ -248,11 +250,17 @@ pub(crate) fn build_compacted_history( summary_text: &str, ) -> Vec { let mut history = initial_context; - let user_messages_text = if user_messages.is_empty() { + let mut user_messages_text = if user_messages.is_empty() { "(none)".to_string() } else { user_messages.join("\n\n") }; + // Truncate the concatenated prior user messages so the bridge message + // stays well under the context window (approx. 4 bytes/token). + let max_bytes = COMPACT_USER_MESSAGE_MAX_TOKENS * 4; + if user_messages_text.len() > max_bytes { + user_messages_text = truncate_middle(&user_messages_text, max_bytes).0; + } let summary_text = if summary_text.is_empty() { "(no summary available)".to_string() } else { @@ -396,4 +404,38 @@ mod tests { assert_eq!(vec!["real user message".to_string()], collected); } + + #[test] + fn build_compacted_history_truncates_overlong_user_messages() { + // Prepare a very large prior user message so the aggregated + // `user_messages_text` exceeds the truncation threshold used by + // `build_compacted_history` (80k bytes). + let big = "X".repeat(200_000); + let history = build_compacted_history(Vec::new(), std::slice::from_ref(&big), "SUMMARY"); + + // Expect exactly one bridge message added to history (plus any initial context we provided, which is none). + assert_eq!(history.len(), 1); + + // Extract the text content of the bridge message. + let bridge_text = match &history[0] { + ResponseItem::Message { role, content, .. } if role == "user" => { + content_items_to_text(content).unwrap_or_default() + } + other => panic!("unexpected item in history: {other:?}"), + }; + + // The bridge should contain the truncation marker and not the full original payload. + assert!( + bridge_text.contains("tokens truncated"), + "expected truncation marker in bridge message" + ); + assert!( + !bridge_text.contains(&big), + "bridge should not include the full oversized user text" + ); + assert!( + bridge_text.contains("SUMMARY"), + "bridge should include the provided summary text" + ); + } } diff --git a/codex-rs/core/src/config.rs b/codex-rs/core/src/config.rs index c84d84e0ff..508a3dc36f 100644 --- a/codex-rs/core/src/config.rs +++ b/codex-rs/core/src/config.rs @@ -37,7 +37,7 @@ use toml_edit::DocumentMut; use toml_edit::Item as TomlItem; use toml_edit::Table as TomlTable; -const OPENAI_DEFAULT_MODEL: &str = "gpt-5"; +const OPENAI_DEFAULT_MODEL: &str = "gpt-5-codex"; const OPENAI_DEFAULT_REVIEW_MODEL: &str = "gpt-5-codex"; pub const GPT_5_CODEX_MEDIUM_MODEL: &str = "gpt-5-codex"; @@ -54,7 +54,7 @@ pub struct Config { /// Optional override of model selection. pub model: String, - /// Model used specifically for review sessions. Defaults to "gpt-5". + /// Model used specifically for review sessions. Defaults to "gpt-5-codex". pub review_model: String, pub model_family: ModelFamily, @@ -333,14 +333,12 @@ pub fn write_global_mcp_servers( entry["env"] = TomlItem::Table(env_table); } - if let Some(timeout) = config.startup_timeout_ms { - let timeout = i64::try_from(timeout).map_err(|_| { - std::io::Error::new( - std::io::ErrorKind::InvalidData, - "startup_timeout_ms exceeds supported range", - ) - })?; - entry["startup_timeout_ms"] = toml_edit::value(timeout); + if let Some(timeout) = config.startup_timeout_sec { + entry["startup_timeout_sec"] = toml_edit::value(timeout.as_secs_f64()); + } + + if let Some(timeout) = config.tool_timeout_sec { + entry["tool_timeout_sec"] = toml_edit::value(timeout.as_secs_f64()); } doc["mcp_servers"][name.as_str()] = TomlItem::Table(entry); @@ -1168,6 +1166,7 @@ mod tests { use super::*; use pretty_assertions::assert_eq; + use std::time::Duration; use tempfile::TempDir; #[test] @@ -1292,7 +1291,8 @@ exclude_slash_tmp = true command: "echo".to_string(), args: vec!["hello".to_string()], env: None, - startup_timeout_ms: None, + startup_timeout_sec: Some(Duration::from_secs(3)), + tool_timeout_sec: Some(Duration::from_secs(5)), }, ); @@ -1303,6 +1303,8 @@ exclude_slash_tmp = true let docs = loaded.get("docs").expect("docs entry"); assert_eq!(docs.command, "echo"); assert_eq!(docs.args, vec!["hello".to_string()]); + assert_eq!(docs.startup_timeout_sec, Some(Duration::from_secs(3))); + assert_eq!(docs.tool_timeout_sec, Some(Duration::from_secs(5))); let empty = BTreeMap::new(); write_global_mcp_servers(codex_home.path(), &empty)?; @@ -1312,6 +1314,28 @@ exclude_slash_tmp = true Ok(()) } + #[test] + fn load_global_mcp_servers_accepts_legacy_ms_field() -> anyhow::Result<()> { + let codex_home = TempDir::new()?; + let config_path = codex_home.path().join(CONFIG_TOML_FILE); + + std::fs::write( + &config_path, + r#" +[mcp_servers] +[mcp_servers.docs] +command = "echo" +startup_timeout_ms = 2500 +"#, + )?; + + let servers = load_global_mcp_servers(codex_home.path())?; + let docs = servers.get("docs").expect("docs entry"); + assert_eq!(docs.startup_timeout_sec, Some(Duration::from_millis(2500))); + + Ok(()) + } + #[tokio::test] async fn persist_model_selection_updates_defaults() -> anyhow::Result<()> { let codex_home = TempDir::new()?; @@ -1342,7 +1366,7 @@ exclude_slash_tmp = true tokio::fs::write( &config_path, r#" -model = "gpt-5" +model = "gpt-5-codex" model_reasoning_effort = "medium" [profiles.dev] @@ -1417,7 +1441,7 @@ model = "gpt-4" model_reasoning_effort = "medium" [profiles.prod] -model = "gpt-5" +model = "gpt-5-codex" "#, ) .await?; @@ -1448,7 +1472,7 @@ model = "gpt-5" .profiles .get("prod") .and_then(|profile| profile.model.as_deref()), - Some("gpt-5"), + Some("gpt-5-codex"), ); Ok(()) diff --git a/codex-rs/core/src/config_edit.rs b/codex-rs/core/src/config_edit.rs index 4b3a5cbdb0..6e68c08ca0 100644 --- a/codex-rs/core/src/config_edit.rs +++ b/codex-rs/core/src/config_edit.rs @@ -136,7 +136,7 @@ async fn persist_overrides_with_behavior( } else { doc.get("profile") .and_then(|i| i.as_str()) - .map(|s| s.to_string()) + .map(str::to_string) }; let mut mutated = false; @@ -228,7 +228,7 @@ mod tests { codex_home, None, &[ - (&[CONFIG_KEY_MODEL], "gpt-5"), + (&[CONFIG_KEY_MODEL], "gpt-5-codex"), (&[CONFIG_KEY_EFFORT], "high"), ], ) @@ -236,7 +236,7 @@ mod tests { .expect("persist"); let contents = read_config(codex_home).await; - let expected = r#"model = "gpt-5" + let expected = r#"model = "gpt-5-codex" model_reasoning_effort = "high" "#; assert_eq!(contents, expected); @@ -348,7 +348,7 @@ model_reasoning_effort = "high" &[ (&["a", "b", "c"], "v"), (&["x"], "y"), - (&["profiles", "p1", CONFIG_KEY_MODEL], "gpt-5"), + (&["profiles", "p1", CONFIG_KEY_MODEL], "gpt-5-codex"), ], ) .await @@ -361,7 +361,7 @@ model_reasoning_effort = "high" c = "v" [profiles.p1] -model = "gpt-5" +model = "gpt-5-codex" "#; assert_eq!(contents, expected); } @@ -454,7 +454,7 @@ existing = "keep" codex_home, None, &[ - (&[CONFIG_KEY_MODEL], "gpt-5"), + (&[CONFIG_KEY_MODEL], "gpt-5-codex"), (&[CONFIG_KEY_EFFORT], "minimal"), ], ) @@ -466,7 +466,7 @@ existing = "keep" # should be preserved existing = "keep" -model = "gpt-5" +model = "gpt-5-codex" model_reasoning_effort = "minimal" "#; assert_eq!(contents, expected); @@ -524,7 +524,7 @@ model = "o3" let codex_home = tmpdir.path(); // Seed with a model value only - let seed = "model = \"gpt-5\"\n"; + let seed = "model = \"gpt-5-codex\"\n"; tokio::fs::write(codex_home.join(CONFIG_TOML_FILE), seed) .await .expect("seed write"); @@ -535,7 +535,7 @@ model = "o3" .expect("persist"); let contents = read_config(codex_home).await; - let expected = r#"model = "gpt-5" + let expected = r#"model = "gpt-5-codex" model_reasoning_effort = "high" "#; assert_eq!(contents, expected); @@ -579,7 +579,7 @@ model = "o4-mini" // No active profile key; we'll target an explicit override let seed = r#"[profiles.team] -model = "gpt-5" +model = "gpt-5-codex" "#; tokio::fs::write(codex_home.join(CONFIG_TOML_FILE), seed) .await @@ -595,7 +595,7 @@ model = "gpt-5" let contents = read_config(codex_home).await; let expected = r#"[profiles.team] -model = "gpt-5" +model = "gpt-5-codex" model_reasoning_effort = "minimal" "#; assert_eq!(contents, expected); @@ -611,7 +611,7 @@ model_reasoning_effort = "minimal" codex_home, None, &[ - (&[CONFIG_KEY_MODEL], Some("gpt-5")), + (&[CONFIG_KEY_MODEL], Some("gpt-5-codex")), (&[CONFIG_KEY_EFFORT], None), ], ) @@ -619,7 +619,7 @@ model_reasoning_effort = "minimal" .expect("persist"); let contents = read_config(codex_home).await; - let expected = "model = \"gpt-5\"\n"; + let expected = "model = \"gpt-5-codex\"\n"; assert_eq!(contents, expected); } @@ -670,7 +670,7 @@ model = "o3" let tmpdir = tempdir().expect("tmp"); let codex_home = tmpdir.path(); - let seed = r#"model = "gpt-5" + let seed = r#"model = "gpt-5-codex" model_reasoning_effort = "medium" "#; tokio::fs::write(codex_home.join(CONFIG_TOML_FILE), seed) diff --git a/codex-rs/core/src/config_types.rs b/codex-rs/core/src/config_types.rs index 3737649871..d273b23d69 100644 --- a/codex-rs/core/src/config_types.rs +++ b/codex-rs/core/src/config_types.rs @@ -5,11 +5,15 @@ use std::collections::HashMap; use std::path::PathBuf; +use std::time::Duration; use wildmatch::WildMatchPattern; use serde::Deserialize; +use serde::Deserializer; +use serde::Serialize; +use serde::de::Error as SerdeError; -#[derive(Deserialize, Debug, Clone, PartialEq)] +#[derive(Serialize, Debug, Clone, PartialEq)] pub struct McpServerConfig { pub command: String, @@ -19,9 +23,84 @@ pub struct McpServerConfig { #[serde(default)] pub env: Option>, - /// Startup timeout in milliseconds for initializing MCP server & initially listing tools. - #[serde(default)] - pub startup_timeout_ms: Option, + /// Startup timeout in seconds for initializing MCP server & initially listing tools. + #[serde( + default, + with = "option_duration_secs", + skip_serializing_if = "Option::is_none" + )] + pub startup_timeout_sec: Option, + + /// Default timeout for MCP tool calls initiated via this server. + #[serde(default, with = "option_duration_secs")] + pub tool_timeout_sec: Option, +} + +impl<'de> Deserialize<'de> for McpServerConfig { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + #[derive(Deserialize)] + struct RawMcpServerConfig { + command: String, + #[serde(default)] + args: Vec, + #[serde(default)] + env: Option>, + #[serde(default)] + startup_timeout_sec: Option, + #[serde(default)] + startup_timeout_ms: Option, + #[serde(default, with = "option_duration_secs")] + tool_timeout_sec: Option, + } + + let raw = RawMcpServerConfig::deserialize(deserializer)?; + + let startup_timeout_sec = match (raw.startup_timeout_sec, raw.startup_timeout_ms) { + (Some(sec), _) => { + let duration = Duration::try_from_secs_f64(sec).map_err(SerdeError::custom)?; + Some(duration) + } + (None, Some(ms)) => Some(Duration::from_millis(ms)), + (None, None) => None, + }; + + Ok(Self { + command: raw.command, + args: raw.args, + env: raw.env, + startup_timeout_sec, + tool_timeout_sec: raw.tool_timeout_sec, + }) + } +} + +mod option_duration_secs { + use serde::Deserialize; + use serde::Deserializer; + use serde::Serializer; + use std::time::Duration; + + pub fn serialize(value: &Option, serializer: S) -> Result + where + S: Serializer, + { + match value { + Some(duration) => serializer.serialize_some(&duration.as_secs_f64()), + None => serializer.serialize_none(), + } + } + + pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + let secs = Option::::deserialize(deserializer)?; + secs.map(|secs| Duration::try_from_secs_f64(secs).map_err(serde::de::Error::custom)) + .transpose() + } } #[derive(Deserialize, Debug, Copy, Clone, PartialEq)] diff --git a/codex-rs/core/src/custom_prompts.rs b/codex-rs/core/src/custom_prompts.rs index 4974e7c52d..357abef55b 100644 --- a/codex-rs/core/src/custom_prompts.rs +++ b/codex-rs/core/src/custom_prompts.rs @@ -52,7 +52,7 @@ pub async fn discover_prompts_in_excluding( let Some(name) = path .file_stem() .and_then(|s| s.to_str()) - .map(|s| s.to_string()) + .map(str::to_string) else { continue; }; diff --git a/codex-rs/core/src/git_info.rs b/codex-rs/core/src/git_info.rs index ca62ad499e..5c16b72da6 100644 --- a/codex-rs/core/src/git_info.rs +++ b/codex-rs/core/src/git_info.rs @@ -108,6 +108,61 @@ pub async fn collect_git_info(cwd: &Path) -> Option { Some(git_info) } +/// A minimal commit summary entry used for pickers (subject + timestamp + sha). +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct CommitLogEntry { + pub sha: String, + /// Unix timestamp (seconds since epoch) of the commit time (committer time). + pub timestamp: i64, + /// Single-line subject of the commit message. + pub subject: String, +} + +/// Return the last `limit` commits reachable from HEAD for the current branch. +/// Each entry contains the SHA, commit timestamp (seconds), and subject line. +/// Returns an empty vector if not in a git repo or on error/timeout. +pub async fn recent_commits(cwd: &Path, limit: usize) -> Vec { + // Ensure we're in a git repo first to avoid noisy errors. + let Some(out) = run_git_command_with_timeout(&["rev-parse", "--git-dir"], cwd).await else { + return Vec::new(); + }; + if !out.status.success() { + return Vec::new(); + } + + let fmt = "%H%x1f%ct%x1f%s"; // + let n = limit.max(1).to_string(); + let Some(log_out) = + run_git_command_with_timeout(&["log", "-n", &n, &format!("--pretty=format:{fmt}")], cwd) + .await + else { + return Vec::new(); + }; + if !log_out.status.success() { + return Vec::new(); + } + + let text = String::from_utf8_lossy(&log_out.stdout); + let mut entries: Vec = Vec::new(); + for line in text.lines() { + let mut parts = line.split('\u{001f}'); + let sha = parts.next().unwrap_or("").trim(); + let ts_s = parts.next().unwrap_or("").trim(); + let subject = parts.next().unwrap_or("").trim(); + if sha.is_empty() || ts_s.is_empty() { + continue; + } + let timestamp = ts_s.parse::().unwrap_or(0); + entries.push(CommitLogEntry { + sha: sha.to_string(), + timestamp, + subject: subject.to_string(), + }); + } + + entries +} + /// Returns the closest git sha to HEAD that is on a remote as well as the diff to that sha. pub async fn git_diff_to_remote(cwd: &Path) -> Option { get_git_repo_root(cwd)?; @@ -145,7 +200,7 @@ async fn get_git_remotes(cwd: &Path) -> Option> { let mut remotes: Vec = String::from_utf8(output.stdout) .ok()? .lines() - .map(|s| s.to_string()) + .map(str::to_string) .collect(); if let Some(pos) = remotes.iter().position(|r| r == "origin") { let origin = remotes.remove(pos); @@ -202,6 +257,11 @@ async fn get_default_branch(cwd: &Path) -> Option { } // No remote-derived default; try common local defaults if they exist + get_default_branch_local(cwd).await +} + +/// Attempt to determine the repository's default branch name from local branches. +async fn get_default_branch_local(cwd: &Path) -> Option { for candidate in ["main", "master"] { if let Some(verify) = run_git_command_with_timeout( &[ @@ -417,7 +477,7 @@ async fn diff_against_sha(cwd: &Path, sha: &GitSha) -> Option { let untracked: Vec = String::from_utf8(untracked_output.stdout) .ok()? .lines() - .map(|s| s.to_string()) + .map(str::to_string) .filter(|s| !s.is_empty()) .collect(); @@ -485,6 +545,46 @@ pub fn resolve_root_git_project_for_trust(cwd: &Path) -> Option { git_dir_path.parent().map(Path::to_path_buf) } +/// Returns a list of local git branches. +/// Includes the default branch at the beginning of the list, if it exists. +pub async fn local_git_branches(cwd: &Path) -> Vec { + let mut branches: Vec = if let Some(out) = + run_git_command_with_timeout(&["branch", "--format=%(refname:short)"], cwd).await + && out.status.success() + { + String::from_utf8_lossy(&out.stdout) + .lines() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect() + } else { + Vec::new() + }; + + branches.sort_unstable(); + + if let Some(base) = get_default_branch_local(cwd).await + && let Some(pos) = branches.iter().position(|name| name == &base) + { + let base_branch = branches.remove(pos); + branches.insert(0, base_branch); + } + + branches +} + +/// Returns the current checked out branch name. +pub async fn current_branch_name(cwd: &Path) -> Option { + let out = run_git_command_with_timeout(&["branch", "--show-current"], cwd).await?; + if !out.status.success() { + return None; + } + String::from_utf8(out.stdout) + .ok() + .map(|s| s.trim().to_string()) + .filter(|name| !name.is_empty()) +} + #[cfg(test)] mod tests { use super::*; @@ -551,6 +651,80 @@ mod tests { repo_path } + #[tokio::test] + async fn test_recent_commits_non_git_directory_returns_empty() { + let temp_dir = TempDir::new().expect("Failed to create temp dir"); + let entries = recent_commits(temp_dir.path(), 10).await; + assert!(entries.is_empty(), "expected no commits outside a git repo"); + } + + #[tokio::test] + async fn test_recent_commits_orders_and_limits() { + use tokio::time::Duration; + use tokio::time::sleep; + + let temp_dir = TempDir::new().expect("Failed to create temp dir"); + let repo_path = create_test_git_repo(&temp_dir).await; + + // Make three distinct commits with small delays to ensure ordering by timestamp. + fs::write(repo_path.join("file.txt"), "one").unwrap(); + Command::new("git") + .args(["add", "file.txt"]) + .current_dir(&repo_path) + .output() + .await + .expect("git add"); + Command::new("git") + .args(["commit", "-m", "first change"]) + .current_dir(&repo_path) + .output() + .await + .expect("git commit 1"); + + sleep(Duration::from_millis(1100)).await; + + fs::write(repo_path.join("file.txt"), "two").unwrap(); + Command::new("git") + .args(["add", "file.txt"]) + .current_dir(&repo_path) + .output() + .await + .expect("git add 2"); + Command::new("git") + .args(["commit", "-m", "second change"]) + .current_dir(&repo_path) + .output() + .await + .expect("git commit 2"); + + sleep(Duration::from_millis(1100)).await; + + fs::write(repo_path.join("file.txt"), "three").unwrap(); + Command::new("git") + .args(["add", "file.txt"]) + .current_dir(&repo_path) + .output() + .await + .expect("git add 3"); + Command::new("git") + .args(["commit", "-m", "third change"]) + .current_dir(&repo_path) + .output() + .await + .expect("git commit 3"); + + // Request the latest 3 commits; should be our three changes in reverse time order. + let entries = recent_commits(&repo_path, 3).await; + assert_eq!(entries.len(), 3); + assert_eq!(entries[0].subject, "third change"); + assert_eq!(entries[1].subject, "second change"); + assert_eq!(entries[2].subject, "first change"); + // Basic sanity on SHA formatting + for e in entries { + assert!(e.sha.len() >= 7 && e.sha.chars().all(|c| c.is_ascii_hexdigit())); + } + } + async fn create_test_git_repo_with_remote(temp_dir: &TempDir) -> (PathBuf, String) { let repo_path = create_test_git_repo(temp_dir).await; let remote_path = temp_dir.path().join("remote.git"); diff --git a/codex-rs/core/src/internal_storage.rs b/codex-rs/core/src/internal_storage.rs index e8e0c09057..666d9287eb 100644 --- a/codex-rs/core/src/internal_storage.rs +++ b/codex-rs/core/src/internal_storage.rs @@ -7,14 +7,27 @@ use std::path::PathBuf; pub(crate) const INTERNAL_STORAGE_FILE: &str = "internal_storage.json"; -#[derive(Debug, Default, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct InternalStorage { #[serde(skip)] storage_path: PathBuf, - #[serde(default)] + #[serde(default = "default_gpt_5_codex_model_prompt_seen")] pub gpt_5_codex_model_prompt_seen: bool, } +const fn default_gpt_5_codex_model_prompt_seen() -> bool { + true +} + +impl Default for InternalStorage { + fn default() -> Self { + Self { + storage_path: PathBuf::new(), + gpt_5_codex_model_prompt_seen: default_gpt_5_codex_model_prompt_seen(), + } + } +} + // TODO(jif) generalise all the file writers and build proper async channel inserters. impl InternalStorage { pub fn load(codex_home: &Path) -> Self { diff --git a/codex-rs/core/src/is_safe_command.rs b/codex-rs/core/src/is_safe_command.rs index f54e247fd8..12eb36e0a5 100644 --- a/codex-rs/core/src/is_safe_command.rs +++ b/codex-rs/core/src/is_safe_command.rs @@ -160,9 +160,10 @@ fn is_valid_sed_n_arg(arg: Option<&str>) -> bool { #[cfg(test)] mod tests { use super::*; + use std::string::ToString; fn vec_str(args: &[&str]) -> Vec { - args.iter().map(|s| s.to_string()).collect() + args.iter().map(ToString::to_string).collect() } #[test] diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index eecda78887..e9c95fc80b 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -40,6 +40,9 @@ const MAX_TOOL_NAME_LENGTH: usize = 64; /// Default timeout for initializing MCP server & initially listing tools. const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(10); +/// Default timeout for individual tool calls. +const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(60); + /// Map that holds a startup error for every MCP server that could **not** be /// spawned successfully. pub type ClientStartErrors = HashMap; @@ -85,6 +88,7 @@ struct ToolInfo { struct ManagedClient { client: Arc, startup_timeout: Duration, + tool_timeout: Option, } /// A thin wrapper around a set of running [`McpClient`] instances. @@ -132,10 +136,9 @@ impl McpConnectionManager { continue; } - let startup_timeout = cfg - .startup_timeout_ms - .map(Duration::from_millis) - .unwrap_or(DEFAULT_STARTUP_TIMEOUT); + let startup_timeout = cfg.startup_timeout_sec.unwrap_or(DEFAULT_STARTUP_TIMEOUT); + + let tool_timeout = cfg.tool_timeout_sec.unwrap_or(DEFAULT_TOOL_TIMEOUT); join_set.spawn(async move { let McpServerConfig { @@ -171,19 +174,19 @@ impl McpConnectionManager { protocol_version: mcp_types::MCP_SCHEMA_VERSION.to_owned(), }; let initialize_notification_params = None; - match client + let init_result = client .initialize( params, initialize_notification_params, Some(startup_timeout), ) - .await - { - Ok(_response) => (server_name, Ok((client, startup_timeout))), - Err(e) => (server_name, Err(e)), - } + .await; + ( + (server_name, tool_timeout), + init_result.map(|_| (client, startup_timeout)), + ) } - Err(e) => (server_name, Err(e.into())), + Err(e) => ((server_name, tool_timeout), Err(e.into())), } }); } @@ -191,8 +194,8 @@ impl McpConnectionManager { let mut clients: HashMap = HashMap::with_capacity(join_set.len()); while let Some(res) = join_set.join_next().await { - let (server_name, client_res) = match res { - Ok((server_name, client_res)) => (server_name, client_res), + let ((server_name, tool_timeout), client_res) = match res { + Ok(result) => result, Err(e) => { warn!("Task panic when starting MCP server: {e:#}"); continue; @@ -206,6 +209,7 @@ impl McpConnectionManager { ManagedClient { client: Arc::new(client), startup_timeout, + tool_timeout: Some(tool_timeout), }, ); } @@ -243,14 +247,13 @@ impl McpConnectionManager { server: &str, tool: &str, arguments: Option, - timeout: Option, ) -> Result { - let client = self + let managed = self .clients .get(server) - .ok_or_else(|| anyhow!("unknown MCP server '{server}'"))? - .client - .clone(); + .ok_or_else(|| anyhow!("unknown MCP server '{server}'"))?; + let client = managed.client.clone(); + let timeout = managed.tool_timeout; client .call_tool(tool.to_string(), arguments, timeout) diff --git a/codex-rs/core/src/mcp_tool_call.rs b/codex-rs/core/src/mcp_tool_call.rs index 57b29262d2..7091a05656 100644 --- a/codex-rs/core/src/mcp_tool_call.rs +++ b/codex-rs/core/src/mcp_tool_call.rs @@ -1,4 +1,3 @@ -use std::time::Duration; use std::time::Instant; use tracing::error; @@ -21,7 +20,6 @@ pub(crate) async fn handle_mcp_tool_call( server: String, tool_name: String, arguments: String, - timeout: Option, ) -> ResponseInputItem { // Parse the `arguments` as JSON. An empty string is OK, but invalid JSON // is not. @@ -58,7 +56,7 @@ pub(crate) async fn handle_mcp_tool_call( let start = Instant::now(); // Perform the tool call. let result = sess - .call_tool(&server, &tool_name, arguments_value.clone(), timeout) + .call_tool(&server, &tool_name, arguments_value.clone()) .await .map_err(|e| format!("tool call error: {e}")); let tool_call_end_event = EventMsg::McpToolCallEnd(McpToolCallEndEvent { diff --git a/codex-rs/core/src/openai_tools.rs b/codex-rs/core/src/openai_tools.rs index 05b71ce6ea..48dca79671 100644 --- a/codex-rs/core/src/openai_tools.rs +++ b/codex-rs/core/src/openai_tools.rs @@ -400,10 +400,7 @@ fn sanitize_json_schema(value: &mut JsonValue) { } // Normalize/ensure type - let mut ty = map - .get("type") - .and_then(|v| v.as_str()) - .map(|s| s.to_string()); + let mut ty = map.get("type").and_then(|v| v.as_str()).map(str::to_string); // If type is an array (union), pick first supported; else leave to inference if ty.is_none() diff --git a/codex-rs/core/src/parse_command.rs b/codex-rs/core/src/parse_command.rs index 1d2948a406..3c89b61c91 100644 --- a/codex-rs/core/src/parse_command.rs +++ b/codex-rs/core/src/parse_command.rs @@ -40,7 +40,7 @@ impl From for codex_protocol::parse_command::ParsedCommand { } fn shlex_join(tokens: &[String]) -> String { - shlex_try_join(tokens.iter().map(|s| s.as_str())) + shlex_try_join(tokens.iter().map(String::as_str)) .unwrap_or_else(|_| "".to_string()) } @@ -72,13 +72,14 @@ pub fn parse_command(command: &[String]) -> Vec { /// Tests are at the top to encourage using TDD + Codex to fix the implementation. mod tests { use super::*; + use std::string::ToString; fn shlex_split_safe(s: &str) -> Vec { - shlex_split(s).unwrap_or_else(|| s.split_whitespace().map(|s| s.to_string()).collect()) + shlex_split(s).unwrap_or_else(|| s.split_whitespace().map(ToString::to_string).collect()) } fn vec_str(args: &[&str]) -> Vec { - args.iter().map(|s| s.to_string()).collect() + args.iter().map(ToString::to_string).collect() } fn assert_parsed(args: &[String], expected: Vec) { @@ -894,7 +895,7 @@ fn simplify_once(commands: &[ParsedCommand]) -> Option> { // echo ... && ...rest => ...rest if let ParsedCommand::Unknown { cmd } = &commands[0] - && shlex_split(cmd).is_some_and(|t| t.first().map(|s| s.as_str()) == Some("echo")) + && shlex_split(cmd).is_some_and(|t| t.first().map(String::as_str) == Some("echo")) { return Some(commands[1..].to_vec()); } @@ -902,7 +903,7 @@ fn simplify_once(commands: &[ParsedCommand]) -> Option> { // cd foo && [any command] => [any command] (keep non-cd when a cd is followed by something) if let Some(idx) = commands.iter().position(|pc| match pc { ParsedCommand::Unknown { cmd } => { - shlex_split(cmd).is_some_and(|t| t.first().map(|s| s.as_str()) == Some("cd")) + shlex_split(cmd).is_some_and(|t| t.first().map(String::as_str) == Some("cd")) } _ => false, }) && commands.len() > idx + 1 @@ -1035,7 +1036,7 @@ fn short_display_path(path: &str) -> String { }); parts .next() - .map(|s| s.to_string()) + .map(str::to_string) .unwrap_or_else(|| trimmed.to_string()) } @@ -1190,8 +1191,8 @@ fn parse_bash_lc_commands(original: &[String]) -> Option> { if had_connectors { let has_pipe = script_tokens.iter().any(|t| t == "|"); let has_sed_n = script_tokens.windows(2).any(|w| { - w.first().map(|s| s.as_str()) == Some("sed") - && w.get(1).map(|s| s.as_str()) == Some("-n") + w.first().map(String::as_str) == Some("sed") + && w.get(1).map(String::as_str) == Some("-n") }); if has_pipe && has_sed_n { ParsedCommand::Read { @@ -1271,7 +1272,7 @@ fn is_small_formatting_command(tokens: &[String]) -> bool { // Keep `sed -n file` (treated as a file read elsewhere); // otherwise consider it a formatting helper in a pipeline. tokens.len() < 4 - || !(tokens[1] == "-n" && is_valid_sed_n_arg(tokens.get(2).map(|s| s.as_str()))) + || !(tokens[1] == "-n" && is_valid_sed_n_arg(tokens.get(2).map(String::as_str))) } _ => false, } @@ -1318,7 +1319,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { (None, non_flags.first().map(|s| short_display_path(s))) } else { ( - non_flags.first().cloned().map(|s| s.to_string()), + non_flags.first().cloned().map(String::from), non_flags.get(1).map(|s| short_display_path(s)), ) }; @@ -1353,7 +1354,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { .collect(); // Do not shorten the query: grep patterns may legitimately contain slashes // and should be preserved verbatim. Only paths should be shortened. - let query = non_flags.first().cloned().map(|s| s.to_string()); + let query = non_flags.first().cloned().map(String::from); let path = non_flags.get(1).map(|s| short_display_path(s)); ParsedCommand::Search { cmd: shlex_join(main_cmd), @@ -1363,7 +1364,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { } Some((head, tail)) if head == "cat" => { // Support both `cat ` and `cat -- ` forms. - let effective_tail: &[String] = if tail.first().map(|s| s.as_str()) == Some("--") { + let effective_tail: &[String] = if tail.first().map(String::as_str) == Some("--") { &tail[1..] } else { tail @@ -1479,7 +1480,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if head == "sed" && tail.len() >= 3 && tail[0] == "-n" - && is_valid_sed_n_arg(tail.get(1).map(|s| s.as_str())) => + && is_valid_sed_n_arg(tail.get(1).map(String::as_str)) => { if let Some(path) = tail.get(2) { let name = short_display_path(path); diff --git a/codex-rs/core/src/shell.rs b/codex-rs/core/src/shell.rs index 3bfef7e1e0..ac93d8b12e 100644 --- a/codex-rs/core/src/shell.rs +++ b/codex-rs/core/src/shell.rs @@ -73,7 +73,7 @@ impl Shell { return Some(command); } - let joined = shlex::try_join(command.iter().map(|s| s.as_str())).ok(); + let joined = shlex::try_join(command.iter().map(String::as_str)).ok(); return joined.map(|arg| { vec![ ps.exe.clone(), @@ -111,7 +111,7 @@ fn format_shell_invocation_with_rc( rc_path: &str, ) -> Option> { let joined = strip_bash_lc(command) - .or_else(|| shlex::try_join(command.iter().map(|s| s.as_str())).ok())?; + .or_else(|| shlex::try_join(command.iter().map(String::as_str)).ok())?; let rc_command = if std::path::Path::new(rc_path).exists() { format!("source {rc_path} && ({joined})") @@ -224,6 +224,7 @@ pub async fn default_user_shell() -> Shell { mod tests { use super::*; use std::process::Command; + use std::string::ToString; #[tokio::test] async fn test_current_shell_detects_zsh() { @@ -327,7 +328,7 @@ mod tests { }); let actual_cmd = shell - .format_default_shell_invocation(input.iter().map(|s| s.to_string()).collect()); + .format_default_shell_invocation(input.iter().map(ToString::to_string).collect()); let expected_cmd = expected_cmd .iter() .map(|s| s.replace("BASHRC_PATH", bashrc_path.to_str().unwrap())) @@ -371,6 +372,7 @@ mod tests { #[cfg(target_os = "macos")] mod macos_tests { use super::*; + use std::string::ToString; #[tokio::test] async fn test_run_with_profile_escaping_and_execution() { @@ -434,7 +436,7 @@ mod macos_tests { }); let actual_cmd = shell - .format_default_shell_invocation(input.iter().map(|s| s.to_string()).collect()); + .format_default_shell_invocation(input.iter().map(ToString::to_string).collect()); let expected_cmd = expected_cmd .iter() .map(|s| s.replace("ZSHRC_PATH", zshrc_path.to_str().unwrap())) @@ -559,10 +561,10 @@ mod tests_windows { for (shell, input, expected_cmd) in cases { let actual_cmd = shell - .format_default_shell_invocation(input.iter().map(|s| s.to_string()).collect()); + .format_default_shell_invocation(input.iter().map(|s| (*s).to_string()).collect()); assert_eq!( actual_cmd, - Some(expected_cmd.iter().map(|s| s.to_string()).collect()) + Some(expected_cmd.iter().map(|s| (*s).to_string()).collect()) ); } } diff --git a/codex-rs/core/src/turn_diff_tracker.rs b/codex-rs/core/src/turn_diff_tracker.rs index 6c12d6cd46..06c40deb90 100644 --- a/codex-rs/core/src/turn_diff_tracker.rs +++ b/codex-rs/core/src/turn_diff_tracker.rs @@ -65,7 +65,7 @@ impl TurnDiffTracker { let baseline_file_info = if path.exists() { let mode = file_mode_for_path(path); let mode_val = mode.unwrap_or(FileMode::Regular); - let content = blob_bytes(path, &mode_val).unwrap_or_default(); + let content = blob_bytes(path, mode_val).unwrap_or_default(); let oid = if mode == Some(FileMode::Symlink) { format!("{:x}", git_blob_sha1_hex_bytes(&content)) } else { @@ -266,7 +266,7 @@ impl TurnDiffTracker { }; let current_mode = file_mode_for_path(¤t_external_path).unwrap_or(FileMode::Regular); - let right_bytes = blob_bytes(¤t_external_path, ¤t_mode); + let right_bytes = blob_bytes(¤t_external_path, current_mode); // Compute displays with &mut self before borrowing any baseline content. let left_display = self.relative_to_git_root_str(&baseline_external_path); @@ -388,7 +388,7 @@ enum FileMode { } impl FileMode { - fn as_str(&self) -> &'static str { + fn as_str(self) -> &'static str { match self { FileMode::Regular => "100644", #[cfg(unix)] @@ -427,9 +427,9 @@ fn file_mode_for_path(_path: &Path) -> Option { Some(FileMode::Regular) } -fn blob_bytes(path: &Path, mode: &FileMode) -> Option> { +fn blob_bytes(path: &Path, mode: FileMode) -> Option> { if path.exists() { - let contents = if *mode == FileMode::Symlink { + let contents = if mode == FileMode::Symlink { symlink_blob_bytes(path) .ok_or_else(|| anyhow!("failed to read symlink target for {}", path.display())) } else { diff --git a/codex-rs/core/tests/common/Cargo.toml b/codex-rs/core/tests/common/Cargo.toml index 2d43051919..0a33be39dc 100644 --- a/codex-rs/core/tests/common/Cargo.toml +++ b/codex-rs/core/tests/common/Cargo.toml @@ -7,8 +7,8 @@ edition = "2024" path = "lib.rs" [dependencies] -codex-core = { path = "../.." } -serde_json = "1" -tempfile = "3" -tokio = { version = "1", features = ["time"] } -wiremock = "0.6" +codex-core = { workspace = true } +serde_json = { workspace = true } +tempfile = { workspace = true } +tokio = { workspace = true, features = ["time"] } +wiremock = { workspace = true } diff --git a/codex-rs/core/tests/common/lib.rs b/codex-rs/core/tests/common/lib.rs index 95af79b220..9b86694e00 100644 --- a/codex-rs/core/tests/common/lib.rs +++ b/codex-rs/core/tests/common/lib.rs @@ -126,3 +126,21 @@ where } } } + +#[macro_export] +macro_rules! non_sandbox_test { + // For tests that return () + () => {{ + if ::std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() { + println!("Skipping test because it cannot execute when network is disabled in a Codex sandbox."); + return; + } + }}; + // For tests that return Result<(), _> + (result $(,)?) => {{ + if ::std::env::var("CODEX_SANDBOX_NETWORK_DISABLED").is_ok() { + println!("Skipping test because it cannot execute when network is disabled in a Codex sandbox."); + return ::core::result::Result::Ok(()); + } + }}; +} diff --git a/codex-rs/core/tests/suite/cli_stream.rs b/codex-rs/core/tests/suite/cli_stream.rs index 1a0c016272..368c47dc68 100644 --- a/codex-rs/core/tests/suite/cli_stream.rs +++ b/codex-rs/core/tests/suite/cli_stream.rs @@ -1,7 +1,7 @@ use assert_cmd::Command as AssertCommand; use codex_core::RolloutRecorder; use codex_core::protocol::GitInfo; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; +use core_test_support::non_sandbox_test; use std::time::Duration; use std::time::Instant; use tempfile::TempDir; @@ -21,12 +21,7 @@ use wiremock::matchers::path; /// 4. Ensures the response is received exactly once and contains "hi" #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn chat_mode_stream_cli() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let server = MockServer::start().await; let sse = concat!( @@ -102,12 +97,7 @@ async fn chat_mode_stream_cli() { /// received by a mock OpenAI Responses endpoint. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn exec_cli_applies_experimental_instructions_file() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); // Start mock server which will capture the request and return a minimal // SSE stream for a single turn. @@ -195,12 +185,7 @@ async fn exec_cli_applies_experimental_instructions_file() { /// 4. Ensures the fixture content is correctly streamed through the CLI #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn responses_api_stream_cli() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let fixture = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/cli_responses_fixture.sse"); @@ -232,12 +217,7 @@ async fn responses_api_stream_cli() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn integration_creates_and_checks_session_file() { // Honor sandbox network restrictions for CI parity with the other tests. - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); // 1. Temp home so we read/write isolated session files. let home = TempDir::new().unwrap(); diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index d0ae608cb0..d885faafee 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -16,12 +16,12 @@ use codex_core::built_in_model_providers; use codex_core::protocol::EventMsg; use codex_core::protocol::InputItem; use codex_core::protocol::Op; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use codex_protocol::mcp_protocol::ConversationId; use codex_protocol::models::ReasoningItemReasoningSummary; use codex_protocol::models::WebSearchAction; use core_test_support::load_default_config_for_test; use core_test_support::load_sse_fixture_with_id; +use core_test_support::non_sandbox_test; use core_test_support::responses; use core_test_support::wait_for_event; use futures::StreamExt; @@ -126,12 +126,7 @@ fn write_auth_json( #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn resume_includes_initial_messages_and_sends_prior_items() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); // Create a fake rollout session file with prior user + system + assistant messages. let tmpdir = TempDir::new().unwrap(); @@ -297,12 +292,7 @@ async fn resume_includes_initial_messages_and_sends_prior_items() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn includes_conversation_id_and_model_headers_in_request() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); // Mock server let server = MockServer::start().await; @@ -427,12 +417,7 @@ async fn includes_base_instructions_override_in_request() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn chatgpt_auth_sends_correct_request() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); // Mock server let server = MockServer::start().await; @@ -506,12 +491,7 @@ async fn chatgpt_auth_sends_correct_request() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); // Mock server let server = MockServer::start().await; @@ -638,12 +618,7 @@ async fn includes_user_instructions_message_in_request() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn azure_responses_request_includes_store_and_reasoning_ids() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let server = MockServer::start().await; @@ -786,10 +761,10 @@ async fn token_count_includes_rate_limits_snapshot() { let response = ResponseTemplate::new(200) .insert_header("content-type", "text/event-stream") .insert_header("x-codex-primary-used-percent", "12.5") - .insert_header("x-codex-protection-used-percent", "40.0") - .insert_header("x-codex-primary-over-protection-limit-percent", "75.0") + .insert_header("x-codex-secondary-used-percent", "40.0") + .insert_header("x-codex-primary-over-secondary-limit-percent", "75.0") .insert_header("x-codex-primary-window-minutes", "10") - .insert_header("x-codex-protection-window-minutes", "60") + .insert_header("x-codex-secondary-window-minutes", "60") .set_body_raw(sse_body, "text/event-stream"); Mock::given(method("POST")) @@ -847,15 +822,15 @@ async fn token_count_includes_rate_limits_snapshot() { "reasoning_output_tokens": 0, "total_tokens": 123 }, - // Default model is gpt-5 in tests → 272000 context window + // Default model is gpt-5-codex in tests → 272000 context window "model_context_window": 272000 }, "rate_limits": { "primary_used_percent": 12.5, - "weekly_used_percent": 40.0, - "primary_to_weekly_ratio_percent": 75.0, + "secondary_used_percent": 40.0, + "primary_to_secondary_ratio_percent": 75.0, "primary_window_minutes": 10, - "weekly_window_minutes": 60 + "secondary_window_minutes": 60 } }) ); @@ -1036,12 +1011,7 @@ fn create_dummy_codex_auth() -> CodexAuth { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn history_dedupes_streamed_and_final_messages_across_turns() { // Skip under Codex sandbox network restrictions (mirrors other tests). - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); // Mock server that will receive three sequential requests and return the same SSE stream // each time: a few deltas, then a final assistant message, then completed. diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index a58de304fb..3cae9841c5 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -9,9 +9,7 @@ use codex_core::protocol::InputItem; use codex_core::protocol::Op; use codex_core::protocol::RolloutItem; use codex_core::protocol::RolloutLine; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use core_test_support::load_default_config_for_test; -use core_test_support::responses; use core_test_support::wait_for_event; use tempfile::TempDir; use wiremock::Mock; @@ -21,11 +19,16 @@ use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; +use core_test_support::non_sandbox_test; +use core_test_support::responses::ev_assistant_message; +use core_test_support::responses::ev_completed; +use core_test_support::responses::ev_completed_with_tokens; +use core_test_support::responses::ev_function_call; +use core_test_support::responses::mount_sse_once; +use core_test_support::responses::sse; +use core_test_support::responses::sse_response; +use core_test_support::responses::start_mock_server; use pretty_assertions::assert_eq; -use responses::ev_assistant_message; -use responses::ev_completed; -use responses::sse; -use responses::start_mock_server; use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::AtomicUsize; @@ -50,12 +53,7 @@ const DUMMY_CALL_ID: &str = "call-multi-auto"; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn summarize_context_three_requests_and_instructions() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); // Set up a mock server that we can inspect after the run. let server = start_mock_server().await; @@ -81,19 +79,19 @@ async fn summarize_context_three_requests_and_instructions() { body.contains("\"text\":\"hello world\"") && !body.contains(&format!("\"text\":\"{SUMMARIZE_TRIGGER}\"")) }; - responses::mount_sse_once(&server, first_matcher, sse1).await; + mount_sse_once(&server, first_matcher, sse1).await; let second_matcher = |req: &wiremock::Request| { let body = std::str::from_utf8(&req.body).unwrap_or(""); body.contains(&format!("\"text\":\"{SUMMARIZE_TRIGGER}\"")) }; - responses::mount_sse_once(&server, second_matcher, sse2).await; + mount_sse_once(&server, second_matcher, sse2).await; let third_matcher = |req: &wiremock::Request| { let body = std::str::from_utf8(&req.body).unwrap_or(""); body.contains(&format!("\"text\":\"{THIRD_USER_MSG}\"")) }; - responses::mount_sse_once(&server, third_matcher, sse3).await; + mount_sse_once(&server, third_matcher, sse3).await; // Build config pointing to the mock server and spawn Codex. let model_provider = ModelProviderInfo { @@ -276,28 +274,23 @@ async fn summarize_context_three_requests_and_instructions() { #[cfg_attr(windows, tokio::test(flavor = "multi_thread", worker_threads = 4))] #[cfg_attr(not(windows), tokio::test(flavor = "multi_thread", worker_threads = 2))] async fn auto_compact_runs_after_token_limit_hit() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let server = start_mock_server().await; let sse1 = sse(vec![ ev_assistant_message("m1", FIRST_REPLY), - responses::ev_completed_with_tokens("r1", 70_000), + ev_completed_with_tokens("r1", 70_000), ]); let sse2 = sse(vec![ ev_assistant_message("m2", "SECOND_REPLY"), - responses::ev_completed_with_tokens("r2", 330_000), + ev_completed_with_tokens("r2", 330_000), ]); let sse3 = sse(vec![ ev_assistant_message("m3", AUTO_SUMMARY_TEXT), - responses::ev_completed_with_tokens("r3", 200), + ev_completed_with_tokens("r3", 200), ]); let first_matcher = |req: &wiremock::Request| { @@ -309,7 +302,7 @@ async fn auto_compact_runs_after_token_limit_hit() { Mock::given(method("POST")) .and(path("/v1/responses")) .and(first_matcher) - .respond_with(responses::sse_response(sse1)) + .respond_with(sse_response(sse1)) .mount(&server) .await; @@ -322,7 +315,7 @@ async fn auto_compact_runs_after_token_limit_hit() { Mock::given(method("POST")) .and(path("/v1/responses")) .and(second_matcher) - .respond_with(responses::sse_response(sse2)) + .respond_with(sse_response(sse2)) .mount(&server) .await; @@ -333,7 +326,7 @@ async fn auto_compact_runs_after_token_limit_hit() { Mock::given(method("POST")) .and(path("/v1/responses")) .and(third_matcher) - .respond_with(responses::sse_response(sse3)) + .respond_with(sse_response(sse3)) .mount(&server) .await; @@ -417,28 +410,23 @@ async fn auto_compact_runs_after_token_limit_hit() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn auto_compact_persists_rollout_entries() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let server = start_mock_server().await; let sse1 = sse(vec![ ev_assistant_message("m1", FIRST_REPLY), - responses::ev_completed_with_tokens("r1", 70_000), + ev_completed_with_tokens("r1", 70_000), ]); let sse2 = sse(vec![ ev_assistant_message("m2", "SECOND_REPLY"), - responses::ev_completed_with_tokens("r2", 330_000), + ev_completed_with_tokens("r2", 330_000), ]); let sse3 = sse(vec![ ev_assistant_message("m3", AUTO_SUMMARY_TEXT), - responses::ev_completed_with_tokens("r3", 200), + ev_completed_with_tokens("r3", 200), ]); let first_matcher = |req: &wiremock::Request| { @@ -450,7 +438,7 @@ async fn auto_compact_persists_rollout_entries() { Mock::given(method("POST")) .and(path("/v1/responses")) .and(first_matcher) - .respond_with(responses::sse_response(sse1)) + .respond_with(sse_response(sse1)) .mount(&server) .await; @@ -463,7 +451,7 @@ async fn auto_compact_persists_rollout_entries() { Mock::given(method("POST")) .and(path("/v1/responses")) .and(second_matcher) - .respond_with(responses::sse_response(sse2)) + .respond_with(sse_response(sse2)) .mount(&server) .await; @@ -474,7 +462,7 @@ async fn auto_compact_persists_rollout_entries() { Mock::given(method("POST")) .and(path("/v1/responses")) .and(third_matcher) - .respond_with(responses::sse_response(sse3)) + .respond_with(sse_response(sse3)) .mount(&server) .await; @@ -550,28 +538,23 @@ async fn auto_compact_persists_rollout_entries() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn auto_compact_stops_after_failed_attempt() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let server = start_mock_server().await; let sse1 = sse(vec![ ev_assistant_message("m1", FIRST_REPLY), - responses::ev_completed_with_tokens("r1", 500), + ev_completed_with_tokens("r1", 500), ]); let sse2 = sse(vec![ ev_assistant_message("m2", SUMMARY_TEXT), - responses::ev_completed_with_tokens("r2", 50), + ev_completed_with_tokens("r2", 50), ]); let sse3 = sse(vec![ ev_assistant_message("m3", STILL_TOO_BIG_REPLY), - responses::ev_completed_with_tokens("r3", 500), + ev_completed_with_tokens("r3", 500), ]); let first_matcher = |req: &wiremock::Request| { @@ -582,7 +565,7 @@ async fn auto_compact_stops_after_failed_attempt() { Mock::given(method("POST")) .and(path("/v1/responses")) .and(first_matcher) - .respond_with(responses::sse_response(sse1.clone())) + .respond_with(sse_response(sse1.clone())) .mount(&server) .await; @@ -593,7 +576,7 @@ async fn auto_compact_stops_after_failed_attempt() { Mock::given(method("POST")) .and(path("/v1/responses")) .and(second_matcher) - .respond_with(responses::sse_response(sse2.clone())) + .respond_with(sse_response(sse2.clone())) .mount(&server) .await; @@ -605,7 +588,7 @@ async fn auto_compact_stops_after_failed_attempt() { Mock::given(method("POST")) .and(path("/v1/responses")) .and(third_matcher) - .respond_with(responses::sse_response(sse3.clone())) + .respond_with(sse_response(sse3.clone())) .mount(&server) .await; @@ -664,38 +647,33 @@ async fn auto_compact_stops_after_failed_attempt() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn auto_compact_allows_multiple_attempts_when_interleaved_with_other_turn_events() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let server = start_mock_server().await; let sse1 = sse(vec![ ev_assistant_message("m1", FIRST_REPLY), - responses::ev_completed_with_tokens("r1", 500), + ev_completed_with_tokens("r1", 500), ]); let sse2 = sse(vec![ ev_assistant_message("m2", FIRST_AUTO_SUMMARY), - responses::ev_completed_with_tokens("r2", 50), + ev_completed_with_tokens("r2", 50), ]); let sse3 = sse(vec![ - responses::ev_function_call(DUMMY_CALL_ID, DUMMY_FUNCTION_NAME, "{}"), - responses::ev_completed_with_tokens("r3", 150), + ev_function_call(DUMMY_CALL_ID, DUMMY_FUNCTION_NAME, "{}"), + ev_completed_with_tokens("r3", 150), ]); let sse4 = sse(vec![ ev_assistant_message("m4", SECOND_LARGE_REPLY), - responses::ev_completed_with_tokens("r4", 450), + ev_completed_with_tokens("r4", 450), ]); let sse5 = sse(vec![ ev_assistant_message("m5", SECOND_AUTO_SUMMARY), - responses::ev_completed_with_tokens("r5", 60), + ev_completed_with_tokens("r5", 60), ]); let sse6 = sse(vec![ ev_assistant_message("m6", FINAL_REPLY), - responses::ev_completed_with_tokens("r6", 120), + ev_completed_with_tokens("r6", 120), ]); #[derive(Clone)] diff --git a/codex-rs/core/tests/suite/compact_resume_fork.rs b/codex-rs/core/tests/suite/compact_resume_fork.rs index 1e752826bb..43d6192f5f 100644 --- a/codex-rs/core/tests/suite/compact_resume_fork.rs +++ b/codex-rs/core/tests/suite/compact_resume_fork.rs @@ -133,7 +133,7 @@ async fn compact_resume_and_fork_preserve_model_history_view() { .to_string(); let user_turn_1 = json!( { - "model": "gpt-5", + "model": "gpt-5-codex", "instructions": prompt, "input": [ { @@ -182,7 +182,7 @@ async fn compact_resume_and_fork_preserve_model_history_view() { }); let compact_1 = json!( { - "model": "gpt-5", + "model": "gpt-5-codex", "instructions": "You have exceeded the maximum number of tokens, please stop coding and instead write a short memento message for the next agent. Your note should: - Summarize what you finished and what still needs work. If there was a recent update_plan call, repeat its steps verbatim. - List outstanding TODOs with file paths / line numbers so they're easy to find. @@ -255,7 +255,7 @@ async fn compact_resume_and_fork_preserve_model_history_view() { }); let user_turn_2_after_compact = json!( { - "model": "gpt-5", + "model": "gpt-5-codex", "instructions": prompt, "input": [ { @@ -320,7 +320,7 @@ SUMMARY_ONLY_CONTEXT" }); let usert_turn_3_after_resume = json!( { - "model": "gpt-5", + "model": "gpt-5-codex", "instructions": prompt, "input": [ { @@ -405,7 +405,7 @@ SUMMARY_ONLY_CONTEXT" }); let user_turn_3_after_fork = json!( { - "model": "gpt-5", + "model": "gpt-5-codex", "instructions": prompt, "input": [ { diff --git a/codex-rs/core/tests/suite/exec.rs b/codex-rs/core/tests/suite/exec.rs index 280917b530..2d1e99b0b7 100644 --- a/codex-rs/core/tests/suite/exec.rs +++ b/codex-rs/core/tests/suite/exec.rs @@ -1,6 +1,7 @@ #![cfg(target_os = "macos")] use std::collections::HashMap; +use std::string::ToString; use codex_core::exec::ExecParams; use codex_core::exec::ExecToolCallOutput; @@ -29,7 +30,7 @@ async fn run_test_cmd(tmp: TempDir, cmd: Vec<&str>) -> Result String { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn continue_after_stream_error() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let server = MockServer::start().await; diff --git a/codex-rs/core/tests/suite/stream_no_completed.rs b/codex-rs/core/tests/suite/stream_no_completed.rs index 6e6938b932..4801376df1 100644 --- a/codex-rs/core/tests/suite/stream_no_completed.rs +++ b/codex-rs/core/tests/suite/stream_no_completed.rs @@ -9,10 +9,10 @@ use codex_core::ModelProviderInfo; use codex_core::protocol::EventMsg; use codex_core::protocol::InputItem; use codex_core::protocol::Op; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use core_test_support::load_default_config_for_test; use core_test_support::load_sse_fixture; use core_test_support::load_sse_fixture_with_id; +use core_test_support::non_sandbox_test; use tempfile::TempDir; use tokio::time::timeout; use wiremock::Mock; @@ -33,12 +33,7 @@ fn sse_completed(id: &str) -> String { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn retries_on_early_close() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let server = MockServer::start().await; diff --git a/codex-rs/docs/codex_mcp_interface.md b/codex-rs/docs/codex_mcp_interface.md index 1b048085c3..8f0c279058 100644 --- a/codex-rs/docs/codex_mcp_interface.md +++ b/codex-rs/docs/codex_mcp_interface.md @@ -51,7 +51,7 @@ Start a new session with optional overrides: Request `newConversation` params (subset): -- `model`: string model id (e.g. "o3", "gpt-5") +- `model`: string model id (e.g. "o3", "gpt-5", "gpt-5-codex") - `profile`: optional named profile - `cwd`: optional working directory - `approvalPolicy`: `untrusted` | `on-request` | `on-failure` | `never` @@ -120,4 +120,3 @@ While processing, the server emits `codex/event` notifications containing agent ## Compatibility and stability This interface is experimental. Method names, fields, and event shapes may evolve. For the authoritative schema, consult `protocol/src/mcp_protocol.rs` and the corresponding server wiring in `mcp-server/`. - diff --git a/codex-rs/exec/Cargo.toml b/codex-rs/exec/Cargo.toml index 2dd121c368..44281c738d 100644 --- a/codex-rs/exec/Cargo.toml +++ b/codex-rs/exec/Cargo.toml @@ -15,37 +15,37 @@ path = "src/lib.rs" workspace = true [dependencies] -anyhow = "1" -chrono = "0.4.40" -clap = { version = "4", features = ["derive"] } -codex-arg0 = { path = "../arg0" } -codex-common = { path = "../common", features = [ +anyhow = { workspace = true } +chrono = { workspace = true } +clap = { workspace = true, features = ["derive"] } +codex-arg0 = { workspace = true } +codex-common = { workspace = true, features = [ "cli", "elapsed", "sandbox_summary", ] } -codex-core = { path = "../core" } -codex-ollama = { path = "../ollama" } -codex-protocol = { path = "../protocol" } -owo-colors = "4.2.0" -serde_json = "1" -shlex = "1.3.0" -tokio = { version = "1", features = [ +codex-core = { workspace = true } +codex-ollama = { workspace = true } +codex-protocol = { workspace = true } +owo-colors = { workspace = true } +serde_json = { workspace = true } +shlex = { workspace = true } +tokio = { workspace = true, features = [ "io-std", "macros", "process", "rt-multi-thread", "signal", ] } -tracing = { version = "0.1.41", features = ["log"] } -tracing-subscriber = { version = "0.3.20", features = ["env-filter"] } +tracing = { workspace = true, features = ["log"] } +tracing-subscriber = { workspace = true, features = ["env-filter"] } [dev-dependencies] -assert_cmd = "2" -core_test_support = { path = "../core/tests/common" } -libc = "0.2" -predicates = "3" -tempfile = "3.13.0" -uuid = "1" -walkdir = "2" -wiremock = "0.6" +assert_cmd = { workspace = true } +core_test_support = { workspace = true } +libc = { workspace = true } +predicates = { workspace = true } +tempfile = { workspace = true } +uuid = { workspace = true } +walkdir = { workspace = true } +wiremock = { workspace = true } diff --git a/codex-rs/exec/src/event_processor_with_human_output.rs b/codex-rs/exec/src/event_processor_with_human_output.rs index 5ef7d51a26..b22d4b7289 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -573,7 +573,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { } fn escape_command(command: &[String]) -> String { - try_join(command.iter().map(|s| s.as_str())).unwrap_or_else(|_| command.join(" ")) + try_join(command.iter().map(String::as_str)).unwrap_or_else(|_| command.join(" ")) } fn format_file_change(change: &FileChange) -> &'static str { diff --git a/codex-rs/exec/tests/suite/apply_patch.rs b/codex-rs/exec/tests/suite/apply_patch.rs index 489f34f9ce..9db1f1cf78 100644 --- a/codex-rs/exec/tests/suite/apply_patch.rs +++ b/codex-rs/exec/tests/suite/apply_patch.rs @@ -48,14 +48,9 @@ fn test_standalone_exec_cli_can_use_apply_patch() -> anyhow::Result<()> { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn test_apply_patch_tool() -> anyhow::Result<()> { use crate::suite::common::run_e2e_exec_test; - use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; + use core_test_support::non_sandbox_test; - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return Ok(()); - } + non_sandbox_test!(result); let tmp_cwd = tempdir().expect("failed to create temp dir"); let tmp_path = tmp_cwd.path().to_path_buf(); @@ -93,14 +88,9 @@ async fn test_apply_patch_tool() -> anyhow::Result<()> { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn test_apply_patch_freeform_tool() -> anyhow::Result<()> { use crate::suite::common::run_e2e_exec_test; - use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; + use core_test_support::non_sandbox_test; - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return Ok(()); - } + non_sandbox_test!(result); let tmp_cwd = tempdir().expect("failed to create temp dir"); let freeform_add_patch = r#"*** Begin Patch diff --git a/codex-rs/exec/tests/suite/resume.rs b/codex-rs/exec/tests/suite/resume.rs index 5868ed8eb2..4c4d343ee3 100644 --- a/codex-rs/exec/tests/suite/resume.rs +++ b/codex-rs/exec/tests/suite/resume.rs @@ -3,6 +3,7 @@ use anyhow::Context; use assert_cmd::prelude::*; use serde_json::Value; use std::process::Command; +use std::string::ToString; use tempfile::TempDir; use uuid::Uuid; use walkdir::WalkDir; @@ -45,7 +46,7 @@ fn find_session_file_containing_marker( && payload.get("type").and_then(|t| t.as_str()) == Some("message") && payload .get("content") - .map(|c| c.to_string()) + .map(ToString::to_string) .unwrap_or_default() .contains(marker) { diff --git a/codex-rs/execpolicy/Cargo.toml b/codex-rs/execpolicy/Cargo.toml index 9f0a25c422..0fe7cd486a 100644 --- a/codex-rs/execpolicy/Cargo.toml +++ b/codex-rs/execpolicy/Cargo.toml @@ -15,19 +15,19 @@ path = "src/lib.rs" workspace = true [dependencies] -allocative = "0.3.3" -anyhow = "1" -clap = { version = "4", features = ["derive"] } -derive_more = { version = "2", features = ["display"] } -env_logger = "0.11.5" -log = "0.4" -multimap = "0.10.0" -path-absolutize = "3.1.1" -regex-lite = "0.1" -serde = { version = "1", features = ["derive"] } -serde_json = "1" -serde_with = { version = "3", features = ["macros"] } -starlark = "0.13.0" +allocative = { workspace = true } +anyhow = { workspace = true } +clap = { workspace = true, features = ["derive"] } +derive_more = { workspace = true, features = ["display"] } +env_logger = { workspace = true } +log = { workspace = true } +multimap = { workspace = true } +path-absolutize = { workspace = true } +regex-lite = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +serde_with = { workspace = true, features = ["macros"] } +starlark = { workspace = true } [dev-dependencies] -tempfile = "3.13.0" +tempfile = { workspace = true } diff --git a/codex-rs/execpolicy/src/execv_checker.rs b/codex-rs/execpolicy/src/execv_checker.rs index ae61d54cf8..1c03f591b1 100644 --- a/codex-rs/execpolicy/src/execv_checker.rs +++ b/codex-rs/execpolicy/src/execv_checker.rs @@ -1,3 +1,4 @@ +use std::borrow::Cow; use std::ffi::OsString; use std::path::Path; use std::path::PathBuf; @@ -108,7 +109,7 @@ fn ensure_absolute_path(path: &str, cwd: &Option) -> Result { file.absolutize() }; result - .map(|path| path.into_owned()) + .map(Cow::into_owned) .map_err(|error| CannotCanonicalizePath { file: path.to_string(), error: error.kind(), diff --git a/codex-rs/execpolicy/src/main.rs b/codex-rs/execpolicy/src/main.rs index 0a4b1764ca..68a72c04ff 100644 --- a/codex-rs/execpolicy/src/main.rs +++ b/codex-rs/execpolicy/src/main.rs @@ -10,6 +10,7 @@ use codex_execpolicy::get_default_policy; use serde::Deserialize; use serde::Serialize; use serde::de; +use starlark::Error as StarlarkError; use std::path::PathBuf; use std::str::FromStr; @@ -71,13 +72,13 @@ fn main() -> Result<()> { } None => get_default_policy(), }; - let policy = policy.map_err(|err| err.into_anyhow())?; + let policy = policy.map_err(StarlarkError::into_anyhow)?; let exec = match args.command { Command::Check { command } => match command.split_first() { Some((first, rest)) => ExecArg { program: first.to_string(), - args: rest.iter().map(|s| s.to_string()).collect(), + args: rest.to_vec(), }, None => { eprintln!("no command provided"); @@ -161,6 +162,6 @@ impl FromStr for ExecArg { type Err = anyhow::Error; fn from_str(s: &str) -> Result { - serde_json::from_str(s).map_err(|e| e.into()) + serde_json::from_str(s).map_err(Into::into) } } diff --git a/codex-rs/execpolicy/src/program.rs b/codex-rs/execpolicy/src/program.rs index fbe0a104af..d0cec3717b 100644 --- a/codex-rs/execpolicy/src/program.rs +++ b/codex-rs/execpolicy/src/program.rs @@ -169,7 +169,7 @@ impl ProgramSpec { let mut options = self .required_options .difference(&matched_opt_names) - .map(|s| s.to_string()) + .map(String::from) .collect::>(); options.sort(); return Err(Error::MissingRequiredOptions { diff --git a/codex-rs/file-search/Cargo.toml b/codex-rs/file-search/Cargo.toml index 023e6936c8..40671389e1 100644 --- a/codex-rs/file-search/Cargo.toml +++ b/codex-rs/file-search/Cargo.toml @@ -12,10 +12,10 @@ name = "codex_file_search" path = "src/lib.rs" [dependencies] -anyhow = "1" -clap = { version = "4", features = ["derive"] } -ignore = "0.4.23" -nucleo-matcher = "0.3.1" -serde = { version = "1", features = ["derive"] } -serde_json = "1" -tokio = { version = "1", features = ["full"] } +anyhow = { workspace = true } +clap = { workspace = true, features = ["derive"] } +ignore = { workspace = true } +nucleo-matcher = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +tokio = { workspace = true, features = ["full"] } diff --git a/codex-rs/linux-sandbox/Cargo.toml b/codex-rs/linux-sandbox/Cargo.toml index e7432357b7..264f15e751 100644 --- a/codex-rs/linux-sandbox/Cargo.toml +++ b/codex-rs/linux-sandbox/Cargo.toml @@ -15,15 +15,15 @@ path = "src/lib.rs" workspace = true [target.'cfg(target_os = "linux")'.dependencies] -clap = { version = "4", features = ["derive"] } -codex-core = { path = "../core" } -landlock = "0.4.1" -libc = "0.2.175" -seccompiler = "0.5.0" +clap = { workspace = true, features = ["derive"] } +codex-core = { workspace = true } +landlock = { workspace = true } +libc = { workspace = true } +seccompiler = { workspace = true } [target.'cfg(target_os = "linux")'.dev-dependencies] -tempfile = "3" -tokio = { version = "1", features = [ +tempfile = { workspace = true } +tokio = { workspace = true, features = [ "io-std", "macros", "process", diff --git a/codex-rs/linux-sandbox/tests/suite/landlock.rs b/codex-rs/linux-sandbox/tests/suite/landlock.rs index ea4930fada..6af59ef0fa 100644 --- a/codex-rs/linux-sandbox/tests/suite/landlock.rs +++ b/codex-rs/linux-sandbox/tests/suite/landlock.rs @@ -38,7 +38,7 @@ async fn run_cmd(cmd: &[&str], writable_roots: &[PathBuf], timeout_ms: u64) { let cwd = std::env::current_dir().expect("cwd should exist"); let sandbox_cwd = cwd.clone(); let params = ExecParams { - command: cmd.iter().map(|elm| elm.to_string()).collect(), + command: cmd.iter().copied().map(str::to_owned).collect(), cwd, timeout_ms: Some(timeout_ms), env: create_env_from_core_vars(), @@ -138,7 +138,7 @@ async fn assert_network_blocked(cmd: &[&str]) { let cwd = std::env::current_dir().expect("cwd should exist"); let sandbox_cwd = cwd.clone(); let params = ExecParams { - command: cmd.iter().map(|s| s.to_string()).collect(), + command: cmd.iter().copied().map(str::to_owned).collect(), cwd, // Give the tool a generous 2-second timeout so even slow DNS timeouts // do not stall the suite. diff --git a/codex-rs/login/Cargo.toml b/codex-rs/login/Cargo.toml index 1e36014995..c0f4a2dd6f 100644 --- a/codex-rs/login/Cargo.toml +++ b/codex-rs/login/Cargo.toml @@ -7,27 +7,28 @@ version = { workspace = true } workspace = true [dependencies] -base64 = "0.22" -chrono = { version = "0.4", features = ["serde"] } -codex-core = { path = "../core" } -codex-protocol = { path = "../protocol" } -rand = "0.8" -reqwest = { version = "0.12", features = ["json", "blocking"] } -serde = { version = "1", features = ["derive"] } -serde_json = "1" -sha2 = "0.10" -tempfile = "3" -tiny_http = "0.12" -tokio = { version = "1", features = [ +base64 = { workspace = true } +chrono = { workspace = true, features = ["serde"] } +codex-core = { workspace = true } +codex-protocol = { workspace = true } +rand = { workspace = true } +reqwest = { workspace = true, features = ["json", "blocking"] } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +sha2 = { workspace = true } +tempfile = { workspace = true } +tiny_http = { workspace = true } +tokio = { workspace = true, features = [ "io-std", "macros", "process", "rt-multi-thread", "signal", ] } -url = "2" -urlencoding = "2.1" -webbrowser = "1.0" +url = { workspace = true } +urlencoding = { workspace = true } +webbrowser = { workspace = true } [dev-dependencies] -tempfile = "3" +core_test_support = { workspace = true } +tempfile = { workspace = true } diff --git a/codex-rs/login/src/pkce.rs b/codex-rs/login/src/pkce.rs index 3c413b11f1..a0eacfc201 100644 --- a/codex-rs/login/src/pkce.rs +++ b/codex-rs/login/src/pkce.rs @@ -11,7 +11,7 @@ pub struct PkceCodes { pub fn generate_pkce() -> PkceCodes { let mut bytes = [0u8; 64]; - rand::thread_rng().fill_bytes(&mut bytes); + rand::rng().fill_bytes(&mut bytes); // Verifier: URL-safe base64 without padding (43..128 chars) let code_verifier = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes); diff --git a/codex-rs/login/src/server.rs b/codex-rs/login/src/server.rs index 26f341b9d9..a1e5e6c3b0 100644 --- a/codex-rs/login/src/server.rs +++ b/codex-rs/login/src/server.rs @@ -20,6 +20,7 @@ use codex_core::default_client::ORIGINATOR; use codex_core::token_data::TokenData; use codex_core::token_data::parse_id_token; use rand::RngCore; +use serde_json::Value as JsonValue; use tiny_http::Header; use tiny_http::Request; use tiny_http::Response; @@ -326,7 +327,7 @@ fn build_authorize_url( fn generate_state() -> String { let mut bytes = [0u8; 32]; - rand::thread_rng().fill_bytes(&mut bytes); + rand::rng().fill_bytes(&mut bytes); base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes) } @@ -496,11 +497,11 @@ fn compose_success_url(port: u16, issuer: &str, id_token: &str, access_token: &s .unwrap_or(""); let completed_onboarding = token_claims .get("completed_platform_onboarding") - .and_then(|v| v.as_bool()) + .and_then(JsonValue::as_bool) .unwrap_or(false); let is_org_owner = token_claims .get("is_org_owner") - .and_then(|v| v.as_bool()) + .and_then(JsonValue::as_bool) .unwrap_or(false); let needs_setup = (!completed_onboarding) && is_org_owner; let plan_type = access_claims diff --git a/codex-rs/login/tests/suite/login_server_e2e.rs b/codex-rs/login/tests/suite/login_server_e2e.rs index dd2cb9048d..1acba00932 100644 --- a/codex-rs/login/tests/suite/login_server_e2e.rs +++ b/codex-rs/login/tests/suite/login_server_e2e.rs @@ -8,10 +8,10 @@ use std::time::Duration; use base64::Engine; use codex_login::ServerOptions; use codex_login::run_login_server; +use core_test_support::non_sandbox_test; use tempfile::tempdir; // See spawn.rs for details -pub const CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR: &str = "CODEX_SANDBOX_NETWORK_DISABLED"; fn start_mock_issuer() -> (SocketAddr, thread::JoinHandle<()>) { // Bind to a random available port @@ -77,12 +77,7 @@ fn start_mock_issuer() -> (SocketAddr, thread::JoinHandle<()>) { #[tokio::test] async fn end_to_end_login_flow_persists_auth_json() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let (issuer_addr, issuer_handle) = start_mock_issuer(); let issuer = format!("http://{}:{}", issuer_addr.ip(), issuer_addr.port()); @@ -152,12 +147,7 @@ async fn end_to_end_login_flow_persists_auth_json() { #[tokio::test] async fn creates_missing_codex_home_dir() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let (issuer_addr, _issuer_handle) = start_mock_issuer(); let issuer = format!("http://{}:{}", issuer_addr.ip(), issuer_addr.port()); @@ -196,12 +186,7 @@ async fn creates_missing_codex_home_dir() { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn cancels_previous_login_server_when_port_is_in_use() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); let (issuer_addr, _issuer_handle) = start_mock_issuer(); let issuer = format!("http://{}:{}", issuer_addr.ip(), issuer_addr.port()); diff --git a/codex-rs/mcp-client/Cargo.toml b/codex-rs/mcp-client/Cargo.toml index 7c71d52180..5025063b0a 100644 --- a/codex-rs/mcp-client/Cargo.toml +++ b/codex-rs/mcp-client/Cargo.toml @@ -7,13 +7,13 @@ edition = "2024" workspace = true [dependencies] -anyhow = "1" -mcp-types = { path = "../mcp-types" } -serde = { version = "1", features = ["derive"] } -serde_json = "1" -tracing = { version = "0.1.41", features = ["log"] } -tracing-subscriber = { version = "0.3", features = ["fmt", "env-filter"] } -tokio = { version = "1", features = [ +anyhow = { workspace = true } +mcp-types = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +tracing = { workspace = true, features = ["log"] } +tracing-subscriber = { workspace = true, features = ["fmt", "env-filter"] } +tokio = { workspace = true, features = [ "io-util", "macros", "process", diff --git a/codex-rs/mcp-server/Cargo.toml b/codex-rs/mcp-server/Cargo.toml index 9eb5f6eba6..e40dd15df7 100644 --- a/codex-rs/mcp-server/Cargo.toml +++ b/codex-rs/mcp-server/Cargo.toml @@ -15,34 +15,35 @@ path = "src/lib.rs" workspace = true [dependencies] -anyhow = "1" -codex-arg0 = { path = "../arg0" } -codex-common = { path = "../common", features = ["cli"] } -codex-core = { path = "../core" } -codex-login = { path = "../login" } -codex-protocol = { path = "../protocol" } -mcp-types = { path = "../mcp-types" } -schemars = "0.8.22" -serde = { version = "1", features = ["derive"] } -serde_json = "1" -shlex = "1.3.0" -tokio = { version = "1", features = [ +anyhow = { workspace = true } +codex-arg0 = { workspace = true } +codex-common = { workspace = true, features = ["cli"] } +codex-core = { workspace = true } +codex-login = { workspace = true } +codex-protocol = { workspace = true } +mcp-types = { workspace = true } +schemars = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +shlex = { workspace = true } +tokio = { workspace = true, features = [ "io-std", "macros", "process", "rt-multi-thread", "signal", ] } -toml = "0.9" -tracing = { version = "0.1.41", features = ["log"] } -tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } -uuid = { version = "1", features = ["serde", "v7"] } +toml = { workspace = true } +tracing = { workspace = true, features = ["log"] } +tracing-subscriber = { workspace = true, features = ["env-filter", "fmt"] } +uuid = { workspace = true, features = ["serde", "v7"] } [dev-dependencies] -assert_cmd = "2" -base64 = "0.22" -mcp_test_support = { path = "tests/common" } -os_info = "3.12.0" -pretty_assertions = "1.4.1" -tempfile = "3" -wiremock = "0.6" +assert_cmd = { workspace = true } +base64 = { workspace = true } +core_test_support = { workspace = true } +mcp_test_support = { workspace = true } +os_info = { workspace = true } +pretty_assertions = { workspace = true } +tempfile = { workspace = true } +wiremock = { workspace = true } diff --git a/codex-rs/mcp-server/src/exec_approval.rs b/codex-rs/mcp-server/src/exec_approval.rs index 1985cc79e6..119481cda9 100644 --- a/codex-rs/mcp-server/src/exec_approval.rs +++ b/codex-rs/mcp-server/src/exec_approval.rs @@ -58,7 +58,7 @@ pub(crate) async fn handle_exec_approval_request( call_id: String, ) { let escaped_command = - shlex::try_join(command.iter().map(|s| s.as_str())).unwrap_or_else(|_| command.join(" ")); + shlex::try_join(command.iter().map(String::as_str)).unwrap_or_else(|_| command.join(" ")); let message = format!( "Allow Codex to run `{escaped_command}` in `{cwd}`?", cwd = cwd.to_string_lossy() diff --git a/codex-rs/mcp-server/tests/common/Cargo.toml b/codex-rs/mcp-server/tests/common/Cargo.toml index 6bdef423cc..e6f7117250 100644 --- a/codex-rs/mcp-server/tests/common/Cargo.toml +++ b/codex-rs/mcp-server/tests/common/Cargo.toml @@ -7,20 +7,20 @@ version = { workspace = true } path = "lib.rs" [dependencies] -anyhow = "1" -assert_cmd = "2" -codex-core = { path = "../../../core" } -codex-mcp-server = { path = "../.." } -codex-protocol = { path = "../../../protocol" } -mcp-types = { path = "../../../mcp-types" } -os_info = "3.12.0" -pretty_assertions = "1.4.1" -serde = { version = "1" } -serde_json = "1" -tokio = { version = "1", features = [ +anyhow = { workspace = true } +assert_cmd = { workspace = true } +codex-core = { workspace = true } +codex-mcp-server = { workspace = true } +codex-protocol = { workspace = true } +mcp-types = { workspace = true } +os_info = { workspace = true } +pretty_assertions = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +tokio = { workspace = true, features = [ "io-std", "macros", "process", "rt-multi-thread", ] } -wiremock = "0.6" +wiremock = { workspace = true } diff --git a/codex-rs/mcp-server/tests/suite/codex_tool.rs b/codex-rs/mcp-server/tests/suite/codex_tool.rs index e7097b6b34..a111539d2f 100644 --- a/codex-rs/mcp-server/tests/suite/codex_tool.rs +++ b/codex-rs/mcp-server/tests/suite/codex_tool.rs @@ -24,6 +24,7 @@ use tempfile::TempDir; use tokio::time::timeout; use wiremock::MockServer; +use core_test_support::non_sandbox_test; use mcp_test_support::McpProcess; use mcp_test_support::create_apply_patch_sse_response; use mcp_test_support::create_final_assistant_message_sse_response; @@ -172,7 +173,7 @@ fn create_expected_elicitation_request( ) -> anyhow::Result { let expected_message = format!( "Allow Codex to run `{}` in `{}`?", - shlex::try_join(command.iter().map(|s| s.as_ref()))?, + shlex::try_join(command.iter().map(std::convert::AsRef::as_ref))?, workdir.to_string_lossy() ); Ok(JSONRPCRequest { @@ -307,12 +308,7 @@ async fn patch_approval_triggers_elicitation() -> anyhow::Result<()> { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_codex_tool_passes_base_instructions() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); // Apparently `#[tokio::test]` must return `()`, so we create a helper // function that returns `Result` so we can use `?` in favor of `unwrap`. diff --git a/codex-rs/mcp-server/tests/suite/config.rs b/codex-rs/mcp-server/tests/suite/config.rs index bc8789ce78..da64648c49 100644 --- a/codex-rs/mcp-server/tests/suite/config.rs +++ b/codex-rs/mcp-server/tests/suite/config.rs @@ -26,7 +26,7 @@ fn create_config_toml(codex_home: &Path) -> std::io::Result<()> { std::fs::write( config_toml, r#" -model = "gpt-5" +model = "gpt-5-codex" approval_policy = "on-request" sandbox_mode = "workspace-write" model_reasoning_summary = "detailed" @@ -92,7 +92,7 @@ async fn get_config_toml_parses_all_fields() { exclude_tmpdir_env_var: Some(true), exclude_slash_tmp: Some(true), }), - model: Some("gpt-5".into()), + model: Some("gpt-5-codex".into()), model_reasoning_effort: Some(ReasoningEffort::High), model_reasoning_summary: Some(ReasoningSummary::Detailed), model_verbosity: Some(Verbosity::Medium), diff --git a/codex-rs/mcp-server/tests/suite/interrupt.rs b/codex-rs/mcp-server/tests/suite/interrupt.rs index 113a8dd291..e4daeae0de 100644 --- a/codex-rs/mcp-server/tests/suite/interrupt.rs +++ b/codex-rs/mcp-server/tests/suite/interrupt.rs @@ -4,7 +4,6 @@ use std::path::Path; use codex_core::protocol::TurnAbortReason; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use codex_protocol::mcp_protocol::AddConversationListenerParams; use codex_protocol::mcp_protocol::InterruptConversationParams; use codex_protocol::mcp_protocol::InterruptConversationResponse; @@ -12,6 +11,7 @@ use codex_protocol::mcp_protocol::NewConversationParams; use codex_protocol::mcp_protocol::NewConversationResponse; use codex_protocol::mcp_protocol::SendUserMessageParams; use codex_protocol::mcp_protocol::SendUserMessageResponse; +use core_test_support::non_sandbox_test; use mcp_types::JSONRPCResponse; use mcp_types::RequestId; use tempfile::TempDir; @@ -26,12 +26,7 @@ const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_shell_command_interruption() { - if std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + non_sandbox_test!(); if let Err(err) = shell_command_interruption().await { panic!("failure: {err}"); diff --git a/codex-rs/mcp-server/tests/suite/set_default_model.rs b/codex-rs/mcp-server/tests/suite/set_default_model.rs index 7ffee3438d..f7e1041fa7 100644 --- a/codex-rs/mcp-server/tests/suite/set_default_model.rs +++ b/codex-rs/mcp-server/tests/suite/set_default_model.rs @@ -69,7 +69,7 @@ fn create_config_toml(codex_home: &Path) -> std::io::Result<()> { std::fs::write( config_toml, r#" -model = "gpt-5" +model = "gpt-5-codex" model_reasoning_effort = "medium" "#, ) diff --git a/codex-rs/mcp-types/Cargo.toml b/codex-rs/mcp-types/Cargo.toml index e39cb64d37..c8dc5819cd 100644 --- a/codex-rs/mcp-types/Cargo.toml +++ b/codex-rs/mcp-types/Cargo.toml @@ -7,6 +7,6 @@ version = { workspace = true } workspace = true [dependencies] -serde = { version = "1", features = ["derive"] } -serde_json = "1" -ts-rs = { version = "11", features = ["serde-json-impl", "no-serde-warnings"] } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +ts-rs = { workspace = true, features = ["serde-json-impl", "no-serde-warnings"] } diff --git a/codex-rs/ollama/Cargo.toml b/codex-rs/ollama/Cargo.toml index e725c2a290..587a193069 100644 --- a/codex-rs/ollama/Cargo.toml +++ b/codex-rs/ollama/Cargo.toml @@ -11,20 +11,20 @@ path = "src/lib.rs" workspace = true [dependencies] -async-stream = "0.3" -bytes = "1.10.1" -codex-core = { path = "../core" } -futures = "0.3" -reqwest = { version = "0.12", features = ["json", "stream"] } -serde_json = "1" -tokio = { version = "1", features = [ +async-stream = { workspace = true } +bytes = { workspace = true } +codex-core = { workspace = true } +futures = { workspace = true } +reqwest = { workspace = true, features = ["json", "stream"] } +serde_json = { workspace = true } +tokio = { workspace = true, features = [ "io-std", "macros", "process", "rt-multi-thread", "signal", ] } -tracing = { version = "0.1.41", features = ["log"] } -wiremock = "0.6" +tracing = { workspace = true, features = ["log"] } +wiremock = { workspace = true } [dev-dependencies] diff --git a/codex-rs/ollama/src/client.rs b/codex-rs/ollama/src/client.rs index 45e0486156..04b7e9dea2 100644 --- a/codex-rs/ollama/src/client.rs +++ b/codex-rs/ollama/src/client.rs @@ -117,7 +117,7 @@ impl OllamaClient { .map(|arr| { arr.iter() .filter_map(|v| v.get("name").and_then(|n| n.as_str())) - .map(|s| s.to_string()) + .map(str::to_string) .collect::>() }) .unwrap_or_default(); diff --git a/codex-rs/ollama/src/parser.rs b/codex-rs/ollama/src/parser.rs index b3ed2ca8c3..c39df6680f 100644 --- a/codex-rs/ollama/src/parser.rs +++ b/codex-rs/ollama/src/parser.rs @@ -16,8 +16,8 @@ pub(crate) fn pull_events_from_value(value: &JsonValue) -> Vec { .and_then(|d| d.as_str()) .unwrap_or("") .to_string(); - let total = value.get("total").and_then(|t| t.as_u64()); - let completed = value.get("completed").and_then(|t| t.as_u64()); + let total = value.get("total").and_then(JsonValue::as_u64); + let completed = value.get("completed").and_then(JsonValue::as_u64); if total.is_some() || completed.is_some() { events.push(PullEvent::ChunkProgress { digest, diff --git a/codex-rs/protocol-ts/Cargo.toml b/codex-rs/protocol-ts/Cargo.toml index 1131a62196..3a0233dec3 100644 --- a/codex-rs/protocol-ts/Cargo.toml +++ b/codex-rs/protocol-ts/Cargo.toml @@ -15,8 +15,8 @@ name = "codex-protocol-ts" path = "src/main.rs" [dependencies] -anyhow = "1" -mcp-types = { path = "../mcp-types" } -codex-protocol = { path = "../protocol" } -ts-rs = "11" -clap = { version = "4", features = ["derive"] } +anyhow = { workspace = true } +mcp-types = { workspace = true } +codex-protocol = { workspace = true } +ts-rs = { workspace = true } +clap = { workspace = true, features = ["derive"] } diff --git a/codex-rs/protocol-ts/src/lib.rs b/codex-rs/protocol-ts/src/lib.rs index 967d9b1fcc..3aec3d892f 100644 --- a/codex-rs/protocol-ts/src/lib.rs +++ b/codex-rs/protocol-ts/src/lib.rs @@ -134,7 +134,7 @@ fn generate_index_ts(out_dir: &Path) -> Result { } let mut content = - String::with_capacity(HEADER.len() + entries.iter().map(|s| s.len()).sum::()); + String::with_capacity(HEADER.len() + entries.iter().map(String::len).sum::()); content.push_str(HEADER); for line in &entries { content.push_str(line); diff --git a/codex-rs/protocol/Cargo.toml b/codex-rs/protocol/Cargo.toml index bbe2ed3f65..9b530712cd 100644 --- a/codex-rs/protocol/Cargo.toml +++ b/codex-rs/protocol/Cargo.toml @@ -11,28 +11,28 @@ path = "src/lib.rs" workspace = true [dependencies] -base64 = "0.22.1" -icu_decimal = "2.0.0" -icu_locale_core = "2.0.0" -mcp-types = { path = "../mcp-types" } -mime_guess = "2.0.5" -serde = { version = "1", features = ["derive"] } -serde_json = "1" -serde_with = { version = "3.14.0", features = ["macros", "base64"] } -strum = "0.27.2" -strum_macros = "0.27.2" -sys-locale = "0.3.2" -tracing = "0.1.41" -ts-rs = { version = "11", features = [ +base64 = { workspace = true } +icu_decimal = { workspace = true } +icu_locale_core = { workspace = true } +mcp-types = { workspace = true } +mime_guess = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +serde_with = { workspace = true, features = ["macros", "base64"] } +strum = { workspace = true } +strum_macros = { workspace = true } +sys-locale = { workspace = true } +tracing = { workspace = true } +ts-rs = { workspace = true, features = [ "uuid-impl", "serde-json-impl", "no-serde-warnings", ] } -uuid = { version = "1", features = ["serde", "v7"] } +uuid = { workspace = true, features = ["serde", "v7"] } [dev-dependencies] -pretty_assertions = "1.4.1" -tempfile = "3" +pretty_assertions = { workspace = true } +tempfile = { workspace = true } [package.metadata.cargo-shear] # Required because the not imported as strum_macros in non-nightly builds. diff --git a/codex-rs/protocol/src/mcp_protocol.rs b/codex-rs/protocol/src/mcp_protocol.rs index c9137d0f94..52418b2755 100644 --- a/codex-rs/protocol/src/mcp_protocol.rs +++ b/codex-rs/protocol/src/mcp_protocol.rs @@ -710,7 +710,7 @@ mod tests { let request = ClientRequest::NewConversation { request_id: RequestId::Integer(42), params: NewConversationParams { - model: Some("gpt-5".to_string()), + model: Some("gpt-5-codex".to_string()), profile: None, cwd: None, approval_policy: Some(AskForApproval::OnRequest), @@ -726,7 +726,7 @@ mod tests { "method": "newConversation", "id": 42, "params": { - "model": "gpt-5", + "model": "gpt-5-codex", "approvalPolicy": "on-request" } }), diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index edcdcbebf8..478fcd5f10 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -596,14 +596,14 @@ pub struct TokenCountEvent { pub struct RateLimitSnapshotEvent { /// Percentage (0-100) of the primary window that has been consumed. pub primary_used_percent: f64, - /// Percentage (0-100) of the protection window that has been consumed. - pub weekly_used_percent: f64, - /// Size of the primary window relative to weekly (0-100). - pub primary_to_weekly_ratio_percent: f64, + /// Percentage (0-100) of the secondary window that has been consumed. + pub secondary_used_percent: f64, + /// Size of the primary window relative to secondary (0-100). + pub primary_to_secondary_ratio_percent: f64, /// Rolling window duration for the primary limit, in minutes. pub primary_window_minutes: u64, - /// Rolling window duration for the weekly limit, in minutes. - pub weekly_window_minutes: u64, + /// Rolling window duration for the secondary limit, in minutes. + pub secondary_window_minutes: u64, } // Includes prompts, tools and space to call compact. diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index c7a5315844..38546d0bc0 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -21,84 +21,83 @@ debug-logs = [] workspace = true [dependencies] -anyhow = "1" -async-stream = "0.3.6" -base64 = "0.22.1" -chrono = { version = "0.4", features = ["serde"] } -clap = { version = "4", features = ["derive"] } -codex-ansi-escape = { path = "../ansi-escape" } -codex-arg0 = { path = "../arg0" } -codex-common = { path = "../common", features = [ +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-arg0 = { workspace = true } +codex-common = { workspace = true, features = [ "cli", "elapsed", "sandbox_summary", ] } -codex-core = { path = "../core" } -codex-file-search = { path = "../file-search" } -codex-login = { path = "../login" } -codex-ollama = { path = "../ollama" } -codex-protocol = { path = "../protocol" } -color-eyre = "0.6.3" -crossterm = { version = "0.28.1", features = [ +codex-core = { workspace = true } +codex-file-search = { workspace = true } +codex-login = { workspace = true } +codex-ollama = { workspace = true } +codex-protocol = { workspace = true } +color-eyre = { workspace = true } +crossterm = { workspace = true, features = [ "bracketed-paste", "event-stream", ] } -dirs = "6" -diffy = "0.4.2" -image = { version = "^0.25.8", default-features = false, features = [ +dirs = { workspace = true } +diffy = { workspace = true } +image = { workspace = true, features = [ "jpeg", "png", ] } -itertools = "0.14.0" -lazy_static = "1" -mcp-types = { path = "../mcp-types" } -once_cell = "1" -path-clean = "1.0.1" -rand = "0.9" -ratatui = { version = "0.29.0", features = [ +itertools = { workspace = true } +lazy_static = { workspace = true } +mcp-types = { workspace = true } +once_cell = { workspace = true } +path-clean = { workspace = true } +rand = { workspace = true } +ratatui = { workspace = true, features = [ "scrolling-regions", "unstable-rendered-line-info", "unstable-widget-ref", ] } -regex-lite = "0.1" -serde = { version = "1", features = ["derive"] } -serde_json = { version = "1", features = ["preserve_order"] } -shlex = "1.3.0" -strum = "0.27.2" -strum_macros = "0.27.2" -supports-color = "3.0.2" -tempfile = "3" -textwrap = "0.16.2" -tokio = { version = "1", features = [ +regex-lite = { workspace = true } +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", ] } -tokio-stream = "0.1.17" -tracing = { version = "0.1.41", features = ["log"] } -tracing-appender = "0.2.3" -tracing-subscriber = { version = "0.3.20", features = ["env-filter"] } -pulldown-cmark = "0.10" -unicode-segmentation = "1.12.0" -unicode-width = "0.1" -url = "2" -pathdiff = "0.2" -owo-colors = "4.2.0" +tokio-stream = { workspace = true } +tracing = { workspace = true, features = ["log"] } +tracing-appender = { workspace = true } +tracing-subscriber = { workspace = true, features = ["env-filter"] } +pulldown-cmark = { workspace = true } +unicode-segmentation = { workspace = true } +unicode-width = { workspace = true } +url = { workspace = true } +pathdiff = { workspace = true } [target.'cfg(unix)'.dependencies] -libc = "0.2" +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 = "3" +arboard = { workspace = true } [dev-dependencies] -chrono = { version = "0.4", features = ["serde"] } -insta = "1.43.2" -pretty_assertions = "1" -rand = "0.9" -vt100 = "0.16.2" +chrono = { workspace = true, features = ["serde"] } +insta = { workspace = true } +pretty_assertions = { workspace = true } +rand = { workspace = true } +vt100 = { workspace = true } diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index f6b735b10b..9c30afdb4b 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -354,6 +354,15 @@ impl App { AppEvent::UpdateSandboxPolicy(policy) => { self.chat_widget.set_sandbox_policy(policy); } + 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(); + } } Ok(true) } @@ -431,11 +440,20 @@ impl App { 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::SessionConfiguredEvent; + use codex_protocol::mcp_protocol::ConversationId; + use ratatui::prelude::Line; + use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -486,4 +504,66 @@ mod tests { 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 { + Arc::new(UserHistoryCell { + message: text.to_string(), + }) as Arc + }; + let agent_cell = |text: &str| -> Arc { + Arc::new(AgentMessageCell::new( + vec![Line::from(text.to_string())], + true, + )) as Arc + }; + + let make_header = |is_first| { + let event = SessionConfiguredEvent { + session_id: ConversationId::new(), + model: "gpt-test".to_string(), + reasoning_effort: None, + history_log_id: 0, + history_entry_count: 0, + initial_messages: None, + rollout_path: PathBuf::new(), + }; + Arc::new(new_session_info( + app.chat_widget.config_ref(), + event, + is_first, + )) as Arc + }; + + // 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)"); + } } diff --git a/codex-rs/tui/src/app_backtrack.rs b/codex-rs/tui/src/app_backtrack.rs index c07be57af1..cbea2c02f7 100644 --- a/codex-rs/tui/src/app_backtrack.rs +++ b/codex-rs/tui/src/app_backtrack.rs @@ -1,7 +1,9 @@ +use std::any::TypeId; use std::path::PathBuf; use std::sync::Arc; use crate::app::App; +use crate::history_cell::CompositeHistoryCell; use crate::history_cell::UserHistoryCell; use crate::pager_overlay::Overlay; use crate::tui; @@ -160,43 +162,47 @@ impl App { self.backtrack.primed = true; self.backtrack.base_id = self.chat_widget.conversation_id(); self.backtrack.overlay_preview_active = true; - let last_user_cell_position = self - .transcript_cells - .iter() - .filter_map(|c| c.as_any().downcast_ref::()) - .count() as i64 - - 1; - if last_user_cell_position >= 0 { - self.apply_backtrack_selection(last_user_cell_position as usize); + 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 last_user_cell_position = self - .transcript_cells - .iter() - .filter(|c| c.as_any().is::()) - .take(self.backtrack.nth_user_message) - .count() - .saturating_sub(1); - self.apply_backtrack_selection(last_user_cell_position); + 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) { - self.backtrack.nth_user_message = nth_user_message; - if let Some(Overlay::Transcript(t)) = &mut self.overlay { - let cell = self - .transcript_cells - .iter() - .enumerate() - .filter(|(_, c)| c.as_any().is::()) - .nth(nth_user_message); - if let Some((idx, _)) = cell { - t.set_highlight_cell(Some(idx)); + 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); } } } @@ -217,13 +223,9 @@ impl App { 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 user_cells = self - .transcript_cells - .iter() - .filter_map(|c| c.as_any().downcast_ref::()) - .collect::>(); - let prefill = user_cells - .get(nth_user_message) + 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::()) .map(|c| c.message.clone()) .unwrap_or_default(); self.close_transcript_overlay(tui); @@ -246,14 +248,12 @@ impl App { /// 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 = self - .transcript_cells - .iter() - .filter(|c| c.as_any().is::()) - .nth(self.backtrack.nth_user_message) - .and_then(|c| c.as_any().downcast_ref::()) - .map(|c| c.message.clone()) - .unwrap_or_default(); + 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::()) + .map(|c| c.message.clone()) + .unwrap_or_default(); self.request_backtrack(prefill, base_id, self.backtrack.nth_user_message); } self.reset_backtrack_state(); @@ -363,13 +363,41 @@ fn trim_transcript_cells_to_nth_user( return; } - let cut_idx = transcript_cells + 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]) -> usize { + user_positions_iter(cells).count() +} + +fn nth_user_position( + cells: &[Arc], + nth: usize, +) -> Option { + user_positions_iter(cells) + .enumerate() + .find_map(|(i, idx)| (i == nth).then_some(idx)) +} + +fn user_positions_iter( + cells: &[Arc], +) -> impl Iterator + '_ { + let header_type = TypeId::of::(); + let user_type = TypeId::of::(); + let type_of = |cell: &Arc| cell.as_any().type_id(); + + let start = cells + .iter() + .rposition(|cell| type_of(cell) == header_type) + .map_or(0, |idx| idx + 1); + + cells .iter() .enumerate() - .filter_map(|(idx, cell)| cell.as_any().is::().then_some(idx)) - .nth(nth_user_message) - .unwrap_or(transcript_cells.len()); - transcript_cells.truncate(cut_idx); + .skip(start) + .filter_map(move |(idx, cell)| (type_of(cell) == user_type).then_some(idx)) } #[cfg(test)] @@ -389,7 +417,6 @@ mod tests { Arc::new(AgentMessageCell::new(vec![Line::from("assistant")], true)) as Arc, ]; - trim_transcript_cells_to_nth_user(&mut cells, 0); assert!(cells.is_empty()); @@ -406,7 +433,6 @@ mod tests { Arc::new(AgentMessageCell::new(vec![Line::from("after")], false)) as Arc, ]; - trim_transcript_cells_to_nth_user(&mut cells, 0); assert_eq!(cells.len(), 1); @@ -440,7 +466,6 @@ mod tests { Arc::new(AgentMessageCell::new(vec![Line::from("tail")], false)) as Arc, ]; - trim_transcript_cells_to_nth_user(&mut cells, 1); assert_eq!(cells.len(), 3); diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 41992cddcc..56c66379a6 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -1,3 +1,5 @@ +use std::path::PathBuf; + use codex_core::protocol::ConversationPathResponseEvent; use codex_core::protocol::Event; use codex_file_search::FileMatch; @@ -65,4 +67,13 @@ pub(crate) enum AppEvent { /// 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, } diff --git a/codex-rs/tui/src/bottom_pane/approval_modal_view.rs b/codex-rs/tui/src/bottom_pane/approval_modal_view.rs index e204051d28..912df6ce5a 100644 --- a/codex-rs/tui/src/bottom_pane/approval_modal_view.rs +++ b/codex-rs/tui/src/bottom_pane/approval_modal_view.rs @@ -7,7 +7,6 @@ use crate::app_event_sender::AppEventSender; use crate::user_approval_widget::ApprovalRequest; use crate::user_approval_widget::UserApprovalWidget; -use super::BottomPane; use super::BottomPaneView; use super::CancellationEvent; @@ -42,12 +41,12 @@ impl ApprovalModalView { } impl BottomPaneView for ApprovalModalView { - fn handle_key_event(&mut self, _pane: &mut BottomPane, key_event: KeyEvent) { + fn handle_key_event(&mut self, key_event: KeyEvent) { self.current.handle_key_event(key_event); self.maybe_advance(); } - fn on_ctrl_c(&mut self, _pane: &mut BottomPane) -> CancellationEvent { + fn on_ctrl_c(&mut self) -> CancellationEvent { self.current.on_ctrl_c(); self.queue.clear(); CancellationEvent::Handled @@ -75,6 +74,7 @@ impl BottomPaneView for ApprovalModalView { mod tests { use super::*; use crate::app_event::AppEvent; + use crate::bottom_pane::BottomPane; use tokio::sync::mpsc::unbounded_channel; fn make_exec_request() -> ApprovalRequest { @@ -94,7 +94,8 @@ mod tests { view.enqueue_request(make_exec_request()); let (tx2, _rx2) = unbounded_channel::(); - let mut pane = BottomPane::new(super::super::BottomPaneParams { + // Why do we have this? + let _pane = BottomPane::new(super::super::BottomPaneParams { app_event_tx: AppEventSender::new(tx2), frame_requester: crate::tui::FrameRequester::test_dummy(), has_input_focus: true, @@ -102,7 +103,7 @@ mod tests { placeholder_text: "Ask Codex to do anything".to_string(), disable_paste_burst: false, }); - assert_eq!(CancellationEvent::Handled, view.on_ctrl_c(&mut pane)); + assert_eq!(CancellationEvent::Handled, view.on_ctrl_c()); assert!(view.queue.is_empty()); assert!(view.current.is_complete()); assert!(view.is_complete()); diff --git a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs index 794dd8c422..6bc436f9dc 100644 --- a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs +++ b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs @@ -3,14 +3,13 @@ use crossterm::event::KeyEvent; use ratatui::buffer::Buffer; use ratatui::layout::Rect; -use super::BottomPane; use super::CancellationEvent; /// Trait implemented by every view that can be shown in the bottom pane. pub(crate) trait BottomPaneView { /// Handle a key event while the view is active. A redraw is always /// scheduled after this call. - fn handle_key_event(&mut self, _pane: &mut BottomPane, _key_event: KeyEvent) {} + 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 { @@ -18,7 +17,7 @@ pub(crate) trait BottomPaneView { } /// Handle Ctrl-C while this view is active. - fn on_ctrl_c(&mut self, _pane: &mut BottomPane) -> CancellationEvent { + fn on_ctrl_c(&mut self) -> CancellationEvent { CancellationEvent::NotHandled } @@ -28,6 +27,17 @@ pub(crate) trait BottomPaneView { /// Render the view: this will be displayed in place of the composer. fn render(&self, area: Rect, buf: &mut Buffer); + /// Optional paste handler. Return true if the view modified its state and + /// needs a redraw. + fn handle_paste(&mut self, _pasted: String) -> bool { + false + } + + /// Cursor position when this view is active. + fn cursor_pos(&self, _area: Rect) -> Option<(u16, u16)> { + None + } + /// Try to handle approval request; return the original value if not /// consumed. fn try_consume_approval_request( diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index bf11ff571d..65203b5193 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -161,8 +161,8 @@ impl ChatComposer { // Leave 1 for border and 1 for padding textarea_rect.width = textarea_rect.width.saturating_sub(LIVE_PREFIX_COLS); textarea_rect.x = textarea_rect.x.saturating_add(LIVE_PREFIX_COLS); - let state = self.textarea_state.borrow(); - self.textarea.cursor_pos_with_state(textarea_rect, &state) + let state = *self.textarea_state.borrow(); + self.textarea.cursor_pos_with_state(textarea_rect, state) } /// Returns true if the composer currently contains no user input. @@ -421,7 +421,7 @@ impl ChatComposer { // Capture any needed data from popup before clearing it. let prompt_content = match sel { CommandItem::UserPrompt(idx) => { - popup.prompt_content(idx).map(|s| s.to_string()) + popup.prompt_content(idx).map(str::to_string) } _ => None, }; @@ -550,7 +550,7 @@ impl ChatComposer { let format_label = match Path::new(&sel_path) .extension() .and_then(|e| e.to_str()) - .map(|s| s.to_ascii_lowercase()) + .map(str::to_ascii_lowercase) { Some(ext) if ext == "png" => "PNG", Some(ext) if ext == "jpg" || ext == "jpeg" => "JPEG", @@ -617,7 +617,7 @@ impl ChatComposer { text[safe_cursor..] .chars() .next() - .map(|c| c.is_whitespace()) + .map(char::is_whitespace) .unwrap_or(false) } else { false @@ -645,7 +645,7 @@ impl ChatComposer { let ws_len_right: usize = after_cursor .chars() .take_while(|c| c.is_whitespace()) - .map(|c| c.len_utf8()) + .map(char::len_utf8) .sum(); let start_right = safe_cursor + ws_len_right; let end_right_rel = text[start_right..] diff --git a/codex-rs/tui/src/bottom_pane/command_popup.rs b/codex-rs/tui/src/bottom_pane/command_popup.rs index a492a2e17e..a0933f4ae6 100644 --- a/codex-rs/tui/src/bottom_pane/command_popup.rs +++ b/codex-rs/tui/src/bottom_pane/command_popup.rs @@ -218,6 +218,7 @@ impl WidgetRef for CommandPopup { #[cfg(test)] mod tests { use super::*; + use std::string::ToString; #[test] fn filter_includes_init_when_typing_prefix() { @@ -287,7 +288,7 @@ mod tests { let mut prompt_names: Vec = items .into_iter() .filter_map(|it| match it { - CommandItem::UserPrompt(i) => popup.prompt_name(i).map(|s| s.to_string()), + CommandItem::UserPrompt(i) => popup.prompt_name(i).map(ToString::to_string), _ => None, }) .collect(); diff --git a/codex-rs/tui/src/bottom_pane/custom_prompt_view.rs b/codex-rs/tui/src/bottom_pane/custom_prompt_view.rs new file mode 100644 index 0000000000..a8084d0d04 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/custom_prompt_view.rs @@ -0,0 +1,243 @@ +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 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; + +/// Minimal multi-line text input view to collect custom review instructions. +pub(crate) struct CustomPromptView { + title: String, + placeholder: String, + context_label: Option, + on_submit: PromptSubmitted, + + // UI state + textarea: TextArea, + textarea_state: RefCell, + complete: bool, +} + +impl CustomPromptView { + pub(crate) fn new( + title: String, + placeholder: String, + context_label: Option, + 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 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> = 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> = 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 handle_paste(&mut self, pasted: String) -> bool { + if pasted.is_empty() { + return false; + } + self.textarea.insert_str(&pasted); + true + } + + 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/tui/src/bottom_pane/list_selection_view.rs b/codex-rs/tui/src/bottom_pane/list_selection_view.rs index 5d5dbf0f33..a856a3c634 100644 --- a/codex-rs/tui/src/bottom_pane/list_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/list_selection_view.rs @@ -11,7 +11,6 @@ use ratatui::widgets::Widget; use crate::app_event_sender::AppEventSender; -use super::BottomPane; use super::CancellationEvent; use super::bottom_pane_view::BottomPaneView; use super::popup_consts::MAX_POPUP_ROWS; @@ -28,6 +27,18 @@ pub(crate) struct SelectionItem { pub description: Option, pub is_current: bool, pub actions: Vec, + pub dismiss_on_select: bool, + pub search_value: Option, +} + +#[derive(Default)] +pub(crate) struct SelectionViewParams { + pub title: String, + pub subtitle: Option, + pub footer_hint: Option, + pub items: Vec, + pub is_searchable: bool, + pub search_placeholder: Option, } pub(crate) struct ListSelectionView { @@ -38,6 +49,10 @@ pub(crate) struct ListSelectionView { state: ScrollState, complete: bool, app_event_tx: AppEventSender, + is_searchable: bool, + search_query: String, + search_placeholder: Option, + filtered_indices: Vec, } impl ListSelectionView { @@ -49,49 +64,144 @@ impl ListSelectionView { let para = Paragraph::new(Line::from(Self::dim_prefix_span())); para.render(area, buf); } - pub fn new( - title: String, - subtitle: Option, - footer_hint: Option, - items: Vec, - app_event_tx: AppEventSender, - ) -> Self { + + pub fn new(params: SelectionViewParams, app_event_tx: AppEventSender) -> Self { let mut s = Self { - title, - subtitle, - footer_hint, - items, + title: params.title, + subtitle: params.subtitle, + 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(), }; - let len = s.items.len(); - if let Some(idx) = s.items.iter().position(|it| it.is_current) { - s.state.selected_idx = Some(idx); - } - s.state.clamp_selection(len); - s.state.ensure_visible(len, MAX_POPUP_ROWS.min(len)); + 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() + }); + + if self.is_searchable && !self.search_query.is_empty() { + let query_lower = self.search_query.to_lowercase(); + self.filtered_indices = self + .items + .iter() + .enumerate() + .filter_map(|(idx, item)| { + let matches = if let Some(search_value) = &item.search_value { + search_value.to_lowercase().contains(&query_lower) + } else { + let mut matches = item.name.to_lowercase().contains(&query_lower); + if !matches && let Some(desc) = &item.description { + matches = desc.to_lowercase().contains(&query_lower); + } + matches + }; + matches.then_some(idx) + }) + .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 { + 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 display_name = format!("{prefix} {n}. {name_with_marker}"); + GenericDisplayRow { + name: display_name, + match_indices: None, + is_current: item.is_current, + description: item.description.clone(), + } + }) + }) + .collect() + } + fn move_up(&mut self) { - let len = self.items.len(); + let len = self.visible_len(); self.state.move_up_wrap(len); - self.state.ensure_visible(len, MAX_POPUP_ROWS.min(len)); + let visible = Self::max_visible_rows(len); + self.state.ensure_visible(len, visible); } fn move_down(&mut self) { - let len = self.items.len(); + let len = self.visible_len(); self.state.move_down_wrap(len); - self.state.ensure_visible(len, MAX_POPUP_ROWS.min(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 { - if let Some(item) = self.items.get(idx) { - for act in &item.actions { - act(&self.app_event_tx); - } + 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) + { + for act in &item.actions { + act(&self.app_event_tx); + } + if item.dismiss_on_select { self.complete = true; } } else { @@ -99,14 +209,15 @@ impl ListSelectionView { } } - fn cancel(&mut self) { - // Close the popup without performing any actions. - self.complete = true; + #[cfg(test)] + pub(crate) fn set_search_query(&mut self, query: String) { + self.search_query = query; + self.apply_filter(); } } impl BottomPaneView for ListSelectionView { - fn handle_key_event(&mut self, _pane: &mut BottomPane, key_event: KeyEvent) { + fn handle_key_event(&mut self, key_event: KeyEvent) { match key_event { KeyEvent { code: KeyCode::Up, .. @@ -115,9 +226,29 @@ impl BottomPaneView for ListSelectionView { code: KeyCode::Down, .. } => self.move_down(), + KeyEvent { + code: KeyCode::Backspace, + .. + } if self.is_searchable => { + self.search_query.pop(); + self.apply_filter(); + } KeyEvent { code: KeyCode::Esc, .. - } => self.cancel(), + } => { + 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::Enter, modifiers: KeyModifiers::NONE, @@ -131,7 +262,7 @@ impl BottomPaneView for ListSelectionView { self.complete } - fn on_ctrl_c(&mut self, _pane: &mut BottomPane) -> CancellationEvent { + fn on_ctrl_c(&mut self) -> CancellationEvent { self.complete = true; CancellationEvent::Handled } @@ -139,33 +270,16 @@ impl BottomPaneView 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: Vec = self - .items - .iter() - .enumerate() - .map(|(i, it)| { - let is_selected = self.state.selected_idx == Some(i); - let prefix = if is_selected { '>' } else { ' ' }; - let name_with_marker = if it.is_current { - format!("{} (current)", it.name) - } else { - it.name.clone() - }; - let display_name = format!("{} {}. {}", prefix, i + 1, name_with_marker); - GenericDisplayRow { - name: display_name, - match_indices: None, - is_current: it.is_current, - description: it.description.clone(), - } - }) - .collect(); + let rows = self.build_rows(); let rows_height = measure_rows_height(&rows, &self.state, MAX_POPUP_ROWS, width); // +1 for the title row, +1 for a spacer line beneath the header, // +1 for optional subtitle, +1 for optional footer (2 lines incl. spacing) let mut height = rows_height + 2; + if self.is_searchable { + height = height.saturating_add(1); + } if self.subtitle.is_some() { // +1 for subtitle (the spacer is accounted for above) height = height.saturating_add(1); @@ -194,6 +308,25 @@ impl BottomPaneView for ListSelectionView { title_para.render(title_area, buf); let mut next_y = area.y.saturating_add(1); + if self.is_searchable { + let search_area = Rect { + x: area.x, + y: next_y, + width: area.width, + height: 1, + }; + 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() + }; + Paragraph::new(Line::from(vec![Self::dim_prefix_span(), query_span])) + .render(search_area, buf); + next_y = next_y.saturating_add(1); + } if let Some(sub) = &self.subtitle { let subtitle_area = Rect { x: area.x, @@ -228,27 +361,7 @@ impl BottomPaneView for ListSelectionView { .saturating_sub(footer_reserved), }; - let rows: Vec = self - .items - .iter() - .enumerate() - .map(|(i, it)| { - let is_selected = self.state.selected_idx == Some(i); - let prefix = if is_selected { '>' } else { ' ' }; - let name_with_marker = if it.is_current { - format!("{} (current)", it.name) - } else { - it.name.clone() - }; - let display_name = format!("{} {}. {}", prefix, i + 1, name_with_marker); - GenericDisplayRow { - name: display_name, - match_indices: None, - is_current: it.is_current, - description: it.description.clone(), - } - }) - .collect(); + let rows = self.build_rows(); if rows_area.height > 0 { render_rows( rows_area, @@ -279,6 +392,7 @@ mod tests { use super::BottomPaneView; 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; @@ -292,19 +406,26 @@ mod tests { description: Some("Codex can read files".to_string()), is_current: true, actions: vec![], + dismiss_on_select: true, + search_value: None, }, SelectionItem { name: "Full Access".to_string(), description: Some("Codex can edit files".to_string()), is_current: false, actions: vec![], + dismiss_on_select: true, + search_value: None, }, ]; ListSelectionView::new( - "Select Approval Mode".to_string(), - subtitle.map(str::to_string), - Some("Press Enter to confirm or Esc to go back".to_string()), - items, + SelectionViewParams { + title: "Select Approval Mode".to_string(), + subtitle: subtitle.map(str::to_string), + footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + items, + ..Default::default() + }, tx, ) } @@ -347,4 +468,33 @@ mod tests { 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::(); + 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, + actions: vec![], + dismiss_on_select: true, + search_value: None, + }]; + let mut view = ListSelectionView::new( + SelectionViewParams { + title: "Select Approval Mode".to_string(), + footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + 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")); + } } diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index f30bd418e9..fc9f06c39d 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -7,6 +7,7 @@ use crate::user_approval_widget::ApprovalRequest; use bottom_pane_view::BottomPaneView; use codex_core::protocol::TokenUsageInfo; use codex_file_search::FileMatch; +use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use ratatui::buffer::Buffer; use ratatui::layout::Constraint; @@ -20,10 +21,12 @@ mod bottom_pane_view; mod chat_composer; mod chat_composer_history; mod command_popup; +pub mod custom_prompt_view; mod file_search_popup; mod list_selection_view; +pub(crate) use list_selection_view::SelectionViewParams; mod paste_burst; -mod popup_consts; +pub mod popup_consts; mod scroll_state; mod selection_popup_common; mod textarea; @@ -49,8 +52,8 @@ pub(crate) struct BottomPane { /// input state is retained when the view is closed. composer: ChatComposer, - /// If present, this is displayed instead of the `composer` (e.g. modals). - active_view: Option>, + /// Stack of views displayed instead of the composer (e.g. popups/modals). + view_stack: Vec>, app_event_tx: AppEventSender, frame_requester: FrameRequester, @@ -87,7 +90,7 @@ impl BottomPane { params.placeholder_text, params.disable_paste_burst, ), - active_view: None, + view_stack: Vec::new(), app_event_tx: params.app_event_tx, frame_requester: params.frame_requester, has_input_focus: params.has_input_focus, @@ -99,12 +102,21 @@ impl BottomPane { } } + fn active_view(&self) -> Option<&dyn BottomPaneView> { + self.view_stack.last().map(std::convert::AsRef::as_ref) + } + + fn push_view(&mut self, view: Box) { + self.view_stack.push(view); + self.request_redraw(); + } + pub fn desired_height(&self, width: u16) -> u16 { // Always reserve one blank row above the pane for visual spacing. let top_margin = 1; // Base height depends on whether a modal/overlay is active. - let base = match self.active_view.as_ref() { + let base = match self.active_view().as_ref() { Some(view) => view.desired_height(width), None => self.composer.desired_height(width).saturating_add( self.status @@ -131,7 +143,7 @@ impl BottomPane { width: area.width, height: area.height - top_margin - bottom_margin, }; - match self.active_view.as_ref() { + match self.active_view() { Some(_) => [Rect::ZERO, area], None => { let status_height = self @@ -148,22 +160,30 @@ impl BottomPane { // status indicator shown while a task is running, or approval modal). // In these states the textarea is not interactable, so we should not // show its caret. - if self.active_view.is_some() { - None + let [_, content] = self.layout(area); + if let Some(view) = self.active_view() { + view.cursor_pos(content) } else { - let [_, content] = self.layout(area); self.composer.cursor_pos(content) } } /// Forward a key event to the active view or the composer. pub fn handle_key_event(&mut self, key_event: KeyEvent) -> InputResult { - if let Some(mut view) = self.active_view.take() { - view.handle_key_event(self, key_event); - if !view.is_complete() { - self.active_view = Some(view); - } else { + // 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 @@ -193,38 +213,36 @@ impl BottomPane { /// 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 { - let mut view = match self.active_view.take() { - Some(view) => view, - None => { - return if self.composer_is_empty() { - CancellationEvent::NotHandled - } else { - self.set_composer_text(String::new()); - self.show_ctrl_c_quit_hint(); - CancellationEvent::Handled - }; - } - }; - - let event = view.on_ctrl_c(self); - match event { - CancellationEvent::Handled => { - if !view.is_complete() { - self.active_view = Some(view); - } else { + 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(); } - CancellationEvent::NotHandled => { - self.active_view = Some(view); - } + event + } else if self.composer_is_empty() { + CancellationEvent::NotHandled + } else { + self.view_stack.pop(); + self.set_composer_text(String::new()); + self.show_ctrl_c_quit_hint(); + CancellationEvent::Handled } - event } pub fn handle_paste(&mut self, pasted: String) { - if self.active_view.is_none() { + 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(); @@ -318,22 +336,9 @@ impl BottomPane { } /// Show a generic list selection view with the provided items. - pub(crate) fn show_selection_view( - &mut self, - title: String, - subtitle: Option, - footer_hint: Option, - items: Vec, - ) { - let view = list_selection_view::ListSelectionView::new( - title, - subtitle, - footer_hint, - items, - self.app_event_tx.clone(), - ); - self.active_view = Some(Box::new(view)); - self.request_redraw(); + 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 shown under the status header. @@ -363,7 +368,7 @@ impl BottomPane { /// 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.active_view.is_none() && !self.composer.popup_active() + !self.is_task_running && self.view_stack.is_empty() && !self.composer.popup_active() } /// Update the *context-window remaining* indicator in the composer. This @@ -373,9 +378,13 @@ impl BottomPane { self.request_redraw(); } + pub(crate) fn show_view(&mut self, view: Box) { + self.push_view(view); + } + /// Called when the agent requests user approval. pub fn push_approval_request(&mut self, request: ApprovalRequest) { - let request = if let Some(view) = self.active_view.as_mut() { + let request = if let Some(view) = self.view_stack.last_mut() { match view.try_consume_approval_request(request) { Some(request) => request, None => { @@ -390,8 +399,7 @@ impl BottomPane { // Otherwise create a new approval modal overlay. let modal = ApprovalModalView::new(request, self.app_event_tx.clone()); self.pause_status_timer_for_modal(); - self.active_view = Some(Box::new(modal)); - self.request_redraw() + self.push_view(Box::new(modal)); } fn on_active_view_complete(&mut self) { @@ -460,7 +468,7 @@ impl BottomPane { height: u32, format_label: &str, ) { - if self.active_view.is_none() { + if self.view_stack.is_empty() { self.composer .attach_image(path, width, height, format_label); self.request_redraw(); @@ -477,7 +485,7 @@ impl WidgetRef for &BottomPane { let [status_area, content] = self.layout(area); // When a modal view is active, it owns the whole content area. - if let Some(view) = &self.active_view { + if let Some(view) = self.active_view() { view.render(content, buf); } else { // No active modal: @@ -587,7 +595,7 @@ mod tests { // After denial, since the task is still running, the status indicator should be // visible above the composer. The modal should be gone. assert!( - pane.active_view.is_none(), + pane.view_stack.is_empty(), "no active modal view after denial" ); diff --git a/codex-rs/tui/src/bottom_pane/paste_burst.rs b/codex-rs/tui/src/bottom_pane/paste_burst.rs index d507dcae37..559744a462 100644 --- a/codex-rs/tui/src/bottom_pane/paste_burst.rs +++ b/codex-rs/tui/src/bottom_pane/paste_burst.rs @@ -183,7 +183,7 @@ impl PasteBurst { let start_byte = retro_start_index(before, retro_chars); let grabbed = before[start_byte..].to_string(); let looks_pastey = - grabbed.chars().any(|c| c.is_whitespace()) || grabbed.chars().count() >= 16; + 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); diff --git a/codex-rs/tui/src/bottom_pane/popup_consts.rs b/codex-rs/tui/src/bottom_pane/popup_consts.rs index 5f447d735c..5147b2ee5f 100644 --- a/codex-rs/tui/src/bottom_pane/popup_consts.rs +++ b/codex-rs/tui/src/bottom_pane/popup_consts.rs @@ -3,3 +3,6 @@ /// 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) const STANDARD_POPUP_HINT_LINE: &str = "Press Enter to confirm or Esc to go back"; diff --git a/codex-rs/tui/src/bottom_pane/selection_popup_common.rs b/codex-rs/tui/src/bottom_pane/selection_popup_common.rs index 684924a44a..38eaab7486 100644 --- a/codex-rs/tui/src/bottom_pane/selection_popup_common.rs +++ b/codex-rs/tui/src/bottom_pane/selection_popup_common.rs @@ -13,6 +13,7 @@ use ratatui::widgets::BorderType; use ratatui::widgets::Borders; use ratatui::widgets::Paragraph; use ratatui::widgets::Widget; +use unicode_width::UnicodeWidthChar; use super::scroll_state::ScrollState; use crate::ui_consts::LIVE_PREFIX_COLS; @@ -55,10 +56,24 @@ fn compute_desc_col( /// 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 = desc_col.saturating_sub(2); + let mut name_spans: Vec = 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); + if used_width + ch_w > name_limit { + truncated = true; + break; + } + used_width += ch_w; + if idx_iter.peek().is_some_and(|next| **next == char_idx) { idx_iter.next(); name_spans.push(ch.to_string().bold()); @@ -67,7 +82,21 @@ fn build_full_line(row: &GenericDisplayRow, desc_col: usize) -> Line<'static> { } } } else { - name_spans.push(row.name.clone().into()); + for ch in row.name.chars() { + let ch_w = UnicodeWidthChar::width(ch).unwrap_or(0); + if used_width + ch_w > name_limit { + truncated = true; + break; + } + used_width += ch_w; + 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(); diff --git a/codex-rs/tui/src/bottom_pane/textarea.rs b/codex-rs/tui/src/bottom_pane/textarea.rs index 9166b8c7f6..269fa345e0 100644 --- a/codex-rs/tui/src/bottom_pane/textarea.rs +++ b/codex-rs/tui/src/bottom_pane/textarea.rs @@ -132,11 +132,11 @@ impl TextArea { #[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()) + 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)> { + 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)?; @@ -1408,7 +1408,7 @@ mod tests { 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(); + let (_x, y) = t.cursor_pos_with_state(small_area, state).unwrap(); assert_eq!(y, 0); // Render with state to update actual scroll value @@ -1429,7 +1429,7 @@ mod tests { // 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(); + 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 @@ -1442,7 +1442,7 @@ mod tests { 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(); + 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) @@ -1456,7 +1456,7 @@ mod tests { let state = TextAreaState { scroll: lines.saturating_mul(2), }; - let (_x, y) = t.cursor_pos_with_state(area, &state).unwrap(); + let (_x, y) = t.cursor_pos_with_state(area, state).unwrap(); assert_eq!(y, area.y); } @@ -1480,7 +1480,7 @@ mod tests { // 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(); + 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' @@ -1510,35 +1510,35 @@ mod tests { // 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(); + 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(); + 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(); + 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(); + 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(); + 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(); + let (x1, y1) = t.cursor_pos_with_state(area, state).unwrap(); assert_eq!((x1, y1), (2, 1)); } @@ -1796,7 +1796,7 @@ mod tests { // cursor_pos_with_state: always within viewport rows let (_x, _y) = ta - .cursor_pos_with_state(area, &state) + .cursor_pos_with_state(area, state) .unwrap_or((area.x, area.y)); // Stateful render should not panic, and updates scroll diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index cb8acd04fb..fc36809672 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -5,6 +5,8 @@ use std::sync::Arc; 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::protocol::AgentMessageDeltaEvent; use codex_core::protocol::AgentMessageEvent; use codex_core::protocol::AgentReasoningDeltaEvent; @@ -63,6 +65,9 @@ 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::get_git_diff::get_git_diff; @@ -87,6 +92,7 @@ mod session_header; use self::session_header::SessionHeader; use crate::streaming::controller::AppEventHistorySink; use crate::streaming::controller::StreamController; +// use codex_common::approval_presets::ApprovalPreset; use codex_common::approval_presets::builtin_approval_presets; use codex_common::model_presets::ModelPreset; @@ -97,6 +103,7 @@ use codex_core::protocol::AskForApproval; use codex_core::protocol::SandboxPolicy; use codex_core::protocol_config_types::ReasoningEffort as ReasoningEffortConfig; use codex_file_search::FileMatch; +use std::path::Path; // Track information about an in-flight exec command. struct RunningCommand { @@ -108,32 +115,36 @@ const RATE_LIMIT_WARNING_THRESHOLDS: [f64; 3] = [50.0, 75.0, 90.0]; #[derive(Default)] struct RateLimitWarningState { - weekly_index: usize, - hourly_index: usize, + secondary_index: usize, + primary_index: usize, } impl RateLimitWarningState { - fn take_warnings(&mut self, weekly_used_percent: f64, hourly_used_percent: f64) -> Vec { + fn take_warnings( + &mut self, + secondary_used_percent: f64, + primary_used_percent: f64, + ) -> Vec { let mut warnings = Vec::new(); - while self.weekly_index < RATE_LIMIT_WARNING_THRESHOLDS.len() - && weekly_used_percent >= RATE_LIMIT_WARNING_THRESHOLDS[self.weekly_index] + while self.secondary_index < RATE_LIMIT_WARNING_THRESHOLDS.len() + && secondary_used_percent >= RATE_LIMIT_WARNING_THRESHOLDS[self.secondary_index] { - let threshold = RATE_LIMIT_WARNING_THRESHOLDS[self.weekly_index]; + let threshold = RATE_LIMIT_WARNING_THRESHOLDS[self.secondary_index]; warnings.push(format!( - "Weekly usage exceeded {threshold:.0}% of the limit. Run /limits for detailed usage." + "Heads up, you've used over {threshold:.0}% of your weekly limit. Run /status for a breakdown." )); - self.weekly_index += 1; + self.secondary_index += 1; } - while self.hourly_index < RATE_LIMIT_WARNING_THRESHOLDS.len() - && hourly_used_percent >= RATE_LIMIT_WARNING_THRESHOLDS[self.hourly_index] + while self.primary_index < RATE_LIMIT_WARNING_THRESHOLDS.len() + && primary_used_percent >= RATE_LIMIT_WARNING_THRESHOLDS[self.primary_index] { - let threshold = RATE_LIMIT_WARNING_THRESHOLDS[self.hourly_index]; + let threshold = RATE_LIMIT_WARNING_THRESHOLDS[self.primary_index]; warnings.push(format!( - "Hourly usage exceeded {threshold:.0}% of the limit. Run /limits for detailed usage." + "Heads up, you've used over {threshold:.0}% of your 5h limit. Run /status for a breakdown." )); - self.hourly_index += 1; + self.primary_index += 1; } warnings @@ -164,7 +175,7 @@ pub(crate) struct ChatWidget { rate_limit_snapshot: Option, rate_limit_warnings: RateLimitWarningState, // Stream lifecycle controller - stream: StreamController, + stream_controller: Option, running_commands: HashMap, task_complete_pending: bool, // Queue of interruptive UI events deferred during an active write cycle @@ -212,8 +223,10 @@ fn create_initial_user_message(text: String, image_paths: Vec) -> Optio impl ChatWidget { fn flush_answer_stream_with_separator(&mut self) { - let sink = AppEventHistorySink(self.app_event_tx.clone()); - let _ = self.stream.finalize(true, &sink); + if let Some(mut controller) = self.stream_controller.take() { + let sink = AppEventHistorySink(self.app_event_tx.clone()); + controller.finalize(&sink); + } } // --- Small event handlers --- fn on_session_configured(&mut self, event: codex_core::protocol::SessionConfiguredEvent) { @@ -242,9 +255,13 @@ impl ChatWidget { } fn on_agent_message(&mut self, message: String) { - let sink = AppEventHistorySink(self.app_event_tx.clone()); - let finished = self.stream.apply_final_answer(&message, &sink); - self.handle_if_stream_finished(finished); + // 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(); } @@ -294,7 +311,6 @@ impl ChatWidget { fn on_task_started(&mut self) { self.bottom_pane.clear_ctrl_c_quit_hint(); self.bottom_pane.set_task_running(true); - self.stream.reset_headers_for_new_turn(); self.full_reasoning_buffer.clear(); self.reasoning_buffer.clear(); self.request_redraw(); @@ -303,9 +319,9 @@ impl ChatWidget { fn on_task_complete(&mut self, last_agent_message: Option) { // If a stream is currently active, finalize only that stream to flush any tail // without emitting stray headers for other streams. - if self.stream.is_write_cycle_active() { + if let Some(mut controller) = self.stream_controller.take() { let sink = AppEventHistorySink(self.app_event_tx.clone()); - let _ = self.stream.finalize(true, &sink); + controller.finalize(&sink); } // Mark task stopped and request redraw now that all content is in history. self.bottom_pane.set_task_running(false); @@ -327,9 +343,10 @@ impl ChatWidget { fn on_rate_limit_snapshot(&mut self, snapshot: Option) { if let Some(snapshot) = snapshot { - let warnings = self - .rate_limit_warnings - .take_warnings(snapshot.weekly_used_percent, snapshot.primary_used_percent); + let warnings = self.rate_limit_warnings.take_warnings( + snapshot.secondary_used_percent, + snapshot.primary_used_percent, + ); self.rate_limit_snapshot = Some(snapshot); if !warnings.is_empty() { for warning in warnings { @@ -346,7 +363,7 @@ impl ChatWidget { // Reset running state and clear streaming buffers. self.bottom_pane.set_task_running(false); self.running_commands.clear(); - self.stream.clear_all(); + self.stream_controller = None; } fn on_error(&mut self, message: String) { @@ -501,12 +518,13 @@ impl ChatWidget { /// 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) { - let sink = AppEventHistorySink(self.app_event_tx.clone()); - let finished = self.stream.on_commit_tick(&sink); - self.handle_if_stream_finished(finished); - } - fn is_write_cycle_active(&self) -> bool { - self.stream.is_write_cycle_active() + if let Some(controller) = self.stream_controller.as_mut() { + let sink = AppEventHistorySink(self.app_event_tx.clone()); + let finished = controller.on_commit_tick(&sink); + if finished { + self.handle_stream_finished(); + } + } } fn flush_interrupt_queue(&mut self) { @@ -524,32 +542,34 @@ impl ChatWidget { // 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.is_write_cycle_active() || !self.interrupts.is_empty() { + if self.stream_controller.is_some() || !self.interrupts.is_empty() { push(&mut self.interrupts); } else { handle(self); } } - #[inline] - fn handle_if_stream_finished(&mut self, finished: bool) { - if finished { - if self.task_complete_pending { - self.bottom_pane.set_task_running(false); - self.task_complete_pending = false; - } - // A completed stream indicates non-exec content was just inserted. - self.flush_interrupt_queue(); + fn handle_stream_finished(&mut self) { + if self.task_complete_pending { + self.bottom_pane.set_task_running(false); + 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_exec_cell(); - let sink = AppEventHistorySink(self.app_event_tx.clone()); - self.stream.begin(&sink); - self.stream.push_and_maybe_commit(&delta, &sink); + + if self.stream_controller.is_none() { + self.stream_controller = Some(StreamController::new(self.config.clone())); + } + if let Some(controller) = self.stream_controller.as_mut() { + let sink = AppEventHistorySink(self.app_event_tx.clone()); + controller.push_and_maybe_commit(&delta, &sink); + } self.request_redraw(); } @@ -601,7 +621,7 @@ impl ChatWidget { self.flush_answer_stream_with_separator(); // Emit the proposed command into history (like proposed patches) self.add_to_history(history_cell::new_proposed_command(&ev.command)); - let command = shlex::try_join(ev.command.iter().map(|s| s.as_str())) + let command = shlex::try_join(ev.command.iter().map(String::as_str)) .unwrap_or_else(|_| ev.command.join(" ")); self.notify(Notification::ExecApprovalRequested { command }); @@ -747,7 +767,7 @@ impl ChatWidget { active_exec_cell: None, config: config.clone(), auth_manager, - session_header: SessionHeader::new(config.model.clone()), + session_header: SessionHeader::new(config.model), initial_user_message: create_initial_user_message( initial_prompt.unwrap_or_default(), initial_images, @@ -755,7 +775,7 @@ impl ChatWidget { token_info: None, rate_limit_snapshot: None, rate_limit_warnings: RateLimitWarningState::default(), - stream: StreamController::new(config), + stream_controller: None, running_commands: HashMap::new(), task_complete_pending: false, interrupts: InterruptManager::new(), @@ -806,7 +826,7 @@ impl ChatWidget { active_exec_cell: None, config: config.clone(), auth_manager, - session_header: SessionHeader::new(config.model.clone()), + session_header: SessionHeader::new(config.model), initial_user_message: create_initial_user_message( initial_prompt.unwrap_or_default(), initial_images, @@ -814,7 +834,7 @@ impl ChatWidget { token_info: None, rate_limit_snapshot: None, rate_limit_warnings: RateLimitWarningState::default(), - stream: StreamController::new(config), + stream_controller: None, running_commands: HashMap::new(), task_complete_pending: false, interrupts: InterruptManager::new(), @@ -941,13 +961,7 @@ impl ChatWidget { self.app_event_tx.send(AppEvent::CodexOp(Op::Compact)); } SlashCommand::Review => { - // Simplified flow: directly send a review op for current changes. - self.submit_op(Op::Review { - review_request: ReviewRequest { - prompt: "review current changes".to_string(), - user_facing_hint: "current changes".to_string(), - }, - }); + self.open_review_popup(); } SlashCommand::Model => { self.open_model_popup(); @@ -987,9 +1001,6 @@ impl ChatWidget { SlashCommand::Status => { self.add_status_output(); } - SlashCommand::Limits => { - self.add_limits_output(); - } SlashCommand::Mcp => { self.add_mcp_output(); } @@ -1346,15 +1357,6 @@ impl ChatWidget { self.request_redraw(); } - pub(crate) fn add_limits_output(&mut self) { - if let Some(snapshot) = &self.rate_limit_snapshot { - self.add_to_history(history_cell::new_limits_output(snapshot)); - } else { - self.add_to_history(history_cell::new_limits_unavailable()); - } - self.request_redraw(); - } - pub(crate) fn add_status_output(&mut self) { let default_usage; let usage_ref = if let Some(ti) = &self.token_info { @@ -1367,6 +1369,7 @@ impl ChatWidget { &self.config, usage_ref, &self.conversation_id, + self.rate_limit_snapshot.as_ref(), )); } @@ -1417,15 +1420,20 @@ impl ChatWidget { description, is_current, actions, + dismiss_on_select: true, + search_value: None, }); } - self.bottom_pane.show_selection_view( - "Select model and reasoning level".to_string(), - Some("Switch between OpenAI models for this and future Codex CLI session".to_string()), - Some("Press Enter to confirm or Esc to go back".to_string()), + self.bottom_pane.show_selection_view(SelectionViewParams { + title: "Select model and reasoning level".to_string(), + subtitle: Some( + "Switch between OpenAI models for this and future Codex CLI session".to_string(), + ), + footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), items, - ); + ..Default::default() + }); } /// Open a popup to choose the approvals mode (ask for approval policy + sandbox policy). @@ -1458,15 +1466,17 @@ impl ChatWidget { description, is_current, actions, + dismiss_on_select: true, + search_value: None, }); } - self.bottom_pane.show_selection_view( - "Select Approval Mode".to_string(), - None, - Some("Press Enter to confirm or Esc to go back".to_string()), + self.bottom_pane.show_selection_view(SelectionViewParams { + title: "Select Approval Mode".to_string(), + footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), items, - ); + ..Default::default() + }); } /// Set the approval policy in the widget's config copy. @@ -1575,6 +1585,176 @@ impl ChatWidget { self.bottom_pane.set_custom_prompts(ev.custom_prompts); } + pub(crate) fn open_review_popup(&mut self) { + let mut items: Vec = Vec::new(); + + items.push(SelectionItem { + name: "Review uncommitted changes".to_string(), + description: None, + is_current: false, + actions: vec![Box::new( + move |tx: &AppEventSender| { + tx.send(AppEvent::CodexOp(Op::Review { + review_request: ReviewRequest { + prompt: "Review the current code changes (staged, unstaged, and untracked files) and provide prioritized findings.".to_string(), + user_facing_hint: "current changes".to_string(), + }, + })); + }, + )], + dismiss_on_select: true, + search_value: None, + }); + + // New: Review a specific commit (opens commit picker) + items.push(SelectionItem { + name: "Review a commit".to_string(), + description: None, + is_current: false, + actions: vec![Box::new({ + let cwd = self.config.cwd.clone(); + move |tx| { + tx.send(AppEvent::OpenReviewCommitPicker(cwd.clone())); + } + })], + dismiss_on_select: false, + search_value: None, + }); + + items.push(SelectionItem { + name: "Review against a base branch".to_string(), + description: None, + is_current: false, + actions: vec![Box::new({ + let cwd = self.config.cwd.clone(); + move |tx| { + tx.send(AppEvent::OpenReviewBranchPicker(cwd.clone())); + } + })], + dismiss_on_select: false, + search_value: None, + }); + + items.push(SelectionItem { + name: "Custom review instructions".to_string(), + description: None, + is_current: false, + actions: vec![Box::new(move |tx| { + tx.send(AppEvent::OpenReviewCustomPrompt); + })], + dismiss_on_select: false, + search_value: None, + }); + + self.bottom_pane.show_selection_view(SelectionViewParams { + title: "Select a review preset".into(), + footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + 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 = Vec::with_capacity(branches.len()); + + for option in branches { + let branch = option.clone(); + items.push(SelectionItem { + name: format!("{current_branch} -> {branch}"), + description: None, + is_current: false, + actions: vec![Box::new(move |tx3: &AppEventSender| { + tx3.send(AppEvent::CodexOp(Op::Review { + review_request: ReviewRequest { + prompt: format!( + "Review the code changes against the base branch '{branch}'. Start by finding the merge diff between the current branch and {branch}'s upstream e.g. (`git merge-base HEAD \"$(git rev-parse --abbrev-ref \"{branch}@{{upstream}}\")\"`), then run `git diff` against that SHA to see what changes we would merge into the {branch} branch. Provide prioritized, actionable findings." + ), + user_facing_hint: format!("changes against '{branch}'"), + }, + })); + })], + dismiss_on_select: true, + search_value: Some(option), + }); + } + + self.bottom_pane.show_selection_view(SelectionViewParams { + title: "Select a base branch".to_string(), + footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + 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 = Vec::with_capacity(commits.len()); + for entry in commits { + let subject = entry.subject.clone(); + let sha = entry.sha.clone(); + let short = sha.chars().take(7).collect::(); + let search_val = format!("{subject} {sha}"); + + items.push(SelectionItem { + name: subject.clone(), + description: None, + is_current: false, + actions: vec![Box::new(move |tx3: &AppEventSender| { + let hint = format!("commit {short}"); + let prompt = format!( + "Review the code changes introduced by commit {sha} (\"{subject}\"). Provide prioritized, actionable findings." + ); + tx3.send(AppEvent::CodexOp(Op::Review { + review_request: ReviewRequest { + prompt, + user_facing_hint: hint, + }, + })); + })], + dismiss_on_select: true, + search_value: Some(search_val), + }); + } + + self.bottom_pane.show_selection_view(SelectionViewParams { + title: "Select a commit to review".to_string(), + footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + 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 { + prompt: trimmed.clone(), + user_facing_hint: trimmed, + }, + })); + }), + ); + self.bottom_pane.show_view(Box::new(view)); + } + /// Programmatically submit a user text message as if typed in the /// composer. The text will be added to conversation history and sent to /// the agent. @@ -1731,5 +1911,48 @@ fn extract_first_bold(s: &str) -> Option { None } +#[cfg(test)] +pub(crate) fn show_review_commit_picker_with_entries( + chat: &mut ChatWidget, + entries: Vec, +) { + let mut items: Vec = Vec::with_capacity(entries.len()); + for entry in entries { + let subject = entry.subject.clone(); + let sha = entry.sha.clone(); + let short = sha.chars().take(7).collect::(); + let search_val = format!("{subject} {sha}"); + + items.push(SelectionItem { + name: subject.clone(), + description: None, + is_current: false, + actions: vec![Box::new(move |tx3: &AppEventSender| { + let hint = format!("commit {short}"); + let prompt = format!( + "Review the code changes introduced by commit {sha} (\"{subject}\"). Provide prioritized, actionable findings." + ); + tx3.send(AppEvent::CodexOp(Op::Review { + review_request: ReviewRequest { + prompt, + user_facing_hint: hint, + }, + })); + })], + dismiss_on_select: true, + search_value: Some(search_val), + }); + } + + chat.bottom_pane.show_selection_view(SelectionViewParams { + title: "Select a commit to review".to_string(), + footer_hint: Some(STANDARD_POPUP_HINT_LINE.to_string()), + 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/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap index 0b6ec3b392..caabd816bb 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__binary_size_ideal_response.snap @@ -1,6 +1,5 @@ --- source: tui/src/chatwidget/tests.rs -assertion_line: 648 expression: visible_after --- > I’m going to scan the workspace and Cargo manifests to see build profiles and @@ -10,6 +9,14 @@ expression: visible_after └ 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 @@ -19,6 +26,79 @@ expression: visible_after • 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. + > Here’s what’s driving size in this workspace’s binaries. Main Causes diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_placeholder.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_placeholder.snap deleted file mode 100644 index fa37b2201f..0000000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_placeholder.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: tui/src/chatwidget/tests.rs -expression: visual ---- -[magenta]/limits[/] - -[bold]Rate limit usage snapshot[/] -[dim] Tip: run `/limits` right after Codex replies for freshest numbers.[/] - Real usage data is not available yet. -[dim] Send a message to Codex, then run /limits again.[/] diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_basic.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_basic.snap deleted file mode 100644 index ced4466837..0000000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_basic.snap +++ /dev/null @@ -1,29 +0,0 @@ ---- -source: tui/src/chatwidget/tests.rs -expression: visual ---- -[magenta]/limits[/] - -[bold]Rate limit usage snapshot[/] -[dim] Tip: run `/limits` right after Codex replies for freshest numbers.[/] - • Hourly limit[dim] (≈5 hours window)[/]: [dark-gray+bold]30.0% used[/] - • Weekly limit[dim] (≈1 week window)[/]: [dark-gray+bold]60.0% used[/] -[green] Within current limits[/] - -[dim] ╭─────────────────────────────────────────────────╮[/] - [dim]│[/][dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/][dim]│[/] - [dim]│[/][dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/][dim]│[/] - [dim]│[/][dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/][dim]│[/] - [dim]│[/][dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/][dim]│[/] - [dim]│[/][dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/][dim]│[/] - [dim]│[/][dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/][dim]│[/] - [dim]│[/][green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/][dim]│[/] - [dim]│[/][green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/][dim]│[/] - [dim]│[/][green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] -[dim] ╰─────────────────────────────────────────────────╯[/] - -[bold]Legend[/] - • [dark-gray+bold]Dark gray[/] = weekly usage so far - • [green+bold]Green[/] = hourly capacity still available - • [bold]Default[/] = weekly capacity beyond the hourly window diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_hourly_remaining.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_hourly_remaining.snap deleted file mode 100644 index defc5f213c..0000000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_hourly_remaining.snap +++ /dev/null @@ -1,29 +0,0 @@ ---- -source: tui/src/chatwidget/tests.rs -expression: visual ---- -[magenta]/limits[/] - -[bold]Rate limit usage snapshot[/] -[dim] Tip: run `/limits` right after Codex replies for freshest numbers.[/] - • Hourly limit[dim] (≈5 hours window)[/]: [dark-gray+bold]0.0% used[/] - • Weekly limit[dim] (≈1 week window)[/]: [dark-gray+bold]20.0% used[/] -[green] Within current limits[/] - -[dim] ╭─────────────────────────────────────────────────╮[/] - [dim]│[/][dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/][dim]│[/] - [dim]│[/][dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/][dim]│[/] - [dim]│[/][green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/][dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] -[dim] ╰─────────────────────────────────────────────────╯[/] - -[bold]Legend[/] - • [dark-gray+bold]Dark gray[/] = weekly usage so far - • [green+bold]Green[/] = hourly capacity still available - • [bold]Default[/] = weekly capacity beyond the hourly window diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_mixed_usage.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_mixed_usage.snap deleted file mode 100644 index 86c82d9247..0000000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_mixed_usage.snap +++ /dev/null @@ -1,29 +0,0 @@ ---- -source: tui/src/chatwidget/tests.rs -expression: visual ---- -[magenta]/limits[/] - -[bold]Rate limit usage snapshot[/] -[dim] Tip: run `/limits` right after Codex replies for freshest numbers.[/] - • Hourly limit[dim] (≈5 hours window)[/]: [dark-gray+bold]20.0% used[/] - • Weekly limit[dim] (≈1 week window)[/]: [dark-gray+bold]20.0% used[/] -[green] Within current limits[/] - -[dim] ╭─────────────────────────────────────────────────╮[/] - [dim]│[/][dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/][dim]│[/] - [dim]│[/][dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/] [dark-gray](>_)[/][dim]│[/] - [dim]│[/][green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] [green](>_)[/] (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] -[dim] ╰─────────────────────────────────────────────────╯[/] - -[bold]Legend[/] - • [dark-gray+bold]Dark gray[/] = weekly usage so far - • [green+bold]Green[/] = hourly capacity still available - • [bold]Default[/] = weekly capacity beyond the hourly window diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_weekly_heavy.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_weekly_heavy.snap deleted file mode 100644 index a1650545b6..0000000000 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__limits_snapshot_weekly_heavy.snap +++ /dev/null @@ -1,29 +0,0 @@ ---- -source: tui/src/chatwidget/tests.rs -expression: visual ---- -[magenta]/limits[/] - -[bold]Rate limit usage snapshot[/] -[dim] Tip: run `/limits` right after Codex replies for freshest numbers.[/] - • Hourly limit[dim] (≈5 hours window)[/]: [dark-gray+bold]98.0% used[/] - • Weekly limit[dim] (≈1 week window)[/]: [dark-gray+bold]0.0% used[/] -[green] Within current limits[/] - -[dim] ╭─────────────────────────────────────────────────╮[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] - [dim]│[/](>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_) (>_)[dim]│[/] -[dim] ╰─────────────────────────────────────────────────╯[/] - -[bold]Legend[/] - • [dark-gray+bold]Dark gray[/] = weekly usage so far - • [green+bold]Green[/] = hourly capacity still available - • [bold]Default[/] = weekly capacity beyond the hourly window diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 7427bb4414..b983f6f553 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -25,7 +25,6 @@ use codex_core::protocol::InputMessageKind; use codex_core::protocol::Op; use codex_core::protocol::PatchApplyBeginEvent; use codex_core::protocol::PatchApplyEndEvent; -use codex_core::protocol::RateLimitSnapshotEvent; use codex_core::protocol::ReviewCodeLocation; use codex_core::protocol::ReviewFinding; use codex_core::protocol::ReviewLineRange; @@ -40,8 +39,6 @@ use crossterm::event::KeyEvent; use crossterm::event::KeyModifiers; use insta::assert_snapshot; use pretty_assertions::assert_eq; -use ratatui::style::Color; -use ratatui::style::Modifier; use std::fs::File; use std::io::BufRead; use std::io::BufReader; @@ -320,12 +317,12 @@ fn make_chatwidget_manual() -> ( active_exec_cell: None, config: cfg.clone(), auth_manager, - session_header: SessionHeader::new(cfg.model.clone()), + session_header: SessionHeader::new(cfg.model), initial_user_message: None, token_info: None, rate_limit_snapshot: None, rate_limit_warnings: RateLimitWarningState::default(), - stream: StreamController::new(cfg), + stream_controller: None, running_commands: HashMap::new(), task_complete_pending: false, interrupts: InterruptManager::new(), @@ -380,115 +377,6 @@ fn lines_to_single_string(lines: &[ratatui::text::Line<'static>]) -> String { s } -fn styled_lines_to_string(lines: &[ratatui::text::Line<'static>]) -> String { - let mut out = String::new(); - for line in lines { - for span in &line.spans { - let mut tags: Vec<&str> = Vec::new(); - if let Some(color) = span.style.fg { - let name = match color { - Color::Black => "black", - Color::Blue => "blue", - Color::Cyan => "cyan", - Color::DarkGray => "dark-gray", - Color::Gray => "gray", - Color::Green => "green", - Color::LightBlue => "light-blue", - Color::LightCyan => "light-cyan", - Color::LightGreen => "light-green", - Color::LightMagenta => "light-magenta", - Color::LightRed => "light-red", - Color::LightYellow => "light-yellow", - Color::Magenta => "magenta", - Color::Red => "red", - Color::Rgb(_, _, _) => "rgb", - Color::Indexed(_) => "indexed", - Color::Reset => "reset", - Color::Yellow => "yellow", - Color::White => "white", - }; - tags.push(name); - } - let modifiers = span.style.add_modifier; - if modifiers.contains(Modifier::BOLD) { - tags.push("bold"); - } - if modifiers.contains(Modifier::DIM) { - tags.push("dim"); - } - if modifiers.contains(Modifier::ITALIC) { - tags.push("italic"); - } - if modifiers.contains(Modifier::UNDERLINED) { - tags.push("underlined"); - } - if !tags.is_empty() { - out.push('['); - out.push_str(&tags.join("+")); - out.push(']'); - } - out.push_str(&span.content); - if !tags.is_empty() { - out.push_str("[/]"); - } - } - out.push('\n'); - } - out -} - -fn sample_rate_limit_snapshot( - primary_used_percent: f64, - weekly_used_percent: f64, - ratio_percent: f64, -) -> RateLimitSnapshotEvent { - RateLimitSnapshotEvent { - primary_used_percent, - weekly_used_percent, - primary_to_weekly_ratio_percent: ratio_percent, - primary_window_minutes: 300, - weekly_window_minutes: 10_080, - } -} - -fn capture_limits_snapshot(snapshot: Option) -> String { - let lines = match snapshot { - Some(ref snapshot) => history_cell::new_limits_output(snapshot).display_lines(80), - None => history_cell::new_limits_unavailable().display_lines(80), - }; - styled_lines_to_string(&lines) -} - -#[test] -fn limits_placeholder() { - let visual = capture_limits_snapshot(None); - assert_snapshot!(visual); -} - -#[test] -fn limits_snapshot_basic() { - let visual = capture_limits_snapshot(Some(sample_rate_limit_snapshot(30.0, 60.0, 40.0))); - assert_snapshot!(visual); -} - -#[test] -fn limits_snapshot_hourly_remaining() { - let visual = capture_limits_snapshot(Some(sample_rate_limit_snapshot(0.0, 20.0, 10.0))); - assert_snapshot!(visual); -} - -#[test] -fn limits_snapshot_mixed_usage() { - let visual = capture_limits_snapshot(Some(sample_rate_limit_snapshot(20.0, 20.0, 10.0))); - assert_snapshot!(visual); -} - -#[test] -fn limits_snapshot_weekly_heavy() { - let visual = capture_limits_snapshot(Some(sample_rate_limit_snapshot(98.0, 0.0, 10.0))); - assert_snapshot!(visual); -} - #[test] fn rate_limit_warnings_emit_thresholds() { let mut state = RateLimitWarningState::default(); @@ -509,26 +397,26 @@ fn rate_limit_warnings_emit_thresholds() { assert!( warnings .iter() - .any(|w| w.contains("Hourly usage exceeded 50%")), - "expected hourly 50% warning" + .any(|w| w.contains("Heads up, you've used over 50% of your 5h limit.")), + "expected hourly 50% warning (new copy)" ); assert!( warnings .iter() - .any(|w| w.contains("Weekly usage exceeded 50%")), - "expected weekly 50% warning" + .any(|w| w.contains("Heads up, you've used over 50% of your weekly limit.")), + "expected weekly 50% warning (new copy)" ); assert!( warnings .iter() - .any(|w| w.contains("Hourly usage exceeded 90%")), - "expected hourly 90% warning" + .any(|w| w.contains("Heads up, you've used over 90% of your 5h limit.")), + "expected hourly 90% warning (new copy)" ); assert!( warnings .iter() - .any(|w| w.contains("Weekly usage exceeded 90%")), - "expected weekly 90% warning" + .any(|w| w.contains("Heads up, you've used over 90% of your weekly limit.")), + "expected weekly 90% warning (new copy)" ); } @@ -801,6 +689,135 @@ fn exec_history_cell_shows_working_then_failed() { assert!(blob.to_lowercase().contains("bloop"), "expected error text"); } +/// 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(); + + // 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"); +} + +/// 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(); + + // 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_ref(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(); + + 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.prompt, + "please audit dependencies".to_string() + ); + assert_eq!( + review_request.user_facing_hint, + "please audit dependencies".to_string() + ); + } + 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(); + + 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"); +} + // Snapshot test: interrupting a running exec finalizes the active cell with a red ✗ // marker (replacing the spinner) and flushes it into history. #[test] @@ -830,6 +847,96 @@ fn interrupt_exec_marks_failed_snapshot() { assert_snapshot!("interrupt_exec_marks_failed", exec_blob); } +/// 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(); + + // 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(flavor = "current_thread")] +async fn review_branch_picker_escape_navigates_back_then_dismisses() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(); + + // 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_ref(area, &mut buf); + let mut row = String::new(); + // Row 0 is the top spacer for the bottom pane; row 1 contains the header line + let y = 1u16.min(height.saturating_sub(1)); + for x in 0..area.width { + let s = buf[(x, y)].symbol(); + if s.is_empty() { + row.push(' '); + } else { + row.push_str(s); + } + } + row +} + #[test] fn exec_history_extends_previous_when_consecutive() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(); @@ -937,7 +1044,10 @@ async fn binary_size_transcript_snapshot() { call_id: e.call_id.clone(), command: e.command, cwd: e.cwd, - parsed_cmd: parsed_cmd.into_iter().map(|c| c.into()).collect(), + parsed_cmd: parsed_cmd + .into_iter() + .map(std::convert::Into::into) + .collect(), }), } } @@ -1014,7 +1124,7 @@ async fn binary_size_transcript_snapshot() { // Trim trailing spaces to match plain text fixture lines.push(s.trim_end().to_string()); } - while lines.last().is_some_and(|l| l.is_empty()) { + while lines.last().is_some_and(std::string::String::is_empty) { lines.pop(); } // Consider content only after the last session banner marker. Skip the transient @@ -1900,8 +2010,12 @@ fn deltas_then_same_final_message_are_rendered_snapshot() { // 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() { - // Setup identical scenario let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); + 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() }), + }); + chat.handle_codex_event(Event { id: "c1".into(), msg: EventMsg::ExecCommandBegin(ExecCommandBeginEvent { @@ -1949,10 +2063,6 @@ fn chatwidget_exec_and_status_layout_vt100_snapshot() { }); chat.bottom_pane .set_composer_text("Summarize recent commits".to_string()); - 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() }), - }); // Dimensions let width: u16 = 80; diff --git a/codex-rs/tui/src/clipboard_paste.rs b/codex-rs/tui/src/clipboard_paste.rs index 8472e804cc..2a669f5c4f 100644 --- a/codex-rs/tui/src/clipboard_paste.rs +++ b/codex-rs/tui/src/clipboard_paste.rs @@ -241,7 +241,7 @@ pub fn pasted_image_format(path: &Path) -> EncodedImageFormat { match path .extension() .and_then(|e| e.to_str()) - .map(|s| s.to_ascii_lowercase()) + .map(str::to_ascii_lowercase) .as_deref() { Some("png") => EncodedImageFormat::Png, diff --git a/codex-rs/tui/src/diff_render.rs b/codex-rs/tui/src/diff_render.rs index 2787f76607..1e0c222bbd 100644 --- a/codex-rs/tui/src/diff_render.rs +++ b/codex-rs/tui/src/diff_render.rs @@ -1,3 +1,4 @@ +use diffy::Hunk; use ratatui::style::Color; use ratatui::style::Modifier; use ratatui::style::Style; @@ -283,7 +284,7 @@ fn calculate_add_remove_from_diff(diff: &str) -> (usize, usize) { patch .hunks() .iter() - .flat_map(|h| h.lines()) + .flat_map(Hunk::lines) .fold((0, 0), |(a, d), l| match l { diffy::Line::Insert(_) => (a + 1, d), diffy::Line::Delete(_) => (a, d + 1), diff --git a/codex-rs/tui/src/exec_command.rs b/codex-rs/tui/src/exec_command.rs index 93c937e0d1..5c9a0d039a 100644 --- a/codex-rs/tui/src/exec_command.rs +++ b/codex-rs/tui/src/exec_command.rs @@ -5,7 +5,7 @@ use dirs::home_dir; use shlex::try_join; pub(crate) fn escape_command(command: &[String]) -> String { - try_join(command.iter().map(|s| s.as_str())).unwrap_or_else(|_| command.join(" ")) + try_join(command.iter().map(String::as_str)).unwrap_or_else(|_| command.join(" ")) } pub(crate) fn strip_bash_lc_and_escape(command: &[String]) -> String { diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 24e6b2844f..9eccf29ab0 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -2,9 +2,6 @@ use crate::diff_render::create_diff_summary; use crate::exec_command::relativize_to_home; use crate::exec_command::strip_bash_lc_and_escape; use crate::markdown::append_markdown; -use crate::rate_limits_view::DEFAULT_GRID_CONFIG; -use crate::rate_limits_view::LimitsView; -use crate::rate_limits_view::build_limits_view; use crate::render::line_utils::line_to_static; use crate::render::line_utils::prefix_lines; use crate::render::line_utils::push_owned_lines; @@ -58,6 +55,10 @@ use std::time::Instant; use tracing::error; use unicode_width::UnicodeWidthStr; +const STATUS_LIMIT_BAR_SEGMENTS: usize = 20; +const STATUS_LIMIT_BAR_FILLED: &str = "█"; +const STATUS_LIMIT_BAR_EMPTY: &str = " "; + #[derive(Clone, Debug)] pub(crate) struct CommandOutput { pub(crate) exit_code: i32, @@ -225,20 +226,6 @@ impl HistoryCell for PlainHistoryCell { } } -#[derive(Debug)] -pub(crate) struct LimitsHistoryCell { - display: LimitsView, -} - -impl HistoryCell for LimitsHistoryCell { - fn display_lines(&self, width: u16) -> Vec> { - let mut lines = self.display.summary_lines.clone(); - lines.extend(self.display.gauge_lines(width)); - lines.extend(self.display.legend_lines.clone()); - lines - } -} - #[derive(Debug)] pub(crate) struct TranscriptOnlyHistoryCell { lines: Vec>, @@ -390,19 +377,18 @@ impl ExecCell { .iter() .all(|c| matches!(c, ParsedCommand::Read { .. })) { - let names: Vec = call + let names = call .parsed .iter() .map(|c| match c { ParsedCommand::Read { name, .. } => name.clone(), _ => unreachable!(), }) - .unique() - .collect(); + .unique(); vec![( "Read", itertools::Itertools::intersperse( - names.into_iter().map(|n| n.into()), + names.into_iter().map(Into::into), ", ".dim(), ) .collect(), @@ -1093,26 +1079,6 @@ pub(crate) fn new_completed_mcp_tool_call( Box::new(PlainHistoryCell { lines }) } -pub(crate) fn new_limits_output(snapshot: &RateLimitSnapshotEvent) -> LimitsHistoryCell { - LimitsHistoryCell { - display: build_limits_view(snapshot, DEFAULT_GRID_CONFIG), - } -} - -pub(crate) fn new_limits_unavailable() -> PlainHistoryCell { - PlainHistoryCell { - lines: vec![ - "/limits".magenta().into(), - "".into(), - vec!["Rate limit usage snapshot".bold()].into(), - vec![" Tip: run `/limits` right after Codex replies for freshest numbers.".dim()] - .into(), - vec![" Real usage data is not available yet.".into()].into(), - vec![" Send a message to Codex, then run /limits again.".dim()].into(), - ], - } -} - #[allow(clippy::disallowed_methods)] pub(crate) fn new_warning_event(message: String) -> PlainHistoryCell { PlainHistoryCell { @@ -1124,6 +1090,7 @@ pub(crate) fn new_status_output( config: &Config, usage: &TokenUsage, session_id: &Option, + rate_limits: Option<&RateLimitSnapshotEvent>, ) -> PlainHistoryCell { let mut lines: Vec> = Vec::new(); lines.push("/status".magenta().into()); @@ -1284,6 +1251,9 @@ pub(crate) fn new_status_output( format_with_separators(usage.blended_total()).into(), ])); + lines.push("".into()); + lines.extend(build_status_limit_lines(rate_limits)); + PlainHistoryCell { lines } } @@ -1641,6 +1611,62 @@ fn format_mcp_invocation<'a>(invocation: McpInvocation) -> Line<'a> { invocation_spans.into() } +fn build_status_limit_lines(snapshot: Option<&RateLimitSnapshotEvent>) -> Vec> { + let mut lines: Vec> = + vec![vec![padded_emoji("⏱️").into(), "Usage Limits".bold()].into()]; + + match snapshot { + Some(snapshot) => { + let rows = [ + ("5h limit".to_string(), snapshot.primary_used_percent), + ("Weekly limit".to_string(), snapshot.secondary_used_percent), + ]; + let label_width = rows + .iter() + .map(|(label, _)| UnicodeWidthStr::width(label.as_str())) + .max() + .unwrap_or(0); + for (label, percent) in rows { + lines.push(build_status_limit_line(&label, percent, label_width)); + } + } + None => lines.push(" • Rate limit data not available yet.".dim().into()), + } + + lines +} + +fn build_status_limit_line(label: &str, percent_used: f64, label_width: usize) -> Line<'static> { + let clamped_percent = percent_used.clamp(0.0, 100.0); + let progress = render_status_limit_progress_bar(clamped_percent); + let summary = format_status_limit_summary(clamped_percent); + + let mut spans: Vec> = Vec::with_capacity(5); + let padded_label = format!("{label: String { + let ratio = (percent_used / 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) + ) +} + +fn format_status_limit_summary(percent_used: f64) -> String { + format!("{percent_used:.0}% used") +} + #[cfg(test)] mod tests { use super::*; diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 92b42732c3..83aa2e2368 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -55,7 +55,6 @@ mod markdown_stream; mod new_model_popup; pub mod onboarding; mod pager_overlay; -mod rate_limits_view; mod render; mod resume_picker; mod session_log; @@ -552,18 +551,24 @@ mod tests { use codex_core::auth::write_auth_json; use codex_core::token_data::IdTokenInfo; use codex_core::token_data::TokenData; - fn make_config() -> Config { - // Create a unique CODEX_HOME per test to isolate auth.json writes. + use std::sync::atomic::AtomicUsize; + use std::sync::atomic::Ordering; + + fn get_next_codex_home() -> PathBuf { + static NEXT_CODEX_HOME_ID: AtomicUsize = AtomicUsize::new(0); let mut codex_home = std::env::temp_dir(); let unique_suffix = format!( "codex_tui_test_{}_{}", std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() + NEXT_CODEX_HOME_ID.fetch_add(1, Ordering::Relaxed) ); codex_home.push(unique_suffix); + codex_home + } + + fn make_config() -> Config { + // Create a unique CODEX_HOME per test to isolate auth.json writes. + let codex_home = get_next_codex_home(); std::fs::create_dir_all(&codex_home).expect("create unique CODEX_HOME"); Config::load_from_base_config_with_overrides( diff --git a/codex-rs/tui/src/main.rs b/codex-rs/tui/src/main.rs index a9b426fe45..50ea95f170 100644 --- a/codex-rs/tui/src/main.rs +++ b/codex-rs/tui/src/main.rs @@ -3,8 +3,6 @@ use codex_arg0::arg0_dispatch_or_else; use codex_common::CliConfigOverrides; use codex_tui::Cli; use codex_tui::run_main; -use owo_colors::OwoColorize; -use supports_color::Stream; #[derive(Parser, Debug)] struct TopCli { @@ -25,19 +23,8 @@ fn main() -> anyhow::Result<()> { .splice(0..0, top_cli.config_overrides.raw_overrides); let exit_info = run_main(inner, codex_linux_sandbox_exe).await?; let token_usage = exit_info.token_usage; - let conversation_id = exit_info.conversation_id; if !token_usage.is_zero() { println!("{}", codex_core::protocol::FinalOutput::from(token_usage),); - if let Some(session_id) = conversation_id { - let command = format!("codex resume {session_id}"); - let prefix = "To continue this session, run "; - let suffix = "."; - if supports_color::on(Stream::Stdout).is_some() { - println!("{}{}{}", prefix, command.cyan(), suffix); - } else { - println!("{prefix}{command}{suffix}"); - } - } } Ok(()) }) diff --git a/codex-rs/tui/src/markdown_render.rs b/codex-rs/tui/src/markdown_render.rs index f20bfd75c0..cac40cffde 100644 --- a/codex-rs/tui/src/markdown_render.rs +++ b/codex-rs/tui/src/markdown_render.rs @@ -50,11 +50,7 @@ pub(crate) fn render_markdown_text_with_citations( let mut options = Options::empty(); options.insert(Options::ENABLE_STRIKETHROUGH); let parser = Parser::new_ext(input, options); - let mut w = Writer::new( - parser, - scheme.map(|s| s.to_string()), - Some(cwd.to_path_buf()), - ); + let mut w = Writer::new(parser, scheme.map(str::to_string), Some(cwd.to_path_buf())); w.run(); w.text } @@ -329,7 +325,7 @@ where let is_ordered = self .list_indices .last() - .map(|index| index.is_some()) + .map(Option::is_some) .unwrap_or(false); let width = depth * 4 - 3; let marker = if let Some(last_index) = self.list_indices.last_mut() { diff --git a/codex-rs/tui/src/markdown_stream.rs b/codex-rs/tui/src/markdown_stream.rs index 12b4308210..51331887e9 100644 --- a/codex-rs/tui/src/markdown_stream.rs +++ b/codex-rs/tui/src/markdown_stream.rs @@ -20,25 +20,11 @@ impl MarkdownStreamCollector { } } - /// Returns the number of logical lines that have already been committed - /// (i.e., previously returned from `commit_complete_lines`). - pub fn committed_count(&self) -> usize { - self.committed_line_count - } - pub fn clear(&mut self) { self.buffer.clear(); self.committed_line_count = 0; } - /// Replace the buffered content and mark that the first `committed_count` - /// logical lines are already committed. - pub fn replace_with_and_mark_committed(&mut self, s: &str, committed_count: usize) { - self.buffer.clear(); - self.buffer.push_str(s); - self.committed_line_count = committed_count; - } - pub fn push_delta(&mut self, delta: &str) { tracing::trace!("push_delta: {delta:?}"); self.buffer.push_str(delta); @@ -310,10 +296,8 @@ mod tests { 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, &cfg); // Wrap to a narrow width to force multiple output lines. - let wrapped = crate::wrapping::word_wrap_lines( - out.iter().collect::>(), - crate::wrapping::RtOptions::new(24), - ); + 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() diff --git a/codex-rs/tui/src/new_model_popup.rs b/codex-rs/tui/src/new_model_popup.rs index 2106e46c67..e2389aad59 100644 --- a/codex-rs/tui/src/new_model_popup.rs +++ b/codex-rs/tui/src/new_model_popup.rs @@ -98,7 +98,7 @@ impl WidgetRef for &ModelUpgradePopup { let mut lines: Vec = Vec::new(); if show_animation { let frame = self.animation.current_frame(); - lines.extend(frame.lines().map(|l| l.into())); + lines.extend(frame.lines().map(Into::into)); // Spacer between animation and text content. lines.push("".into()); } diff --git a/codex-rs/tui/src/onboarding/welcome.rs b/codex-rs/tui/src/onboarding/welcome.rs index c62b6402d8..645c86ba43 100644 --- a/codex-rs/tui/src/onboarding/welcome.rs +++ b/codex-rs/tui/src/onboarding/welcome.rs @@ -62,7 +62,7 @@ impl WidgetRef for &WelcomeWidget { let frame = self.animation.current_frame(); // let frame_line_count = frame.lines().count(); // lines.reserve(frame_line_count + 2); - lines.extend(frame.lines().map(|l| l.into())); + lines.extend(frame.lines().map(Into::into)); lines.push("".into()); } lines.push(Line::from(vec![ diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index e5524b252b..b92939a1a5 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -18,7 +18,9 @@ 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; pub(crate) enum Overlay { @@ -98,6 +100,7 @@ impl PagerView { } fn render(&mut self, area: Rect, buf: &mut Buffer) { + Clear.render(area, buf); self.render_header(area, buf); let content_area = self.scroll_area(area); self.update_last_content_height(content_area.height); @@ -139,6 +142,7 @@ impl PagerView { // Removed unused render_content_page (replaced by render_content_page_prepared) fn render_content_page_prepared(&self, area: Rect, buf: &mut Buffer, page: &[Line<'static>]) { + Clear.render(area, buf); Paragraph::new(page.to_vec()).render_ref(area, buf); let visible = page.len(); @@ -382,7 +386,7 @@ impl TranscriptOverlay { let cell_lines = if Some(idx) == highlight_cell { cell.transcript_lines() .into_iter() - .map(|l| l.reversed()) + .map(Stylize::reversed) .collect() } else { cell.transcript_lines() @@ -547,6 +551,17 @@ impl StaticOverlay { mod tests { use super::*; use insta::assert_snapshot; + use std::collections::HashMap; + use std::path::PathBuf; + use std::sync::Arc; + use std::time::Duration; + + use crate::history_cell::CommandOutput; + use crate::history_cell::HistoryCell; + use crate::history_cell::PatchEventType; + 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; @@ -610,6 +625,99 @@ mod tests { 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> = 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 = Arc::new(new_patch_event( + PatchEventType::ApprovalRequest, + 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 = Arc::new(new_patch_event( + PatchEventType::ApplyBegin { + auto_approved: false, + }, + apply_changes, + &cwd, + )); + cells.push(apply_begin_cell); + + let apply_end_cell: Arc = + Arc::new(crate::history_cell::new_user_approval_decision(vec![ + "✓ Patch applied".green().bold().into(), + "src/foo.txt".dim().into(), + ])); + cells.push(apply_end_cell); + + let mut exec_cell = crate::history_cell::new_active_exec_command( + "exec-1".into(), + vec!["bash".into(), "-lc".into(), "ls".into()], + vec![ParsedCommand::Unknown { cmd: "ls".into() }], + ); + exec_cell.complete_call( + "exec-1", + CommandOutput { + exit_code: 0, + stdout: "src\nREADME.md\n".into(), + stderr: String::new(), + formatted_output: "src\nREADME.md\n".into(), + }, + Duration::from_millis(420), + ); + let exec_cell: Arc = 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.view.wrap_cache = None; + 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( diff --git a/codex-rs/tui/src/rate_limits_view.rs b/codex-rs/tui/src/rate_limits_view.rs deleted file mode 100644 index 72fc6e9763..0000000000 --- a/codex-rs/tui/src/rate_limits_view.rs +++ /dev/null @@ -1,504 +0,0 @@ -use codex_core::protocol::RateLimitSnapshotEvent; -use ratatui::prelude::*; -use ratatui::style::Stylize; - -/// Aggregated output used by the `/limits` command. -/// It contains the rendered summary lines, optional legend, -/// and the precomputed gauge state when one can be shown. -#[derive(Debug)] -pub(crate) struct LimitsView { - pub(crate) summary_lines: Vec>, - pub(crate) legend_lines: Vec>, - grid_state: Option, - grid: GridConfig, -} - -impl LimitsView { - /// Render the gauge for the provided width if the data supports it. - pub(crate) fn gauge_lines(&self, width: u16) -> Vec> { - match self.grid_state { - Some(state) => render_limit_grid(state, self.grid, width), - None => Vec::new(), - } - } -} - -/// Configuration for the simple grid gauge rendered by `/limits`. -#[derive(Clone, Copy, Debug)] -pub(crate) struct GridConfig { - pub(crate) weekly_slots: usize, - pub(crate) logo: &'static str, -} - -/// Default gauge configuration used by the TUI. -pub(crate) const DEFAULT_GRID_CONFIG: GridConfig = GridConfig { - weekly_slots: 100, - logo: "(>_)", -}; - -/// Build the lines and optional gauge used by the `/limits` view. -pub(crate) fn build_limits_view( - snapshot: &RateLimitSnapshotEvent, - grid_config: GridConfig, -) -> LimitsView { - let metrics = RateLimitMetrics::from_snapshot(snapshot); - let grid_state = extract_capacity_fraction(snapshot) - .and_then(|fraction| compute_grid_state(&metrics, fraction)) - .map(|state| scale_grid_state(state, grid_config)); - - LimitsView { - summary_lines: build_summary_lines(&metrics), - legend_lines: build_legend_lines(grid_state.is_some()), - grid_state, - grid: grid_config, - } -} - -#[derive(Debug)] -struct RateLimitMetrics { - hourly_used: f64, - weekly_used: f64, - hourly_remaining: f64, - weekly_remaining: f64, - hourly_window_label: String, - weekly_window_label: String, - hourly_reset_hint: String, - weekly_reset_hint: String, -} - -impl RateLimitMetrics { - fn from_snapshot(snapshot: &RateLimitSnapshotEvent) -> Self { - let hourly_used = snapshot.primary_used_percent.clamp(0.0, 100.0); - let weekly_used = snapshot.weekly_used_percent.clamp(0.0, 100.0); - Self { - hourly_used, - weekly_used, - hourly_remaining: (100.0 - hourly_used).max(0.0), - weekly_remaining: (100.0 - weekly_used).max(0.0), - hourly_window_label: format_window_label(Some(snapshot.primary_window_minutes)), - weekly_window_label: format_window_label(Some(snapshot.weekly_window_minutes)), - hourly_reset_hint: format_reset_hint(Some(snapshot.primary_window_minutes)), - weekly_reset_hint: format_reset_hint(Some(snapshot.weekly_window_minutes)), - } - } - - fn hourly_exhausted(&self) -> bool { - self.hourly_remaining <= 0.0 - } - - fn weekly_exhausted(&self) -> bool { - self.weekly_remaining <= 0.0 - } -} - -fn format_window_label(minutes: Option) -> String { - approximate_duration(minutes) - .map(|(value, unit)| format!("≈{value} {} window", pluralize_unit(unit, value))) - .unwrap_or_else(|| "window unknown".to_string()) -} - -fn format_reset_hint(minutes: Option) -> String { - approximate_duration(minutes) - .map(|(value, unit)| format!("≈{value} {}", pluralize_unit(unit, value))) - .unwrap_or_else(|| "unknown".to_string()) -} - -fn approximate_duration(minutes: Option) -> Option<(u64, DurationUnit)> { - let minutes = minutes?; - if minutes == 0 { - return Some((1, DurationUnit::Minute)); - } - if minutes < 60 { - return Some((minutes, DurationUnit::Minute)); - } - if minutes < 1_440 { - let hours = ((minutes as f64) / 60.0).round().max(1.0) as u64; - return Some((hours, DurationUnit::Hour)); - } - let days = ((minutes as f64) / 1_440.0).round().max(1.0) as u64; - if days >= 7 { - let weeks = ((days as f64) / 7.0).round().max(1.0) as u64; - Some((weeks, DurationUnit::Week)) - } else { - Some((days, DurationUnit::Day)) - } -} - -fn pluralize_unit(unit: DurationUnit, value: u64) -> String { - match unit { - DurationUnit::Minute => { - if value == 1 { - "minute".to_string() - } else { - "minutes".to_string() - } - } - DurationUnit::Hour => { - if value == 1 { - "hour".to_string() - } else { - "hours".to_string() - } - } - DurationUnit::Day => { - if value == 1 { - "day".to_string() - } else { - "days".to_string() - } - } - DurationUnit::Week => { - if value == 1 { - "week".to_string() - } else { - "weeks".to_string() - } - } - } -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum DurationUnit { - Minute, - Hour, - Day, - Week, -} - -#[derive(Clone, Copy, Debug)] -struct GridState { - weekly_used_ratio: f64, - hourly_remaining_ratio: f64, -} - -fn build_summary_lines(metrics: &RateLimitMetrics) -> Vec> { - let mut lines: Vec> = vec![ - "/limits".magenta().into(), - "".into(), - vec!["Rate limit usage snapshot".bold()].into(), - vec![" Tip: run `/limits` right after Codex replies for freshest numbers.".dim()].into(), - build_usage_line( - " • Hourly limit", - &metrics.hourly_window_label, - metrics.hourly_used, - ), - build_usage_line( - " • Weekly limit", - &metrics.weekly_window_label, - metrics.weekly_used, - ), - ]; - lines.push(build_status_line(metrics)); - lines -} - -fn build_usage_line(label: &str, window_label: &str, used_percent: f64) -> Line<'static> { - Line::from(vec![ - label.to_string().into(), - format!(" ({window_label})").dim(), - ": ".into(), - format!("{used_percent:.1}% used").dark_gray().bold(), - ]) -} - -fn build_status_line(metrics: &RateLimitMetrics) -> Line<'static> { - let mut spans: Vec> = Vec::new(); - if metrics.weekly_exhausted() || metrics.hourly_exhausted() { - spans.push(" Rate limited: ".into()); - let reason = match (metrics.hourly_exhausted(), metrics.weekly_exhausted()) { - (true, true) => "weekly and hourly windows exhausted", - (true, false) => "hourly window exhausted", - (false, true) => "weekly window exhausted", - (false, false) => unreachable!(), - }; - spans.push(reason.red()); - if metrics.hourly_exhausted() { - spans.push(" — hourly resets in ".into()); - spans.push(metrics.hourly_reset_hint.clone().dim()); - } - if metrics.weekly_exhausted() { - spans.push(" — weekly resets in ".into()); - spans.push(metrics.weekly_reset_hint.clone().dim()); - } - } else { - spans.push(" Within current limits".green()); - } - Line::from(spans) -} - -fn build_legend_lines(show_gauge: bool) -> Vec> { - if !show_gauge { - return Vec::new(); - } - vec![ - vec!["Legend".bold()].into(), - vec![ - " • ".into(), - "Dark gray".dark_gray().bold(), - " = weekly usage so far".into(), - ] - .into(), - vec![ - " • ".into(), - "Green".green().bold(), - " = hourly capacity still available".into(), - ] - .into(), - vec![ - " • ".into(), - "Default".bold(), - " = weekly capacity beyond the hourly window".into(), - ] - .into(), - ] -} - -fn extract_capacity_fraction(snapshot: &RateLimitSnapshotEvent) -> Option { - let ratio = snapshot.primary_to_weekly_ratio_percent; - if ratio.is_finite() { - Some((ratio / 100.0).clamp(0.0, 1.0)) - } else { - None - } -} - -fn compute_grid_state(metrics: &RateLimitMetrics, capacity_fraction: f64) -> Option { - if capacity_fraction <= 0.0 { - return None; - } - - let weekly_used_ratio = (metrics.weekly_used / 100.0).clamp(0.0, 1.0); - let weekly_remaining_ratio = (1.0 - weekly_used_ratio).max(0.0); - - let hourly_used_ratio = (metrics.hourly_used / 100.0).clamp(0.0, 1.0); - let hourly_used_within_capacity = - (hourly_used_ratio * capacity_fraction).min(capacity_fraction); - let hourly_remaining_within_capacity = - (capacity_fraction - hourly_used_within_capacity).max(0.0); - - let hourly_remaining_ratio = hourly_remaining_within_capacity.min(weekly_remaining_ratio); - - Some(GridState { - weekly_used_ratio, - hourly_remaining_ratio, - }) -} - -fn scale_grid_state(state: GridState, grid: GridConfig) -> GridState { - if grid.weekly_slots == 0 { - return GridState { - weekly_used_ratio: 0.0, - hourly_remaining_ratio: 0.0, - }; - } - state -} - -/// Convert the grid state to rendered lines for the TUI. -fn render_limit_grid(state: GridState, grid_config: GridConfig, width: u16) -> Vec> { - GridLayout::new(grid_config, width) - .map(|layout| layout.render(state)) - .unwrap_or_default() -} - -/// Precomputed layout information for the usage grid. -struct GridLayout { - size: usize, - inner_width: usize, - config: GridConfig, -} - -impl GridLayout { - const MIN_SIDE: usize = 4; - const MAX_SIDE: usize = 12; - const PREFIX: &'static str = " "; - - fn new(config: GridConfig, width: u16) -> Option { - if config.weekly_slots == 0 || config.logo.is_empty() { - return None; - } - let cell_width = config.logo.chars().count(); - if cell_width == 0 { - return None; - } - - let available_inner = width.saturating_sub((Self::PREFIX.len() + 2) as u16) as usize; - if available_inner == 0 { - return None; - } - - let base_side = (config.weekly_slots as f64) - .sqrt() - .round() - .clamp(1.0, Self::MAX_SIDE as f64) as usize; - let width_limited_side = - ((available_inner + 1) / (cell_width + 1)).clamp(1, Self::MAX_SIDE); - - let mut side = base_side.min(width_limited_side); - if width_limited_side >= Self::MIN_SIDE { - side = side.max(Self::MIN_SIDE.min(width_limited_side)); - } - let side = side.clamp(1, Self::MAX_SIDE); - if side == 0 { - return None; - } - - let inner_width = side * cell_width + side.saturating_sub(1); - Some(Self { - size: side, - inner_width, - config, - }) - } - - /// Render the grid into styled lines for the history cell. - fn render(&self, state: GridState) -> Vec> { - let counts = self.cell_counts(state); - let mut lines = Vec::new(); - lines.push("".into()); - lines.push(self.render_border('╭', '╮')); - - let mut cell_index = 0isize; - for _ in 0..self.size { - let mut spans: Vec> = Vec::new(); - spans.push(Self::PREFIX.into()); - spans.push("│".dim()); - - for col in 0..self.size { - if col > 0 { - spans.push(" ".into()); - } - let span = if cell_index < counts.dark_cells { - self.config.logo.dark_gray() - } else if cell_index < counts.dark_cells + counts.green_cells { - self.config.logo.green() - } else { - self.config.logo.into() - }; - spans.push(span); - cell_index += 1; - } - - spans.push("│".dim()); - lines.push(Line::from(spans)); - } - - lines.push(self.render_border('╰', '╯')); - lines.push("".into()); - - if counts.white_cells == 0 { - lines.push(vec![" (No unused weekly capacity remaining)".dim()].into()); - lines.push("".into()); - } - - lines - } - - fn render_border(&self, left: char, right: char) -> Line<'static> { - let mut text = String::from(Self::PREFIX); - text.push(left); - text.push_str(&"─".repeat(self.inner_width)); - text.push(right); - vec![Span::from(text).dim()].into() - } - - /// Translate usage ratios into the number of coloured cells. - fn cell_counts(&self, state: GridState) -> GridCellCounts { - let total_cells = self.size * self.size; - let mut dark_cells = (state.weekly_used_ratio * total_cells as f64).round() as isize; - dark_cells = dark_cells.clamp(0, total_cells as isize); - let mut green_cells = (state.hourly_remaining_ratio * total_cells as f64).round() as isize; - if dark_cells + green_cells > total_cells as isize { - green_cells = (total_cells as isize - dark_cells).max(0); - } - let white_cells = (total_cells as isize - dark_cells - green_cells).max(0); - - GridCellCounts { - dark_cells, - green_cells, - white_cells, - } - } -} - -/// Number of weekly (dark), hourly (green) and unused (default) cells. -struct GridCellCounts { - dark_cells: isize, - green_cells: isize, - white_cells: isize, -} - -#[cfg(test)] -mod tests { - use super::*; - - fn snapshot() -> RateLimitSnapshotEvent { - RateLimitSnapshotEvent { - primary_used_percent: 30.0, - weekly_used_percent: 60.0, - primary_to_weekly_ratio_percent: 40.0, - primary_window_minutes: 300, - weekly_window_minutes: 10_080, - } - } - - #[test] - fn approximate_duration_handles_hours_and_weeks() { - assert_eq!( - approximate_duration(Some(299)), - Some((5, DurationUnit::Hour)) - ); - assert_eq!( - approximate_duration(Some(10_080)), - Some((1, DurationUnit::Week)) - ); - assert_eq!( - approximate_duration(Some(90)), - Some((2, DurationUnit::Hour)) - ); - } - - #[test] - fn build_display_constructs_summary_and_gauge() { - let display = build_limits_view(&snapshot(), DEFAULT_GRID_CONFIG); - assert!(display.summary_lines.iter().any(|line| { - line.spans - .iter() - .any(|span| span.content.contains("Weekly limit")) - })); - assert!(display.summary_lines.iter().any(|line| { - line.spans - .iter() - .any(|span| span.content.contains("Hourly limit")) - })); - assert!(!display.gauge_lines(80).is_empty()); - } - - #[test] - fn hourly_and_weekly_percentages_are_not_swapped() { - let display = build_limits_view(&snapshot(), DEFAULT_GRID_CONFIG); - let summary = display - .summary_lines - .iter() - .map(|line| { - line.spans - .iter() - .map(|span| span.content.as_ref()) - .collect::() - }) - .collect::>() - .join("\n"); - - assert!(summary.contains("Hourly limit (≈5 hours window): 30.0% used")); - assert!(summary.contains("Weekly limit (≈1 week window): 60.0% used")); - } - - #[test] - fn build_display_without_ratio_skips_gauge() { - let mut s = snapshot(); - s.primary_to_weekly_ratio_percent = f64::NAN; - let display = build_limits_view(&s, DEFAULT_GRID_CONFIG); - assert!(display.gauge_lines(80).is_empty()); - assert!(display.legend_lines.is_empty()); - } -} diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 4d4c806727..f043d62f46 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -21,7 +21,6 @@ pub enum SlashCommand { Diff, Mention, Status, - Limits, Mcp, Logout, Quit, @@ -36,12 +35,11 @@ impl SlashCommand { 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::Review => "review my changes and find issues", SlashCommand::Quit => "exit Codex", SlashCommand::Diff => "show git diff (including untracked files)", SlashCommand::Mention => "mention a file", SlashCommand::Status => "show current session configuration and token usage", - SlashCommand::Limits => "visualize weekly and hourly rate limits", 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", @@ -70,7 +68,6 @@ impl SlashCommand { SlashCommand::Diff | SlashCommand::Mention | SlashCommand::Status - | SlashCommand::Limits | SlashCommand::Mcp | SlashCommand::Quit => true, diff --git a/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap new file mode 100644 index 0000000000..725f210c8d --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__pager_overlay__tests__transcript_overlay_apply_patch_scroll_vt100.snap @@ -0,0 +1,16 @@ +--- +source: tui/src/pager_overlay.rs +assertion_line: 721 +expression: snapshot +--- +/ T R A N S C R I P T / / / / / / / / / / / / / / / / / / / / / / / / / / / / / +• Proposed Change foo.txt (+2 -0) + 1 +hello + 2 +world + +• Change Approved foo.txt (+2 -0) + +✓ Patch applied +─────────────────────────────────────────────────────────────────────────── 0% ─ + ↑/↓ scroll PgUp/PgDn page Home/End jump + q quit Esc edit prev diff --git a/codex-rs/tui/src/streaming/controller.rs b/codex-rs/tui/src/streaming/controller.rs index 490d1f6de9..89b7ab95d3 100644 --- a/codex-rs/tui/src/streaming/controller.rs +++ b/codex-rs/tui/src/streaming/controller.rs @@ -3,7 +3,6 @@ use crate::history_cell::HistoryCell; use codex_core::config::Config; use ratatui::text::Line; -use super::HeaderEmitter; use super::StreamState; /// Sink for history insertions and animation control. @@ -36,56 +35,25 @@ type Lines = Vec>; /// commit animation across streams. pub(crate) struct StreamController { config: Config, - header: HeaderEmitter, state: StreamState, - active: bool, finishing_after_drain: bool, + header_emitted: bool, } impl StreamController { pub(crate) fn new(config: Config) -> Self { Self { config, - header: HeaderEmitter::new(), state: StreamState::new(), - active: false, finishing_after_drain: false, + header_emitted: false, } } - pub(crate) fn reset_headers_for_new_turn(&mut self) { - self.header.reset_for_new_turn(); - } - - pub(crate) fn is_write_cycle_active(&self) -> bool { - self.active - } - - pub(crate) fn clear_all(&mut self) { - self.state.clear(); - self.active = false; - self.finishing_after_drain = false; - // leave header state unchanged; caller decides when to reset - } - - /// Begin an answer stream. Does not emit header yet; it is emitted on first commit. - pub(crate) fn begin(&mut self, _sink: &impl HistorySink) { - // Starting a new stream cancels any pending finish-from-previous-stream animation. - if !self.active { - self.header.reset_for_stream(); - } - self.finishing_after_drain = false; - self.active = true; - } - /// Push a delta; if it contains a newline, commit completed lines and start animation. pub(crate) fn push_and_maybe_commit(&mut self, delta: &str, sink: &impl HistorySink) { - if !self.active { - return; - } let cfg = self.config.clone(); let state = &mut self.state; - // Record that at least one delta was received for this stream if !delta.is_empty() { state.has_seen_delta = true; } @@ -99,117 +67,54 @@ impl StreamController { } } - /// Finalize the active stream. If `flush_immediately` is true, drain and emit now. - pub(crate) fn finalize(&mut self, flush_immediately: bool, sink: &impl HistorySink) -> bool { - if !self.active { - return false; - } + /// Finalize the active stream. Drain and emit now. + pub(crate) fn finalize(&mut self, sink: &impl HistorySink) { let cfg = self.config.clone(); // Finalize collector first. let remaining = { let state = &mut self.state; state.collector.finalize_and_drain(&cfg) }; - if flush_immediately { - // Collect all output first to avoid emitting headers when there is no content. - let mut out_lines: Lines = Vec::new(); - { - let state = &mut self.state; - if !remaining.is_empty() { - state.enqueue(remaining); - } - let step = state.drain_all(); - out_lines.extend(step.history); - } - if !out_lines.is_empty() { - // Insert as a HistoryCell so display drops the header while transcript keeps it. - sink.insert_history_cell(Box::new(history_cell::AgentMessageCell::new( - out_lines, - self.header.maybe_emit_header(), - ))); - } - - // Cleanup - self.state.clear(); - // Allow a subsequent block in this turn to emit its header. - self.header.allow_reemit_in_turn(); - // Also clear the per-stream emitted flag so the header can render again. - self.header.reset_for_stream(); - self.active = false; - self.finishing_after_drain = false; - true - } else { + // Collect all output first to avoid emitting headers when there is no content. + let mut out_lines: Lines = Vec::new(); + { + let state = &mut self.state; if !remaining.is_empty() { - let state = &mut self.state; state.enqueue(remaining); } - // Spacer animated out - self.state.enqueue(vec![Line::from("")]); - self.finishing_after_drain = true; - sink.start_commit_animation(); - false + let step = state.drain_all(); + out_lines.extend(step.history); } + if !out_lines.is_empty() { + // Insert as a HistoryCell so display drops the header while transcript keeps it. + self.emit(sink, out_lines); + } + + // Cleanup + self.state.clear(); + self.finishing_after_drain = false; } /// Step animation: commit at most one queued line and handle end-of-drain cleanup. pub(crate) fn on_commit_tick(&mut self, sink: &impl HistorySink) -> bool { - if !self.active { - return false; - } let step = { self.state.step() }; if !step.history.is_empty() { - sink.insert_history_cell(Box::new(history_cell::AgentMessageCell::new( - step.history, - self.header.maybe_emit_header(), - ))); + self.emit(sink, step.history); } let is_idle = self.state.is_idle(); if is_idle { sink.stop_commit_animation(); - if self.finishing_after_drain { - // Reset and notify - self.state.clear(); - // Allow a subsequent block in this turn to emit its header. - self.header.allow_reemit_in_turn(); - // Also clear the per-stream emitted flag so the header can render again. - self.header.reset_for_stream(); - self.active = false; - self.finishing_after_drain = false; - return true; - } } false } - /// Apply a full final answer: replace queued content with only the remaining tail, - /// then finalize immediately and notify completion. - pub(crate) fn apply_final_answer(&mut self, message: &str, sink: &impl HistorySink) -> bool { - self.apply_full_final(message, sink) - } - - fn apply_full_final(&mut self, message: &str, sink: &impl HistorySink) -> bool { - self.begin(sink); - - { - let state = &mut self.state; - // Only inject the final full message if we have not seen any deltas for this stream. - // If deltas were received, rely on the collector's existing buffer to avoid duplication. - if !state.has_seen_delta && !message.is_empty() { - // normalize to end with newline - let mut msg = message.to_owned(); - if !msg.ends_with('\n') { - msg.push('\n'); - } - - // replace while preserving already committed count - let committed = state.collector.committed_count(); - state - .collector - .replace_with_and_mark_committed(&msg, committed); - } - } - self.finalize(true, sink) + fn emit(&mut self, sink: &impl HistorySink, lines: Vec>) { + sink.insert_history_cell(Box::new(history_cell::AgentMessageCell::new( + lines, + !self.header_emitted, + ))); + self.header_emitted = true; } } @@ -268,7 +173,6 @@ mod tests { let cfg = test_config(); let mut ctrl = StreamController::new(cfg.clone()); let sink = TestSink::new(); - ctrl.begin(&sink); // Exact deltas from the session log (section: Loose vs. tight list items) let deltas = vec![ @@ -347,7 +251,7 @@ mod tests { let _ = ctrl.on_commit_tick(&sink); } // Finalize and flush remaining lines now. - let _ = ctrl.finalize(true, &sink); + ctrl.finalize(&sink); // Flatten sink output and strip the header that the controller inserts (blank + "codex"). let mut flat: Vec> = Vec::new(); diff --git a/codex-rs/tui/src/streaming/mod.rs b/codex-rs/tui/src/streaming/mod.rs index 3fc81360ba..dbb260bc68 100644 --- a/codex-rs/tui/src/streaming/mod.rs +++ b/codex-rs/tui/src/streaming/mod.rs @@ -34,41 +34,3 @@ impl StreamState { self.streamer.enqueue(lines) } } - -pub(crate) struct HeaderEmitter { - emitted_this_turn: bool, - emitted_in_stream: bool, -} - -impl HeaderEmitter { - pub(crate) fn new() -> Self { - Self { - emitted_this_turn: false, - emitted_in_stream: false, - } - } - - pub(crate) fn reset_for_new_turn(&mut self) { - self.emitted_this_turn = false; - self.emitted_in_stream = false; - } - - pub(crate) fn reset_for_stream(&mut self) { - self.emitted_in_stream = false; - } - - /// Allow emitting the header again within the current turn after a finalize. - pub(crate) fn allow_reemit_in_turn(&mut self) { - self.emitted_this_turn = false; - } - - pub(crate) fn maybe_emit_header(&mut self) -> bool { - if !self.emitted_in_stream && !self.emitted_this_turn { - self.emitted_in_stream = true; - self.emitted_this_turn = true; - true - } else { - false - } - } -} diff --git a/codex-rs/tui/src/wrapping.rs b/codex-rs/tui/src/wrapping.rs index c97f0e3c6c..bd3c451bf9 100644 --- a/codex-rs/tui/src/wrapping.rs +++ b/codex-rs/tui/src/wrapping.rs @@ -329,6 +329,7 @@ mod tests { 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 @@ -511,7 +512,7 @@ mod tests { .subsequent_indent(Line::from(" ")); let lines = [Line::from("hello world"), Line::from("foo bar baz")]; - let out = word_wrap_lines_borrowed(lines.iter().collect::>(), opts); + let out = word_wrap_lines_borrowed(lines.iter(), opts); let rendered: Vec = out.iter().map(concat_line).collect(); assert!(rendered.first().unwrap().starts_with("- ")); @@ -523,7 +524,7 @@ mod tests { #[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().collect::>(), 10); + let out = word_wrap_lines_borrowed(lines.iter(), 10); let rendered: Vec = out.iter().map(concat_line).collect(); assert_eq!(rendered, vec!["hello", "world!"]); } @@ -543,7 +544,7 @@ mod tests { 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(|l| l.to_string()).join("\n"); + let joined: String = wrapped.iter().map(ToString::to_string).join("\n"); assert_eq!( joined, r#"Years passed, and Willowmere thrived diff --git a/codex-rs/tui/tests/fixtures/binary-size-log.jsonl b/codex-rs/tui/tests/fixtures/binary-size-log.jsonl index 2b243d18ec..392cf55250 100644 --- a/codex-rs/tui/tests/fixtures/binary-size-log.jsonl +++ b/codex-rs/tui/tests/fixtures/binary-size-log.jsonl @@ -1,4 +1,4 @@ -{"ts":"2025-08-09T15:51:04.827Z","dir":"meta","kind":"session_start","cwd":"/Users/easong/code/codex/codex-rs","model":"gpt-5","reasoning_effort":"medium","model_provider_id":"openai","model_provider_name":"OpenAI"} +{"ts":"2025-08-09T15:51:04.827Z","dir":"meta","kind":"session_start","cwd":"/Users/easong/code/codex/codex-rs","model":"gpt-5-codex","reasoning_effort":"medium","model_provider_id":"openai","model_provider_name":"OpenAI"} {"ts":"2025-08-09T15:51:04.827Z","dir":"to_tui","kind":"key_event","event":"KeyEvent { code: Char('c'), modifiers: KeyModifiers(0x0), kind: Press, state: KeyEventState(0x0) }"} {"ts":"2025-08-09T15:51:04.827Z","dir":"to_tui","kind":"key_event","event":"KeyEvent { code: Char('o'), modifiers: KeyModifiers(0x0), kind: Press, state: KeyEventState(0x0) }"} {"ts":"2025-08-09T15:51:04.827Z","dir":"to_tui","kind":"key_event","event":"KeyEvent { code: Char('m'), modifiers: KeyModifiers(0x0), kind: Press, state: KeyEventState(0x0) }"} @@ -34,7 +34,7 @@ {"ts":"2025-08-09T15:51:04.829Z","dir":"to_tui","kind":"app_event","variant":"RequestRedraw"} {"ts":"2025-08-09T15:51:04.829Z","dir":"to_tui","kind":"log_line","line":"[INFO codex_core::codex] resume_path: None"} {"ts":"2025-08-09T15:51:04.830Z","dir":"to_tui","kind":"app_event","variant":"Redraw"} -{"ts":"2025-08-09T15:51:04.856Z","dir":"to_tui","kind":"codex_event","payload":{"id":"0","msg":{"type":"session_configured","session_id":"d126e3d0-80ed-480a-be8c-09d97ff602cf","model":"gpt-5","reasoning_effort":"medium","history_log_id":2532619,"history_entry_count":339,"rollout_path":"/tmp/codex-test-rollout.jsonl"}}} +{"ts":"2025-08-09T15:51:04.856Z","dir":"to_tui","kind":"codex_event","payload":{"id":"0","msg":{"type":"session_configured","session_id":"d126e3d0-80ed-480a-be8c-09d97ff602cf","model":"gpt-5-codex","reasoning_effort":"medium","history_log_id":2532619,"history_entry_count":339,"rollout_path":"/tmp/codex-test-rollout.jsonl"}}} {"ts":"2025-08-09T15:51:04.856Z","dir":"to_tui","kind":"insert_history","lines":9} {"ts":"2025-08-09T15:51:04.857Z","dir":"to_tui","kind":"app_event","variant":"RequestRedraw"} {"ts":"2025-08-09T15:51:04.857Z","dir":"to_tui","kind":"app_event","variant":"RequestRedraw"} @@ -16447,7 +16447,7 @@ {"ts":"2025-08-09T16:06:58.083Z","dir":"to_tui","kind":"app_event","variant":"RequestRedraw"} {"ts":"2025-08-09T16:06:58.085Z","dir":"to_tui","kind":"app_event","variant":"Redraw"} {"ts":"2025-08-09T16:06:58.085Z","dir":"to_tui","kind":"log_line","line":"[INFO codex_core::codex] resume_path: None"} -{"ts":"2025-08-09T16:06:58.136Z","dir":"to_tui","kind":"codex_event","payload":{"id":"0","msg":{"type":"session_configured","session_id":"c7df96da-daec-4fe9-aed9-3cd19b7a6192","model":"gpt-5","reasoning_effort":"medium","history_log_id":2532619,"history_entry_count":342,"rollout_path":"/tmp/codex-test-rollout.jsonl"}}} +{"ts":"2025-08-09T16:06:58.136Z","dir":"to_tui","kind":"codex_event","payload":{"id":"0","msg":{"type":"session_configured","session_id":"c7df96da-daec-4fe9-aed9-3cd19b7a6192","model":"gpt-5-codex","reasoning_effort":"medium","history_log_id":2532619,"history_entry_count":342,"rollout_path":"/tmp/codex-test-rollout.jsonl"}}} {"ts":"2025-08-09T16:06:58.136Z","dir":"to_tui","kind":"insert_history","lines":9} {"ts":"2025-08-09T16:06:58.136Z","dir":"to_tui","kind":"app_event","variant":"RequestRedraw"} {"ts":"2025-08-09T16:06:58.136Z","dir":"to_tui","kind":"app_event","variant":"RequestRedraw"} diff --git a/docs/config.md b/docs/config.md index 4f287b824e..ba204ee00a 100644 --- a/docs/config.md +++ b/docs/config.md @@ -21,7 +21,7 @@ Both the `--config` flag and the `config.toml` file support the following option The model that Codex should use. ```toml -model = "o3" # overrides the default of "gpt-5" +model = "o3" # overrides the default of "gpt-5-codex" ``` ## model_providers @@ -223,11 +223,11 @@ Users can specify config values at multiple levels. Order of precedence is as fo 1. custom command-line argument, e.g., `--model o3` 2. as part of a profile, where the `--profile` is specified via a CLI (or in the config file itself) 3. as an entry in `config.toml`, e.g., `model = "o3"` -4. the default value that comes with Codex CLI (i.e., Codex CLI defaults to `gpt-5`) +4. the default value that comes with Codex CLI (i.e., Codex CLI defaults to `gpt-5-codex`) ## model_reasoning_effort -If the selected model is known to support reasoning (for example: `o3`, `o4-mini`, `codex-*`, `gpt-5`), reasoning is enabled by default when using the Responses API. As explained in the [OpenAI Platform documentation](https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning), this can be set to: +If the selected model is known to support reasoning (for example: `o3`, `o4-mini`, `codex-*`, `gpt-5`, `gpt-5-codex`), reasoning is enabled by default when using the Responses API. As explained in the [OpenAI Platform documentation](https://platform.openai.com/docs/guides/reasoning?api-mode=responses#get-started-with-reasoning), this can be set to: - `"minimal"` - `"low"` @@ -342,7 +342,8 @@ Defines the list of MCP servers that Codex can consult for tool use. Currently, **Note:** Codex may cache the list of tools and resources from an MCP server so that Codex can include this information in context at startup without spawning all the servers. This is designed to save resources by loading MCP servers lazily. -Each server may set `startup_timeout_ms` to adjust how long Codex waits for it to start and respond to a tools listing. The default is `10_000` (10 seconds). +Each server may set `startup_timeout_sec` to adjust how long Codex waits for it to start and respond to a tools listing. The default is `10` seconds. +Similarly, `tool_timeout_sec` limits how long individual tool calls may run (default: `60` seconds), and Codex will fall back to the default when this value is omitted. This config option is comparable to how Claude and Cursor define `mcpServers` in their respective JSON config files, though because Codex uses TOML for its config language, the format is slightly different. For example, the following config in JSON: @@ -369,7 +370,9 @@ command = "npx" args = ["-y", "mcp-server"] env = { "API_KEY" = "value" } # Optional: override the default 10s startup timeout -startup_timeout_ms = 20_000 +startup_timeout_sec = 20 +# Optional: override the default 60s per-tool timeout +tool_timeout_sec = 30 ``` You can also manage these entries from the CLI [experimental]: @@ -603,7 +606,7 @@ notifications = [ "agent-turn-complete", "approval-requested" ] | Key | Type / Values | Notes | | --- | --- | --- | -| `model` | string | Model to use (e.g., `gpt-5`). | +| `model` | string | Model to use (e.g., `gpt-5-codex`). | | `model_provider` | string | Provider id from `model_providers` (default: `openai`). | | `model_context_window` | number | Context window tokens. | | `model_max_output_tokens` | number | Max output tokens. | @@ -619,7 +622,8 @@ notifications = [ "agent-turn-complete", "approval-requested" ] | `mcp_servers..command` | string | MCP server launcher command. | | `mcp_servers..args` | array | MCP server args. | | `mcp_servers..env` | map | MCP server env vars. | -| `mcp_servers..startup_timeout_ms` | number | Startup timeout in milliseconds (default: 10_000). Timeout is applied both for initializing MCP server and initially listing tools. | +| `mcp_servers..startup_timeout_sec` | number | Startup timeout in seconds (default: 10). Timeout is applied both for initializing MCP server and initially listing tools. | +| `mcp_servers..tool_timeout_sec` | number | Per-tool timeout in seconds (default: 60). Accepts fractional values; omit to use the default. | | `model_providers..name` | string | Display name. | | `model_providers..base_url` | string | API base URL. | | `model_providers..env_key` | string | Env var for API key. |