From e258f0f0441c56eac0623a514814733137d38ee4 Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Thu, 23 Oct 2025 20:04:15 -0700 Subject: [PATCH 01/35] Use Option symbol for mac key hints (#5582) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - show the Option (⌥) symbol in key hints when the TUI is built for macOS so the shortcut text matches the platform terminology ## Testing - cargo test -p codex-tui ------ https://chatgpt.com/codex/tasks/task_i_68fab7505530832992780a9e13fb707b --- codex-rs/tui/src/key_hint.rs | 3 +++ ...__tests__renders_with_queued_messages@macos.snap | 13 +++++++++++++ codex-rs/tui/src/status_indicator_widget.rs | 5 +++++ 3 files changed, 21 insertions(+) create mode 100644 codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages@macos.snap diff --git a/codex-rs/tui/src/key_hint.rs b/codex-rs/tui/src/key_hint.rs index b79c2a2703..795d1545f8 100644 --- a/codex-rs/tui/src/key_hint.rs +++ b/codex-rs/tui/src/key_hint.rs @@ -6,6 +6,9 @@ use ratatui::style::Style; use ratatui::style::Stylize; use ratatui::text::Span; +#[cfg(target_os = "macos")] +const ALT_PREFIX: &str = "⌥ + "; +#[cfg(not(target_os = "macos"))] const ALT_PREFIX: &str = "alt + "; const CTRL_PREFIX: &str = "ctrl + "; const SHIFT_PREFIX: &str = "shift + "; diff --git a/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages@macos.snap b/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages@macos.snap new file mode 100644 index 0000000000..5974455c89 --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__status_indicator_widget__tests__renders_with_queued_messages@macos.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/status_indicator_widget.rs +assertion_line: 289 +expression: terminal.backend() +--- +"• Working (0s • esc to interrupt) " +" " +" ↳ first " +" ↳ second " +" ⌥ + ↑ edit " +" " +" " +" " diff --git a/codex-rs/tui/src/status_indicator_widget.rs b/codex-rs/tui/src/status_indicator_widget.rs index 4bcc5cf267..81efde71f2 100644 --- a/codex-rs/tui/src/status_indicator_widget.rs +++ b/codex-rs/tui/src/status_indicator_widget.rs @@ -284,6 +284,11 @@ mod tests { terminal .draw(|f| w.render_ref(f.area(), f.buffer_mut())) .expect("draw"); + #[cfg(target_os = "macos")] + insta::with_settings!({ snapshot_suffix => "macos" }, { + insta::assert_snapshot!(terminal.backend()); + }); + #[cfg(not(target_os = "macos"))] insta::assert_snapshot!(terminal.backend()); } From 0f4fd33ddd2233307953c45f3c73dc7d9f8e1ea1 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 23 Oct 2025 20:30:58 -0700 Subject: [PATCH 02/35] Moving `token_info` to `ConversationHistory` (#5581) I want to centralize input processing and management to `ConversationHistory`. This would need `ConversationHistory` to have access to `token_info` (i.e. preventing adding a big input to the history). Besides, it makes more sense to have it on `ConversationHistory` than `state`. --- codex-rs/core/src/conversation_history.rs | 33 ++++++++++++++++++++++- codex-rs/core/src/state/session.rs | 23 +++++----------- 2 files changed, 39 insertions(+), 17 deletions(-) diff --git a/codex-rs/core/src/conversation_history.rs b/codex-rs/core/src/conversation_history.rs index 93234a4936..b7f153d29f 100644 --- a/codex-rs/core/src/conversation_history.rs +++ b/codex-rs/core/src/conversation_history.rs @@ -1,5 +1,7 @@ use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::TokenUsage; +use codex_protocol::protocol::TokenUsageInfo; use tracing::error; /// Transcript of conversation history @@ -7,11 +9,28 @@ use tracing::error; pub(crate) struct ConversationHistory { /// The oldest items are at the beginning of the vector. items: Vec, + token_info: Option, } impl ConversationHistory { pub(crate) fn new() -> Self { - Self { items: Vec::new() } + Self { + items: Vec::new(), + token_info: TokenUsageInfo::new_or_append(&None, &None, None), + } + } + + pub(crate) fn token_info(&self) -> Option { + self.token_info.clone() + } + + pub(crate) fn set_token_usage_full(&mut self, context_window: i64) { + match &mut self.token_info { + Some(info) => info.fill_to_context_window(context_window), + None => { + self.token_info = Some(TokenUsageInfo::full_context_window(context_window)); + } + } } /// `items` is ordered from oldest to newest. @@ -301,6 +320,18 @@ impl ConversationHistory { self.items.remove(pos); } } + + pub(crate) fn update_token_info( + &mut self, + usage: &TokenUsage, + model_context_window: Option, + ) { + self.token_info = TokenUsageInfo::new_or_append( + &self.token_info, + &Some(usage.clone()), + model_context_window, + ); + } } #[inline] diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index f8a58c3b2a..7c4603d9ec 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -12,7 +12,6 @@ use crate::protocol::TokenUsageInfo; pub(crate) struct SessionState { pub(crate) session_configuration: SessionConfiguration, pub(crate) history: ConversationHistory, - pub(crate) token_info: Option, pub(crate) latest_rate_limits: Option, } @@ -22,7 +21,6 @@ impl SessionState { Self { session_configuration, history: ConversationHistory::new(), - token_info: None, latest_rate_limits: None, } } @@ -54,11 +52,11 @@ impl SessionState { usage: &TokenUsage, model_context_window: Option, ) { - self.token_info = TokenUsageInfo::new_or_append( - &self.token_info, - &Some(usage.clone()), - model_context_window, - ); + self.history.update_token_info(usage, model_context_window); + } + + pub(crate) fn token_info(&self) -> Option { + self.history.token_info() } pub(crate) fn set_rate_limits(&mut self, snapshot: RateLimitSnapshot) { @@ -68,17 +66,10 @@ impl SessionState { pub(crate) fn token_info_and_rate_limits( &self, ) -> (Option, Option) { - (self.token_info.clone(), self.latest_rate_limits.clone()) + (self.token_info(), self.latest_rate_limits.clone()) } pub(crate) fn set_token_usage_full(&mut self, context_window: i64) { - match &mut self.token_info { - Some(info) => info.fill_to_context_window(context_window), - None => { - self.token_info = Some(TokenUsageInfo::full_context_window(context_window)); - } - } + self.history.set_token_usage_full(context_window); } - - // Pending input/approval moved to TurnState. } From abccd3e367296462c15cce54e2dea5f71b1ebfde Mon Sep 17 00:00:00 2001 From: Gabriel Peal Date: Thu, 23 Oct 2025 20:45:29 -0700 Subject: [PATCH 03/35] [MCP] Update rmcp to 0.8.3 (#5542) Picks up modelcontextprotocol/rust-sdk#497 which fixes #5208 by allowing 204 response to MCP initialize notifications instead of just 202. --- codex-rs/Cargo.lock | 8 ++++---- codex-rs/Cargo.toml | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 1a274985e8..449774bf27 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -4954,9 +4954,9 @@ dependencies = [ [[package]] name = "rmcp" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e35d31f89beb59c83bc31363426da25b323ce0c2e5b53c7bf29867d16ee7898" +checksum = "1fdad1258f7259fdc0f2dfc266939c82c3b5d1fd72bcde274d600cdc27e60243" dependencies = [ "base64", "bytes", @@ -4988,9 +4988,9 @@ dependencies = [ [[package]] name = "rmcp-macros" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d88518b38110c439a03f0f4eee40e5105d648a530711cb87f98991e3f324a664" +checksum = "ede0589a208cc7ce81d1be68aa7e74b917fcd03c81528408bab0457e187dcd9b" dependencies = [ "darling 0.21.3", "proc-macro2", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index d72c527bc2..c6e75dca61 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -153,7 +153,7 @@ ratatui = "0.29.0" ratatui-macros = "0.6.0" regex-lite = "0.1.7" reqwest = "0.12" -rmcp = { version = "0.8.2", default-features = false } +rmcp = { version = "0.8.3", default-features = false } schemars = "0.8.22" seccompiler = "0.5.0" sentry = "0.34.0" From ed77d2d977c1a6a2dac5174367963c2c71bdf35c Mon Sep 17 00:00:00 2001 From: Gabriel Peal Date: Thu, 23 Oct 2025 22:54:45 -0700 Subject: [PATCH 04/35] [MCP] Improve startup errors for timeouts and github (#5595) 1. I have seen too many reports of people hitting startup timeout errors and thinking Codex is broken. Hopefully this will help people self-serve. We may also want to consider raising the timeout to ~15s. 2. Make it more clear what PAT is (personal access token) in the GitHub error CleanShot 2025-10-23 at 22 05 06 --- codex-rs/core/src/codex.rs | 36 +++++++++++++++++++-- codex-rs/core/src/mcp_connection_manager.rs | 2 +- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 77ac35ae2a..b9e98e0cd8 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -8,6 +8,7 @@ use crate::AuthManager; use crate::client_common::REVIEW_PROMPT; use crate::function_tool::FunctionCallError; use crate::mcp::auth::McpAuthStatusEntry; +use crate::mcp_connection_manager::DEFAULT_STARTUP_TIMEOUT; use crate::parse_command::parse_command; use crate::parse_turn_item; use crate::response_processing::process_items; @@ -2199,12 +2200,24 @@ fn mcp_init_error_display( // That means that the user has to specify a personal access token either via bearer_token_env_var or http_headers. // https://github.com/github/github-mcp-server/issues/921#issuecomment-3221026448 format!( - "GitHub MCP does not support OAuth. Log in by adding `bearer_token_env_var = CODEX_GITHUB_PAT` in the `mcp_servers.{server_name}` section of your config.toml" + "GitHub MCP does not support OAuth. Log in by adding a personal access token (https://github.com/settings/personal-access-tokens) to your environment and config.toml:\n[mcp_servers.{server_name}]\nbearer_token_env_var = CODEX_GITHUB_PERSONAL_ACCESS_TOKEN" ) } else if is_mcp_client_auth_required_error(err) { format!( "The {server_name} MCP server is not logged in. Run `codex mcp login {server_name}`." ) + } else if is_mcp_client_startup_timeout_error(err) { + let startup_timeout_secs = match entry { + Some(entry) => match entry.config.startup_timeout_sec { + Some(timeout) => timeout, + None => DEFAULT_STARTUP_TIMEOUT, + }, + None => DEFAULT_STARTUP_TIMEOUT, + } + .as_secs(); + format!( + "MCP client for `{server_name}` timed out after {startup_timeout_secs} seconds. Add or adjust `startup_timeout_sec` in your config.toml:\n[mcp_servers.{server_name}]\nstartup_timeout_sec = XX" + ) } else { format!("MCP client for `{server_name}` failed to start: {err:#}") } @@ -2215,6 +2228,12 @@ fn is_mcp_client_auth_required_error(error: &anyhow::Error) -> bool { error.to_string().contains("Auth required") } +fn is_mcp_client_startup_timeout_error(error: &anyhow::Error) -> bool { + let error_message = error.to_string(); + error_message.contains("request timed out") + || error_message.contains("timed out handshaking with MCP server") +} + #[cfg(test)] pub(crate) use tests::make_session_and_context; @@ -3072,7 +3091,7 @@ mod tests { let display = mcp_init_error_display(server_name, Some(&entry), &err); let expected = format!( - "GitHub MCP does not support OAuth. Log in by adding `bearer_token_env_var = CODEX_GITHUB_PAT` in the `mcp_servers.{server_name}` section of your config.toml" + "GitHub MCP does not support OAuth. Log in by adding a personal access token (https://github.com/settings/personal-access-tokens) to your environment and config.toml:\n[mcp_servers.{server_name}]\nbearer_token_env_var = CODEX_GITHUB_PERSONAL_ACCESS_TOKEN" ); assert_eq!(expected, display); @@ -3119,4 +3138,17 @@ mod tests { assert_eq!(expected, display); } + + #[test] + fn mcp_init_error_display_includes_startup_timeout_hint() { + let server_name = "slow"; + let err = anyhow::anyhow!("request timed out"); + + let display = mcp_init_error_display(server_name, None, &err); + + assert_eq!( + "MCP client for `slow` timed out after 10 seconds. Add or adjust `startup_timeout_sec` in your config.toml:\n[mcp_servers.slow]\nstartup_timeout_sec = XX", + display + ); + } } diff --git a/codex-rs/core/src/mcp_connection_manager.rs b/codex-rs/core/src/mcp_connection_manager.rs index 8cc2f48b72..ebe17d2c25 100644 --- a/codex-rs/core/src/mcp_connection_manager.rs +++ b/codex-rs/core/src/mcp_connection_manager.rs @@ -49,7 +49,7 @@ const MCP_TOOL_NAME_DELIMITER: &str = "__"; 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); +pub const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(10); /// Default timeout for individual tool calls. const DEFAULT_TOOL_TIMEOUT: Duration = Duration::from_secs(60); From 80783a7bb958c3ff81dfced1f8de67738f516e0d Mon Sep 17 00:00:00 2001 From: jif-oai Date: Fri, 24 Oct 2025 13:56:41 +0100 Subject: [PATCH 05/35] fix: flaky tests (#5625) --- codex-rs/core/tests/suite/unified_exec.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index 5d5c21d0e4..4a29d6ccd0 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -156,6 +156,12 @@ async fn unified_exec_emits_exec_command_end_event() -> Result<()> { "cmd": "/bin/echo END-EVENT".to_string(), "yield_time_ms": 250, }); + let poll_call_id = "uexec-end-event-poll"; + let poll_args = json!({ + "chars": "", + "session_id": 0, + "yield_time_ms": 250, + }); let responses = vec![ sse(vec![ @@ -165,9 +171,18 @@ async fn unified_exec_emits_exec_command_end_event() -> Result<()> { ]), sse(vec![ ev_response_created("resp-2"), - ev_assistant_message("msg-1", "finished"), + ev_function_call( + poll_call_id, + "write_stdin", + &serde_json::to_string(&poll_args)?, + ), ev_completed("resp-2"), ]), + sse(vec![ + ev_response_created("resp-3"), + ev_assistant_message("msg-1", "finished"), + ev_completed("resp-3"), + ]), ]; mount_sse_sequence(&server, responses).await; From c72b2ad76657fd1100159043e01c5840ff156b82 Mon Sep 17 00:00:00 2001 From: zhao-oai Date: Fri, 24 Oct 2025 08:46:31 -0700 Subject: [PATCH 06/35] adding messaging for stale rate limits + when no rate limits are cached (#5570) --- codex-rs/tui/src/chatwidget.rs | 1 + codex-rs/tui/src/status/card.rs | 103 +++++++++++------ codex-rs/tui/src/status/rate_limits.rs | 12 ++ ...snapshot_shows_missing_limits_message.snap | 2 +- ...s_snapshot_shows_stale_limits_message.snap | 21 ++++ codex-rs/tui/src/status/tests.rs | 109 ++++++++++++++++-- 6 files changed, 207 insertions(+), 41 deletions(-) create mode 100644 codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index c090d212da..75dad91372 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1631,6 +1631,7 @@ impl ChatWidget { context_usage, &self.conversation_id, self.rate_limit_snapshot.as_ref(), + Local::now(), )); } diff --git a/codex-rs/tui/src/status/card.rs b/codex-rs/tui/src/status/card.rs index a077a92661..9333509700 100644 --- a/codex-rs/tui/src/status/card.rs +++ b/codex-rs/tui/src/status/card.rs @@ -3,6 +3,8 @@ use crate::history_cell::HistoryCell; use crate::history_cell::PlainHistoryCell; use crate::history_cell::with_border_with_inner_width; use crate::version::CODEX_CLI_VERSION; +use chrono::DateTime; +use chrono::Local; use codex_common::create_config_summary_entries; use codex_core::config::Config; use codex_core::protocol::SandboxPolicy; @@ -25,6 +27,7 @@ use super::helpers::format_directory_display; use super::helpers::format_tokens_compact; use super::rate_limits::RateLimitSnapshotDisplay; use super::rate_limits::StatusRateLimitData; +use super::rate_limits::StatusRateLimitRow; use super::rate_limits::compose_rate_limit_data; use super::rate_limits::format_status_limit_summary; use super::rate_limits::render_status_limit_progress_bar; @@ -64,9 +67,17 @@ pub(crate) fn new_status_output( context_usage: Option<&TokenUsage>, session_id: &Option, rate_limits: Option<&RateLimitSnapshotDisplay>, + now: DateTime, ) -> CompositeHistoryCell { let command = PlainHistoryCell::new(vec!["/status".magenta().into()]); - let card = StatusHistoryCell::new(config, total_usage, context_usage, session_id, rate_limits); + let card = StatusHistoryCell::new( + config, + total_usage, + context_usage, + session_id, + rate_limits, + now, + ); CompositeHistoryCell::new(vec![Box::new(command), Box::new(card)]) } @@ -78,6 +89,7 @@ impl StatusHistoryCell { context_usage: Option<&TokenUsage>, session_id: &Option, rate_limits: Option<&RateLimitSnapshotDisplay>, + now: DateTime, ) -> Self { let config_entries = create_config_summary_entries(config); let (model_name, model_details) = compose_model_display(config, &config_entries); @@ -108,7 +120,7 @@ impl StatusHistoryCell { output: total_usage.output_tokens, context_window, }; - let rate_limits = compose_rate_limit_data(rate_limits); + let rate_limits = compose_rate_limit_data(rate_limits, now); Self { model_name, @@ -171,47 +183,66 @@ impl StatusHistoryCell { ]; } - let mut lines = Vec::with_capacity(rows_data.len() * 2); - - for row in rows_data { - let value_spans = vec![ - Span::from(render_status_limit_progress_bar(row.percent_used)), - Span::from(" "), - Span::from(format_status_limit_summary(row.percent_used)), - ]; - let base_spans = formatter.full_spans(row.label.as_str(), value_spans); - let base_line = Line::from(base_spans.clone()); - - if let Some(resets_at) = row.resets_at.as_ref() { - let resets_span = Span::from(format!("(resets {resets_at})")).dim(); - let mut inline_spans = base_spans.clone(); - inline_spans.push(Span::from(" ").dim()); - inline_spans.push(resets_span.clone()); - - if line_display_width(&Line::from(inline_spans.clone())) - <= available_inner_width - { - lines.push(Line::from(inline_spans)); - } else { - lines.push(base_line); - lines.push(formatter.continuation(vec![resets_span])); - } - } else { - lines.push(base_line); - } - } - + self.rate_limit_row_lines(rows_data, available_inner_width, formatter) + } + StatusRateLimitData::Stale(rows_data) => { + let mut lines = + self.rate_limit_row_lines(rows_data, available_inner_width, formatter); + lines.push(formatter.line( + "Warning", + vec![Span::from("limits may be stale - start new turn to refresh.").dim()], + )); lines } StatusRateLimitData::Missing => { vec![formatter.line( "Limits", - vec![Span::from("send a message to load usage data").dim()], + vec![ + Span::from("visit ").dim(), + "chatgpt.com/codex/settings/usage".cyan().underlined(), + ], )] } } } + fn rate_limit_row_lines( + &self, + rows: &[StatusRateLimitRow], + available_inner_width: usize, + formatter: &FieldFormatter, + ) -> Vec> { + let mut lines = Vec::with_capacity(rows.len().saturating_mul(2)); + + for row in rows { + let value_spans = vec![ + Span::from(render_status_limit_progress_bar(row.percent_used)), + Span::from(" "), + Span::from(format_status_limit_summary(row.percent_used)), + ]; + let base_spans = formatter.full_spans(row.label.as_str(), value_spans); + let base_line = Line::from(base_spans.clone()); + + if let Some(resets_at) = row.resets_at.as_ref() { + let resets_span = Span::from(format!("(resets {resets_at})")).dim(); + let mut inline_spans = base_spans.clone(); + inline_spans.push(Span::from(" ").dim()); + inline_spans.push(resets_span.clone()); + + if line_display_width(&Line::from(inline_spans.clone())) <= available_inner_width { + lines.push(Line::from(inline_spans)); + } else { + lines.push(base_line); + lines.push(formatter.continuation(vec![resets_span])); + } + } else { + lines.push(base_line); + } + } + + lines + } + fn collect_rate_limit_labels(&self, seen: &mut BTreeSet, labels: &mut Vec) { match &self.rate_limits { StatusRateLimitData::Available(rows) => { @@ -223,6 +254,12 @@ impl StatusHistoryCell { } } } + StatusRateLimitData::Stale(rows) => { + for row in rows { + push_label(labels, seen, row.label.as_str()); + } + push_label(labels, seen, "Warning"); + } StatusRateLimitData::Missing => push_label(labels, seen, "Limits"), } } diff --git a/codex-rs/tui/src/status/rate_limits.rs b/codex-rs/tui/src/status/rate_limits.rs index ea63f189f3..4c08cdd673 100644 --- a/codex-rs/tui/src/status/rate_limits.rs +++ b/codex-rs/tui/src/status/rate_limits.rs @@ -2,6 +2,7 @@ use crate::chatwidget::get_limits_duration; use super::helpers::format_reset_timestamp; use chrono::DateTime; +use chrono::Duration as ChronoDuration; use chrono::Local; use chrono::Utc; use codex_core::protocol::RateLimitSnapshot; @@ -21,9 +22,12 @@ pub(crate) struct StatusRateLimitRow { #[derive(Debug, Clone)] pub(crate) enum StatusRateLimitData { Available(Vec), + Stale(Vec), Missing, } +pub(crate) const RATE_LIMIT_STALE_THRESHOLD_MINUTES: i64 = 15; + #[derive(Debug, Clone)] pub(crate) struct RateLimitWindowDisplay { pub used_percent: f64, @@ -49,6 +53,7 @@ impl RateLimitWindowDisplay { #[derive(Debug, Clone)] pub(crate) struct RateLimitSnapshotDisplay { + pub captured_at: DateTime, pub primary: Option, pub secondary: Option, } @@ -58,6 +63,7 @@ pub(crate) fn rate_limit_snapshot_display( captured_at: DateTime, ) -> RateLimitSnapshotDisplay { RateLimitSnapshotDisplay { + captured_at, primary: snapshot .primary .as_ref() @@ -71,6 +77,7 @@ pub(crate) fn rate_limit_snapshot_display( pub(crate) fn compose_rate_limit_data( snapshot: Option<&RateLimitSnapshotDisplay>, + now: DateTime, ) -> StatusRateLimitData { match snapshot { Some(snapshot) => { @@ -102,8 +109,13 @@ pub(crate) fn compose_rate_limit_data( }); } + let is_stale = now.signed_duration_since(snapshot.captured_at) + > ChronoDuration::minutes(RATE_LIMIT_STALE_THRESHOLD_MINUTES); + if rows.is_empty() { StatusRateLimitData::Available(vec![]) + } else if is_stale { + StatusRateLimitData::Stale(rows) } else { StatusRateLimitData::Available(rows) } diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap index 66bcfa3e21..9997006357 100644 --- a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_missing_limits_message.snap @@ -15,5 +15,5 @@ expression: sanitized │ │ │ Token usage: 750 total (500 input + 250 output) │ │ Context window: 100% left (750 used / 272K) │ -│ Limits: send a message to load usage data │ +│ Limits: visit chatgpt.com/codex/settings/usage │ ╰─────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap new file mode 100644 index 0000000000..bd07335210 --- /dev/null +++ b/codex-rs/tui/src/status/snapshots/codex_tui__status__tests__status_snapshot_shows_stale_limits_message.snap @@ -0,0 +1,21 @@ +--- +source: tui/src/status/tests.rs +expression: sanitized +--- +/status + +╭─────────────────────────────────────────────────────────────────────╮ +│ >_ OpenAI Codex (v0.0.0) │ +│ │ +│ Model: gpt-5-codex (reasoning none, summaries auto) │ +│ Directory: [[workspace]] │ +│ Approval: on-request │ +│ Sandbox: read-only │ +│ Agents.md: │ +│ │ +│ Token usage: 1.9K total (1K input + 900 output) │ +│ Context window: 100% left (2.1K used / 272K) │ +│ 5h limit: [███████████████░░░░░] 72% used (resets 03:14) │ +│ Weekly limit: [████████░░░░░░░░░░░░] 40% used (resets 03:34) │ +│ Warning: limits may be stale - start new turn to refresh. │ +╰─────────────────────────────────────────────────────────────────────╯ diff --git a/codex-rs/tui/src/status/tests.rs b/codex-rs/tui/src/status/tests.rs index b8c945eeec..4ab4a8ea63 100644 --- a/codex-rs/tui/src/status/tests.rs +++ b/codex-rs/tui/src/status/tests.rs @@ -111,7 +111,14 @@ fn status_snapshot_includes_reasoning_details() { }; let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); - let composite = new_status_output(&config, &usage, Some(&usage), &None, Some(&rate_display)); + let composite = new_status_output( + &config, + &usage, + Some(&usage), + &None, + Some(&rate_display), + captured_at, + ); let mut rendered_lines = render_lines(&composite.display_lines(80)); if cfg!(windows) { for line in &mut rendered_lines { @@ -152,7 +159,14 @@ fn status_snapshot_includes_monthly_limit() { }; let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); - let composite = new_status_output(&config, &usage, Some(&usage), &None, Some(&rate_display)); + let composite = new_status_output( + &config, + &usage, + Some(&usage), + &None, + Some(&rate_display), + captured_at, + ); let mut rendered_lines = render_lines(&composite.display_lines(80)); if cfg!(windows) { for line in &mut rendered_lines { @@ -178,7 +192,12 @@ fn status_card_token_usage_excludes_cached_tokens() { total_tokens: 2_100, }; - let composite = new_status_output(&config, &usage, Some(&usage), &None, None); + let now = chrono::Local + .with_ymd_and_hms(2024, 1, 1, 0, 0, 0) + .single() + .expect("timestamp"); + + let composite = new_status_output(&config, &usage, Some(&usage), &None, None, now); let rendered = render_lines(&composite.display_lines(120)); assert!( @@ -219,7 +238,14 @@ fn status_snapshot_truncates_in_narrow_terminal() { }; let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); - let composite = new_status_output(&config, &usage, Some(&usage), &None, Some(&rate_display)); + let composite = new_status_output( + &config, + &usage, + Some(&usage), + &None, + Some(&rate_display), + captured_at, + ); let mut rendered_lines = render_lines(&composite.display_lines(46)); if cfg!(windows) { for line in &mut rendered_lines { @@ -246,7 +272,12 @@ fn status_snapshot_shows_missing_limits_message() { total_tokens: 750, }; - let composite = new_status_output(&config, &usage, Some(&usage), &None, None); + let now = chrono::Local + .with_ymd_and_hms(2024, 2, 3, 4, 5, 6) + .single() + .expect("timestamp"); + + let composite = new_status_output(&config, &usage, Some(&usage), &None, None, now); let mut rendered_lines = render_lines(&composite.display_lines(80)); if cfg!(windows) { for line in &mut rendered_lines { @@ -282,7 +313,66 @@ fn status_snapshot_shows_empty_limits_message() { .expect("timestamp"); let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); - let composite = new_status_output(&config, &usage, Some(&usage), &None, Some(&rate_display)); + let composite = new_status_output( + &config, + &usage, + Some(&usage), + &None, + Some(&rate_display), + captured_at, + ); + let mut rendered_lines = render_lines(&composite.display_lines(80)); + if cfg!(windows) { + for line in &mut rendered_lines { + *line = line.replace('\\', "/"); + } + } + let sanitized = sanitize_directory(rendered_lines).join("\n"); + assert_snapshot!(sanitized); +} + +#[test] +fn status_snapshot_shows_stale_limits_message() { + let temp_home = TempDir::new().expect("temp home"); + let mut config = test_config(&temp_home); + config.model = "gpt-5-codex".to_string(); + config.cwd = PathBuf::from("/workspace/tests"); + + let usage = TokenUsage { + input_tokens: 1_200, + cached_input_tokens: 200, + output_tokens: 900, + reasoning_output_tokens: 150, + total_tokens: 2_250, + }; + + let captured_at = chrono::Local + .with_ymd_and_hms(2024, 1, 2, 3, 4, 5) + .single() + .expect("timestamp"); + let snapshot = RateLimitSnapshot { + primary: Some(RateLimitWindow { + used_percent: 72.5, + window_minutes: Some(300), + resets_at: Some(reset_at_from(&captured_at, 600)), + }), + secondary: Some(RateLimitWindow { + used_percent: 40.0, + window_minutes: Some(10_080), + resets_at: Some(reset_at_from(&captured_at, 1_800)), + }), + }; + let rate_display = rate_limit_snapshot_display(&snapshot, captured_at); + let now = captured_at + ChronoDuration::minutes(20); + + let composite = new_status_output( + &config, + &usage, + Some(&usage), + &None, + Some(&rate_display), + now, + ); let mut rendered_lines = render_lines(&composite.display_lines(80)); if cfg!(windows) { for line in &mut rendered_lines { @@ -314,7 +404,12 @@ fn status_context_window_uses_last_usage() { total_tokens: 13_679, }; - let composite = new_status_output(&config, &total_usage, Some(&last_usage), &None, None); + let now = chrono::Local + .with_ymd_and_hms(2024, 6, 1, 12, 0, 0) + .single() + .expect("timestamp"); + + let composite = new_status_output(&config, &total_usage, Some(&last_usage), &None, None, now); let rendered_lines = render_lines(&composite.display_lines(80)); let context_line = rendered_lines .into_iter() From 061862a0e20d54741000f534c3ea47d2fd08ee6a Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Fri, 24 Oct 2025 09:47:52 -0700 Subject: [PATCH 07/35] Add CodexHttpClient wrapper with request logging (#5564) ## Summary - wrap the default reqwest::Client inside a new CodexHttpClient/CodexRequestBuilder pair and log the HTTP method, URL, and status for each request - update the auth/model/provider plumbing to use the new builder helpers so headers and bearer auth continue to be applied consistently - add the shared `http` dependency that backs the header conversion helpers ## Testing - `CODEX_SANDBOX=seatbelt CODEX_SANDBOX_NETWORK_DISABLED=1 cargo test -p codex-core` - `CODEX_SANDBOX=seatbelt CODEX_SANDBOX_NETWORK_DISABLED=1 cargo test -p codex-chatgpt` - `CODEX_SANDBOX=seatbelt CODEX_SANDBOX_NETWORK_DISABLED=1 cargo test -p codex-tui` ------ https://chatgpt.com/codex/tasks/task_i_68fa5038c17483208b1148661c5873be --- codex-rs/Cargo.lock | 1 + codex-rs/Cargo.toml | 1 + codex-rs/core/Cargo.toml | 1 + codex-rs/core/src/auth.rs | 7 +- codex-rs/core/src/chat_completions.rs | 3 +- codex-rs/core/src/client.rs | 10 +- codex-rs/core/src/default_client.rs | 133 ++++++++++++++++++++++- codex-rs/core/src/model_provider_info.rs | 12 +- 8 files changed, 148 insertions(+), 20 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 449774bf27..0d8522a67b 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1075,6 +1075,7 @@ dependencies = [ "escargot", "eventsource-stream", "futures", + "http", "indexmap 2.10.0", "landlock", "libc", diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index c6e75dca61..46a46e23e8 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -116,6 +116,7 @@ env_logger = "0.11.5" escargot = "0.5" eventsource-stream = "0.2.3" futures = { version = "0.3", default-features = false } +http = "1.3.1" icu_decimal = "2.0.0" icu_locale_core = "2.0.0" ignore = "0.4.23" diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index b05e488511..9b0e433972 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -34,6 +34,7 @@ dunce = { workspace = true } env-flags = { workspace = true } eventsource-stream = { workspace = true } futures = { workspace = true } +http = { workspace = true } indexmap = { workspace = true } libc = { workspace = true } mcp-types = { workspace = true } diff --git a/codex-rs/core/src/auth.rs b/codex-rs/core/src/auth.rs index 3dcc037bd9..30394e7991 100644 --- a/codex-rs/core/src/auth.rs +++ b/codex-rs/core/src/auth.rs @@ -21,6 +21,7 @@ use codex_app_server_protocol::AuthMode; use codex_protocol::config_types::ForcedLoginMethod; use crate::config::Config; +use crate::default_client::CodexHttpClient; use crate::token_data::PlanType; use crate::token_data::TokenData; use crate::token_data::parse_id_token; @@ -32,7 +33,7 @@ pub struct CodexAuth { pub(crate) api_key: Option, pub(crate) auth_dot_json: Arc>>, pub(crate) auth_file: PathBuf, - pub(crate) client: reqwest::Client, + pub(crate) client: CodexHttpClient, } impl PartialEq for CodexAuth { @@ -180,7 +181,7 @@ impl CodexAuth { } } - fn from_api_key_with_client(api_key: &str, client: reqwest::Client) -> Self { + fn from_api_key_with_client(api_key: &str, client: CodexHttpClient) -> Self { Self { api_key: Some(api_key.to_owned()), mode: AuthMode::ApiKey, @@ -400,7 +401,7 @@ async fn update_tokens( async fn try_refresh_token( refresh_token: String, - client: &reqwest::Client, + client: &CodexHttpClient, ) -> std::io::Result { let refresh_request = RefreshRequest { client_id: CLIENT_ID, diff --git a/codex-rs/core/src/chat_completions.rs b/codex-rs/core/src/chat_completions.rs index 27937a48d0..ac1d7f9cf5 100644 --- a/codex-rs/core/src/chat_completions.rs +++ b/codex-rs/core/src/chat_completions.rs @@ -4,6 +4,7 @@ use crate::ModelProviderInfo; use crate::client_common::Prompt; use crate::client_common::ResponseEvent; use crate::client_common::ResponseStream; +use crate::default_client::CodexHttpClient; use crate::error::CodexErr; use crate::error::ConnectionFailedError; use crate::error::ResponseStreamFailed; @@ -36,7 +37,7 @@ use tracing::trace; pub(crate) async fn stream_chat_completions( prompt: &Prompt, model_family: &ModelFamily, - client: &reqwest::Client, + client: &CodexHttpClient, provider: &ModelProviderInfo, otel_event_manager: &OtelEventManager, ) -> Result { diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 1bf1ad0d8b..1708df6a82 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -39,6 +39,7 @@ use crate::client_common::ResponsesApiRequest; use crate::client_common::create_reasoning_param_for_request; use crate::client_common::create_text_param_for_request; use crate::config::Config; +use crate::default_client::CodexHttpClient; use crate::default_client::create_client; use crate::error::CodexErr; use crate::error::ConnectionFailedError; @@ -81,7 +82,7 @@ pub struct ModelClient { config: Arc, auth_manager: Option>, otel_event_manager: OtelEventManager, - client: reqwest::Client, + client: CodexHttpClient, provider: ModelProviderInfo, conversation_id: ConversationId, effort: Option, @@ -335,13 +336,6 @@ impl ModelClient { .headers() .get("cf-ray") .map(|v| v.to_str().unwrap_or_default().to_string()); - - debug!( - "Response status: {}, cf-ray: {:?}, version: {:?}", - resp.status(), - request_id, - resp.version() - ); } match res { diff --git a/codex-rs/core/src/default_client.rs b/codex-rs/core/src/default_client.rs index 42690e04cc..821a4c8044 100644 --- a/codex-rs/core/src/default_client.rs +++ b/codex-rs/core/src/default_client.rs @@ -1,5 +1,12 @@ use crate::spawn::CODEX_SANDBOX_ENV_VAR; +use http::Error as HttpError; +use reqwest::IntoUrl; +use reqwest::Method; +use reqwest::Response; +use reqwest::header::HeaderName; use reqwest::header::HeaderValue; +use serde::Serialize; +use std::fmt::Display; use std::sync::LazyLock; use std::sync::Mutex; use std::sync::OnceLock; @@ -22,6 +29,125 @@ use std::sync::OnceLock; pub static USER_AGENT_SUFFIX: LazyLock>> = LazyLock::new(|| Mutex::new(None)); pub const DEFAULT_ORIGINATOR: &str = "codex_cli_rs"; pub const CODEX_INTERNAL_ORIGINATOR_OVERRIDE_ENV_VAR: &str = "CODEX_INTERNAL_ORIGINATOR_OVERRIDE"; + +#[derive(Clone, Debug)] +pub struct CodexHttpClient { + inner: reqwest::Client, +} + +impl CodexHttpClient { + fn new(inner: reqwest::Client) -> Self { + Self { inner } + } + + pub fn get(&self, url: U) -> CodexRequestBuilder + where + U: IntoUrl, + { + self.request(Method::GET, url) + } + + pub fn post(&self, url: U) -> CodexRequestBuilder + where + U: IntoUrl, + { + self.request(Method::POST, url) + } + + pub fn request(&self, method: Method, url: U) -> CodexRequestBuilder + where + U: IntoUrl, + { + let url_str = url.as_str().to_string(); + CodexRequestBuilder::new(self.inner.request(method.clone(), url), method, url_str) + } +} + +#[must_use = "requests are not sent unless `send` is awaited"] +#[derive(Debug)] +pub struct CodexRequestBuilder { + builder: reqwest::RequestBuilder, + method: Method, + url: String, +} + +impl CodexRequestBuilder { + fn new(builder: reqwest::RequestBuilder, method: Method, url: String) -> Self { + Self { + builder, + method, + url, + } + } + + fn map(self, f: impl FnOnce(reqwest::RequestBuilder) -> reqwest::RequestBuilder) -> Self { + Self { + builder: f(self.builder), + method: self.method, + url: self.url, + } + } + + pub fn header(self, key: K, value: V) -> Self + where + HeaderName: TryFrom, + >::Error: Into, + HeaderValue: TryFrom, + >::Error: Into, + { + self.map(|builder| builder.header(key, value)) + } + + pub fn bearer_auth(self, token: T) -> Self + where + T: Display, + { + self.map(|builder| builder.bearer_auth(token)) + } + + pub fn json(self, value: &T) -> Self + where + T: ?Sized + Serialize, + { + self.map(|builder| builder.json(value)) + } + + pub async fn send(self) -> Result { + match self.builder.send().await { + Ok(response) => { + let request_id = response + .headers() + .get("cf-ray") + .map(|v| v.to_str().unwrap_or_default().to_string()) + .unwrap_or_default(); + + let version = format!("{:?}", response.version()); + + tracing::debug!( + method = %self.method, + url = %self.url, + status = %response.status(), + request_id = %request_id, + version = %version, + "Request completed" + ); + + Ok(response) + } + Err(error) => { + let status = error.status(); + tracing::debug!( + method = %self.method, + url = %self.url, + status = status.map(|s| s.as_u16()), + error = %error, + "Request failed" + ); + Err(error) + } + } + } +} #[derive(Debug, Clone)] pub struct Originator { pub value: String, @@ -124,8 +250,8 @@ fn sanitize_user_agent(candidate: String, fallback: &str) -> String { } } -/// Create a reqwest client with default `originator` and `User-Agent` headers set. -pub fn create_client() -> reqwest::Client { +/// Create an HTTP client with default `originator` and `User-Agent` headers set. +pub fn create_client() -> CodexHttpClient { use reqwest::header::HeaderMap; let mut headers = HeaderMap::new(); @@ -140,7 +266,8 @@ pub fn create_client() -> reqwest::Client { builder = builder.no_proxy(); } - builder.build().unwrap_or_else(|_| reqwest::Client::new()) + let inner = builder.build().unwrap_or_else(|_| reqwest::Client::new()); + CodexHttpClient::new(inner) } fn is_sandboxed() -> bool { diff --git a/codex-rs/core/src/model_provider_info.rs b/codex-rs/core/src/model_provider_info.rs index 429a260653..8dc252aa7c 100644 --- a/codex-rs/core/src/model_provider_info.rs +++ b/codex-rs/core/src/model_provider_info.rs @@ -6,6 +6,8 @@ //! key. These override or extend the defaults at runtime. use crate::CodexAuth; +use crate::default_client::CodexHttpClient; +use crate::default_client::CodexRequestBuilder; use codex_app_server_protocol::AuthMode; use serde::Deserialize; use serde::Serialize; @@ -95,7 +97,7 @@ pub struct ModelProviderInfo { impl ModelProviderInfo { /// Construct a `POST` RequestBuilder for the given URL using the provided - /// reqwest Client applying: + /// [`CodexHttpClient`] applying: /// • provider-specific headers (static + env based) /// • Bearer auth header when an API key is available. /// • Auth token for OAuth. @@ -104,9 +106,9 @@ impl ModelProviderInfo { /// one produced by [`ModelProviderInfo::api_key`]. pub async fn create_request_builder<'a>( &'a self, - client: &'a reqwest::Client, + client: &'a CodexHttpClient, auth: &Option, - ) -> crate::error::Result { + ) -> crate::error::Result { let effective_auth = if let Some(secret_key) = &self.experimental_bearer_token { Some(CodexAuth::from_api_key(secret_key)) } else { @@ -187,9 +189,9 @@ impl ModelProviderInfo { } /// Apply provider-specific HTTP headers (both static and environment-based) - /// onto an existing `reqwest::RequestBuilder` and return the updated + /// onto an existing [`CodexRequestBuilder`] and return the updated /// builder. - fn apply_http_headers(&self, mut builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder { + fn apply_http_headers(&self, mut builder: CodexRequestBuilder) -> CodexRequestBuilder { if let Some(extra) = &self.http_headers { for (k, v) in extra { builder = builder.header(k, v); From 190e7eb104fff387310cf35ddb0a933cd634b883 Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Fri, 24 Oct 2025 11:17:46 -0700 Subject: [PATCH 08/35] [app-server] fix account/read response annotation (#5642) The API schema export is currently broken: ``` > cargo run -p codex-app-server-protocol --bin export -- --out DIR Error: this type cannot be exported ``` This PR fixes the error message so we get more info: ``` > cargo run -p codex-app-server-protocol --bin export -- --out DIR Error: failed to export client responses: dependency core::option::Option cannot be exported ``` And fixes the root cause which is the `account/read` response. --- codex-rs/app-server-protocol/src/export.rs | 30 ++++++++++++++++---- codex-rs/app-server-protocol/src/protocol.rs | 8 +++++- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index 21ba3facc4..486abf8e5f 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -23,6 +23,7 @@ use std::io::Write; use std::path::Path; use std::path::PathBuf; use std::process::Command; +use ts_rs::ExportError; use ts_rs::TS; const HEADER: &str = "// GENERATED CODE! DO NOT MODIFY BY HAND!\n\n"; @@ -104,6 +105,19 @@ macro_rules! for_each_schema_type { }; } +fn export_ts_with_context(label: &str, export: F) -> Result<()> +where + F: FnOnce() -> std::result::Result<(), ExportError>, +{ + match export() { + Ok(()) => Ok(()), + Err(ExportError::CannotBeExported(ty)) => Err(anyhow!( + "failed to export {label}: dependency {ty} cannot be exported" + )), + Err(err) => Err(err.into()), + } +} + pub fn generate_types(out_dir: &Path, prettier: Option<&Path>) -> Result<()> { generate_ts(out_dir, prettier)?; generate_json(out_dir)?; @@ -113,13 +127,17 @@ pub fn generate_types(out_dir: &Path, prettier: Option<&Path>) -> Result<()> { pub fn generate_ts(out_dir: &Path, prettier: Option<&Path>) -> Result<()> { ensure_dir(out_dir)?; - ClientRequest::export_all_to(out_dir)?; - export_client_responses(out_dir)?; - ClientNotification::export_all_to(out_dir)?; + export_ts_with_context("ClientRequest", || ClientRequest::export_all_to(out_dir))?; + export_ts_with_context("client responses", || export_client_responses(out_dir))?; + export_ts_with_context("ClientNotification", || { + ClientNotification::export_all_to(out_dir) + })?; - ServerRequest::export_all_to(out_dir)?; - export_server_responses(out_dir)?; - ServerNotification::export_all_to(out_dir)?; + export_ts_with_context("ServerRequest", || ServerRequest::export_all_to(out_dir))?; + export_ts_with_context("server responses", || export_server_responses(out_dir))?; + export_ts_with_context("ServerNotification", || { + ServerNotification::export_all_to(out_dir) + })?; generate_index_ts(out_dir)?; diff --git a/codex-rs/app-server-protocol/src/protocol.rs b/codex-rs/app-server-protocol/src/protocol.rs index 4b4563aadc..ceeeb48919 100644 --- a/codex-rs/app-server-protocol/src/protocol.rs +++ b/codex-rs/app-server-protocol/src/protocol.rs @@ -127,7 +127,7 @@ client_request_definitions! { #[ts(rename = "account/read")] GetAccount { params: #[ts(type = "undefined")] #[serde(skip_serializing_if = "Option::is_none")] Option<()>, - response: Option, + response: GetAccountResponse, }, /// DEPRECATED APIs below @@ -534,6 +534,12 @@ pub struct GetAccountRateLimitsResponse { pub rate_limits: RateLimitSnapshot, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(transparent)] +#[ts(export)] +#[ts(type = "Account | null")] +pub struct GetAccountResponse(#[ts(type = "Account | null")] pub Option); + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] pub struct GetAuthStatusResponse { From 00c1de0c56951a322603bc1fff7147db66919a54 Mon Sep 17 00:00:00 2001 From: Shijie Rao Date: Fri, 24 Oct 2025 11:30:34 -0700 Subject: [PATCH 09/35] Add instruction for upgrading codex with brew (#5640) Include instruction for upgrading codex with brew when there is switch from formula to cask. --- README.md | 2 ++ docs/faq.md | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/README.md b/README.md index 722048b30b..4678abd800 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,8 @@ Then simply run `codex` to get started: codex ``` +If you're running into upgrade issues with Homebrew, see the [FAQ entry on brew upgrade codex](./docs/faq.md#brew-update-codex-isnt-upgrading-me). +
You can also go to the latest GitHub Release and download the appropriate binary for your platform. diff --git a/docs/faq.md b/docs/faq.md index 55a6e5e33b..6ad0d51efc 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -42,3 +42,14 @@ Running Codex directly on Windows may work, but is not officially supported. We ### Where should I start after installation? Follow the quick setup in [Install & build](./install.md) and then jump into [Getting started](./getting-started.md) for interactive usage tips, prompt examples, and AGENTS.md guidance. + +### `brew upgrade codex` isn't upgrading me + +If you're running Codex v0.46.0 or older, `brew upgrade codex` will not move you to the latest version because we migrated from a Homebrew formula to a cask. To upgrade, uninstall the existing oudated formula and then install the new cask: + +```bash +brew uninstall --formula codex +brew install --cask codex +``` + +After reinstalling, `brew upgrade --cask codex` will keep future releases up to date. From a4be4d78b937e06cd76469fb3b6f7b5244d23058 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Fri, 24 Oct 2025 12:12:03 -0700 Subject: [PATCH 10/35] Log more types of request IDs (#5645) Different services return different sets of IDs, log all of them to simplify debugging. --- codex-rs/core/src/auth.rs | 7 ++++++- codex-rs/core/src/client.rs | 1 + codex-rs/core/src/default_client.rs | 26 ++++++++++++++++---------- codex-rs/feedback/src/lib.rs | 2 +- 4 files changed, 24 insertions(+), 12 deletions(-) diff --git a/codex-rs/core/src/auth.rs b/codex-rs/core/src/auth.rs index 30394e7991..55386ca5ec 100644 --- a/codex-rs/core/src/auth.rs +++ b/codex-rs/core/src/auth.rs @@ -44,6 +44,8 @@ impl PartialEq for CodexAuth { impl CodexAuth { pub async fn refresh_token(&self) -> Result { + tracing::info!("Refreshing token"); + let token_data = self .get_current_token_data() .ok_or(std::io::Error::other("Token data is not available."))?; @@ -917,7 +919,10 @@ impl AuthManager { self.reload(); Ok(Some(token)) } - Err(e) => Err(e), + Err(e) => { + tracing::error!("Failed to refresh token: {}", e); + Err(e) + } } } diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 1708df6a82..62e003a915 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -301,6 +301,7 @@ impl ModelClient { "POST to {}: {:?}", self.provider.get_full_url(&auth), serde_json::to_string(payload_json) + .unwrap_or("".to_string()) ); let mut req_builder = self diff --git a/codex-rs/core/src/default_client.rs b/codex-rs/core/src/default_client.rs index 821a4c8044..8e4635460c 100644 --- a/codex-rs/core/src/default_client.rs +++ b/codex-rs/core/src/default_client.rs @@ -6,6 +6,7 @@ use reqwest::Response; use reqwest::header::HeaderName; use reqwest::header::HeaderValue; use serde::Serialize; +use std::collections::HashMap; use std::fmt::Display; use std::sync::LazyLock; use std::sync::Mutex; @@ -115,20 +116,13 @@ impl CodexRequestBuilder { pub async fn send(self) -> Result { match self.builder.send().await { Ok(response) => { - let request_id = response - .headers() - .get("cf-ray") - .map(|v| v.to_str().unwrap_or_default().to_string()) - .unwrap_or_default(); - - let version = format!("{:?}", response.version()); - + let request_ids = Self::extract_request_ids(&response); tracing::debug!( method = %self.method, url = %self.url, status = %response.status(), - request_id = %request_id, - version = %version, + request_ids = ?request_ids, + version = ?response.version(), "Request completed" ); @@ -147,6 +141,18 @@ impl CodexRequestBuilder { } } } + + fn extract_request_ids(response: &Response) -> HashMap { + ["cf-ray", "x-request-id", "x-oai-request-id"] + .iter() + .filter_map(|&name| { + let header_name = HeaderName::from_static(name); + let value = response.headers().get(header_name)?; + let value = value.to_str().ok()?.to_owned(); + Some((name.to_owned(), value)) + }) + .collect() + } } #[derive(Debug, Clone)] pub struct Originator { diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index 285ab0661d..2399646311 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -12,7 +12,7 @@ use anyhow::anyhow; use codex_protocol::ConversationId; use tracing_subscriber::fmt::writer::MakeWriter; -const DEFAULT_MAX_BYTES: usize = 2 * 1024 * 1024; // 2 MiB +const DEFAULT_MAX_BYTES: usize = 4 * 1024 * 1024; // 4 MiB const SENTRY_DSN: &str = "https://ae32ed50620d7a7792c1ce5df38b3e3e@o33249.ingest.us.sentry.io/4510195390611458"; const UPLOAD_TIMEOUT_SECS: u64 = 10; From f8af4f5c8d7d70093acb4adcd9da71211f76943d Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Fri, 24 Oct 2025 17:23:44 -0500 Subject: [PATCH 11/35] Added model summary and risk assessment for commands that violate sandbox policy (#5536) This PR adds support for a model-based summary and risk assessment for commands that violate the sandbox policy and require user approval. This aids the user in evaluating whether the command should be approved. The feature works by taking a failed command and passing it back to the model and asking it to summarize the command, give it a risk level (low, medium, high) and a risk category (e.g. "data deletion" or "data exfiltration"). It uses a new conversation thread so the context in the existing thread doesn't influence the answer. If the call to the model fails or takes longer than 5 seconds, it falls back to the current behavior. For now, this is an experimental feature and is gated by a config key `experimental_sandbox_command_assessment`. Here is a screen shot of the approval prompt showing the risk assessment and summary. image --- codex-rs/app-server-protocol/src/protocol.rs | 4 + .../app-server/src/codex_message_processor.rs | 3 + .../suite/codex_message_processor_flow.rs | 1 + codex-rs/core/src/client.rs | 8 + codex-rs/core/src/codex.rs | 29 ++ codex-rs/core/src/config.rs | 14 + codex-rs/core/src/config_profile.rs | 1 + codex-rs/core/src/features.rs | 12 + codex-rs/core/src/features/legacy.rs | 11 + codex-rs/core/src/sandboxing/assessment.rs | 275 ++++++++++++++++++ codex-rs/core/src/sandboxing/mod.rs | 3 + codex-rs/core/src/tools/orchestrator.rs | 25 ++ .../core/src/tools/runtimes/apply_patch.rs | 12 +- codex-rs/core/src/tools/runtimes/shell.rs | 16 +- .../core/src/tools/runtimes/unified_exec.rs | 14 +- codex-rs/core/src/tools/sandboxing.rs | 14 + .../templates/sandboxing/assessment_prompt.md | 27 ++ codex-rs/exec/src/lib.rs | 1 + codex-rs/mcp-server/src/codex_tool_config.rs | 1 + codex-rs/mcp-server/src/codex_tool_runner.rs | 2 + codex-rs/mcp-server/src/exec_approval.rs | 5 + codex-rs/mcp-server/tests/suite/codex_tool.rs | 1 + codex-rs/otel/src/otel_event_manager.rs | 59 ++++ codex-rs/protocol/src/approvals.rs | 91 ++++++ codex-rs/protocol/src/lib.rs | 1 + codex-rs/protocol/src/protocol.rs | 33 +-- .../tui/src/bottom_pane/approval_overlay.rs | 63 +++- codex-rs/tui/src/bottom_pane/mod.rs | 1 + codex-rs/tui/src/chatwidget.rs | 1 + codex-rs/tui/src/chatwidget/tests.rs | 6 + codex-rs/tui/src/lib.rs | 1 + 31 files changed, 701 insertions(+), 34 deletions(-) create mode 100644 codex-rs/core/src/sandboxing/assessment.rs create mode 100644 codex-rs/core/templates/sandboxing/assessment_prompt.md create mode 100644 codex-rs/protocol/src/approvals.rs diff --git a/codex-rs/app-server-protocol/src/protocol.rs b/codex-rs/app-server-protocol/src/protocol.rs index ceeeb48919..7340871f0f 100644 --- a/codex-rs/app-server-protocol/src/protocol.rs +++ b/codex-rs/app-server-protocol/src/protocol.rs @@ -17,6 +17,7 @@ use codex_protocol::protocol::EventMsg; use codex_protocol::protocol::FileChange; use codex_protocol::protocol::RateLimitSnapshot; use codex_protocol::protocol::ReviewDecision; +use codex_protocol::protocol::SandboxCommandAssessment; use codex_protocol::protocol::SandboxPolicy; use codex_protocol::protocol::TurnAbortReason; use paste::paste; @@ -847,6 +848,8 @@ pub struct ExecCommandApprovalParams { pub cwd: PathBuf, #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub risk: Option, pub parsed_cmd: Vec, } @@ -1063,6 +1066,7 @@ mod tests { command: vec!["echo".to_string(), "hello".to_string()], cwd: PathBuf::from("/tmp"), reason: Some("because tests".to_string()), + risk: None, parsed_cmd: vec![ParsedCommand::Unknown { cmd: "echo hello".to_string(), }], diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 5c10a89c38..ff1a43f5e5 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -1447,6 +1447,7 @@ async fn apply_bespoke_event_handling( command, cwd, reason, + risk, parsed_cmd, }) => { let params = ExecCommandApprovalParams { @@ -1455,6 +1456,7 @@ async fn apply_bespoke_event_handling( command, cwd, reason, + risk, parsed_cmd, }; let rx = outgoing @@ -1523,6 +1525,7 @@ async fn derive_config_from_params( include_view_image_tool: None, show_raw_agent_reasoning: None, tools_web_search_request: None, + experimental_sandbox_command_assessment: None, additional_writable_roots: Vec::new(), }; diff --git a/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs b/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs index 30b90f6e4a..6d3e2b42c4 100644 --- a/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs +++ b/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs @@ -311,6 +311,7 @@ async fn test_send_user_turn_changes_approval_policy_behavior() { ], cwd: working_directory.clone(), reason: None, + risk: None, parsed_cmd: vec![ParsedCommand::Unknown { cmd: "python3 -c 'print(42)'".to_string() }], diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index 62e003a915..de10d6406f 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -134,6 +134,14 @@ impl ModelClient { self.stream_with_task_kind(prompt, TaskKind::Regular).await } + pub fn config(&self) -> Arc { + Arc::clone(&self.config) + } + + pub fn provider(&self) -> &ModelProviderInfo { + &self.provider + } + pub(crate) async fn stream_with_task_kind( &self, prompt: &Prompt, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index b9e98e0cd8..4eba28c4aa 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -88,6 +88,7 @@ use crate::protocol::Op; use crate::protocol::RateLimitSnapshot; use crate::protocol::ReviewDecision; use crate::protocol::ReviewOutputEvent; +use crate::protocol::SandboxCommandAssessment; use crate::protocol::SandboxPolicy; use crate::protocol::SessionConfiguredEvent; use crate::protocol::StreamErrorEvent; @@ -755,6 +756,32 @@ impl Session { } } + pub(crate) async fn assess_sandbox_command( + &self, + turn_context: &TurnContext, + call_id: &str, + command: &[String], + failure_message: Option<&str>, + ) -> Option { + let config = turn_context.client.config(); + let provider = turn_context.client.provider().clone(); + let auth_manager = Arc::clone(&self.services.auth_manager); + let otel = self.services.otel_event_manager.clone(); + crate::sandboxing::assessment::assess_command( + config, + provider, + auth_manager, + &otel, + self.conversation_id, + call_id, + command, + &turn_context.sandbox_policy, + &turn_context.cwd, + failure_message, + ) + .await + } + /// Emit an exec approval request event and await the user's decision. /// /// The request is keyed by `sub_id`/`call_id` so matching responses are delivered @@ -767,6 +794,7 @@ impl Session { command: Vec, cwd: PathBuf, reason: Option, + risk: Option, ) -> ReviewDecision { let sub_id = turn_context.sub_id.clone(); // Add the tx_approve callback to the map before sending the request. @@ -792,6 +820,7 @@ impl Session { command, cwd, reason, + risk, parsed_cmd, }); self.send_event(turn_context, event).await; diff --git a/codex-rs/core/src/config.rs b/codex-rs/core/src/config.rs index 0af01f6857..b04aba5db5 100644 --- a/codex-rs/core/src/config.rs +++ b/codex-rs/core/src/config.rs @@ -223,6 +223,9 @@ pub struct Config { pub tools_web_search_request: bool, + /// When `true`, run a model-based assessment for commands denied by the sandbox. + pub experimental_sandbox_command_assessment: bool, + pub use_experimental_streamable_shell_tool: bool, /// If set to `true`, used only the experimental unified exec tool. @@ -958,6 +961,7 @@ pub struct ConfigToml { pub experimental_use_unified_exec_tool: Option, pub experimental_use_rmcp_client: Option, pub experimental_use_freeform_apply_patch: Option, + pub experimental_sandbox_command_assessment: Option, } impl From for UserSavedConfig { @@ -1118,6 +1122,7 @@ pub struct ConfigOverrides { pub include_view_image_tool: Option, pub show_raw_agent_reasoning: Option, pub tools_web_search_request: Option, + pub experimental_sandbox_command_assessment: Option, /// Additional directories that should be treated as writable roots for this session. pub additional_writable_roots: Vec, } @@ -1147,6 +1152,7 @@ impl Config { include_view_image_tool: include_view_image_tool_override, show_raw_agent_reasoning, tools_web_search_request: override_tools_web_search_request, + experimental_sandbox_command_assessment: sandbox_command_assessment_override, additional_writable_roots, } = overrides; @@ -1172,6 +1178,7 @@ impl Config { include_apply_patch_tool: include_apply_patch_tool_override, include_view_image_tool: include_view_image_tool_override, web_search_request: override_tools_web_search_request, + experimental_sandbox_command_assessment: sandbox_command_assessment_override, }; let features = Features::from_config(&cfg, &config_profile, feature_overrides); @@ -1269,6 +1276,8 @@ impl Config { let use_experimental_streamable_shell_tool = features.enabled(Feature::StreamableShell); let use_experimental_unified_exec_tool = features.enabled(Feature::UnifiedExec); let use_experimental_use_rmcp_client = features.enabled(Feature::RmcpClient); + let experimental_sandbox_command_assessment = + features.enabled(Feature::SandboxCommandAssessment); let forced_chatgpt_workspace_id = cfg.forced_chatgpt_workspace_id.as_ref().and_then(|value| { @@ -1390,6 +1399,7 @@ impl Config { forced_login_method, include_apply_patch_tool: include_apply_patch_tool_flag, tools_web_search_request, + experimental_sandbox_command_assessment, use_experimental_streamable_shell_tool, use_experimental_unified_exec_tool, use_experimental_use_rmcp_client, @@ -2873,6 +2883,7 @@ model_verbosity = "high" forced_login_method: None, include_apply_patch_tool: false, tools_web_search_request: false, + experimental_sandbox_command_assessment: false, use_experimental_streamable_shell_tool: false, use_experimental_unified_exec_tool: false, use_experimental_use_rmcp_client: false, @@ -2941,6 +2952,7 @@ model_verbosity = "high" forced_login_method: None, include_apply_patch_tool: false, tools_web_search_request: false, + experimental_sandbox_command_assessment: false, use_experimental_streamable_shell_tool: false, use_experimental_unified_exec_tool: false, use_experimental_use_rmcp_client: false, @@ -3024,6 +3036,7 @@ model_verbosity = "high" forced_login_method: None, include_apply_patch_tool: false, tools_web_search_request: false, + experimental_sandbox_command_assessment: false, use_experimental_streamable_shell_tool: false, use_experimental_unified_exec_tool: false, use_experimental_use_rmcp_client: false, @@ -3093,6 +3106,7 @@ model_verbosity = "high" forced_login_method: None, include_apply_patch_tool: false, tools_web_search_request: false, + experimental_sandbox_command_assessment: false, use_experimental_streamable_shell_tool: false, use_experimental_unified_exec_tool: false, use_experimental_use_rmcp_client: false, diff --git a/codex-rs/core/src/config_profile.rs b/codex-rs/core/src/config_profile.rs index 1986d42ffa..84b90f5adb 100644 --- a/codex-rs/core/src/config_profile.rs +++ b/codex-rs/core/src/config_profile.rs @@ -26,6 +26,7 @@ pub struct ConfigProfile { pub experimental_use_exec_command_tool: Option, pub experimental_use_rmcp_client: Option, pub experimental_use_freeform_apply_patch: Option, + pub experimental_sandbox_command_assessment: Option, pub tools_web_search: Option, pub tools_view_image: Option, /// Optional feature toggles scoped to this profile. diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index ead4604d54..8e8a203062 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -39,6 +39,8 @@ pub enum Feature { ViewImageTool, /// Allow the model to request web searches. WebSearchRequest, + /// Enable the model-based risk assessments for sandboxed commands. + SandboxCommandAssessment, } impl Feature { @@ -73,6 +75,7 @@ pub struct FeatureOverrides { pub include_apply_patch_tool: Option, pub include_view_image_tool: Option, pub web_search_request: Option, + pub experimental_sandbox_command_assessment: Option, } impl FeatureOverrides { @@ -137,6 +140,7 @@ impl Features { let mut features = Features::with_defaults(); let base_legacy = LegacyFeatureToggles { + experimental_sandbox_command_assessment: cfg.experimental_sandbox_command_assessment, experimental_use_freeform_apply_patch: cfg.experimental_use_freeform_apply_patch, experimental_use_exec_command_tool: cfg.experimental_use_exec_command_tool, experimental_use_unified_exec_tool: cfg.experimental_use_unified_exec_tool, @@ -154,6 +158,8 @@ impl Features { let profile_legacy = LegacyFeatureToggles { include_apply_patch_tool: config_profile.include_apply_patch_tool, include_view_image_tool: config_profile.include_view_image_tool, + experimental_sandbox_command_assessment: config_profile + .experimental_sandbox_command_assessment, experimental_use_freeform_apply_patch: config_profile .experimental_use_freeform_apply_patch, experimental_use_exec_command_tool: config_profile.experimental_use_exec_command_tool, @@ -236,4 +242,10 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::Stable, default_enabled: false, }, + FeatureSpec { + id: Feature::SandboxCommandAssessment, + key: "experimental_sandbox_command_assessment", + stage: Stage::Experimental, + default_enabled: false, + }, ]; diff --git a/codex-rs/core/src/features/legacy.rs b/codex-rs/core/src/features/legacy.rs index 22d8442ace..54f6a2d549 100644 --- a/codex-rs/core/src/features/legacy.rs +++ b/codex-rs/core/src/features/legacy.rs @@ -9,6 +9,10 @@ struct Alias { } const ALIASES: &[Alias] = &[ + Alias { + legacy_key: "experimental_sandbox_command_assessment", + feature: Feature::SandboxCommandAssessment, + }, Alias { legacy_key: "experimental_use_unified_exec_tool", feature: Feature::UnifiedExec, @@ -53,6 +57,7 @@ pub(crate) fn feature_for_key(key: &str) -> Option { pub struct LegacyFeatureToggles { pub include_apply_patch_tool: Option, pub include_view_image_tool: Option, + pub experimental_sandbox_command_assessment: Option, pub experimental_use_freeform_apply_patch: Option, pub experimental_use_exec_command_tool: Option, pub experimental_use_unified_exec_tool: Option, @@ -69,6 +74,12 @@ impl LegacyFeatureToggles { self.include_apply_patch_tool, "include_apply_patch_tool", ); + set_if_some( + features, + Feature::SandboxCommandAssessment, + self.experimental_sandbox_command_assessment, + "experimental_sandbox_command_assessment", + ); set_if_some( features, Feature::ApplyPatchFreeform, diff --git a/codex-rs/core/src/sandboxing/assessment.rs b/codex-rs/core/src/sandboxing/assessment.rs new file mode 100644 index 0000000000..f02a90b46e --- /dev/null +++ b/codex-rs/core/src/sandboxing/assessment.rs @@ -0,0 +1,275 @@ +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; +use std::time::Instant; + +use crate::AuthManager; +use crate::ModelProviderInfo; +use crate::client::ModelClient; +use crate::client_common::Prompt; +use crate::client_common::ResponseEvent; +use crate::config::Config; +use crate::protocol::SandboxPolicy; +use askama::Template; +use codex_otel::otel_event_manager::OtelEventManager; +use codex_protocol::ConversationId; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; +use codex_protocol::protocol::SandboxCommandAssessment; +use futures::StreamExt; +use serde_json::json; +use tokio::time::timeout; +use tracing::warn; + +const SANDBOX_ASSESSMENT_TIMEOUT: Duration = Duration::from_secs(5); + +const SANDBOX_RISK_CATEGORY_VALUES: &[&str] = &[ + "data_deletion", + "data_exfiltration", + "privilege_escalation", + "system_modification", + "network_access", + "resource_exhaustion", + "compliance", +]; + +#[derive(Template)] +#[template(path = "sandboxing/assessment_prompt.md", escape = "none")] +struct SandboxAssessmentPromptTemplate<'a> { + platform: &'a str, + sandbox_policy: &'a str, + filesystem_roots: Option<&'a str>, + working_directory: &'a str, + command_argv: &'a str, + command_joined: &'a str, + sandbox_failure_message: Option<&'a str>, +} + +#[allow(clippy::too_many_arguments)] +pub(crate) async fn assess_command( + config: Arc, + provider: ModelProviderInfo, + auth_manager: Arc, + parent_otel: &OtelEventManager, + conversation_id: ConversationId, + call_id: &str, + command: &[String], + sandbox_policy: &SandboxPolicy, + cwd: &Path, + failure_message: Option<&str>, +) -> Option { + if !config.experimental_sandbox_command_assessment || command.is_empty() { + return None; + } + + let command_json = serde_json::to_string(command).unwrap_or_else(|_| "[]".to_string()); + let command_joined = + shlex::try_join(command.iter().map(String::as_str)).unwrap_or_else(|_| command.join(" ")); + let failure = failure_message + .map(str::trim) + .filter(|msg| !msg.is_empty()) + .map(str::to_string); + + let cwd_str = cwd.to_string_lossy().to_string(); + let sandbox_summary = summarize_sandbox_policy(sandbox_policy); + let mut roots = sandbox_roots_for_prompt(sandbox_policy, cwd); + roots.sort(); + roots.dedup(); + + let platform = std::env::consts::OS; + let roots_formatted = roots.iter().map(|root| root.to_string_lossy().to_string()); + let filesystem_roots = match roots_formatted.collect::>() { + collected if collected.is_empty() => None, + collected => Some(collected.join(", ")), + }; + + let prompt_template = SandboxAssessmentPromptTemplate { + platform, + sandbox_policy: sandbox_summary.as_str(), + filesystem_roots: filesystem_roots.as_deref(), + working_directory: cwd_str.as_str(), + command_argv: command_json.as_str(), + command_joined: command_joined.as_str(), + sandbox_failure_message: failure.as_deref(), + }; + let rendered_prompt = match prompt_template.render() { + Ok(rendered) => rendered, + Err(err) => { + warn!("failed to render sandbox assessment prompt: {err}"); + return None; + } + }; + let (system_prompt_section, user_prompt_section) = match rendered_prompt.split_once("\n---\n") { + Some(split) => split, + None => { + warn!("rendered sandbox assessment prompt missing separator"); + return None; + } + }; + let system_prompt = system_prompt_section + .strip_prefix("System Prompt:\n") + .unwrap_or(system_prompt_section) + .trim() + .to_string(); + let user_prompt = user_prompt_section + .strip_prefix("User Prompt:\n") + .unwrap_or(user_prompt_section) + .trim() + .to_string(); + + let prompt = Prompt { + input: vec![ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { text: user_prompt }], + }], + tools: Vec::new(), + parallel_tool_calls: false, + base_instructions_override: Some(system_prompt), + output_schema: Some(sandbox_assessment_schema()), + }; + + let child_otel = + parent_otel.with_model(config.model.as_str(), config.model_family.slug.as_str()); + + let client = ModelClient::new( + Arc::clone(&config), + Some(auth_manager), + child_otel, + provider, + config.model_reasoning_effort, + config.model_reasoning_summary, + conversation_id, + ); + + let start = Instant::now(); + let assessment_result = timeout(SANDBOX_ASSESSMENT_TIMEOUT, async move { + let mut stream = client.stream(&prompt).await?; + let mut last_json: Option = None; + while let Some(event) = stream.next().await { + match event { + Ok(ResponseEvent::OutputItemDone(item)) => { + if let Some(text) = response_item_text(&item) { + last_json = Some(text); + } + } + Ok(ResponseEvent::RateLimits(_)) => {} + Ok(ResponseEvent::Completed { .. }) => break, + Ok(_) => continue, + Err(err) => return Err(err), + } + } + Ok(last_json) + }) + .await; + let duration = start.elapsed(); + parent_otel.sandbox_assessment_latency(call_id, duration); + + match assessment_result { + Ok(Ok(Some(raw))) => match serde_json::from_str::(raw.trim()) { + Ok(assessment) => { + parent_otel.sandbox_assessment( + call_id, + "success", + Some(assessment.risk_level), + &assessment.risk_categories, + duration, + ); + return Some(assessment); + } + Err(err) => { + warn!("failed to parse sandbox assessment JSON: {err}"); + parent_otel.sandbox_assessment(call_id, "parse_error", None, &[], duration); + } + }, + Ok(Ok(None)) => { + warn!("sandbox assessment response did not include any message"); + parent_otel.sandbox_assessment(call_id, "no_output", None, &[], duration); + } + Ok(Err(err)) => { + warn!("sandbox assessment failed: {err}"); + parent_otel.sandbox_assessment(call_id, "model_error", None, &[], duration); + } + Err(_) => { + warn!("sandbox assessment timed out"); + parent_otel.sandbox_assessment(call_id, "timeout", None, &[], duration); + } + } + + None +} + +fn summarize_sandbox_policy(policy: &SandboxPolicy) -> String { + match policy { + SandboxPolicy::DangerFullAccess => "danger-full-access".to_string(), + SandboxPolicy::ReadOnly => "read-only".to_string(), + SandboxPolicy::WorkspaceWrite { network_access, .. } => { + let network = if *network_access { + "network" + } else { + "no-network" + }; + format!("workspace-write (network_access={network})") + } + } +} + +fn sandbox_roots_for_prompt(policy: &SandboxPolicy, cwd: &Path) -> Vec { + let mut roots = vec![cwd.to_path_buf()]; + if let SandboxPolicy::WorkspaceWrite { writable_roots, .. } = policy { + roots.extend(writable_roots.iter().cloned()); + } + roots +} + +fn sandbox_assessment_schema() -> serde_json::Value { + json!({ + "type": "object", + "required": ["description", "risk_level", "risk_categories"], + "properties": { + "description": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "risk_level": { + "type": "string", + "enum": ["low", "medium", "high"] + }, + "risk_categories": { + "type": "array", + "items": { + "type": "string", + "enum": SANDBOX_RISK_CATEGORY_VALUES + } + } + }, + "additionalProperties": false + }) +} + +fn response_item_text(item: &ResponseItem) -> Option { + match item { + ResponseItem::Message { content, .. } => { + let mut buffers: Vec<&str> = Vec::new(); + for segment in content { + match segment { + ContentItem::InputText { text } | ContentItem::OutputText { text } => { + if !text.is_empty() { + buffers.push(text); + } + } + ContentItem::InputImage { .. } => {} + } + } + if buffers.is_empty() { + None + } else { + Some(buffers.join("\n")) + } + } + ResponseItem::FunctionCallOutput { output, .. } => Some(output.content.clone()), + _ => None, + } +} diff --git a/codex-rs/core/src/sandboxing/mod.rs b/codex-rs/core/src/sandboxing/mod.rs index d632b5da19..c11f3588fe 100644 --- a/codex-rs/core/src/sandboxing/mod.rs +++ b/codex-rs/core/src/sandboxing/mod.rs @@ -5,6 +5,9 @@ Build platform wrappers and produce ExecEnv for execution. Owns low‑level sandbox placement and transformation of portable CommandSpec into a ready‑to‑spawn environment. */ + +pub mod assessment; + use crate::exec::ExecToolCallOutput; use crate::exec::SandboxType; use crate::exec::StdoutStream; diff --git a/codex-rs/core/src/tools/orchestrator.rs b/codex-rs/core/src/tools/orchestrator.rs index 38aac5c1ed..e39c0703f8 100644 --- a/codex-rs/core/src/tools/orchestrator.rs +++ b/codex-rs/core/src/tools/orchestrator.rs @@ -7,9 +7,11 @@ retry without sandbox on denial (no re‑approval thanks to caching). */ use crate::error::CodexErr; use crate::error::SandboxErr; +use crate::error::get_error_message_ui; use crate::exec::ExecToolCallOutput; use crate::sandboxing::SandboxManager; use crate::tools::sandboxing::ApprovalCtx; +use crate::tools::sandboxing::ProvidesSandboxRetryData; use crate::tools::sandboxing::SandboxAttempt; use crate::tools::sandboxing::ToolCtx; use crate::tools::sandboxing::ToolError; @@ -38,6 +40,7 @@ impl ToolOrchestrator { ) -> Result where T: ToolRuntime, + Rq: ProvidesSandboxRetryData, { let otel = turn_ctx.client.get_otel_event_manager(); let otel_tn = &tool_ctx.tool_name; @@ -56,6 +59,7 @@ impl ToolOrchestrator { turn: turn_ctx, call_id: &tool_ctx.call_id, retry_reason: None, + risk: None, }; let decision = tool.start_approval_async(req, approval_ctx).await; @@ -107,12 +111,33 @@ impl ToolOrchestrator { // Ask for approval before retrying without sandbox. if !tool.should_bypass_approval(approval_policy, already_approved) { + let mut risk = None; + + if let Some(metadata) = req.sandbox_retry_data() { + let err = SandboxErr::Denied { + output: output.clone(), + }; + let friendly = get_error_message_ui(&CodexErr::Sandbox(err)); + let failure_summary = format!("failed in sandbox: {friendly}"); + + risk = tool_ctx + .session + .assess_sandbox_command( + turn_ctx, + &tool_ctx.call_id, + &metadata.command, + Some(failure_summary.as_str()), + ) + .await; + } + let reason_msg = build_denial_reason_from_output(output.as_ref()); let approval_ctx = ApprovalCtx { session: tool_ctx.session, turn: turn_ctx, call_id: &tool_ctx.call_id, retry_reason: Some(reason_msg), + risk, }; let decision = tool.start_approval_async(req, approval_ctx).await; diff --git a/codex-rs/core/src/tools/runtimes/apply_patch.rs b/codex-rs/core/src/tools/runtimes/apply_patch.rs index 18abbfee4a..0cdddd5087 100644 --- a/codex-rs/core/src/tools/runtimes/apply_patch.rs +++ b/codex-rs/core/src/tools/runtimes/apply_patch.rs @@ -10,7 +10,9 @@ use crate::sandboxing::CommandSpec; use crate::sandboxing::execute_env; use crate::tools::sandboxing::Approvable; use crate::tools::sandboxing::ApprovalCtx; +use crate::tools::sandboxing::ProvidesSandboxRetryData; use crate::tools::sandboxing::SandboxAttempt; +use crate::tools::sandboxing::SandboxRetryData; use crate::tools::sandboxing::Sandboxable; use crate::tools::sandboxing::SandboxablePreference; use crate::tools::sandboxing::ToolCtx; @@ -32,6 +34,12 @@ pub struct ApplyPatchRequest { pub codex_exe: Option, } +impl ProvidesSandboxRetryData for ApplyPatchRequest { + fn sandbox_retry_data(&self) -> Option { + None + } +} + #[derive(Default)] pub struct ApplyPatchRuntime; @@ -106,9 +114,10 @@ impl Approvable for ApplyPatchRuntime { let call_id = ctx.call_id.to_string(); let cwd = req.cwd.clone(); let retry_reason = ctx.retry_reason.clone(); + let risk = ctx.risk.clone(); let user_explicitly_approved = req.user_explicitly_approved; Box::pin(async move { - with_cached_approval(&session.services, key, || async move { + with_cached_approval(&session.services, key, move || async move { if let Some(reason) = retry_reason { session .request_command_approval( @@ -117,6 +126,7 @@ impl Approvable for ApplyPatchRuntime { vec!["apply_patch".to_string()], cwd, Some(reason), + risk, ) .await } else if user_explicitly_approved { diff --git a/codex-rs/core/src/tools/runtimes/shell.rs b/codex-rs/core/src/tools/runtimes/shell.rs index bfc2114fb3..f29224fcc1 100644 --- a/codex-rs/core/src/tools/runtimes/shell.rs +++ b/codex-rs/core/src/tools/runtimes/shell.rs @@ -12,7 +12,9 @@ use crate::sandboxing::execute_env; use crate::tools::runtimes::build_command_spec; use crate::tools::sandboxing::Approvable; use crate::tools::sandboxing::ApprovalCtx; +use crate::tools::sandboxing::ProvidesSandboxRetryData; use crate::tools::sandboxing::SandboxAttempt; +use crate::tools::sandboxing::SandboxRetryData; use crate::tools::sandboxing::Sandboxable; use crate::tools::sandboxing::SandboxablePreference; use crate::tools::sandboxing::ToolCtx; @@ -34,6 +36,15 @@ pub struct ShellRequest { pub justification: Option, } +impl ProvidesSandboxRetryData for ShellRequest { + fn sandbox_retry_data(&self) -> Option { + Some(SandboxRetryData { + command: self.command.clone(), + cwd: self.cwd.clone(), + }) + } +} + #[derive(Default)] pub struct ShellRuntime; @@ -90,13 +101,14 @@ impl Approvable for ShellRuntime { .retry_reason .clone() .or_else(|| req.justification.clone()); + let risk = ctx.risk.clone(); let session = ctx.session; let turn = ctx.turn; let call_id = ctx.call_id.to_string(); Box::pin(async move { - with_cached_approval(&session.services, key, || async move { + with_cached_approval(&session.services, key, move || async move { session - .request_command_approval(turn, call_id, command, cwd, reason) + .request_command_approval(turn, call_id, command, cwd, reason, risk) .await }) .await diff --git a/codex-rs/core/src/tools/runtimes/unified_exec.rs b/codex-rs/core/src/tools/runtimes/unified_exec.rs index c7d136ebfd..85c996387a 100644 --- a/codex-rs/core/src/tools/runtimes/unified_exec.rs +++ b/codex-rs/core/src/tools/runtimes/unified_exec.rs @@ -9,7 +9,9 @@ use crate::error::SandboxErr; use crate::tools::runtimes::build_command_spec; use crate::tools::sandboxing::Approvable; use crate::tools::sandboxing::ApprovalCtx; +use crate::tools::sandboxing::ProvidesSandboxRetryData; use crate::tools::sandboxing::SandboxAttempt; +use crate::tools::sandboxing::SandboxRetryData; use crate::tools::sandboxing::Sandboxable; use crate::tools::sandboxing::SandboxablePreference; use crate::tools::sandboxing::ToolCtx; @@ -31,6 +33,15 @@ pub struct UnifiedExecRequest { pub env: HashMap, } +impl ProvidesSandboxRetryData for UnifiedExecRequest { + fn sandbox_retry_data(&self) -> Option { + Some(SandboxRetryData { + command: self.command.clone(), + cwd: self.cwd.clone(), + }) + } +} + #[derive(serde::Serialize, Clone, Debug, Eq, PartialEq, Hash)] pub struct UnifiedExecApprovalKey { pub command: Vec, @@ -85,10 +96,11 @@ impl Approvable for UnifiedExecRuntime<'_> { let command = req.command.clone(); let cwd = req.cwd.clone(); let reason = ctx.retry_reason.clone(); + let risk = ctx.risk.clone(); Box::pin(async move { with_cached_approval(&session.services, key, || async move { session - .request_command_approval(turn, call_id, command, cwd, reason) + .request_command_approval(turn, call_id, command, cwd, reason, risk) .await }) .await diff --git a/codex-rs/core/src/tools/sandboxing.rs b/codex-rs/core/src/tools/sandboxing.rs index 0dd7a99f47..ad483e2f93 100644 --- a/codex-rs/core/src/tools/sandboxing.rs +++ b/codex-rs/core/src/tools/sandboxing.rs @@ -7,6 +7,7 @@ use crate::codex::Session; use crate::codex::TurnContext; use crate::error::CodexErr; +use crate::protocol::SandboxCommandAssessment; use crate::protocol::SandboxPolicy; use crate::sandboxing::CommandSpec; use crate::sandboxing::SandboxManager; @@ -18,6 +19,7 @@ use std::collections::HashMap; use std::fmt::Debug; use std::hash::Hash; use std::path::Path; +use std::path::PathBuf; use futures::Future; use futures::future::BoxFuture; @@ -81,6 +83,7 @@ pub(crate) struct ApprovalCtx<'a> { pub turn: &'a TurnContext, pub call_id: &'a str, pub retry_reason: Option, + pub risk: Option, } pub(crate) trait Approvable { @@ -156,6 +159,17 @@ pub(crate) struct ToolCtx<'a> { pub tool_name: String, } +/// Captures the command metadata needed to re-run a tool request without sandboxing. +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct SandboxRetryData { + pub command: Vec, + pub cwd: PathBuf, +} + +pub(crate) trait ProvidesSandboxRetryData { + fn sandbox_retry_data(&self) -> Option; +} + #[derive(Debug)] pub(crate) enum ToolError { Rejected(String), diff --git a/codex-rs/core/templates/sandboxing/assessment_prompt.md b/codex-rs/core/templates/sandboxing/assessment_prompt.md new file mode 100644 index 0000000000..7e5664a0ad --- /dev/null +++ b/codex-rs/core/templates/sandboxing/assessment_prompt.md @@ -0,0 +1,27 @@ +You are a security analyst evaluating shell commands that were blocked by a sandbox. Given the provided metadata, summarize the command's likely intent and assess the risk. Return strictly valid JSON with the keys: +- description (concise summary, at most two sentences) +- risk_level ("low", "medium", or "high") +- risk_categories (optional array of zero or more category strings) +Risk level examples: +- low: read-only inspections, listing files, printing configuration +- medium: modifying project files, installing dependencies, fetching artifacts from trusted sources +- high: deleting or overwriting data, exfiltrating secrets, escalating privileges, or disabling security controls +Recognized risk_categories: data_deletion, data_exfiltration, privilege_escalation, system_modification, network_access, resource_exhaustion, compliance. +Use multiple categories when appropriate. +If information is insufficient, choose the most cautious risk level supported by the evidence. +Respond with JSON only, without markdown code fences or extra commentary. + +--- + +Command metadata: +Platform: {{ platform }} +Sandbox policy: {{ sandbox_policy }} +{% if let Some(roots) = filesystem_roots %} +Filesystem roots: {{ roots }} +{% endif %} +Working directory: {{ working_directory }} +Command argv: {{ command_argv }} +Command (joined): {{ command_joined }} +{% if let Some(message) = sandbox_failure_message %} +Sandbox failure message: {{ message }} +{% endif %} diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index e470194cad..2e615df0c6 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -179,6 +179,7 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any include_view_image_tool: None, show_raw_agent_reasoning: oss.then_some(true), tools_web_search_request: None, + experimental_sandbox_command_assessment: None, additional_writable_roots: Vec::new(), }; // Parse `-c` overrides. diff --git a/codex-rs/mcp-server/src/codex_tool_config.rs b/codex-rs/mcp-server/src/codex_tool_config.rs index b4c4eb749d..24a5eec4b8 100644 --- a/codex-rs/mcp-server/src/codex_tool_config.rs +++ b/codex-rs/mcp-server/src/codex_tool_config.rs @@ -158,6 +158,7 @@ impl CodexToolCallParam { include_view_image_tool: None, show_raw_agent_reasoning: None, tools_web_search_request: None, + experimental_sandbox_command_assessment: None, additional_writable_roots: Vec::new(), }; diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index a59755008d..05d653aff9 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -178,6 +178,7 @@ async fn run_codex_tool_session_inner( cwd, call_id, reason: _, + risk, parsed_cmd, }) => { handle_exec_approval_request( @@ -190,6 +191,7 @@ async fn run_codex_tool_session_inner( event.id.clone(), call_id, parsed_cmd, + risk, ) .await; continue; diff --git a/codex-rs/mcp-server/src/exec_approval.rs b/codex-rs/mcp-server/src/exec_approval.rs index 44607b754d..033523ac0d 100644 --- a/codex-rs/mcp-server/src/exec_approval.rs +++ b/codex-rs/mcp-server/src/exec_approval.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use codex_core::CodexConversation; use codex_core::protocol::Op; use codex_core::protocol::ReviewDecision; +use codex_core::protocol::SandboxCommandAssessment; use codex_protocol::parse_command::ParsedCommand; use mcp_types::ElicitRequest; use mcp_types::ElicitRequestParamsRequestedSchema; @@ -37,6 +38,8 @@ pub struct ExecApprovalElicitRequestParams { pub codex_command: Vec, pub codex_cwd: PathBuf, pub codex_parsed_cmd: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + pub codex_risk: Option, } // TODO(mbolin): ExecApprovalResponse does not conform to ElicitResult. See: @@ -59,6 +62,7 @@ pub(crate) async fn handle_exec_approval_request( event_id: String, call_id: String, codex_parsed_cmd: Vec, + codex_risk: Option, ) { let escaped_command = shlex::try_join(command.iter().map(String::as_str)).unwrap_or_else(|_| command.join(" ")); @@ -81,6 +85,7 @@ pub(crate) async fn handle_exec_approval_request( codex_command: command, codex_cwd: cwd, codex_parsed_cmd, + codex_risk, }; let params_json = match serde_json::to_value(¶ms) { Ok(value) => value, diff --git a/codex-rs/mcp-server/tests/suite/codex_tool.rs b/codex-rs/mcp-server/tests/suite/codex_tool.rs index d7cd200f07..4ab83ca24e 100644 --- a/codex-rs/mcp-server/tests/suite/codex_tool.rs +++ b/codex-rs/mcp-server/tests/suite/codex_tool.rs @@ -196,6 +196,7 @@ fn create_expected_elicitation_request( codex_cwd: workdir.to_path_buf(), codex_call_id: "call1234".to_string(), codex_parsed_cmd, + codex_risk: None, })?), }) } diff --git a/codex-rs/otel/src/otel_event_manager.rs b/codex-rs/otel/src/otel_event_manager.rs index 486683dae0..4006df17d9 100644 --- a/codex-rs/otel/src/otel_event_manager.rs +++ b/codex-rs/otel/src/otel_event_manager.rs @@ -8,6 +8,8 @@ use codex_protocol::models::ResponseItem; use codex_protocol::protocol::AskForApproval; use codex_protocol::protocol::ReviewDecision; use codex_protocol::protocol::SandboxPolicy; +use codex_protocol::protocol::SandboxRiskCategory; +use codex_protocol::protocol::SandboxRiskLevel; use codex_protocol::user_input::UserInput; use eventsource_stream::Event as StreamEvent; use eventsource_stream::EventStreamError as StreamError; @@ -366,6 +368,63 @@ impl OtelEventManager { ); } + pub fn sandbox_assessment( + &self, + call_id: &str, + status: &str, + risk_level: Option, + risk_categories: &[SandboxRiskCategory], + duration: Duration, + ) { + let level = risk_level.map(|level| level.as_str()); + let categories = if risk_categories.is_empty() { + String::new() + } else { + risk_categories + .iter() + .map(SandboxRiskCategory::as_str) + .collect::>() + .join(", ") + }; + + tracing::event!( + tracing::Level::INFO, + event.name = "codex.sandbox_assessment", + event.timestamp = %timestamp(), + conversation.id = %self.metadata.conversation_id, + app.version = %self.metadata.app_version, + auth_mode = self.metadata.auth_mode, + user.account_id = self.metadata.account_id, + user.email = self.metadata.account_email, + terminal.type = %self.metadata.terminal_type, + model = %self.metadata.model, + slug = %self.metadata.slug, + call_id = %call_id, + status = %status, + risk_level = level, + risk_categories = categories, + duration_ms = %duration.as_millis(), + ); + } + + pub fn sandbox_assessment_latency(&self, call_id: &str, duration: Duration) { + tracing::event!( + tracing::Level::INFO, + event.name = "codex.sandbox_assessment_latency", + event.timestamp = %timestamp(), + conversation.id = %self.metadata.conversation_id, + app.version = %self.metadata.app_version, + auth_mode = self.metadata.auth_mode, + user.account_id = self.metadata.account_id, + user.email = self.metadata.account_email, + terminal.type = %self.metadata.terminal_type, + model = %self.metadata.model, + slug = %self.metadata.slug, + call_id = %call_id, + duration_ms = %duration.as_millis(), + ); + } + pub async fn log_tool_result( &self, tool_name: &str, diff --git a/codex-rs/protocol/src/approvals.rs b/codex-rs/protocol/src/approvals.rs new file mode 100644 index 0000000000..d608dba639 --- /dev/null +++ b/codex-rs/protocol/src/approvals.rs @@ -0,0 +1,91 @@ +use std::collections::HashMap; +use std::path::PathBuf; + +use crate::parse_command::ParsedCommand; +use crate::protocol::FileChange; +use schemars::JsonSchema; +use serde::Deserialize; +use serde::Serialize; +use ts_rs::TS; + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash, JsonSchema, TS)] +#[serde(rename_all = "snake_case")] +pub enum SandboxRiskLevel { + Low, + Medium, + High, +} + +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash, JsonSchema, TS)] +#[serde(rename_all = "snake_case")] +pub enum SandboxRiskCategory { + DataDeletion, + DataExfiltration, + PrivilegeEscalation, + SystemModification, + NetworkAccess, + ResourceExhaustion, + Compliance, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, JsonSchema, TS)] +pub struct SandboxCommandAssessment { + pub description: String, + pub risk_level: SandboxRiskLevel, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub risk_categories: Vec, +} + +impl SandboxRiskLevel { + pub fn as_str(&self) -> &'static str { + match self { + Self::Low => "low", + Self::Medium => "medium", + Self::High => "high", + } + } +} + +impl SandboxRiskCategory { + pub fn as_str(&self) -> &'static str { + match self { + Self::DataDeletion => "data_deletion", + Self::DataExfiltration => "data_exfiltration", + Self::PrivilegeEscalation => "privilege_escalation", + Self::SystemModification => "system_modification", + Self::NetworkAccess => "network_access", + Self::ResourceExhaustion => "resource_exhaustion", + Self::Compliance => "compliance", + } + } +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +pub struct ExecApprovalRequestEvent { + /// Identifier for the associated exec call, if available. + pub call_id: String, + /// The command to be executed. + pub command: Vec, + /// The command's working directory. + pub cwd: PathBuf, + /// Optional human-readable reason for the approval (e.g. retry without sandbox). + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// Optional model-provided risk assessment describing the blocked command. + #[serde(skip_serializing_if = "Option::is_none")] + pub risk: Option, + pub parsed_cmd: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +pub struct ApplyPatchApprovalRequestEvent { + /// Responses API call id for the associated patch apply call, if available. + pub call_id: String, + pub changes: HashMap, + /// Optional explanatory reason (e.g. request for extra write access). + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + /// When set, the agent is asking the user to allow writes under this root for the remainder of the session. + #[serde(skip_serializing_if = "Option::is_none")] + pub grant_root: Option, +} diff --git a/codex-rs/protocol/src/lib.rs b/codex-rs/protocol/src/lib.rs index 3b8747e63a..08ea753347 100644 --- a/codex-rs/protocol/src/lib.rs +++ b/codex-rs/protocol/src/lib.rs @@ -1,6 +1,7 @@ pub mod account; mod conversation_id; pub use conversation_id::ConversationId; +pub mod approvals; pub mod config_types; pub mod custom_prompts; pub mod items; diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 105f028049..cd10c2786b 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -34,6 +34,12 @@ use serde_with::serde_as; use strum_macros::Display; use ts_rs::TS; +pub use crate::approvals::ApplyPatchApprovalRequestEvent; +pub use crate::approvals::ExecApprovalRequestEvent; +pub use crate::approvals::SandboxCommandAssessment; +pub use crate::approvals::SandboxRiskCategory; +pub use crate::approvals::SandboxRiskLevel; + /// Open/close tags for special user-input blocks. Used across crates to avoid /// duplicated hardcoded strings. pub const USER_INSTRUCTIONS_OPEN_TAG: &str = ""; @@ -1126,33 +1132,6 @@ pub struct ExecCommandOutputDeltaEvent { pub chunk: Vec, } -#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -pub struct ExecApprovalRequestEvent { - /// Identifier for the associated exec call, if available. - pub call_id: String, - /// The command to be executed. - pub command: Vec, - /// The command's working directory. - pub cwd: PathBuf, - /// Optional human-readable reason for the approval (e.g. retry without sandbox). - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - pub parsed_cmd: Vec, -} - -#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -pub struct ApplyPatchApprovalRequestEvent { - /// Responses API call id for the associated patch apply call, if available. - pub call_id: String, - pub changes: HashMap, - /// Optional explanatory reason (e.g. request for extra write access). - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// When set, the agent is asking the user to allow writes under this root for the remainder of the session. - #[serde(skip_serializing_if = "Option::is_none")] - pub grant_root: Option, -} - #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct BackgroundEventEvent { pub message: String, diff --git a/codex-rs/tui/src/bottom_pane/approval_overlay.rs b/codex-rs/tui/src/bottom_pane/approval_overlay.rs index e8ecc084c4..ba36870005 100644 --- a/codex-rs/tui/src/bottom_pane/approval_overlay.rs +++ b/codex-rs/tui/src/bottom_pane/approval_overlay.rs @@ -19,6 +19,9 @@ use crate::render::renderable::Renderable; use codex_core::protocol::FileChange; use codex_core::protocol::Op; use codex_core::protocol::ReviewDecision; +use codex_core::protocol::SandboxCommandAssessment; +use codex_core::protocol::SandboxRiskCategory; +use codex_core::protocol::SandboxRiskLevel; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyEventKind; @@ -38,6 +41,7 @@ pub(crate) enum ApprovalRequest { id: String, command: Vec, reason: Option, + risk: Option, }, ApplyPatch { id: String, @@ -285,12 +289,17 @@ impl From for ApprovalRequestState { id, command, reason, + risk, } => { + let reason = reason.filter(|item| !item.is_empty()); + let has_reason = reason.is_some(); let mut header: Vec> = Vec::new(); - if let Some(reason) = reason - && !reason.is_empty() - { + if let Some(reason) = reason { header.push(Line::from(vec!["Reason: ".into(), reason.italic()])); + } + if let Some(risk) = risk.as_ref() { + header.extend(render_risk_lines(risk)); + } else if has_reason { header.push(Line::from("")); } let full_cmd = strip_bash_lc_and_escape(&command); @@ -330,6 +339,52 @@ impl From for ApprovalRequestState { } } +fn render_risk_lines(risk: &SandboxCommandAssessment) -> Vec> { + let level_span = match risk.risk_level { + SandboxRiskLevel::Low => "LOW".green().bold(), + SandboxRiskLevel::Medium => "MEDIUM".cyan().bold(), + SandboxRiskLevel::High => "HIGH".red().bold(), + }; + + let mut lines = Vec::new(); + + let description = risk.description.trim(); + if !description.is_empty() { + lines.push(Line::from(vec![ + "Summary: ".into(), + description.to_string().into(), + ])); + } + + let mut spans: Vec> = vec!["Risk: ".into(), level_span]; + if !risk.risk_categories.is_empty() { + spans.push(" (".into()); + for (idx, category) in risk.risk_categories.iter().enumerate() { + if idx > 0 { + spans.push(", ".into()); + } + spans.push(risk_category_label(*category).into()); + } + spans.push(")".into()); + } + + lines.push(Line::from(spans)); + lines.push(Line::from("")); + lines +} + +fn risk_category_label(category: SandboxRiskCategory) -> &'static str { + match category { + SandboxRiskCategory::DataDeletion => "data deletion", + SandboxRiskCategory::DataExfiltration => "data exfiltration", + SandboxRiskCategory::PrivilegeEscalation => "privilege escalation", + SandboxRiskCategory::SystemModification => "system modification", + SandboxRiskCategory::NetworkAccess => "network access", + SandboxRiskCategory::ResourceExhaustion => "resource exhaustion", + SandboxRiskCategory::Compliance => "compliance", + } +} + #[derive(Clone)] enum ApprovalVariant { Exec { id: String, command: Vec }, @@ -404,6 +459,7 @@ mod tests { id: "test".to_string(), command: vec!["echo".to_string(), "hi".to_string()], reason: Some("reason".to_string()), + risk: None, } } @@ -445,6 +501,7 @@ mod tests { id: "test".into(), command, reason: None, + risk: None, }; let view = ApprovalOverlay::new(exec_request, tx); diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 69405cd823..48bc0e9d4c 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -557,6 +557,7 @@ mod tests { id: "1".to_string(), command: vec!["echo".into(), "ok".into()], reason: None, + risk: None, } } diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 75dad91372..64f680d2ff 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -777,6 +777,7 @@ impl ChatWidget { id, command: ev.command, reason: ev.reason, + risk: ev.risk, }; self.bottom_pane.push_approval_request(request); self.request_redraw(); diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 738fc31e42..e25e04e09e 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -402,6 +402,7 @@ fn exec_approval_emits_proposed_command_and_decision_history() { reason: Some( "this is a test reason such as one that would be produced by the model".into(), ), + risk: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -444,6 +445,7 @@ fn exec_approval_decision_truncates_multiline_and_long_commands() { reason: Some( "this is a test reason such as one that would be produced by the model".into(), ), + risk: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -492,6 +494,7 @@ fn exec_approval_decision_truncates_multiline_and_long_commands() { command: vec!["bash".into(), "-lc".into(), long], cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), reason: None, + risk: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -1421,6 +1424,7 @@ fn approval_modal_exec_snapshot() { reason: Some( "this is a test reason such as one that would be produced by the model".into(), ), + risk: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -1465,6 +1469,7 @@ fn approval_modal_exec_without_reason_snapshot() { command: vec!["bash".into(), "-lc".into(), "echo hello world".into()], cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), reason: None, + risk: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { @@ -1675,6 +1680,7 @@ fn status_widget_and_approval_modal_snapshot() { reason: Some( "this is a test reason such as one that would be produced by the model".into(), ), + risk: None, parsed_cmd: vec![], }; chat.handle_codex_event(Event { diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 681b4c6ca1..50f6b1a0dd 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -148,6 +148,7 @@ pub async fn run_main( include_view_image_tool: None, show_raw_agent_reasoning: cli.oss.then_some(true), tools_web_search_request: cli.web_search.then_some(true), + experimental_sandbox_command_assessment: None, additional_writable_roots: additional_dirs, }; let raw_overrides = cli.config_overrides.raw_overrides.clone(); From 817d1508bc331d6b0ceca1719d826437d1237d4c Mon Sep 17 00:00:00 2001 From: Gabriel Peal Date: Fri, 24 Oct 2025 15:30:20 -0700 Subject: [PATCH 12/35] [MCP] Redact environment variable values in `/mcp` and `mcp get` (#5648) Fixes #5524 --- codex-rs/cli/src/mcp_cmd.rs | 12 ++- codex-rs/cli/tests/mcp_list.rs | 12 +-- codex-rs/common/src/format_env_display.rs | 14 +-- codex-rs/tui/src/history_cell.rs | 100 +++++++++++++++++- ...p_tools_output_masks_sensitive_values.snap | 27 +++++ 5 files changed, 142 insertions(+), 23 deletions(-) create mode 100644 codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__mcp_tools_output_masks_sensitive_values.snap diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index a4eefb9fd8..d750baecc9 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -523,10 +523,12 @@ async fn run_list(config_overrides: &CliConfigOverrides, list_args: ListArgs) -> .map(|entry| entry.auth_status) .unwrap_or(McpAuthStatus::Unsupported) .to_string(); + let bearer_token_display = + bearer_token_env_var.as_deref().unwrap_or("-").to_string(); http_rows.push([ name.clone(), url.clone(), - bearer_token_env_var.clone().unwrap_or("-".to_string()), + bearer_token_display, status, auth_status, ]); @@ -752,15 +754,15 @@ async fn run_get(config_overrides: &CliConfigOverrides, get_args: GetArgs) -> Re } => { println!(" transport: streamable_http"); println!(" url: {url}"); - let env_var = bearer_token_env_var.as_deref().unwrap_or("-"); - println!(" bearer_token_env_var: {env_var}"); + let bearer_token_display = bearer_token_env_var.as_deref().unwrap_or("-"); + println!(" bearer_token_env_var: {bearer_token_display}"); let headers_display = match http_headers { Some(map) if !map.is_empty() => { let mut pairs: Vec<_> = map.iter().collect(); pairs.sort_by(|(a, _), (b, _)| a.cmp(b)); pairs .into_iter() - .map(|(k, v)| format!("{k}={v}")) + .map(|(k, _)| format!("{k}=*****")) .collect::>() .join(", ") } @@ -773,7 +775,7 @@ async fn run_get(config_overrides: &CliConfigOverrides, get_args: GetArgs) -> Re pairs.sort_by(|(a, _), (b, _)| a.cmp(b)); pairs .into_iter() - .map(|(k, v)| format!("{k}={v}")) + .map(|(k, var)| format!("{k}={var}")) .collect::>() .join(", ") } diff --git a/codex-rs/cli/tests/mcp_list.rs b/codex-rs/cli/tests/mcp_list.rs index 6440660cdf..553c731576 100644 --- a/codex-rs/cli/tests/mcp_list.rs +++ b/codex-rs/cli/tests/mcp_list.rs @@ -68,9 +68,9 @@ async fn list_and_get_render_expected_output() -> Result<()> { assert!(stdout.contains("Name")); assert!(stdout.contains("docs")); assert!(stdout.contains("docs-server")); - assert!(stdout.contains("TOKEN=secret")); - assert!(stdout.contains("APP_TOKEN=$APP_TOKEN")); - assert!(stdout.contains("WORKSPACE_ID=$WORKSPACE_ID")); + assert!(stdout.contains("TOKEN=*****")); + assert!(stdout.contains("APP_TOKEN=*****")); + assert!(stdout.contains("WORKSPACE_ID=*****")); assert!(stdout.contains("Status")); assert!(stdout.contains("Auth")); assert!(stdout.contains("enabled")); @@ -119,9 +119,9 @@ async fn list_and_get_render_expected_output() -> Result<()> { assert!(stdout.contains("transport: stdio")); assert!(stdout.contains("command: docs-server")); assert!(stdout.contains("args: --port 4000")); - assert!(stdout.contains("env: TOKEN=secret")); - assert!(stdout.contains("APP_TOKEN=$APP_TOKEN")); - assert!(stdout.contains("WORKSPACE_ID=$WORKSPACE_ID")); + assert!(stdout.contains("env: TOKEN=*****")); + assert!(stdout.contains("APP_TOKEN=*****")); + assert!(stdout.contains("WORKSPACE_ID=*****")); assert!(stdout.contains("enabled: true")); assert!(stdout.contains("remove: codex mcp remove docs")); diff --git a/codex-rs/common/src/format_env_display.rs b/codex-rs/common/src/format_env_display.rs index 640be30783..fa35bdce25 100644 --- a/codex-rs/common/src/format_env_display.rs +++ b/codex-rs/common/src/format_env_display.rs @@ -6,15 +6,11 @@ pub fn format_env_display(env: Option<&HashMap>, env_vars: &[Str if let Some(map) = env { let mut pairs: Vec<_> = map.iter().collect(); pairs.sort_by(|(a, _), (b, _)| a.cmp(b)); - parts.extend( - pairs - .into_iter() - .map(|(key, value)| format!("{key}={value}")), - ); + parts.extend(pairs.into_iter().map(|(key, _)| format!("{key}=*****"))); } if !env_vars.is_empty() { - parts.extend(env_vars.iter().map(|var| format!("{var}=${var}"))); + parts.extend(env_vars.iter().map(|var| format!("{var}=*****"))); } if parts.is_empty() { @@ -42,14 +38,14 @@ mod tests { env.insert("B".to_string(), "two".to_string()); env.insert("A".to_string(), "one".to_string()); - assert_eq!(format_env_display(Some(&env), &[]), "A=one, B=two"); + assert_eq!(format_env_display(Some(&env), &[]), "A=*****, B=*****"); } #[test] fn formats_env_vars_with_dollar_prefix() { let vars = vec!["TOKEN".to_string(), "PATH".to_string()]; - assert_eq!(format_env_display(None, &vars), "TOKEN=$TOKEN, PATH=$PATH"); + assert_eq!(format_env_display(None, &vars), "TOKEN=*****, PATH=*****"); } #[test] @@ -60,7 +56,7 @@ mod tests { assert_eq!( format_env_display(Some(&env), &vars), - "HOME=/tmp, TOKEN=$TOKEN" + "HOME=*****, TOKEN=*****" ); } } diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 7228d39e9c..e630e00175 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -1047,7 +1047,10 @@ pub(crate) fn new_mcp_tools_output( return PlainHistoryCell { lines }; } - for (server, cfg) in config.mcp_servers.iter() { + let mut servers: Vec<_> = config.mcp_servers.iter().collect(); + servers.sort_by(|(a, _), (b, _)| a.cmp(b)); + + for (server, cfg) in servers { let prefix = format!("mcp__{server}__"); let mut names: Vec = tools .keys() @@ -1111,7 +1114,7 @@ pub(crate) fn new_mcp_tools_output( pairs.sort_by(|(a, _), (b, _)| a.cmp(b)); let display = pairs .into_iter() - .map(|(name, value)| format!("{name}={value}")) + .map(|(name, _)| format!("{name}=*****")) .collect::>() .join(", "); lines.push(vec![" • HTTP headers: ".into(), display.into()].into()); @@ -1123,7 +1126,7 @@ pub(crate) fn new_mcp_tools_output( pairs.sort_by(|(a, _), (b, _)| a.cmp(b)); let display = pairs .into_iter() - .map(|(name, env_var)| format!("{name}={env_var}")) + .map(|(name, var)| format!("{name}={var}")) .collect::>() .join(", "); lines.push(vec![" • Env HTTP headers: ".into(), display.into()].into()); @@ -1415,14 +1418,20 @@ mod tests { use codex_core::config::Config; use codex_core::config::ConfigOverrides; use codex_core::config::ConfigToml; + use codex_core::config_types::McpServerConfig; + use codex_core::config_types::McpServerTransportConfig; + use codex_core::protocol::McpAuthStatus; use codex_protocol::parse_command::ParsedCommand; use dirs::home_dir; use pretty_assertions::assert_eq; use serde_json::json; + use std::collections::HashMap; use mcp_types::CallToolResult; use mcp_types::ContentBlock; use mcp_types::TextContent; + use mcp_types::Tool; + use mcp_types::ToolInputSchema; fn test_config() -> Config { Config::load_from_base_config_with_overrides( @@ -1449,6 +1458,91 @@ mod tests { render_lines(&cell.transcript_lines(u16::MAX)) } + #[test] + fn mcp_tools_output_masks_sensitive_values() { + let mut config = test_config(); + let mut env = HashMap::new(); + env.insert("TOKEN".to_string(), "secret".to_string()); + let stdio_config = McpServerConfig { + transport: McpServerTransportConfig::Stdio { + command: "docs-server".to_string(), + args: vec![], + env: Some(env), + env_vars: vec!["APP_TOKEN".to_string()], + cwd: None, + }, + enabled: true, + startup_timeout_sec: None, + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + }; + config.mcp_servers.insert("docs".to_string(), stdio_config); + + let mut headers = HashMap::new(); + headers.insert("Authorization".to_string(), "Bearer secret".to_string()); + let mut env_headers = HashMap::new(); + env_headers.insert("X-API-Key".to_string(), "API_KEY_ENV".to_string()); + let http_config = McpServerConfig { + transport: McpServerTransportConfig::StreamableHttp { + url: "https://example.com/mcp".to_string(), + bearer_token_env_var: Some("MCP_TOKEN".to_string()), + http_headers: Some(headers), + env_http_headers: Some(env_headers), + }, + enabled: true, + startup_timeout_sec: None, + tool_timeout_sec: None, + enabled_tools: None, + disabled_tools: None, + }; + config.mcp_servers.insert("http".to_string(), http_config); + + let mut tools: HashMap = HashMap::new(); + tools.insert( + "mcp__docs__list".to_string(), + Tool { + annotations: None, + description: None, + input_schema: ToolInputSchema { + properties: None, + required: None, + r#type: "object".to_string(), + }, + name: "list".to_string(), + output_schema: None, + title: None, + }, + ); + tools.insert( + "mcp__http__ping".to_string(), + Tool { + annotations: None, + description: None, + input_schema: ToolInputSchema { + properties: None, + required: None, + r#type: "object".to_string(), + }, + name: "ping".to_string(), + output_schema: None, + title: None, + }, + ); + + let auth_statuses: HashMap = HashMap::new(); + let cell = new_mcp_tools_output( + &config, + tools, + HashMap::new(), + HashMap::new(), + &auth_statuses, + ); + let rendered = render_lines(&cell.display_lines(120)).join("\n"); + + insta::assert_snapshot!(rendered); + } + #[test] fn empty_agent_message_cell_transcript() { let cell = AgentMessageCell::new(vec![Line::default()], false); diff --git a/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__mcp_tools_output_masks_sensitive_values.snap b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__mcp_tools_output_masks_sensitive_values.snap new file mode 100644 index 0000000000..b9c0dfdee5 --- /dev/null +++ b/codex-rs/tui/src/snapshots/codex_tui__history_cell__tests__mcp_tools_output_masks_sensitive_values.snap @@ -0,0 +1,27 @@ +--- +source: tui/src/history_cell.rs +assertion_line: 1540 +expression: rendered +--- +/mcp + +🔌 MCP Tools + + • docs + • Status: enabled + • Auth: Unsupported + • Command: docs-server + • Env: TOKEN=*****, APP_TOKEN=***** + • Tools: list + • Resources: (none) + • Resource templates: (none) + + • http + • Status: enabled + • Auth: Unsupported + • URL: https://example.com/mcp + • HTTP headers: Authorization=***** + • Env HTTP headers: X-API-Key=API_KEY_ENV + • Tools: ping + • Resources: (none) + • Resource templates: (none) From e2e1b65da63e2baa5207386407fa4feccc4edaf7 Mon Sep 17 00:00:00 2001 From: Gabriel Peal Date: Fri, 24 Oct 2025 15:32:15 -0700 Subject: [PATCH 13/35] [MCP] Properly gate login after `mcp add` with `experimental_use_rmcp_client` (#5653) There was supposed to be a check here like in other places. --- codex-rs/cli/src/mcp_cmd.rs | 38 +++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/codex-rs/cli/src/mcp_cmd.rs b/codex-rs/cli/src/mcp_cmd.rs index d750baecc9..21676dece0 100644 --- a/codex-rs/cli/src/mcp_cmd.rs +++ b/codex-rs/cli/src/mcp_cmd.rs @@ -274,19 +274,33 @@ async fn run_add(config_overrides: &CliConfigOverrides, add_args: AddArgs) -> Re http_headers, env_http_headers, } = transport - && matches!(supports_oauth_login(&url).await, Ok(true)) { - println!("Detected OAuth support. Starting OAuth flow…"); - perform_oauth_login( - &name, - &url, - config.mcp_oauth_credentials_store_mode, - http_headers.clone(), - env_http_headers.clone(), - &Vec::new(), - ) - .await?; - println!("Successfully logged in."); + match supports_oauth_login(&url).await { + Ok(true) => { + if !config.features.enabled(Feature::RmcpClient) { + println!( + "MCP server supports login. Add `experimental_use_rmcp_client = true` \ + to your config.toml and run `codex mcp login {name}` to login." + ); + } else { + println!("Detected OAuth support. Starting OAuth flow…"); + perform_oauth_login( + &name, + &url, + config.mcp_oauth_credentials_store_mode, + http_headers.clone(), + env_http_headers.clone(), + &Vec::new(), + ) + .await?; + println!("Successfully logged in."); + } + } + Ok(false) => {} + Err(_) => println!( + "MCP server may or may not require login. Run `codex mcp login {name}` to login." + ), + } } Ok(()) From 6af83d86ffd6176b1949f877cae76735f4584a9c Mon Sep 17 00:00:00 2001 From: Anton Panasenko Date: Fri, 24 Oct 2025 15:41:52 -0700 Subject: [PATCH 14/35] [codex][app-server] introduce codex/event/raw_item events (#5578) --- codex-rs/app-server-protocol/src/protocol.rs | 2 + .../app-server/src/codex_message_processor.rs | 10 +- .../suite/codex_message_processor_flow.rs | 15 +- .../tests/suite/create_conversation.rs | 5 +- codex-rs/app-server/tests/suite/interrupt.rs | 5 +- .../app-server/tests/suite/send_message.rs | 211 +++++++++++++++++- codex-rs/core/src/codex.rs | 67 ++++-- codex-rs/core/src/response_processing.rs | 4 +- codex-rs/core/src/rollout/policy.rs | 1 + .../src/event_processor_with_human_output.rs | 1 + codex-rs/mcp-server/src/codex_tool_runner.rs | 1 + codex-rs/protocol/src/protocol.rs | 2 + codex-rs/tui/src/chatwidget.rs | 4 +- 13 files changed, 300 insertions(+), 28 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol.rs b/codex-rs/app-server-protocol/src/protocol.rs index 7340871f0f..71a4d77f8d 100644 --- a/codex-rs/app-server-protocol/src/protocol.rs +++ b/codex-rs/app-server-protocol/src/protocol.rs @@ -717,6 +717,8 @@ pub struct SendUserMessageResponse {} #[serde(rename_all = "camelCase")] pub struct AddConversationListenerParams { pub conversation_id: ConversationId, + #[serde(default)] + pub experimental_raw_events: bool, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index ff1a43f5e5..b2b242fb29 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -1256,7 +1256,10 @@ impl CodexMessageProcessor { request_id: RequestId, params: AddConversationListenerParams, ) { - let AddConversationListenerParams { conversation_id } = params; + let AddConversationListenerParams { + conversation_id, + experimental_raw_events, + } = params; let Ok(conversation) = self .conversation_manager .get_conversation(conversation_id) @@ -1293,6 +1296,11 @@ impl CodexMessageProcessor { } }; + if let EventMsg::RawResponseItem(_) = &event.msg + && !experimental_raw_events { + continue; + } + // For now, we send a notification for every event, // JSON-serializing the `Event` as-is, but these should // be migrated to be variants of `ServerNotification` diff --git a/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs b/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs index 6d3e2b42c4..5c010bf034 100644 --- a/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs +++ b/codex-rs/app-server/tests/suite/codex_message_processor_flow.rs @@ -103,7 +103,10 @@ async fn test_codex_jsonrpc_conversation_flow() { // 2) addConversationListener let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { conversation_id }) + .send_add_conversation_listener_request(AddConversationListenerParams { + conversation_id, + experimental_raw_events: false, + }) .await .expect("send addConversationListener"); let add_listener_resp: JSONRPCResponse = timeout( @@ -252,7 +255,10 @@ async fn test_send_user_turn_changes_approval_policy_behavior() { // 2) addConversationListener let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { conversation_id }) + .send_add_conversation_listener_request(AddConversationListenerParams { + conversation_id, + experimental_raw_events: false, + }) .await .expect("send addConversationListener"); let _: AddConversationSubscriptionResponse = @@ -459,7 +465,10 @@ async fn test_send_user_turn_updates_sandbox_and_cwd_between_turns() { .expect("deserialize newConversation response"); let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { conversation_id }) + .send_add_conversation_listener_request(AddConversationListenerParams { + conversation_id, + experimental_raw_events: false, + }) .await .expect("send addConversationListener"); timeout( diff --git a/codex-rs/app-server/tests/suite/create_conversation.rs b/codex-rs/app-server/tests/suite/create_conversation.rs index 37a0db84fa..f507baa30d 100644 --- a/codex-rs/app-server/tests/suite/create_conversation.rs +++ b/codex-rs/app-server/tests/suite/create_conversation.rs @@ -67,7 +67,10 @@ async fn test_conversation_create_and_send_message_ok() { // Add a listener so we receive notifications for this conversation (not strictly required for this test). let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { conversation_id }) + .send_add_conversation_listener_request(AddConversationListenerParams { + conversation_id, + experimental_raw_events: false, + }) .await .expect("send addConversationListener"); let _sub: AddConversationSubscriptionResponse = diff --git a/codex-rs/app-server/tests/suite/interrupt.rs b/codex-rs/app-server/tests/suite/interrupt.rs index 2500d20ff4..1c4c05e368 100644 --- a/codex-rs/app-server/tests/suite/interrupt.rs +++ b/codex-rs/app-server/tests/suite/interrupt.rs @@ -88,7 +88,10 @@ async fn shell_command_interruption() -> anyhow::Result<()> { // 2) addConversationListener let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { conversation_id }) + .send_add_conversation_listener_request(AddConversationListenerParams { + conversation_id, + experimental_raw_events: false, + }) .await?; let _add_listener_resp: JSONRPCResponse = timeout( DEFAULT_READ_TIMEOUT, diff --git a/codex-rs/app-server/tests/suite/send_message.rs b/codex-rs/app-server/tests/suite/send_message.rs index 22fb02dca9..b3f04c3393 100644 --- a/codex-rs/app-server/tests/suite/send_message.rs +++ b/codex-rs/app-server/tests/suite/send_message.rs @@ -15,6 +15,8 @@ use codex_app_server_protocol::RequestId; use codex_app_server_protocol::SendUserMessageParams; use codex_app_server_protocol::SendUserMessageResponse; use codex_protocol::ConversationId; +use codex_protocol::models::ContentItem; +use codex_protocol::models::ResponseItem; use pretty_assertions::assert_eq; use tempfile::TempDir; use tokio::time::timeout; @@ -62,7 +64,10 @@ async fn test_send_message_success() { // 2) addConversationListener let add_listener_id = mcp - .send_add_conversation_listener_request(AddConversationListenerParams { conversation_id }) + .send_add_conversation_listener_request(AddConversationListenerParams { + conversation_id, + experimental_raw_events: false, + }) .await .expect("send addConversationListener"); let add_listener_resp: JSONRPCResponse = timeout( @@ -124,6 +129,105 @@ async fn send_message(message: &str, conversation_id: ConversationId, mcp: &mut .expect("should have conversationId"), &serde_json::Value::String(conversation_id.to_string()) ); + + let raw_attempt = tokio::time::timeout( + std::time::Duration::from_millis(200), + mcp.read_stream_until_notification_message("codex/event/raw_response_item"), + ) + .await; + assert!( + raw_attempt.is_err(), + "unexpected raw item notification when not opted in" + ); +} + +#[tokio::test] +async fn test_send_message_raw_notifications_opt_in() { + let responses = vec![ + create_final_assistant_message_sse_response("Done").expect("build mock assistant message"), + ]; + let server = create_mock_chat_completions_server(responses).await; + + let codex_home = TempDir::new().expect("create temp dir"); + create_config_toml(codex_home.path(), &server.uri()).expect("write config.toml"); + + let mut mcp = McpProcess::new(codex_home.path()) + .await + .expect("spawn mcp process"); + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()) + .await + .expect("init timed out") + .expect("init failed"); + + let new_conv_id = mcp + .send_new_conversation_request(NewConversationParams::default()) + .await + .expect("send newConversation"); + let new_conv_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(new_conv_id)), + ) + .await + .expect("newConversation timeout") + .expect("newConversation resp"); + let NewConversationResponse { + conversation_id, .. + } = to_response::<_>(new_conv_resp).expect("deserialize newConversation response"); + + let add_listener_id = mcp + .send_add_conversation_listener_request(AddConversationListenerParams { + conversation_id, + experimental_raw_events: true, + }) + .await + .expect("send addConversationListener"); + let add_listener_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(add_listener_id)), + ) + .await + .expect("addConversationListener timeout") + .expect("addConversationListener resp"); + let AddConversationSubscriptionResponse { subscription_id: _ } = + to_response::<_>(add_listener_resp).expect("deserialize addConversationListener response"); + + let send_id = mcp + .send_send_user_message_request(SendUserMessageParams { + conversation_id, + items: vec![InputItem::Text { + text: "Hello".to_string(), + }], + }) + .await + .expect("send sendUserMessage"); + + let instructions = read_raw_response_item(&mut mcp, conversation_id).await; + assert_instructions_message(&instructions); + + let environment = read_raw_response_item(&mut mcp, conversation_id).await; + assert_environment_message(&environment); + + let response: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(send_id)), + ) + .await + .expect("sendUserMessage response timeout") + .expect("sendUserMessage response error"); + let _ok: SendUserMessageResponse = to_response::(response) + .expect("deserialize sendUserMessage response"); + + let user_message = read_raw_response_item(&mut mcp, conversation_id).await; + assert_user_message(&user_message, "Hello"); + + let assistant_message = read_raw_response_item(&mut mcp, conversation_id).await; + assert_assistant_message(&assistant_message, "Done"); + + let _ = tokio::time::timeout( + std::time::Duration::from_millis(250), + mcp.read_stream_until_notification_message("codex/event/task_complete"), + ) + .await; } #[tokio::test] @@ -184,3 +288,108 @@ stream_max_retries = 0 ), ) } + +#[expect(clippy::expect_used)] +async fn read_raw_response_item( + mcp: &mut McpProcess, + conversation_id: ConversationId, +) -> ResponseItem { + let raw_notification: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("codex/event/raw_response_item"), + ) + .await + .expect("codex/event/raw_response_item notification timeout") + .expect("codex/event/raw_response_item notification resp"); + + let serde_json::Value::Object(params) = raw_notification + .params + .expect("codex/event/raw_response_item should have params") + else { + panic!("codex/event/raw_response_item should have params"); + }; + + let conversation_id_value = params + .get("conversationId") + .and_then(|value| value.as_str()) + .expect("raw response item should include conversationId"); + + assert_eq!( + conversation_id_value, + conversation_id.to_string(), + "raw response item conversation mismatch" + ); + + let msg_value = params + .get("msg") + .cloned() + .expect("raw response item should include msg payload"); + + serde_json::from_value(msg_value).expect("deserialize raw response item") +} + +fn assert_instructions_message(item: &ResponseItem) { + match item { + ResponseItem::Message { role, content, .. } => { + assert_eq!(role, "user"); + let texts = content_texts(content); + assert!( + texts + .iter() + .any(|text| text.contains("")), + "expected instructions message, got {texts:?}" + ); + } + other => panic!("expected instructions message, got {other:?}"), + } +} + +fn assert_environment_message(item: &ResponseItem) { + match item { + ResponseItem::Message { role, content, .. } => { + assert_eq!(role, "user"); + let texts = content_texts(content); + assert!( + texts + .iter() + .any(|text| text.contains("")), + "expected environment context message, got {texts:?}" + ); + } + other => panic!("expected environment message, got {other:?}"), + } +} + +fn assert_user_message(item: &ResponseItem, expected_text: &str) { + match item { + ResponseItem::Message { role, content, .. } => { + assert_eq!(role, "user"); + let texts = content_texts(content); + assert_eq!(texts, vec![expected_text]); + } + other => panic!("expected user message, got {other:?}"), + } +} + +fn assert_assistant_message(item: &ResponseItem, expected_text: &str) { + match item { + ResponseItem::Message { role, content, .. } => { + assert_eq!(role, "assistant"); + let texts = content_texts(content); + assert_eq!(texts, vec![expected_text]); + } + other => panic!("expected assistant message, got {other:?}"), + } +} + +fn content_texts(content: &[ContentItem]) -> Vec<&str> { + content + .iter() + .filter_map(|item| match item { + ContentItem::InputText { text } | ContentItem::OutputText { text } => { + Some(text.as_str()) + } + _ => None, + }) + .collect() +} diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 4eba28c4aa..d89ce5f886 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -570,7 +570,6 @@ impl Session { // Dispatch the SessionConfiguredEvent first and then report any errors. // If resuming, include converted initial messages in the payload so UIs can render them immediately. let initial_messages = initial_history.get_event_msgs(); - sess.record_initial_history(initial_history).await; let events = std::iter::once(Event { id: INITIAL_SUBMIT_ID.to_owned(), @@ -589,6 +588,9 @@ impl Session { sess.send_event_raw(event).await; } + // record_initial_history can emit events. We record only after the SessionConfiguredEvent is emitted. + sess.record_initial_history(initial_history).await; + Ok(sess) } @@ -609,7 +611,7 @@ impl Session { InitialHistory::New => { // Build and record initial items (user instructions + environment context) let items = self.build_initial_context(&turn_context); - self.record_conversation_items(&items).await; + self.record_conversation_items(&turn_context, &items).await; } InitialHistory::Resumed(_) | InitialHistory::Forked(_) => { let rollout_items = conversation_history.get_rollout_items(); @@ -886,9 +888,14 @@ impl Session { /// Records input items: always append to conversation history and /// persist these response items to rollout. - pub(crate) async fn record_conversation_items(&self, items: &[ResponseItem]) { + pub(crate) async fn record_conversation_items( + &self, + turn_context: &TurnContext, + items: &[ResponseItem], + ) { self.record_into_history(items).await; self.persist_rollout_response_items(items).await; + self.send_raw_response_items(turn_context, items).await; } fn reconstruct_history_from_rollout( @@ -938,6 +945,13 @@ impl Session { self.persist_rollout_items(&rollout_items).await; } + async fn send_raw_response_items(&self, turn_context: &TurnContext, items: &[ResponseItem]) { + for item in items { + self.send_event(turn_context, EventMsg::RawResponseItem(item.clone())) + .await; + } + } + pub(crate) fn build_initial_context(&self, turn_context: &TurnContext) -> Vec { let mut items = Vec::::with_capacity(2); if let Some(user_instructions) = turn_context.user_instructions.as_deref() { @@ -1033,7 +1047,7 @@ impl Session { ) { let response_item: ResponseItem = response_input.clone().into(); // Add to conversation history and persist response item to rollout - self.record_conversation_items(std::slice::from_ref(&response_item)) + self.record_conversation_items(turn_context, std::slice::from_ref(&response_item)) .await; // Derive user message events and persist only UserMessage to rollout @@ -1224,8 +1238,11 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv if let Some(env_item) = sess .build_environment_update_item(previous_context.as_ref(), ¤t_context) { - sess.record_conversation_items(std::slice::from_ref(&env_item)) - .await; + sess.record_conversation_items( + ¤t_context, + std::slice::from_ref(&env_item), + ) + .await; } sess.spawn_task(Arc::clone(¤t_context), items, RegularTask) @@ -1597,7 +1614,8 @@ pub(crate) async fn run_task( } review_thread_history.get_history() } else { - sess.record_conversation_items(&pending_input).await; + sess.record_conversation_items(&turn_context, &pending_input) + .await; sess.history_snapshot().await }; @@ -1644,6 +1662,7 @@ pub(crate) async fn run_task( is_review_mode, &mut review_thread_history, &sess, + &turn_context, ) .await; @@ -1692,6 +1711,7 @@ pub(crate) async fn run_task( is_review_mode, &mut review_thread_history, &sess, + &turn_context, ) .await; // Aborted turn is reported via a different event. @@ -2202,11 +2222,14 @@ pub(crate) async fn exit_review_mode( } session - .record_conversation_items(&[ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { text: user_message }], - }]) + .record_conversation_items( + &turn_context, + &[ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { text: user_message }], + }], + ) .await; } @@ -2801,13 +2824,19 @@ mod tests { EventMsg::ExitedReviewMode(ev) => assert!(ev.review_output.is_none()), other => panic!("unexpected first event: {other:?}"), } - let second = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) - .await - .expect("timeout waiting for second event") - .expect("second event"); - match second.msg { - EventMsg::TurnAborted(e) => assert_eq!(TurnAbortReason::Interrupted, e.reason), - other => panic!("unexpected second event: {other:?}"), + loop { + let evt = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv()) + .await + .expect("timeout waiting for next event") + .expect("event"); + match evt.msg { + EventMsg::RawResponseItem(_) => continue, + EventMsg::TurnAborted(e) => { + assert_eq!(TurnAbortReason::Interrupted, e.reason); + break; + } + other => panic!("unexpected second event: {other:?}"), + } } let history = sess.history_snapshot().await; diff --git a/codex-rs/core/src/response_processing.rs b/codex-rs/core/src/response_processing.rs index b9139ce6c0..e18fdd45c8 100644 --- a/codex-rs/core/src/response_processing.rs +++ b/codex-rs/core/src/response_processing.rs @@ -1,4 +1,5 @@ use crate::codex::Session; +use crate::codex::TurnContext; use crate::conversation_history::ConversationHistory; use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseInputItem; @@ -13,6 +14,7 @@ pub(crate) async fn process_items( is_review_mode: bool, review_thread_history: &mut ConversationHistory, sess: &Session, + turn_context: &TurnContext, ) -> (Vec, Vec) { let mut items_to_record_in_conversation_history = Vec::::new(); let mut responses = Vec::::new(); @@ -104,7 +106,7 @@ pub(crate) async fn process_items( if is_review_mode { review_thread_history.record_items(items_to_record_in_conversation_history.iter()); } else { - sess.record_conversation_items(&items_to_record_in_conversation_history) + sess.record_conversation_items(turn_context, &items_to_record_in_conversation_history) .await; } } diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index fdf1f5ccb2..ea2954fac5 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -50,6 +50,7 @@ pub(crate) fn should_persist_event_msg(ev: &EventMsg) -> bool { | EventMsg::AgentReasoningDelta(_) | EventMsg::AgentReasoningRawContentDelta(_) | EventMsg::AgentReasoningSectionBreak(_) + | EventMsg::RawResponseItem(_) | EventMsg::SessionConfigured(_) | EventMsg::McpToolCallBegin(_) | EventMsg::McpToolCallEnd(_) 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 9a85c5de71..b07cd16d4b 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -519,6 +519,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { EventMsg::AgentReasoningRawContentDelta(_) => {} EventMsg::ItemStarted(_) => {} EventMsg::ItemCompleted(_) => {} + EventMsg::RawResponseItem(_) => {} } CodexStatus::Running } diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index 05d653aff9..a6af754d21 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -285,6 +285,7 @@ async fn run_codex_tool_session_inner( | EventMsg::UserMessage(_) | EventMsg::ShutdownComplete | EventMsg::ViewImageToolCall(_) + | EventMsg::RawResponseItem(_) | EventMsg::EnteredReviewMode(_) | EventMsg::ItemStarted(_) | EventMsg::ItemCompleted(_) diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index cd10c2786b..2334561e0e 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -527,6 +527,8 @@ pub enum EventMsg { /// Exited review mode with an optional final result to apply. ExitedReviewMode(ExitedReviewModeEvent), + RawResponseItem(ResponseItem), + ItemStarted(ItemStartedEvent), ItemCompleted(ItemCompletedEvent), } diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 64f680d2ff..833ae5d862 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1498,7 +1498,9 @@ impl ChatWidget { self.on_entered_review_mode(review_request) } EventMsg::ExitedReviewMode(review) => self.on_exited_review_mode(review), - EventMsg::ItemStarted(_) | EventMsg::ItemCompleted(_) => {} + EventMsg::RawResponseItem(_) + | EventMsg::ItemStarted(_) + | EventMsg::ItemCompleted(_) => {} } } From 0533bd2e7cc65c3ae46b51baa3a9128eda230492 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Fri, 24 Oct 2025 18:31:24 -0500 Subject: [PATCH 15/35] Fixed flaky unit test (#5654) This PR fixes a test that is sporadically failing in CI. The problem is that two unit tests (the older `login_and_cancel_chatgpt` and a recently added `login_chatgpt_includes_forced_workspace_query_param`) exercise code paths that start the login server. The server binds to a hard-coded localhost port number, so attempts to start more than one server at the same time will fail. If these two tests happen to run concurrently, one of them will fail. To fix this, I've added a simple mutex. We can use this same mutex for future tests that use the same pattern. --- codex-rs/Cargo.lock | 1 + codex-rs/app-server/Cargo.toml | 1 + codex-rs/app-server/tests/suite/login.rs | 5 +++++ 3 files changed, 7 insertions(+) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 0d8522a67b..a2e49fc506 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -853,6 +853,7 @@ dependencies = [ "pretty_assertions", "serde", "serde_json", + "serial_test", "tempfile", "tokio", "toml", diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 5efbefd6b0..c1efb2ef93 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -47,6 +47,7 @@ base64 = { workspace = true } core_test_support = { workspace = true } os_info = { workspace = true } pretty_assertions = { workspace = true } +serial_test = { workspace = true } tempfile = { workspace = true } toml = { workspace = true } wiremock = { workspace = true } diff --git a/codex-rs/app-server/tests/suite/login.rs b/codex-rs/app-server/tests/suite/login.rs index 220769b7d6..d4d6374bc4 100644 --- a/codex-rs/app-server/tests/suite/login.rs +++ b/codex-rs/app-server/tests/suite/login.rs @@ -13,6 +13,7 @@ use codex_app_server_protocol::LoginChatGptResponse; use codex_app_server_protocol::LogoutChatGptResponse; use codex_app_server_protocol::RequestId; use codex_login::login_with_api_key; +use serial_test::serial; use tempfile::TempDir; use tokio::time::timeout; @@ -94,6 +95,8 @@ async fn logout_chatgpt_removes_auth() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +// Serialize tests that launch the login server since it binds to a fixed port. +#[serial(login_port)] async fn login_and_cancel_chatgpt() { let codex_home = TempDir::new().unwrap_or_else(|e| panic!("create tempdir: {e}")); create_config_toml(codex_home.path()).unwrap_or_else(|err| panic!("write config.toml: {err}")); @@ -208,6 +211,8 @@ async fn login_chatgpt_rejected_when_forced_api() { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] +// Serialize tests that launch the login server since it binds to a fixed port. +#[serial(login_port)] async fn login_chatgpt_includes_forced_workspace_query_param() { let codex_home = TempDir::new().unwrap_or_else(|e| panic!("create tempdir: {e}")); create_config_toml_forced_workspace(codex_home.path(), "ws-forced") From 71f838389bac8ef07d6024b64f55ebfdee9d392e Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Fri, 24 Oct 2025 22:28:14 -0700 Subject: [PATCH 16/35] Improve feedback (#5661) image image image --- codex-rs/core/src/error.rs | 4 +- codex-rs/feedback/src/lib.rs | 130 +++- codex-rs/tui/src/app.rs | 9 + codex-rs/tui/src/app_event.rs | 19 + codex-rs/tui/src/bottom_pane/feedback_view.rs | 605 +++++++++++++----- codex-rs/tui/src/bottom_pane/mod.rs | 4 +- ...view__tests__feedback_view_bad_result.snap | 9 + ...edback_view__tests__feedback_view_bug.snap | 9 + ...iew__tests__feedback_view_good_result.snap | 9 + ...back_view__tests__feedback_view_other.snap | 9 + codex-rs/tui/src/chatwidget.rs | 59 +- ...dget__tests__feedback_selection_popup.snap | 11 + ..._tests__feedback_upload_consent_popup.snap | 11 + ...tests__interrupted_turn_error_message.snap | 5 + codex-rs/tui/src/chatwidget/tests.rs | 54 ++ 15 files changed, 758 insertions(+), 189 deletions(-) create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bad_result.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bug.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_good_result.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_other.snap create mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_selection_popup.snap create mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap create mode 100644 codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__interrupted_turn_error_message.snap diff --git a/codex-rs/core/src/error.rs b/codex-rs/core/src/error.rs index e733b3c67f..0901e426ad 100644 --- a/codex-rs/core/src/error.rs +++ b/codex-rs/core/src/error.rs @@ -55,7 +55,7 @@ pub enum SandboxErr { #[derive(Error, Debug)] pub enum CodexErr { // todo(aibrahim): git rid of this error carrying the dangling artifacts - #[error("turn aborted")] + #[error("turn aborted. Something went wrong? Hit `/feedback` to report the issue.")] TurnAborted { dangling_artifacts: Vec, }, @@ -91,7 +91,7 @@ pub enum CodexErr { /// Returned by run_command_stream when the user pressed Ctrl‑C (SIGINT). Session uses this to /// surface a polite FunctionCallOutput back to the model instead of crashing the CLI. - #[error("interrupted (Ctrl-C)")] + #[error("interrupted (Ctrl-C). Something went wrong? Hit `/feedback` to report the issue.")] Interrupted, /// Unexpected HTTP status code. diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index 2399646311..fc696f2ab1 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -167,8 +167,18 @@ impl CodexLogSnapshot { Ok(path) } - pub fn upload_to_sentry(&self) -> Result<()> { + /// Uploads feedback to Sentry with both the in-memory Codex logs and an optional + /// rollout file attached. Also records metadata such as classification, + /// reason (free-form note), and CLI version as Sentry tags or message. + pub fn upload_feedback_with_rollout( + &self, + classification: &str, + reason: Option<&str>, + cli_version: &str, + rollout_path: Option<&std::path::Path>, + ) -> Result<()> { use std::collections::BTreeMap; + use std::fs; use std::str::FromStr; use std::sync::Arc; @@ -182,22 +192,47 @@ impl CodexLogSnapshot { use sentry::transports::DefaultTransportFactory; use sentry::types::Dsn; + // Build Sentry client let client = Client::from_config(ClientOptions { dsn: Some(Dsn::from_str(SENTRY_DSN).map_err(|e| anyhow!("invalid DSN: {}", e))?), transport: Some(Arc::new(DefaultTransportFactory {})), ..Default::default() }); - let tags = BTreeMap::from([(String::from("thread_id"), self.thread_id.to_string())]); + // Tags: thread id, classification, cli_version + let mut tags = BTreeMap::from([ + (String::from("thread_id"), self.thread_id.to_string()), + (String::from("classification"), classification.to_string()), + (String::from("cli_version"), cli_version.to_string()), + ]); + // Reason (freeform) – include entire note as a tag; keep title in message. + if let Some(r) = reason { + tags.insert(String::from("reason"), r.to_string()); + } + + // Elevate level for error-like classifications + let level = match classification { + "bug" | "bad_result" => Level::Error, + _ => Level::Info, + }; + + let mut envelope = Envelope::new(); + // Title is the message in Sentry: "[Classification]: Codex session " + let title = format!( + "[{}]: Codex session {}", + display_classification(classification), + self.thread_id + ); let event = Event { - level: Level::Error, - message: Some("Codex Log Upload ".to_string() + &self.thread_id), + level, + message: Some(title), tags, ..Default::default() }; - let mut envelope = Envelope::new(); envelope.add_item(EnvelopeItem::Event(event)); + + // Attachment 1: Codex logs snapshot envelope.add_item(EnvelopeItem::Attachment(Attachment { buffer: self.bytes.clone(), filename: String::from("codex-logs.log"), @@ -205,11 +240,96 @@ impl CodexLogSnapshot { ty: None, })); + // Attachment 2: rollout file (if provided and readable) + if let Some((path, data)) = rollout_path.and_then(|p| fs::read(p).ok().map(|d| (p, d))) { + // Name the file by suffix so users can spot it. + let fname = path + .file_name() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_else(|| "rollout.jsonl".to_string()); + envelope.add_item(EnvelopeItem::Attachment(Attachment { + buffer: data, + filename: fname, + content_type: Some("application/jsonl".to_string()), + ty: None, + })); + } + client.send_envelope(envelope); client.flush(Some(Duration::from_secs(UPLOAD_TIMEOUT_SECS))); Ok(()) } + + /// Upload a metadata-only feedback event (no attachments). Includes classification, + /// optional reason, CLI version and thread ID as tags. + pub fn upload_feedback_metadata_only( + &self, + classification: &str, + reason: Option<&str>, + cli_version: &str, + ) -> Result<()> { + use std::collections::BTreeMap; + use std::str::FromStr; + use std::sync::Arc; + + use sentry::Client; + use sentry::ClientOptions; + use sentry::protocol::Envelope; + use sentry::protocol::EnvelopeItem; + use sentry::protocol::Event; + use sentry::protocol::Level; + use sentry::transports::DefaultTransportFactory; + use sentry::types::Dsn; + + let client = Client::from_config(ClientOptions { + dsn: Some(Dsn::from_str(SENTRY_DSN).map_err(|e| anyhow!("invalid DSN: {}", e))?), + transport: Some(Arc::new(DefaultTransportFactory {})), + ..Default::default() + }); + + let mut tags = BTreeMap::from([ + (String::from("thread_id"), self.thread_id.to_string()), + (String::from("classification"), classification.to_string()), + (String::from("cli_version"), cli_version.to_string()), + ]); + if let Some(r) = reason { + tags.insert(String::from("reason"), r.to_string()); + } + + let level = match classification { + "bug" | "bad_result" => Level::Error, + _ => Level::Info, + }; + + let mut envelope = Envelope::new(); + // Title is the message in Sentry: "[Classification]: Codex session " + let title = format!( + "[{}]: Codex session {}", + display_classification(classification), + self.thread_id + ); + let event = Event { + level, + message: Some(title), + tags, + ..Default::default() + }; + envelope.add_item(EnvelopeItem::Event(event)); + + client.send_envelope(envelope); + client.flush(Some(Duration::from_secs(UPLOAD_TIMEOUT_SECS))); + Ok(()) + } +} + +fn display_classification(classification: &str) -> String { + match classification { + "bug" => "Bug".to_string(), + "bad_result" => "Bad result".to_string(), + "good_result" => "Good result".to_string(), + _ => "Other".to_string(), + } } #[cfg(test)] diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 5a47e40f91..c8eab72969 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -360,6 +360,15 @@ impl App { AppEvent::OpenFullAccessConfirmation { preset } => { self.chat_widget.open_full_access_confirmation(preset); } + AppEvent::OpenFeedbackNote { + category, + include_logs, + } => { + self.chat_widget.open_feedback_note(category, include_logs); + } + AppEvent::OpenFeedbackConsent { category } => { + self.chat_widget.open_feedback_consent(category); + } AppEvent::PersistModelSelection { model, effort } => { let profile = self.active_profile.as_deref(); match persist_model_selection(&self.config.codex_home, profile, &model, effort) diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 8592032df3..8b14b0be6f 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -101,4 +101,23 @@ pub(crate) enum AppEvent { /// Open the approval popup. FullScreenApprovalRequest(ApprovalRequest), + + /// Open the feedback note entry overlay after the user selects a category. + OpenFeedbackNote { + category: FeedbackCategory, + include_logs: bool, + }, + + /// Open the upload consent popup for feedback after selecting a category. + OpenFeedbackConsent { + category: FeedbackCategory, + }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum FeedbackCategory { + BadResult, + GoodResult, + Bug, + Other, } diff --git a/codex-rs/tui/src/bottom_pane/feedback_view.rs b/codex-rs/tui/src/bottom_pane/feedback_view.rs index 9c75e32bdf..fce3a795c3 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_view.rs @@ -1,165 +1,432 @@ -use crate::app_event::AppEvent; -use crate::app_event_sender::AppEventSender; -use crate::history_cell; -use crate::history_cell::PlainHistoryCell; -use crate::render::renderable::Renderable; +use std::cell::RefCell; +use std::path::PathBuf; + +use crossterm::event::KeyCode; +use crossterm::event::KeyEvent; +use crossterm::event::KeyModifiers; use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::style::Stylize; use ratatui::text::Line; -use std::path::PathBuf; +use ratatui::text::Span; +use ratatui::widgets::Clear; +use ratatui::widgets::Paragraph; +use ratatui::widgets::StatefulWidgetRef; +use ratatui::widgets::Widget; -use super::BottomPane; -use super::SelectionAction; -use super::SelectionItem; -use super::SelectionViewParams; +use crate::app_event::AppEvent; +use crate::app_event::FeedbackCategory; +use crate::app_event_sender::AppEventSender; +use crate::history_cell; +use crate::render::renderable::Renderable; + +use super::CancellationEvent; +use super::bottom_pane_view::BottomPaneView; +use super::popup_consts::standard_popup_hint_line; +use super::textarea::TextArea; +use super::textarea::TextAreaState; const BASE_ISSUE_URL: &str = "https://github.com/openai/codex/issues/new?template=2-bug-report.yml"; -pub(crate) struct FeedbackView; +/// Minimal input overlay to collect an optional feedback note, then upload +/// both logs and rollout with classification + metadata. +pub(crate) struct FeedbackNoteView { + category: FeedbackCategory, + snapshot: codex_feedback::CodexLogSnapshot, + rollout_path: Option, + app_event_tx: AppEventSender, + include_logs: bool, -impl FeedbackView { - pub fn show( - bottom_pane: &mut BottomPane, - file_path: PathBuf, + // UI state + textarea: TextArea, + textarea_state: RefCell, + complete: bool, +} + +impl FeedbackNoteView { + pub(crate) fn new( + category: FeedbackCategory, snapshot: codex_feedback::CodexLogSnapshot, - ) { - bottom_pane.show_selection_view(Self::selection_params(file_path, snapshot)); + rollout_path: Option, + app_event_tx: AppEventSender, + include_logs: bool, + ) -> Self { + Self { + category, + snapshot, + rollout_path, + app_event_tx, + include_logs, + textarea: TextArea::new(), + textarea_state: RefCell::new(TextAreaState::default()), + complete: false, + } } - fn selection_params( - file_path: PathBuf, - snapshot: codex_feedback::CodexLogSnapshot, - ) -> SelectionViewParams { - let header = FeedbackHeader::new(file_path); + fn submit(&mut self) { + let note = self.textarea.text().trim().to_string(); + let reason_opt = if note.is_empty() { + None + } else { + Some(note.as_str()) + }; + let rollout_path_ref = self.rollout_path.as_deref(); + let classification = feedback_classification(self.category); - let thread_id = snapshot.thread_id.clone(); + let cli_version = crate::version::CODEX_CLI_VERSION; + let mut thread_id = self.snapshot.thread_id.clone(); - let upload_action_tread_id = thread_id.clone(); - let upload_action: SelectionAction = Box::new(move |tx: &AppEventSender| { - match snapshot.upload_to_sentry() { - Ok(()) => { - let issue_url = format!( - "{BASE_ISSUE_URL}&steps=Uploaded%20thread:%20{upload_action_tread_id}", - ); - tx.send(AppEvent::InsertHistoryCell(Box::new(PlainHistoryCell::new(vec![ - Line::from( - "• Codex logs uploaded. Please open an issue using the following URL:", - ), + let result = if self.include_logs { + self.snapshot.upload_feedback_with_rollout( + classification, + reason_opt, + cli_version, + rollout_path_ref, + ) + } else { + self.snapshot + .upload_feedback_metadata_only(classification, reason_opt, cli_version) + }; + + match result { + Ok(()) => { + let issue_url = format!("{BASE_ISSUE_URL}&steps=Uploaded%20thread:%20{thread_id}"); + let prefix = if self.include_logs { + "• Feedback uploaded." + } else { + "• Feedback recorded (no logs)." + }; + self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new( + history_cell::PlainHistoryCell::new(vec![ + Line::from(format!( + "{prefix} Please open an issue using the following URL:" + )), "".into(), Line::from(vec![" ".into(), issue_url.cyan().underlined()]), "".into(), - Line::from(vec![" Or mention your thread ID ".into(), upload_action_tread_id.clone().bold(), " in an existing issue.".into()]) - ])))); - } - Err(e) => { - tx.send(AppEvent::InsertHistoryCell(Box::new( - history_cell::new_error_event(format!("Failed to upload logs: {e}")), - ))); - } - } - }); - - let upload_item = SelectionItem { - name: "Yes".to_string(), - description: Some( - "Share the current Codex session logs with the team for troubleshooting." - .to_string(), - ), - actions: vec![upload_action], - dismiss_on_select: true, - ..Default::default() - }; - - let no_action: SelectionAction = Box::new(move |tx: &AppEventSender| { - let issue_url = format!("{BASE_ISSUE_URL}&steps=Thread%20ID:%20{thread_id}",); - - tx.send(AppEvent::InsertHistoryCell(Box::new( - PlainHistoryCell::new(vec![ - Line::from("• Please open an issue using the following URL:"), - "".into(), - Line::from(vec![" ".into(), issue_url.cyan().underlined()]), - "".into(), - Line::from(vec![ - " Or mention your thread ID ".into(), - thread_id.clone().bold(), - " in an existing issue.".into(), + Line::from(vec![ + " Or mention your thread ID ".into(), + std::mem::take(&mut thread_id).bold(), + " in an existing issue.".into(), + ]), ]), - ]), - ))); - }); + ))); + } + Err(e) => { + self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new( + history_cell::new_error_event(format!("Failed to upload feedback: {e}")), + ))); + } + } + self.complete = true; + } +} - let no_item = SelectionItem { - name: "No".to_string(), - actions: vec![no_action], - dismiss_on_select: true, - ..Default::default() - }; - - let cancel_item = SelectionItem { - name: "Cancel".to_string(), - dismiss_on_select: true, - ..Default::default() - }; - - SelectionViewParams { - header: Box::new(header), - items: vec![upload_item, no_item, cancel_item], - ..Default::default() +impl BottomPaneView for FeedbackNoteView { + fn handle_key_event(&mut self, key_event: KeyEvent) { + match key_event { + KeyEvent { + code: KeyCode::Esc, .. + } => { + self.on_ctrl_c(); + } + KeyEvent { + code: KeyCode::Enter, + modifiers: KeyModifiers::NONE, + .. + } => { + self.submit(); + } + KeyEvent { + code: KeyCode::Enter, + .. + } => { + self.textarea.input(key_event); + } + other => { + self.textarea.input(other); + } } } -} -struct FeedbackHeader { - file_path: PathBuf, -} - -impl FeedbackHeader { - fn new(file_path: PathBuf) -> Self { - Self { file_path } + fn on_ctrl_c(&mut self) -> CancellationEvent { + self.complete = true; + CancellationEvent::Handled } - fn lines(&self) -> Vec> { - vec![ - Line::from("Do you want to upload logs before reporting issue?".bold()), - "".into(), - Line::from( - "Logs may include the full conversation history of this Codex process, including prompts, tool calls, and their results.", - ), - Line::from( - "These logs are retained for 90 days and are used solely for troubleshooting and diagnostic purposes.", - ), - "".into(), - Line::from(vec![ - "You can review the exact content of the logs before they’re uploaded at:".into(), - ]), - Line::from(self.file_path.display().to_string().dim()), - "".into(), - ] + fn is_complete(&self) -> bool { + self.complete + } + + fn handle_paste(&mut self, pasted: String) -> bool { + if pasted.is_empty() { + return false; + } + self.textarea.insert_str(&pasted); + true + } + + fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> { + if area.height < 2 || area.width <= 2 { + return None; + } + let text_area_height = self.input_height(area.width).saturating_sub(1); + if text_area_height == 0 { + return None; + } + let top_line_count = 1u16; // title only + let textarea_rect = Rect { + x: area.x.saturating_add(2), + y: area.y.saturating_add(top_line_count).saturating_add(1), + width: area.width.saturating_sub(2), + height: text_area_height, + }; + let state = *self.textarea_state.borrow(); + self.textarea.cursor_pos_with_state(textarea_rect, state) } } -impl Renderable for FeedbackHeader { +impl Renderable for FeedbackNoteView { + fn desired_height(&self, width: u16) -> u16 { + 1u16 + self.input_height(width) + 3u16 + } + fn render(&self, area: Rect, buf: &mut Buffer) { - if area.width == 0 || area.height == 0 { + if area.height == 0 || area.width == 0 { return; } - for (i, line) in self.lines().into_iter().enumerate() { - let y = area.y.saturating_add(i as u16); - if y >= area.y.saturating_add(area.height) { - break; + let (title, placeholder) = feedback_title_and_placeholder(self.category); + let input_height = self.input_height(area.width); + + // Title line + let title_area = Rect { + x: area.x, + y: area.y, + width: area.width, + height: 1, + }; + let title_spans: Vec> = vec![gutter(), title.bold()]; + Paragraph::new(Line::from(title_spans)).render(title_area, buf); + + // Input line + let input_area = Rect { + x: area.x, + y: area.y.saturating_add(1), + width: area.width, + height: input_height, + }; + if input_area.width >= 2 { + for row in 0..input_area.height { + Paragraph::new(Line::from(vec![gutter()])).render( + Rect { + x: input_area.x, + y: input_area.y.saturating_add(row), + width: 2, + height: 1, + }, + buf, + ); } - let line_area = Rect::new(area.x, y, area.width, 1).intersection(area); - line.render(line_area, buf); + + let text_area_height = input_area.height.saturating_sub(1); + if text_area_height > 0 { + if input_area.width > 2 { + let blank_rect = Rect { + x: input_area.x.saturating_add(2), + y: input_area.y, + width: input_area.width.saturating_sub(2), + height: 1, + }; + Clear.render(blank_rect, buf); + } + let textarea_rect = Rect { + x: input_area.x.saturating_add(2), + y: input_area.y.saturating_add(1), + width: input_area.width.saturating_sub(2), + height: text_area_height, + }; + let mut state = self.textarea_state.borrow_mut(); + StatefulWidgetRef::render_ref(&(&self.textarea), textarea_rect, buf, &mut state); + if self.textarea.text().is_empty() { + Paragraph::new(Line::from(placeholder.dim())).render(textarea_rect, buf); + } + } + } + + let hint_blank_y = input_area.y.saturating_add(input_height); + if hint_blank_y < area.y.saturating_add(area.height) { + let blank_area = Rect { + x: area.x, + y: hint_blank_y, + width: area.width, + height: 1, + }; + Clear.render(blank_area, buf); + } + + let hint_y = hint_blank_y.saturating_add(1); + if hint_y < area.y.saturating_add(area.height) { + Paragraph::new(standard_popup_hint_line()).render( + Rect { + x: area.x, + y: hint_y, + width: area.width, + height: 1, + }, + buf, + ); } } +} - fn desired_height(&self, width: u16) -> u16 { - self.lines() - .iter() - .map(|line| line.desired_height(width)) - .sum() +impl FeedbackNoteView { + fn input_height(&self, width: u16) -> u16 { + let usable_width = width.saturating_sub(2); + let text_height = self.textarea.desired_height(usable_width).clamp(1, 8); + text_height.saturating_add(1).min(9) + } +} + +fn gutter() -> Span<'static> { + "▌ ".cyan() +} + +fn feedback_title_and_placeholder(category: FeedbackCategory) -> (String, String) { + match category { + FeedbackCategory::BadResult => ( + "Tell us more (bad result)".to_string(), + "(optional) Write a short description to help us further".to_string(), + ), + FeedbackCategory::GoodResult => ( + "Tell us more (good result)".to_string(), + "(optional) Write a short description to help us further".to_string(), + ), + FeedbackCategory::Bug => ( + "Tell us more (bug)".to_string(), + "(optional) Write a short description to help us further".to_string(), + ), + FeedbackCategory::Other => ( + "Tell us more (other)".to_string(), + "(optional) Write a short description to help us further".to_string(), + ), + } +} + +fn feedback_classification(category: FeedbackCategory) -> &'static str { + match category { + FeedbackCategory::BadResult => "bad_result", + FeedbackCategory::GoodResult => "good_result", + FeedbackCategory::Bug => "bug", + FeedbackCategory::Other => "other", + } +} + +// Build the selection popup params for feedback categories. +pub(crate) fn feedback_selection_params( + app_event_tx: AppEventSender, +) -> super::SelectionViewParams { + super::SelectionViewParams { + title: Some("How was this?".to_string()), + items: vec![ + make_feedback_item( + app_event_tx.clone(), + "bug", + "Crash, error message, hang, or broken UI/behavior.", + FeedbackCategory::Bug, + ), + make_feedback_item( + app_event_tx.clone(), + "bad result", + "Output was off-target, incorrect, incomplete, or unhelpful.", + FeedbackCategory::BadResult, + ), + make_feedback_item( + app_event_tx.clone(), + "good result", + "Helpful, correct, high‑quality, or delightful result worth celebrating.", + FeedbackCategory::GoodResult, + ), + make_feedback_item( + app_event_tx, + "other", + "Slowness, feature suggestion, UX feedback, or anything else.", + FeedbackCategory::Other, + ), + ], + ..Default::default() + } +} + +fn make_feedback_item( + app_event_tx: AppEventSender, + name: &str, + description: &str, + category: FeedbackCategory, +) -> super::SelectionItem { + let action: super::SelectionAction = Box::new(move |_sender: &AppEventSender| { + app_event_tx.send(AppEvent::OpenFeedbackConsent { category }); + }); + super::SelectionItem { + name: name.to_string(), + description: Some(description.to_string()), + actions: vec![action], + dismiss_on_select: true, + ..Default::default() + } +} + +/// Build the upload consent popup params for a given feedback category. +pub(crate) fn feedback_upload_consent_params( + app_event_tx: AppEventSender, + category: FeedbackCategory, +) -> super::SelectionViewParams { + use super::popup_consts::standard_popup_hint_line; + let yes_action: super::SelectionAction = Box::new({ + let tx = app_event_tx.clone(); + move |sender: &AppEventSender| { + let _ = sender; + tx.send(AppEvent::OpenFeedbackNote { + category, + include_logs: true, + }); + } + }); + + let no_action: super::SelectionAction = Box::new({ + let tx = app_event_tx; + move |sender: &AppEventSender| { + let _ = sender; + tx.send(AppEvent::OpenFeedbackNote { + category, + include_logs: false, + }); + } + }); + + super::SelectionViewParams { + title: Some("Upload logs?".to_string()), + footer_hint: Some(standard_popup_hint_line()), + items: vec![ + super::SelectionItem { + name: "Yes".to_string(), + description: Some( + "Share the current Codex session logs with the team for troubleshooting." + .to_string(), + ), + actions: vec![yes_action], + dismiss_on_select: true, + ..Default::default() + }, + super::SelectionItem { + name: "No".to_string(), + description: Some("".to_string()), + actions: vec![no_action], + dismiss_on_select: true, + ..Default::default() + }, + ], + ..Default::default() } } @@ -167,22 +434,19 @@ impl Renderable for FeedbackHeader { mod tests { use super::*; use crate::app_event::AppEvent; - use crate::bottom_pane::list_selection_view::ListSelectionView; - use crate::style::user_message_style; - use codex_feedback::CodexFeedback; - use codex_protocol::ConversationId; - use insta::assert_snapshot; - use ratatui::buffer::Buffer; - use ratatui::layout::Rect; - use ratatui::style::Color; - use tokio::sync::mpsc::unbounded_channel; + use crate::app_event_sender::AppEventSender; - fn buffer_to_string(buffer: &Buffer) -> String { - (0..buffer.area.height) + fn render(view: &FeedbackNoteView, width: u16) -> String { + let height = view.desired_height(width); + let area = Rect::new(0, 0, width, height); + let mut buf = Buffer::empty(area); + view.render(area, &mut buf); + + let mut lines: Vec = (0..area.height) .map(|row| { let mut line = String::new(); - for col in 0..buffer.area.width { - let symbol = buffer[(buffer.area.x + col, buffer.area.y + row)].symbol(); + for col in 0..area.width { + let symbol = buf[(area.x + col, area.y + row)].symbol(); if symbol.is_empty() { line.push(' '); } else { @@ -191,34 +455,49 @@ mod tests { } line.trim_end().to_string() }) - .collect::>() - .join("\n") + .collect(); + + while lines.first().is_some_and(|l| l.trim().is_empty()) { + lines.remove(0); + } + while lines.last().is_some_and(|l| l.trim().is_empty()) { + lines.pop(); + } + lines.join("\n") + } + + fn make_view(category: FeedbackCategory) -> FeedbackNoteView { + let (tx_raw, _rx) = tokio::sync::mpsc::unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let snapshot = codex_feedback::CodexFeedback::new().snapshot(None); + FeedbackNoteView::new(category, snapshot, None, tx, true) } #[test] - fn renders_feedback_view_header() { - let (tx_raw, _rx) = unbounded_channel::(); - let app_event_tx = AppEventSender::new(tx_raw); - let snapshot = CodexFeedback::new().snapshot(Some( - ConversationId::from_string("550e8400-e29b-41d4-a716-446655440000").unwrap(), - )); - let file_path = PathBuf::from("/tmp/codex-feedback.log"); + fn feedback_view_bad_result() { + let view = make_view(FeedbackCategory::BadResult); + let rendered = render(&view, 60); + insta::assert_snapshot!("feedback_view_bad_result", rendered); + } - let params = FeedbackView::selection_params(file_path.clone(), snapshot); - let view = ListSelectionView::new(params, app_event_tx); + #[test] + fn feedback_view_good_result() { + let view = make_view(FeedbackCategory::GoodResult); + let rendered = render(&view, 60); + insta::assert_snapshot!("feedback_view_good_result", rendered); + } - let width = 72; - let height = view.desired_height(width).max(1); - let area = Rect::new(0, 0, width, height); - let mut buf = Buffer::empty(area); - view.render(area, &mut buf); + #[test] + fn feedback_view_bug() { + let view = make_view(FeedbackCategory::Bug); + let rendered = render(&view, 60); + insta::assert_snapshot!("feedback_view_bug", rendered); + } - let rendered = - buffer_to_string(&buf).replace(&file_path.display().to_string(), ""); - assert_snapshot!("feedback_view_render", rendered); - - let cell_style = buf[(area.x, area.y)].style(); - let expected_bg = user_message_style().bg.unwrap_or(Color::Reset); - assert_eq!(cell_style.bg.unwrap_or(Color::Reset), expected_bg); + #[test] + fn feedback_view_other() { + let view = make_view(FeedbackCategory::Other); + let rendered = render(&view, 60); + insta::assert_snapshot!("feedback_view_other", rendered); } } diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 48bc0e9d4c..cf9e354737 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -28,12 +28,14 @@ mod list_selection_view; mod prompt_args; pub(crate) use list_selection_view::SelectionViewParams; mod feedback_view; +pub(crate) use feedback_view::feedback_selection_params; +pub(crate) use feedback_view::feedback_upload_consent_params; mod paste_burst; pub mod popup_consts; mod scroll_state; mod selection_popup_common; mod textarea; -pub(crate) use feedback_view::FeedbackView; +pub(crate) use feedback_view::FeedbackNoteView; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum CancellationEvent { diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bad_result.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bad_result.snap new file mode 100644 index 0000000000..465f0f9c4f --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bad_result.snap @@ -0,0 +1,9 @@ +--- +source: tui/src/bottom_pane/feedback_view.rs +expression: rendered +--- +▌ Tell us more (bad result) +▌ +▌ (optional) Write a short description to help us further + +Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bug.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bug.snap new file mode 100644 index 0000000000..a0b5660135 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_bug.snap @@ -0,0 +1,9 @@ +--- +source: tui/src/bottom_pane/feedback_view.rs +expression: rendered +--- +▌ Tell us more (bug) +▌ +▌ (optional) Write a short description to help us further + +Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_good_result.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_good_result.snap new file mode 100644 index 0000000000..73074d61fa --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_good_result.snap @@ -0,0 +1,9 @@ +--- +source: tui/src/bottom_pane/feedback_view.rs +expression: rendered +--- +▌ Tell us more (good result) +▌ +▌ (optional) Write a short description to help us further + +Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_other.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_other.snap new file mode 100644 index 0000000000..80e4ffeffe --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__feedback_view__tests__feedback_view_other.snap @@ -0,0 +1,9 @@ +--- +source: tui/src/bottom_pane/feedback_view.rs +expression: rendered +--- +▌ Tell us more (other) +▌ +▌ (optional) Write a short description to help us further + +Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 833ae5d862..81661aa3a2 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -276,6 +276,8 @@ pub(crate) struct ChatWidget { last_rendered_width: std::cell::Cell>, // Feedback sink for /feedback feedback: codex_feedback::CodexFeedback, + // Current session rollout path (if known) + current_rollout_path: Option, } struct UserMessage { @@ -322,6 +324,7 @@ impl ChatWidget { self.bottom_pane .set_history_metadata(event.history_log_id, event.history_entry_count); self.conversation_id = Some(event.session_id); + self.current_rollout_path = Some(event.rollout_path.clone()); let initial_messages = event.initial_messages.clone(); let model_for_header = event.model.clone(); self.session_header.set_model(&model_for_header); @@ -343,6 +346,36 @@ impl ChatWidget { } } + pub(crate) fn open_feedback_note( + &mut self, + category: crate::app_event::FeedbackCategory, + include_logs: bool, + ) { + // Build a fresh snapshot at the time of opening the note overlay. + let snapshot = self.feedback.snapshot(self.conversation_id); + let rollout = if include_logs { + self.current_rollout_path.clone() + } else { + None + }; + let view = crate::bottom_pane::FeedbackNoteView::new( + category, + snapshot, + rollout, + self.app_event_tx.clone(), + include_logs, + ); + self.bottom_pane.show_view(Box::new(view)); + self.request_redraw(); + } + + pub(crate) fn open_feedback_consent(&mut self, category: crate::app_event::FeedbackCategory) { + let params = + crate::bottom_pane::feedback_upload_consent_params(self.app_event_tx.clone(), category); + self.bottom_pane.show_selection_view(params); + self.request_redraw(); + } + fn on_agent_message(&mut self, message: String) { // If we have a stream_controller, then the final agent message is redundant and will be a // duplicate of what has already been streamed. @@ -496,7 +529,7 @@ impl ChatWidget { if reason != TurnAbortReason::ReviewEnded { self.add_to_history(history_cell::new_error_event( - "Conversation interrupted - tell the model what to do differently".to_owned(), + "Conversation interrupted - tell the model what to do differently. Something went wrong? Hit `/feedback` to report the issue.".to_owned(), )); } @@ -958,6 +991,7 @@ impl ChatWidget { needs_final_message_separator: false, last_rendered_width: std::cell::Cell::new(None), feedback, + current_rollout_path: None, } } @@ -1025,6 +1059,7 @@ impl ChatWidget { needs_final_message_separator: false, last_rendered_width: std::cell::Cell::new(None), feedback, + current_rollout_path: None, } } @@ -1129,23 +1164,11 @@ impl ChatWidget { } match cmd { SlashCommand::Feedback => { - let snapshot = self.feedback.snapshot(self.conversation_id); - match snapshot.save_to_temp_file() { - Ok(path) => { - crate::bottom_pane::FeedbackView::show( - &mut self.bottom_pane, - path, - snapshot, - ); - self.request_redraw(); - } - Err(e) => { - self.add_to_history(history_cell::new_error_event(format!( - "Failed to save feedback logs: {e}" - ))); - self.request_redraw(); - } - } + // Step 1: pick a category (UI built in feedback_view) + let params = + crate::bottom_pane::feedback_selection_params(self.app_event_tx.clone()); + self.bottom_pane.show_selection_view(params); + self.request_redraw(); } SlashCommand::New => { self.app_event_tx.send(AppEvent::NewSession); diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_selection_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_selection_popup.snap new file mode 100644 index 0000000000..4a98242027 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_selection_popup.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: popup +--- + How was this? + +› 1. bug Crash, error message, hang, or broken UI/behavior. + 2. bad result Output was off-target, incorrect, incomplete, or unhelpful. + 3. good result Helpful, correct, high‑quality, or delightful result worth + celebrating. + 4. other Slowness, feature suggestion, UX feedback, or anything else. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap new file mode 100644 index 0000000000..092e961d58 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap @@ -0,0 +1,11 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: popup +--- + Upload logs? + +› 1. Yes Share the current Codex session logs with the team for + troubleshooting. + 2. No + + Press enter to confirm or esc to go back diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__interrupted_turn_error_message.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__interrupted_turn_error_message.snap new file mode 100644 index 0000000000..60715e581e --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__interrupted_turn_error_message.snap @@ -0,0 +1,5 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: last +--- +■ Conversation interrupted - tell the model what to do differently. Something went wrong? Hit `/feedback` to report the issue. diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index e25e04e09e..6ec877656c 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -299,6 +299,7 @@ fn make_chatwidget_manual() -> ( needs_final_message_separator: false, last_rendered_width: std::cell::Cell::new(None), feedback: codex_feedback::CodexFeedback::new(), + current_rollout_path: None, }; (widget, rx, op_rx) } @@ -998,6 +999,37 @@ fn interrupt_exec_marks_failed_snapshot() { assert_snapshot!("interrupt_exec_marks_failed", exec_blob); } +// Snapshot test: after an interrupted turn, a gentle error message is inserted +// suggesting the user to tell the model what to do differently and to use /feedback. +#[test] +fn interrupted_turn_error_message_snapshot() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); + + // Simulate an in-progress task so the widget is in a running state. + chat.handle_codex_event(Event { + id: "task-1".into(), + msg: EventMsg::TaskStarted(TaskStartedEvent { + model_context_window: None, + }), + }); + + // Abort the turn (like pressing Esc) and drain inserted history. + chat.handle_codex_event(Event { + id: "task-1".into(), + msg: EventMsg::TurnAborted(codex_core::protocol::TurnAbortedEvent { + reason: TurnAbortReason::Interrupted, + }), + }); + + let cells = drain_insert_history(&mut rx); + assert!( + !cells.is_empty(), + "expected error message to be inserted after interruption" + ); + let last = lines_to_single_string(cells.last().unwrap()); + assert_snapshot!("interrupted_turn_error_message", last); +} + /// Opening custom prompt from the review popup, pressing Esc returns to the /// parent popup, pressing Esc again dismisses all panels (back to normal mode). #[test] @@ -1175,6 +1207,28 @@ fn model_reasoning_selection_popup_snapshot() { assert_snapshot!("model_reasoning_selection_popup", popup); } +#[test] +fn feedback_selection_popup_snapshot() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(); + + // Open the feedback category selection popup via slash command. + chat.dispatch_command(SlashCommand::Feedback); + + let popup = render_bottom_popup(&chat, 80); + assert_snapshot!("feedback_selection_popup", popup); +} + +#[test] +fn feedback_upload_consent_popup_snapshot() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(); + + // Open the consent popup directly for a chosen category. + chat.open_feedback_consent(crate::app_event::FeedbackCategory::Bug); + + let popup = render_bottom_popup(&chat, 80); + assert_snapshot!("feedback_upload_consent_popup", popup); +} + #[test] fn reasoning_popup_escape_returns_to_model_popup() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(); From 88abbf58cec9843a7cebe250d71146314ebbcf1a Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Fri, 24 Oct 2025 23:07:40 -0700 Subject: [PATCH 17/35] Followup feedback (#5663) - Added files to be uploaded - Refactored - Updated title --- codex-rs/feedback/src/lib.rs | 123 +++++------------- codex-rs/tui/src/bottom_pane/feedback_view.rs | 40 ++++-- codex-rs/tui/src/chatwidget.rs | 7 +- ..._tests__feedback_upload_consent_popup.snap | 3 + 4 files changed, 69 insertions(+), 104 deletions(-) diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index fc696f2ab1..b1adb3db3f 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -167,14 +167,13 @@ impl CodexLogSnapshot { Ok(path) } - /// Uploads feedback to Sentry with both the in-memory Codex logs and an optional - /// rollout file attached. Also records metadata such as classification, - /// reason (free-form note), and CLI version as Sentry tags or message. - pub fn upload_feedback_with_rollout( + /// Upload feedback to Sentry with optional attachments. + pub fn upload_feedback( &self, classification: &str, reason: Option<&str>, cli_version: &str, + include_logs: bool, rollout_path: Option<&std::path::Path>, ) -> Result<()> { use std::collections::BTreeMap; @@ -194,129 +193,73 @@ impl CodexLogSnapshot { // Build Sentry client let client = Client::from_config(ClientOptions { - dsn: Some(Dsn::from_str(SENTRY_DSN).map_err(|e| anyhow!("invalid DSN: {}", e))?), + dsn: Some(Dsn::from_str(SENTRY_DSN).map_err(|e| anyhow!("invalid DSN: {e}"))?), transport: Some(Arc::new(DefaultTransportFactory {})), ..Default::default() }); - // Tags: thread id, classification, cli_version let mut tags = BTreeMap::from([ (String::from("thread_id"), self.thread_id.to_string()), (String::from("classification"), classification.to_string()), (String::from("cli_version"), cli_version.to_string()), ]); - - // Reason (freeform) – include entire note as a tag; keep title in message. if let Some(r) = reason { tags.insert(String::from("reason"), r.to_string()); } - // Elevate level for error-like classifications let level = match classification { "bug" | "bad_result" => Level::Error, _ => Level::Info, }; let mut envelope = Envelope::new(); - // Title is the message in Sentry: "[Classification]: Codex session " let title = format!( "[{}]: Codex session {}", display_classification(classification), self.thread_id ); - let event = Event { + + let mut event = Event { level, - message: Some(title), + message: Some(title.clone()), tags, ..Default::default() }; + if let Some(r) = reason { + use sentry::protocol::Exception; + use sentry::protocol::Values; + + event.exception = Values::from(vec![Exception { + ty: title.clone(), + value: Some(r.to_string()), + ..Default::default() + }]); + } envelope.add_item(EnvelopeItem::Event(event)); - // Attachment 1: Codex logs snapshot - envelope.add_item(EnvelopeItem::Attachment(Attachment { - buffer: self.bytes.clone(), - filename: String::from("codex-logs.log"), - content_type: Some("text/plain".to_string()), - ty: None, - })); - - // Attachment 2: rollout file (if provided and readable) - if let Some((path, data)) = rollout_path.and_then(|p| fs::read(p).ok().map(|d| (p, d))) { - // Name the file by suffix so users can spot it. - let fname = path - .file_name() - .map(|s| s.to_string_lossy().to_string()) - .unwrap_or_else(|| "rollout.jsonl".to_string()); + if include_logs { envelope.add_item(EnvelopeItem::Attachment(Attachment { - buffer: data, - filename: fname, - content_type: Some("application/jsonl".to_string()), + buffer: self.bytes.clone(), + filename: String::from("codex-logs.log"), + content_type: Some("text/plain".to_string()), ty: None, })); } - client.send_envelope(envelope); - client.flush(Some(Duration::from_secs(UPLOAD_TIMEOUT_SECS))); - - Ok(()) - } - - /// Upload a metadata-only feedback event (no attachments). Includes classification, - /// optional reason, CLI version and thread ID as tags. - pub fn upload_feedback_metadata_only( - &self, - classification: &str, - reason: Option<&str>, - cli_version: &str, - ) -> Result<()> { - use std::collections::BTreeMap; - use std::str::FromStr; - use std::sync::Arc; - - use sentry::Client; - use sentry::ClientOptions; - use sentry::protocol::Envelope; - use sentry::protocol::EnvelopeItem; - use sentry::protocol::Event; - use sentry::protocol::Level; - use sentry::transports::DefaultTransportFactory; - use sentry::types::Dsn; - - let client = Client::from_config(ClientOptions { - dsn: Some(Dsn::from_str(SENTRY_DSN).map_err(|e| anyhow!("invalid DSN: {}", e))?), - transport: Some(Arc::new(DefaultTransportFactory {})), - ..Default::default() - }); - - let mut tags = BTreeMap::from([ - (String::from("thread_id"), self.thread_id.to_string()), - (String::from("classification"), classification.to_string()), - (String::from("cli_version"), cli_version.to_string()), - ]); - if let Some(r) = reason { - tags.insert(String::from("reason"), r.to_string()); + if let Some((path, data)) = rollout_path.and_then(|p| fs::read(p).ok().map(|d| (p, d))) { + let fname = path + .file_name() + .map(|s| s.to_string_lossy().to_string()) + .unwrap_or_else(|| "rollout.jsonl".to_string()); + let content_type = "text/plain".to_string(); + envelope.add_item(EnvelopeItem::Attachment(Attachment { + buffer: data, + filename: fname, + content_type: Some(content_type), + ty: None, + })); } - let level = match classification { - "bug" | "bad_result" => Level::Error, - _ => Level::Info, - }; - - let mut envelope = Envelope::new(); - // Title is the message in Sentry: "[Classification]: Codex session " - let title = format!( - "[{}]: Codex session {}", - display_classification(classification), - self.thread_id - ); - let event = Event { - level, - message: Some(title), - tags, - ..Default::default() - }; - envelope.add_item(EnvelopeItem::Event(event)); - client.send_envelope(envelope); client.flush(Some(Duration::from_secs(UPLOAD_TIMEOUT_SECS))); Ok(()) diff --git a/codex-rs/tui/src/bottom_pane/feedback_view.rs b/codex-rs/tui/src/bottom_pane/feedback_view.rs index fce3a795c3..234dbbd253 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_view.rs @@ -76,17 +76,17 @@ impl FeedbackNoteView { let cli_version = crate::version::CODEX_CLI_VERSION; let mut thread_id = self.snapshot.thread_id.clone(); - let result = if self.include_logs { - self.snapshot.upload_feedback_with_rollout( - classification, - reason_opt, - cli_version, - rollout_path_ref, - ) - } else { - self.snapshot - .upload_feedback_metadata_only(classification, reason_opt, cli_version) - }; + let result = self.snapshot.upload_feedback( + classification, + reason_opt, + cli_version, + self.include_logs, + if self.include_logs { + rollout_path_ref + } else { + None + }, + ); match result { Ok(()) => { @@ -380,6 +380,7 @@ fn make_feedback_item( pub(crate) fn feedback_upload_consent_params( app_event_tx: AppEventSender, category: FeedbackCategory, + rollout_path: Option, ) -> super::SelectionViewParams { use super::popup_consts::standard_popup_hint_line; let yes_action: super::SelectionAction = Box::new({ @@ -404,8 +405,20 @@ pub(crate) fn feedback_upload_consent_params( } }); + // Build header listing files that would be sent if user consents. + let mut header_lines: Vec> = vec![ + Line::from("Upload logs?".bold()).into(), + Line::from("").into(), + Line::from("The following files will be sent:".dim()).into(), + Line::from(vec![" • ".into(), "codex-logs.log".into()]).into(), + ]; + if let Some(path) = rollout_path.as_deref() + && let Some(name) = path.file_name().map(|s| s.to_string_lossy().to_string()) + { + header_lines.push(Line::from(vec![" • ".into(), name.into()]).into()); + } + super::SelectionViewParams { - title: Some("Upload logs?".to_string()), footer_hint: Some(standard_popup_hint_line()), items: vec![ super::SelectionItem { @@ -426,6 +439,9 @@ pub(crate) fn feedback_upload_consent_params( ..Default::default() }, ], + header: Box::new(crate::render::renderable::ColumnRenderable::with( + header_lines, + )), ..Default::default() } } diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 81661aa3a2..fdebe15826 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -370,8 +370,11 @@ impl ChatWidget { } pub(crate) fn open_feedback_consent(&mut self, category: crate::app_event::FeedbackCategory) { - let params = - crate::bottom_pane::feedback_upload_consent_params(self.app_event_tx.clone(), category); + let params = crate::bottom_pane::feedback_upload_consent_params( + self.app_event_tx.clone(), + category, + self.current_rollout_path.clone(), + ); self.bottom_pane.show_selection_view(params); self.request_redraw(); } diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap index 092e961d58..cc3d8e3755 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__feedback_upload_consent_popup.snap @@ -4,6 +4,9 @@ expression: popup --- Upload logs? + The following files will be sent: + • codex-logs.log + › 1. Yes Share the current Codex session logs with the team for troubleshooting. 2. No From c7e4e6d0eeb4d5f35ad3015580aef6484bc9582b Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Sat, 25 Oct 2025 12:11:16 -0700 Subject: [PATCH 18/35] Skip flaky test (#5680) Did an investigation but couldn't find anything obvious. Let's skip for now. --- sdk/typescript/tests/run.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/sdk/typescript/tests/run.test.ts b/sdk/typescript/tests/run.test.ts index f495b1e6ec..a8a9c7fbe8 100644 --- a/sdk/typescript/tests/run.test.ts +++ b/sdk/typescript/tests/run.test.ts @@ -3,7 +3,7 @@ import os from "node:os"; import path from "node:path"; import { codexExecSpy } from "./codexExecSpy"; -import { describe, expect, it } from "@jest/globals"; +import { describe, expect, it, xit } from "@jest/globals"; import { Codex } from "../src/codex"; @@ -308,7 +308,8 @@ describe("Codex", () => { await close(); } }); - it("forwards images to exec", async () => { + // TODO(pakrym): unskip the test + xit("forwards images to exec", async () => { const { url, close } = await startResponsesTestProxy({ statusCode: 200, responseBodies: [ From c124f243545b2abf3442fe4326f38cb6a6906c50 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Sat, 25 Oct 2025 18:52:26 -0500 Subject: [PATCH 19/35] Added support for `sandbox_mode` in profiles (#5686) Currently, `approval_policy` is supported in profiles, but `sandbox_mode` is not. This PR adds support for `sandbox_mode`. Note: a fix for this was submitted in [this PR](https://github.com/openai/codex/pull/2397), but the underlying code has changed significantly since then. This addresses issue #3034 --- codex-rs/core/src/config.rs | 104 +++++++++++++++++++++++++--- codex-rs/core/src/config_profile.rs | 2 + 2 files changed, 96 insertions(+), 10 deletions(-) diff --git a/codex-rs/core/src/config.rs b/codex-rs/core/src/config.rs index b04aba5db5..c5406b1d27 100644 --- a/codex-rs/core/src/config.rs +++ b/codex-rs/core/src/config.rs @@ -1027,9 +1027,11 @@ impl ConfigToml { fn derive_sandbox_policy( &self, sandbox_mode_override: Option, + profile_sandbox_mode: Option, resolved_cwd: &Path, ) -> SandboxPolicy { let resolved_sandbox_mode = sandbox_mode_override + .or(profile_sandbox_mode) .or(self.sandbox_mode) .or_else(|| { // if no sandbox_mode is set, but user has marked directory as trusted, use WorkspaceWrite @@ -1219,7 +1221,8 @@ impl Config { .get_active_project(&resolved_cwd) .unwrap_or(ProjectConfig { trust_level: None }); - let mut sandbox_policy = cfg.derive_sandbox_policy(sandbox_mode, &resolved_cwd); + let mut sandbox_policy = + cfg.derive_sandbox_policy(sandbox_mode, config_profile.sandbox_mode, &resolved_cwd); if let SandboxPolicy::WorkspaceWrite { writable_roots, .. } = &mut sandbox_policy { for path in additional_writable_roots { if !writable_roots.iter().any(|existing| existing == &path) { @@ -1242,8 +1245,8 @@ impl Config { .is_some() || config_profile.approval_policy.is_some() || cfg.approval_policy.is_some() - // TODO(#3034): profile.sandbox_mode is not implemented || sandbox_mode.is_some() + || config_profile.sandbox_mode.is_some() || cfg.sandbox_mode.is_some(); let mut model_providers = built_in_model_providers(); @@ -1603,8 +1606,11 @@ network_access = false # This should be ignored. let sandbox_mode_override = None; assert_eq!( SandboxPolicy::DangerFullAccess, - sandbox_full_access_cfg - .derive_sandbox_policy(sandbox_mode_override, &PathBuf::from("/tmp/test")) + sandbox_full_access_cfg.derive_sandbox_policy( + sandbox_mode_override, + None, + &PathBuf::from("/tmp/test") + ) ); let sandbox_read_only = r#" @@ -1619,8 +1625,11 @@ network_access = true # This should be ignored. let sandbox_mode_override = None; assert_eq!( SandboxPolicy::ReadOnly, - sandbox_read_only_cfg - .derive_sandbox_policy(sandbox_mode_override, &PathBuf::from("/tmp/test")) + sandbox_read_only_cfg.derive_sandbox_policy( + sandbox_mode_override, + None, + &PathBuf::from("/tmp/test") + ) ); let sandbox_workspace_write = r#" @@ -1644,8 +1653,11 @@ exclude_slash_tmp = true exclude_tmpdir_env_var: true, exclude_slash_tmp: true, }, - sandbox_workspace_write_cfg - .derive_sandbox_policy(sandbox_mode_override, &PathBuf::from("/tmp/test")) + sandbox_workspace_write_cfg.derive_sandbox_policy( + sandbox_mode_override, + None, + &PathBuf::from("/tmp/test") + ) ); let sandbox_workspace_write = r#" @@ -1672,8 +1684,11 @@ trust_level = "trusted" exclude_tmpdir_env_var: true, exclude_slash_tmp: true, }, - sandbox_workspace_write_cfg - .derive_sandbox_policy(sandbox_mode_override, &PathBuf::from("/tmp/test")) + sandbox_workspace_write_cfg.derive_sandbox_policy( + sandbox_mode_override, + None, + &PathBuf::from("/tmp/test") + ) ); } @@ -1765,6 +1780,75 @@ trust_level = "trusted" Ok(()) } + #[test] + fn profile_sandbox_mode_overrides_base() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let mut profiles = HashMap::new(); + profiles.insert( + "work".to_string(), + ConfigProfile { + sandbox_mode: Some(SandboxMode::DangerFullAccess), + ..Default::default() + }, + ); + let cfg = ConfigToml { + profiles, + profile: Some("work".to_string()), + sandbox_mode: Some(SandboxMode::ReadOnly), + ..Default::default() + }; + + let config = Config::load_from_base_config_with_overrides( + cfg, + ConfigOverrides::default(), + codex_home.path().to_path_buf(), + )?; + + assert!(matches!( + config.sandbox_policy, + SandboxPolicy::DangerFullAccess + )); + assert!(config.did_user_set_custom_approval_policy_or_sandbox_mode); + + Ok(()) + } + + #[test] + fn cli_override_takes_precedence_over_profile_sandbox_mode() -> std::io::Result<()> { + let codex_home = TempDir::new()?; + let mut profiles = HashMap::new(); + profiles.insert( + "work".to_string(), + ConfigProfile { + sandbox_mode: Some(SandboxMode::DangerFullAccess), + ..Default::default() + }, + ); + let cfg = ConfigToml { + profiles, + profile: Some("work".to_string()), + ..Default::default() + }; + + let overrides = ConfigOverrides { + sandbox_mode: Some(SandboxMode::WorkspaceWrite), + ..Default::default() + }; + + let config = Config::load_from_base_config_with_overrides( + cfg, + overrides, + codex_home.path().to_path_buf(), + )?; + + assert!(matches!( + config.sandbox_policy, + SandboxPolicy::WorkspaceWrite { .. } + )); + + Ok(()) + } + #[test] fn feature_table_overrides_legacy_flags() -> std::io::Result<()> { let codex_home = TempDir::new()?; diff --git a/codex-rs/core/src/config_profile.rs b/codex-rs/core/src/config_profile.rs index 84b90f5adb..7b7cafedbc 100644 --- a/codex-rs/core/src/config_profile.rs +++ b/codex-rs/core/src/config_profile.rs @@ -4,6 +4,7 @@ use std::path::PathBuf; use crate::protocol::AskForApproval; use codex_protocol::config_types::ReasoningEffort; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::config_types::SandboxMode; use codex_protocol::config_types::Verbosity; /// Collection of common configuration options that a user can define as a unit @@ -15,6 +16,7 @@ pub struct ConfigProfile { /// [`ModelProviderInfo`] to use. pub model_provider: Option, pub approval_policy: Option, + pub sandbox_mode: Option, pub model_reasoning_effort: Option, pub model_reasoning_summary: Option, pub model_verbosity: Option, From bcd64c7e7231d6316a2377d1525a0fa74f21b783 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Sun, 26 Oct 2025 01:46:08 -0500 Subject: [PATCH 20/35] Reduced runtime of unit test that was taking multiple minutes (#5688) Modified `build_compacted_history_truncates_overlong_user_messages` test to reduce runtime from minutes to tens of seconds --- codex-rs/core/src/codex/compact.rs | 31 +++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/codex-rs/core/src/codex/compact.rs b/codex-rs/core/src/codex/compact.rs index 26f9f9eb9e..304452b060 100644 --- a/codex-rs/core/src/codex/compact.rs +++ b/codex-rs/core/src/codex/compact.rs @@ -200,7 +200,20 @@ pub(crate) fn build_compacted_history( user_messages: &[String], summary_text: &str, ) -> Vec { - let mut history = initial_context; + build_compacted_history_with_limit( + initial_context, + user_messages, + summary_text, + COMPACT_USER_MESSAGE_MAX_TOKENS * 4, + ) +} + +fn build_compacted_history_with_limit( + mut history: Vec, + user_messages: &[String], + summary_text: &str, + max_bytes: usize, +) -> Vec { let mut user_messages_text = if user_messages.is_empty() { "(none)".to_string() } else { @@ -208,7 +221,6 @@ pub(crate) fn build_compacted_history( }; // 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; } @@ -361,11 +373,16 @@ mod tests { #[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"); + // Use a small truncation limit so the test remains fast while still validating + // that oversized user content is truncated. + let max_bytes = 128; + let big = "X".repeat(max_bytes + 50); + let history = super::build_compacted_history_with_limit( + Vec::new(), + std::slice::from_ref(&big), + "SUMMARY", + max_bytes, + ); // Expect exactly one bridge message added to history (plus any initial context we provided, which is none). assert_eq!(history.len(), 1); From 7aab45e0609e721e4d18795aa9c170738a54cc98 Mon Sep 17 00:00:00 2001 From: Gabriel Peal Date: Sun, 26 Oct 2025 10:38:30 -0700 Subject: [PATCH 21/35] [MCP] Minor docs clarifications around stdio tokens (#5676) Noticed [here](https://github.com/openai/codex/issues/4707#issuecomment-3446547561) --- docs/config.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/config.md b/docs/config.md index 4186c4ff34..9223f48d26 100644 --- a/docs/config.md +++ b/docs/config.md @@ -417,7 +417,7 @@ cwd = "/Users//code/my-server" [mcp_servers.figma] url = "https://mcp.linear.app/mcp" # Optional environment variable containing a bearer token to use for auth -bearer_token_env_var = "" +bearer_token_env_var = "ENV_VAR" # Optional map of headers with hard-coded values. http_headers = { "HEADER_NAME" = "HEADER_VALUE" } # Optional map of headers whose values will be replaced with the environment variable. From 224222f09fb398d5957ece12ff46ffa1b85c3d02 Mon Sep 17 00:00:00 2001 From: Thibault Sottiaux Date: Sun, 26 Oct 2025 18:55:12 -0700 Subject: [PATCH 22/35] fix: use codex-exp prefix for experimental models and consider codex- models to be production (#5797) --- codex-rs/core/src/model_family.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codex-rs/core/src/model_family.rs b/codex-rs/core/src/model_family.rs index 40b00408fb..e6e5fbfdf2 100644 --- a/codex-rs/core/src/model_family.rs +++ b/codex-rs/core/src/model_family.rs @@ -131,7 +131,7 @@ pub fn find_family_for_model(slug: &str) -> Option { ) // Internal models. - } else if slug.starts_with("codex-") { + } else if slug.starts_with("codex-exp-") { model_family!( slug, slug, supports_reasoning_summaries: true, @@ -147,7 +147,7 @@ pub fn find_family_for_model(slug: &str) -> Option { ) // Production models. - } else if slug.starts_with("gpt-5-codex") { + } else if slug.starts_with("gpt-5-codex") || slug.starts_with("codex-") { model_family!( slug, slug, supports_reasoning_summaries: true, From a55b0c4bcc42089d7b53a1aebd5b31709c536c55 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Sun, 26 Oct 2025 18:57:42 -0700 Subject: [PATCH 23/35] fix: revert "[app-server] fix account/read response annotation (#5642)" (#5796) Revert #5642 because this generates: ``` // GENERATED CODE! DO NOT MODIFY BY HAND! // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. export type GetAccountResponse = Account | null; ``` But `Account` is unknown. The unique use of `#[ts(export)]` on `GetAccountResponse` is also suspicious as are the changes to `codex-rs/app-server-protocol/src/export.rs` since the existing system has worked fine for quite some time. Though a pure backout of #5642 puts things in a state where, as the PR noted, the following does not work: ``` cargo run -p codex-app-server-protocol --bin export -- --out DIR ``` So in addition to the backout, this PR adds: ```rust #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] pub struct GetAccountResponse { pub account: Account, } ``` and changes `GetAccount.response` as follows: ```diff - response: Option, + response: GetAccountResponse, ``` making it consistent with other types. With this change, I verified that both of the following work: ``` just codex generate-ts --out /tmp/somewhere cargo run -p codex-app-server-protocol --bin export -- --out /tmp/somewhere-else ``` The generated TypeScript is as follows: ```typescript // GetAccountResponse.ts import type { Account } from "./Account"; export type GetAccountResponse = { account: Account, }; ``` and ```typescript // Account.ts import type { PlanType } from "./PlanType"; export type Account = { "type": "ApiKey", api_key: string, } | { "type": "chatgpt", email: string | null, plan_type: PlanType, }; ``` Though while the inconsistency between `"type": "ApiKey"` and `"type": "chatgpt"` is quite concerning, I'm not sure if that format is ever written to disk in any case, but @owenlin0, I would recommend looking into that. Also, it appears that the types in `codex-rs/protocol/src/account.rs` are used exclusively by the `app-server-protocol` crate, so perhaps they should just be moved there? --- codex-rs/app-server-protocol/src/export.rs | 30 ++++---------------- codex-rs/app-server-protocol/src/protocol.rs | 12 ++++---- 2 files changed, 12 insertions(+), 30 deletions(-) diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index 486abf8e5f..21ba3facc4 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -23,7 +23,6 @@ use std::io::Write; use std::path::Path; use std::path::PathBuf; use std::process::Command; -use ts_rs::ExportError; use ts_rs::TS; const HEADER: &str = "// GENERATED CODE! DO NOT MODIFY BY HAND!\n\n"; @@ -105,19 +104,6 @@ macro_rules! for_each_schema_type { }; } -fn export_ts_with_context(label: &str, export: F) -> Result<()> -where - F: FnOnce() -> std::result::Result<(), ExportError>, -{ - match export() { - Ok(()) => Ok(()), - Err(ExportError::CannotBeExported(ty)) => Err(anyhow!( - "failed to export {label}: dependency {ty} cannot be exported" - )), - Err(err) => Err(err.into()), - } -} - pub fn generate_types(out_dir: &Path, prettier: Option<&Path>) -> Result<()> { generate_ts(out_dir, prettier)?; generate_json(out_dir)?; @@ -127,17 +113,13 @@ pub fn generate_types(out_dir: &Path, prettier: Option<&Path>) -> Result<()> { pub fn generate_ts(out_dir: &Path, prettier: Option<&Path>) -> Result<()> { ensure_dir(out_dir)?; - export_ts_with_context("ClientRequest", || ClientRequest::export_all_to(out_dir))?; - export_ts_with_context("client responses", || export_client_responses(out_dir))?; - export_ts_with_context("ClientNotification", || { - ClientNotification::export_all_to(out_dir) - })?; + ClientRequest::export_all_to(out_dir)?; + export_client_responses(out_dir)?; + ClientNotification::export_all_to(out_dir)?; - export_ts_with_context("ServerRequest", || ServerRequest::export_all_to(out_dir))?; - export_ts_with_context("server responses", || export_server_responses(out_dir))?; - export_ts_with_context("ServerNotification", || { - ServerNotification::export_all_to(out_dir) - })?; + ServerRequest::export_all_to(out_dir)?; + export_server_responses(out_dir)?; + ServerNotification::export_all_to(out_dir)?; generate_index_ts(out_dir)?; diff --git a/codex-rs/app-server-protocol/src/protocol.rs b/codex-rs/app-server-protocol/src/protocol.rs index 71a4d77f8d..ab7341a2ab 100644 --- a/codex-rs/app-server-protocol/src/protocol.rs +++ b/codex-rs/app-server-protocol/src/protocol.rs @@ -225,6 +225,12 @@ client_request_definitions! { }, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +pub struct GetAccountResponse { + pub account: Account, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)] #[serde(rename_all = "camelCase")] pub struct InitializeParams { @@ -535,12 +541,6 @@ pub struct GetAccountRateLimitsResponse { pub rate_limits: RateLimitSnapshot, } -#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] -#[serde(transparent)] -#[ts(export)] -#[ts(type = "Account | null")] -pub struct GetAccountResponse(#[ts(type = "Account | null")] pub Option); - #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] pub struct GetAuthStatusResponse { From f1788052529f692c3ffdc6a07ab1d537de341aca Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Sun, 26 Oct 2025 22:53:39 -0700 Subject: [PATCH 24/35] Add feedback upload request handling (#5682) --- codex-rs/Cargo.lock | 1 + codex-rs/app-server-protocol/src/protocol.rs | 24 ++++++ codex-rs/app-server/Cargo.toml | 1 + .../app-server/src/codex_message_processor.rs | 80 +++++++++++++++++++ codex-rs/app-server/src/lib.rs | 13 +++ codex-rs/app-server/src/message_processor.rs | 3 + .../app-server/tests/common/mcp_process.rs | 10 +++ codex-rs/core/src/codex.rs | 48 +++++------ codex-rs/core/src/codex_conversation.rs | 13 ++- codex-rs/core/src/conversation_manager.rs | 5 +- codex-rs/core/src/rollout/policy.rs | 1 - codex-rs/core/src/rollout/recorder.rs | 4 - .../core/tests/suite/compact_resume_fork.rs | 29 ++----- .../core/tests/suite/fork_conversation.rs | 29 +------ codex-rs/core/tests/suite/review.rs | 17 +--- .../src/event_processor_with_human_output.rs | 1 - codex-rs/feedback/src/lib.rs | 2 +- codex-rs/mcp-server/src/codex_tool_runner.rs | 1 - codex-rs/protocol/src/protocol.rs | 6 -- codex-rs/tui/src/app_backtrack.rs | 13 ++- codex-rs/tui/src/bottom_pane/feedback_view.rs | 2 - codex-rs/tui/src/chatwidget.rs | 8 +- 22 files changed, 194 insertions(+), 117 deletions(-) diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index a2e49fc506..5025c82e7a 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -843,6 +843,7 @@ dependencies = [ "codex-backend-client", "codex-common", "codex-core", + "codex-feedback", "codex-file-search", "codex-login", "codex-protocol", diff --git a/codex-rs/app-server-protocol/src/protocol.rs b/codex-rs/app-server-protocol/src/protocol.rs index ab7341a2ab..ca4be39e25 100644 --- a/codex-rs/app-server-protocol/src/protocol.rs +++ b/codex-rs/app-server-protocol/src/protocol.rs @@ -124,6 +124,13 @@ client_request_definitions! { response: GetAccountRateLimitsResponse, }, + #[serde(rename = "feedback/upload")] + #[ts(rename = "feedback/upload")] + UploadFeedback { + params: UploadFeedbackParams, + response: UploadFeedbackResponse, + }, + #[serde(rename = "account/read")] #[ts(rename = "account/read")] GetAccount { @@ -384,6 +391,23 @@ pub struct ListModelsResponse { pub next_cursor: Option, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +pub struct UploadFeedbackParams { + pub classification: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub conversation_id: Option, + pub include_logs: bool, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +pub struct UploadFeedbackResponse { + pub thread_id: String, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(tag = "type")] #[ts(tag = "type")] diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index c1efb2ef93..d693e7bb7f 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -24,6 +24,7 @@ codex-file-search = { workspace = true } codex-login = { workspace = true } codex-protocol = { workspace = true } codex-app-server-protocol = { workspace = true } +codex-feedback = { workspace = true } codex-utils-json-to-toml = { workspace = true } chrono = { workspace = true } serde = { workspace = true, features = ["derive"] } diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index b2b242fb29..59dd0f63e5 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -52,6 +52,8 @@ use codex_app_server_protocol::ServerRequestPayload; use codex_app_server_protocol::SessionConfiguredNotification; use codex_app_server_protocol::SetDefaultModelParams; use codex_app_server_protocol::SetDefaultModelResponse; +use codex_app_server_protocol::UploadFeedbackParams; +use codex_app_server_protocol::UploadFeedbackResponse; use codex_app_server_protocol::UserInfoResponse; use codex_app_server_protocol::UserSavedConfig; use codex_backend_client::Client as BackendClient; @@ -85,6 +87,7 @@ use codex_core::protocol::EventMsg; use codex_core::protocol::ExecApprovalRequestEvent; use codex_core::protocol::Op; use codex_core::protocol::ReviewDecision; +use codex_feedback::CodexFeedback; use codex_login::ServerOptions as LoginServerOptions; use codex_login::ShutdownHandle; use codex_login::run_login_server; @@ -136,6 +139,7 @@ pub(crate) struct CodexMessageProcessor { // Queue of pending interrupt requests per conversation. We reply when TurnAborted arrives. pending_interrupts: Arc>>>, pending_fuzzy_searches: Arc>>>, + feedback: CodexFeedback, } impl CodexMessageProcessor { @@ -145,6 +149,7 @@ impl CodexMessageProcessor { outgoing: Arc, codex_linux_sandbox_exe: Option, config: Arc, + feedback: CodexFeedback, ) -> Self { Self { auth_manager, @@ -156,6 +161,7 @@ impl CodexMessageProcessor { active_login: Arc::new(Mutex::new(None)), pending_interrupts: Arc::new(Mutex::new(HashMap::new())), pending_fuzzy_searches: Arc::new(Mutex::new(HashMap::new())), + feedback, } } @@ -275,6 +281,9 @@ impl CodexMessageProcessor { } => { self.get_account_rate_limits(request_id).await; } + ClientRequest::UploadFeedback { request_id, params } => { + self.upload_feedback(request_id, params).await; + } } } @@ -1418,6 +1427,77 @@ impl CodexMessageProcessor { let response = FuzzyFileSearchResponse { files: results }; self.outgoing.send_response(request_id, response).await; } + + async fn upload_feedback(&self, request_id: RequestId, params: UploadFeedbackParams) { + let UploadFeedbackParams { + classification, + reason, + conversation_id, + include_logs, + } = params; + + let snapshot = self.feedback.snapshot(conversation_id); + let thread_id = snapshot.thread_id.clone(); + + let validated_rollout_path = if include_logs { + match conversation_id { + Some(conv_id) => self.resolve_rollout_path(conv_id).await, + None => None, + } + } else { + None + }; + + let upload_result = tokio::task::spawn_blocking(move || { + let rollout_path_ref = validated_rollout_path.as_deref(); + snapshot.upload_feedback( + &classification, + reason.as_deref(), + include_logs, + rollout_path_ref, + ) + }) + .await; + + let upload_result = match upload_result { + Ok(result) => result, + Err(join_err) => { + let error = JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: format!("failed to upload feedback: {join_err}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + } + }; + + match upload_result { + Ok(()) => { + let response = UploadFeedbackResponse { thread_id }; + self.outgoing.send_response(request_id, response).await; + } + Err(err) => { + let error = JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: format!("failed to upload feedback: {err}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + } + } + } + + async fn resolve_rollout_path(&self, conversation_id: ConversationId) -> Option { + match self + .conversation_manager + .get_conversation(conversation_id) + .await + { + Ok(conv) => Some(conv.rollout_path()), + Err(_) => None, + } + } } async fn apply_bespoke_event_handling( diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index c4102f8262..6ef986919f 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -12,16 +12,19 @@ use crate::message_processor::MessageProcessor; use crate::outgoing_message::OutgoingMessage; use crate::outgoing_message::OutgoingMessageSender; use codex_app_server_protocol::JSONRPCMessage; +use codex_feedback::CodexFeedback; use tokio::io::AsyncBufReadExt; use tokio::io::AsyncWriteExt; use tokio::io::BufReader; use tokio::io::{self}; use tokio::sync::mpsc; +use tracing::Level; use tracing::debug; use tracing::error; use tracing::info; use tracing_subscriber::EnvFilter; use tracing_subscriber::Layer; +use tracing_subscriber::filter::Targets; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; @@ -82,6 +85,8 @@ pub async fn run_main( std::io::Error::new(ErrorKind::InvalidData, format!("error loading config: {e}")) })?; + let feedback = CodexFeedback::new(); + let otel = codex_core::otel_init::build_provider(&config, env!("CARGO_PKG_VERSION")).map_err(|e| { std::io::Error::new( @@ -96,8 +101,15 @@ pub async fn run_main( .with_writer(std::io::stderr) .with_filter(EnvFilter::from_default_env()); + let feedback_layer = tracing_subscriber::fmt::layer() + .with_writer(feedback.make_writer()) + .with_ansi(false) + .with_target(false) + .with_filter(Targets::new().with_default(Level::TRACE)); + let _ = tracing_subscriber::registry() .with(stderr_fmt) + .with(feedback_layer) .with(otel.as_ref().map(|provider| { OpenTelemetryTracingBridge::new(&provider.logger).with_filter( tracing_subscriber::filter::filter_fn(codex_core::otel_init::codex_export_filter), @@ -112,6 +124,7 @@ pub async fn run_main( outgoing_message_sender, codex_linux_sandbox_exe, std::sync::Arc::new(config), + feedback.clone(), ); async move { while let Some(msg) = incoming_rx.recv().await { diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 15086c19e1..a2c192cf2a 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -17,6 +17,7 @@ use codex_core::ConversationManager; use codex_core::config::Config; use codex_core::default_client::USER_AGENT_SUFFIX; use codex_core::default_client::get_codex_user_agent; +use codex_feedback::CodexFeedback; use codex_protocol::protocol::SessionSource; use std::sync::Arc; @@ -33,6 +34,7 @@ impl MessageProcessor { outgoing: OutgoingMessageSender, codex_linux_sandbox_exe: Option, config: Arc, + feedback: CodexFeedback, ) -> Self { let outgoing = Arc::new(outgoing); let auth_manager = AuthManager::shared(config.codex_home.clone(), false); @@ -46,6 +48,7 @@ impl MessageProcessor { outgoing.clone(), codex_linux_sandbox_exe, config, + feedback, ); Self { diff --git a/codex-rs/app-server/tests/common/mcp_process.rs b/codex-rs/app-server/tests/common/mcp_process.rs index f6d35b8d96..90c7645d58 100644 --- a/codex-rs/app-server/tests/common/mcp_process.rs +++ b/codex-rs/app-server/tests/common/mcp_process.rs @@ -30,6 +30,7 @@ use codex_app_server_protocol::SendUserMessageParams; use codex_app_server_protocol::SendUserTurnParams; use codex_app_server_protocol::ServerRequest; use codex_app_server_protocol::SetDefaultModelParams; +use codex_app_server_protocol::UploadFeedbackParams; use codex_app_server_protocol::JSONRPCError; use codex_app_server_protocol::JSONRPCMessage; @@ -242,6 +243,15 @@ impl McpProcess { self.send_request("account/rateLimits/read", None).await } + /// Send a `feedback/upload` JSON-RPC request. + pub async fn send_upload_feedback_request( + &mut self, + params: UploadFeedbackParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("feedback/upload", params).await + } + /// Send a `userInfo` JSON-RPC request. pub async fn send_user_info_request(&mut self) -> anyhow::Result { self.send_request("userInfo", None).await diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index d89ce5f886..a7134c9c9c 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -20,7 +20,6 @@ use async_channel::Sender; use codex_apply_patch::ApplyPatchAction; use codex_protocol::ConversationId; use codex_protocol::items::TurnItem; -use codex_protocol::protocol::ConversationPathResponseEvent; use codex_protocol::protocol::ExitedReviewModeEvent; use codex_protocol::protocol::ItemCompletedEvent; use codex_protocol::protocol::ItemStartedEvent; @@ -598,6 +597,19 @@ impl Session { self.tx_event.clone() } + /// Ensure all rollout writes are durably flushed. + pub(crate) async fn flush_rollout(&self) { + let recorder = { + let guard = self.services.rollout.lock().await; + guard.clone() + }; + if let Some(rec) = recorder + && let Err(e) = rec.flush().await + { + warn!("failed to flush rollout recorder: {e}"); + } + } + fn next_internal_sub_id(&self) -> String { let id = self .next_internal_sub_id @@ -612,6 +624,8 @@ impl Session { // Build and record initial items (user instructions + environment context) let items = self.build_initial_context(&turn_context); self.record_conversation_items(&turn_context, &items).await; + // Ensure initial items are visible to immediate readers (e.g., tests, forks). + self.flush_rollout().await; } InitialHistory::Resumed(_) | InitialHistory::Forked(_) => { let rollout_items = conversation_history.get_rollout_items(); @@ -628,6 +642,8 @@ impl Session { if persist && !rollout_items.is_empty() { self.persist_rollout_items(&rollout_items).await; } + // Flush after seeding history and any persisted rollout copy. + self.flush_rollout().await; } } } @@ -1401,33 +1417,7 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv sess.send_event_raw(event).await; break; } - Op::GetPath => { - let sub_id = sub.id.clone(); - // Flush rollout writes before returning the path so readers observe a consistent file. - let (path, rec_opt) = { - let guard = sess.services.rollout.lock().await; - match guard.as_ref() { - Some(rec) => (rec.get_rollout_path(), Some(rec.clone())), - None => { - error!("rollout recorder not found"); - continue; - } - } - }; - if let Some(rec) = rec_opt - && let Err(e) = rec.flush().await - { - warn!("failed to flush rollout recorder before GetHistory: {e}"); - } - let event = Event { - id: sub_id.clone(), - msg: EventMsg::ConversationPath(ConversationPathResponseEvent { - conversation_id: sess.conversation_id, - path, - }), - }; - sess.send_event_raw(event).await; - } + Op::Review { review_request } => { let turn_context = sess .new_turn_with_sub_id(sub.id.clone(), SessionSettingsUpdate::default()) @@ -2231,6 +2221,8 @@ pub(crate) async fn exit_review_mode( }], ) .await; + // Make the recorded review note visible immediately for readers. + session.flush_rollout().await; } fn mcp_init_error_display( diff --git a/codex-rs/core/src/codex_conversation.rs b/codex-rs/core/src/codex_conversation.rs index d3b00046fc..5bb9c97c5b 100644 --- a/codex-rs/core/src/codex_conversation.rs +++ b/codex-rs/core/src/codex_conversation.rs @@ -3,16 +3,21 @@ use crate::error::Result as CodexResult; use crate::protocol::Event; use crate::protocol::Op; use crate::protocol::Submission; +use std::path::PathBuf; pub struct CodexConversation { codex: Codex, + rollout_path: PathBuf, } /// Conduit for the bidirectional stream of messages that compose a conversation /// in Codex. impl CodexConversation { - pub(crate) fn new(codex: Codex) -> Self { - Self { codex } + pub(crate) fn new(codex: Codex, rollout_path: PathBuf) -> Self { + Self { + codex, + rollout_path, + } } pub async fn submit(&self, op: Op) -> CodexResult { @@ -27,4 +32,8 @@ impl CodexConversation { pub async fn next_event(&self) -> CodexResult { self.codex.next_event().await } + + pub fn rollout_path(&self) -> PathBuf { + self.rollout_path.clone() + } } diff --git a/codex-rs/core/src/conversation_manager.rs b/codex-rs/core/src/conversation_manager.rs index a30038f2eb..b911526f68 100644 --- a/codex-rs/core/src/conversation_manager.rs +++ b/codex-rs/core/src/conversation_manager.rs @@ -98,7 +98,10 @@ impl ConversationManager { } }; - let conversation = Arc::new(CodexConversation::new(codex)); + let conversation = Arc::new(CodexConversation::new( + codex, + session_configured.rollout_path.clone(), + )); self.conversations .write() .await diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index ea2954fac5..64688de9a5 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -72,7 +72,6 @@ pub(crate) fn should_persist_event_msg(ev: &EventMsg) -> bool { | EventMsg::PlanUpdate(_) | EventMsg::ShutdownComplete | EventMsg::ViewImageToolCall(_) - | EventMsg::ConversationPath(_) | EventMsg::ItemStarted(_) | EventMsg::ItemCompleted(_) => false, } diff --git a/codex-rs/core/src/rollout/recorder.rs b/codex-rs/core/src/rollout/recorder.rs index 95f5d479b8..93b614f922 100644 --- a/codex-rs/core/src/rollout/recorder.rs +++ b/codex-rs/core/src/rollout/recorder.rs @@ -267,10 +267,6 @@ impl RolloutRecorder { })) } - pub(crate) fn get_rollout_path(&self) -> PathBuf { - self.rollout_path.clone() - } - pub async fn shutdown(&self) -> std::io::Result<()> { let (tx_done, rx_done) = oneshot::channel(); match self.tx.send(RolloutCmd::Shutdown { ack: tx_done }).await { diff --git a/codex-rs/core/tests/suite/compact_resume_fork.rs b/codex-rs/core/tests/suite/compact_resume_fork.rs index 4261a30510..cea03ee751 100644 --- a/codex-rs/core/tests/suite/compact_resume_fork.rs +++ b/codex-rs/core/tests/suite/compact_resume_fork.rs @@ -18,7 +18,6 @@ use codex_core::built_in_model_providers; use codex_core::codex::compact::SUMMARIZATION_PROMPT; use codex_core::config::Config; use codex_core::config::OPENAI_DEFAULT_MODEL; -use codex_core::protocol::ConversationPathResponseEvent; use codex_core::protocol::EventMsg; use codex_core::protocol::Op; use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; @@ -61,7 +60,7 @@ async fn compact_resume_and_fork_preserve_model_history_view() { user_turn(&base, "hello world").await; compact_conversation(&base).await; user_turn(&base, "AFTER_COMPACT").await; - let base_path = fetch_conversation_path(&base, "base conversation").await; + let base_path = fetch_conversation_path(&base).await; assert!( base_path.exists(), "compact+resume test expects base path {base_path:?} to exist", @@ -69,7 +68,7 @@ async fn compact_resume_and_fork_preserve_model_history_view() { let resumed = resume_conversation(&manager, &config, base_path).await; user_turn(&resumed, "AFTER_RESUME").await; - let resumed_path = fetch_conversation_path(&resumed, "resumed conversation").await; + let resumed_path = fetch_conversation_path(&resumed).await; assert!( resumed_path.exists(), "compact+resume test expects resumed path {resumed_path:?} to exist", @@ -518,7 +517,7 @@ async fn compact_resume_after_second_compaction_preserves_history() { user_turn(&base, "hello world").await; compact_conversation(&base).await; user_turn(&base, "AFTER_COMPACT").await; - let base_path = fetch_conversation_path(&base, "base conversation").await; + let base_path = fetch_conversation_path(&base).await; assert!( base_path.exists(), "second compact test expects base path {base_path:?} to exist", @@ -526,7 +525,7 @@ async fn compact_resume_after_second_compaction_preserves_history() { let resumed = resume_conversation(&manager, &config, base_path).await; user_turn(&resumed, "AFTER_RESUME").await; - let resumed_path = fetch_conversation_path(&resumed, "resumed conversation").await; + let resumed_path = fetch_conversation_path(&resumed).await; assert!( resumed_path.exists(), "second compact test expects resumed path {resumed_path:?} to exist", @@ -537,7 +536,7 @@ async fn compact_resume_after_second_compaction_preserves_history() { compact_conversation(&forked).await; user_turn(&forked, "AFTER_COMPACT_2").await; - let forked_path = fetch_conversation_path(&forked, "forked conversation").await; + let forked_path = fetch_conversation_path(&forked).await; assert!( forked_path.exists(), "second compact test expects forked path {forked_path:?} to exist", @@ -792,22 +791,8 @@ async fn compact_conversation(conversation: &Arc) { wait_for_event(conversation, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; } -async fn fetch_conversation_path( - conversation: &Arc, - context: &str, -) -> std::path::PathBuf { - conversation - .submit(Op::GetPath) - .await - .expect("request conversation path"); - match wait_for_event(conversation, |ev| { - matches!(ev, EventMsg::ConversationPath(_)) - }) - .await - { - EventMsg::ConversationPath(ConversationPathResponseEvent { path, .. }) => path, - _ => panic!("expected ConversationPath event for {context}"), - } +async fn fetch_conversation_path(conversation: &Arc) -> std::path::PathBuf { + conversation.rollout_path() } async fn resume_conversation( diff --git a/codex-rs/core/tests/suite/fork_conversation.rs b/codex-rs/core/tests/suite/fork_conversation.rs index da2ff8c3f6..75b37ae7ef 100644 --- a/codex-rs/core/tests/suite/fork_conversation.rs +++ b/codex-rs/core/tests/suite/fork_conversation.rs @@ -4,7 +4,6 @@ use codex_core::ModelProviderInfo; use codex_core::NewConversation; use codex_core::built_in_model_providers; use codex_core::parse_turn_item; -use codex_core::protocol::ConversationPathResponseEvent; use codex_core::protocol::EventMsg; use codex_core::protocol::Op; use codex_core::protocol::RolloutItem; @@ -79,13 +78,7 @@ async fn fork_conversation_twice_drops_to_first_message() { } // Request history from the base conversation to obtain rollout path. - codex.submit(Op::GetPath).await.unwrap(); - let base_history = - wait_for_event(&codex, |ev| matches!(ev, EventMsg::ConversationPath(_))).await; - let base_path = match &base_history { - EventMsg::ConversationPath(ConversationPathResponseEvent { path, .. }) => path.clone(), - _ => panic!("expected ConversationHistory event"), - }; + let base_path = codex.rollout_path(); // GetHistory flushes before returning the path; no wait needed. @@ -140,15 +133,7 @@ async fn fork_conversation_twice_drops_to_first_message() { .await .expect("fork 1"); - codex_fork1.submit(Op::GetPath).await.unwrap(); - let fork1_history = wait_for_event(&codex_fork1, |ev| { - matches!(ev, EventMsg::ConversationPath(_)) - }) - .await; - let fork1_path = match &fork1_history { - EventMsg::ConversationPath(ConversationPathResponseEvent { path, .. }) => path.clone(), - _ => panic!("expected ConversationHistory event after first fork"), - }; + let fork1_path = codex_fork1.rollout_path(); // GetHistory on fork1 flushed; the file is ready. let fork1_items = read_items(&fork1_path); @@ -166,15 +151,7 @@ async fn fork_conversation_twice_drops_to_first_message() { .await .expect("fork 2"); - codex_fork2.submit(Op::GetPath).await.unwrap(); - let fork2_history = wait_for_event(&codex_fork2, |ev| { - matches!(ev, EventMsg::ConversationPath(_)) - }) - .await; - let fork2_path = match &fork2_history { - EventMsg::ConversationPath(ConversationPathResponseEvent { path, .. }) => path.clone(), - _ => panic!("expected ConversationHistory event after second fork"), - }; + let fork2_path = codex_fork2.rollout_path(); // GetHistory on fork2 flushed; the file is ready. let fork1_items = read_items(&fork1_path); let fork1_user_inputs = find_user_input_positions(&fork1_items); diff --git a/codex-rs/core/tests/suite/review.rs b/codex-rs/core/tests/suite/review.rs index 422acd922f..5577de7caa 100644 --- a/codex-rs/core/tests/suite/review.rs +++ b/codex-rs/core/tests/suite/review.rs @@ -7,7 +7,6 @@ use codex_core::REVIEW_PROMPT; use codex_core::ResponseItem; use codex_core::built_in_model_providers; use codex_core::config::Config; -use codex_core::protocol::ConversationPathResponseEvent; use codex_core::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG; use codex_core::protocol::EventMsg; use codex_core::protocol::ExitedReviewModeEvent; @@ -120,13 +119,7 @@ async fn review_op_emits_lifecycle_and_review_output() { // Also verify that a user message with the header and a formatted finding // was recorded back in the parent session's rollout. - codex.submit(Op::GetPath).await.unwrap(); - let history_event = - wait_for_event(&codex, |ev| matches!(ev, EventMsg::ConversationPath(_))).await; - let path = match history_event { - EventMsg::ConversationPath(ConversationPathResponseEvent { path, .. }) => path, - other => panic!("expected ConversationPath event, got {other:?}"), - }; + let path = codex.rollout_path(); let text = std::fs::read_to_string(&path).expect("read rollout file"); let mut saw_header = false; @@ -482,13 +475,7 @@ async fn review_input_isolated_from_parent_history() { assert_eq!(instructions, REVIEW_PROMPT); // Also verify that a user interruption note was recorded in the rollout. - codex.submit(Op::GetPath).await.unwrap(); - let history_event = - wait_for_event(&codex, |ev| matches!(ev, EventMsg::ConversationPath(_))).await; - let path = match history_event { - EventMsg::ConversationPath(ConversationPathResponseEvent { path, .. }) => path, - other => panic!("expected ConversationPath event, got {other:?}"), - }; + let path = codex.rollout_path(); let text = std::fs::read_to_string(&path).expect("read rollout file"); let mut saw_interruption_message = false; for line in text.lines() { 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 b07cd16d4b..bd37a438fb 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -510,7 +510,6 @@ impl EventProcessor for EventProcessorWithHumanOutput { } }, EventMsg::ShutdownComplete => return CodexStatus::Shutdown, - EventMsg::ConversationPath(_) => {} EventMsg::UserMessage(_) => {} EventMsg::EnteredReviewMode(_) => {} EventMsg::ExitedReviewMode(_) => {} diff --git a/codex-rs/feedback/src/lib.rs b/codex-rs/feedback/src/lib.rs index b1adb3db3f..e1ccc3aac9 100644 --- a/codex-rs/feedback/src/lib.rs +++ b/codex-rs/feedback/src/lib.rs @@ -172,7 +172,6 @@ impl CodexLogSnapshot { &self, classification: &str, reason: Option<&str>, - cli_version: &str, include_logs: bool, rollout_path: Option<&std::path::Path>, ) -> Result<()> { @@ -198,6 +197,7 @@ impl CodexLogSnapshot { ..Default::default() }); + let cli_version = env!("CARGO_PKG_VERSION"); let mut tags = BTreeMap::from([ (String::from("thread_id"), self.thread_id.to_string()), (String::from("classification"), classification.to_string()), diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index a6af754d21..9f826f4e86 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -281,7 +281,6 @@ async fn run_codex_tool_session_inner( | EventMsg::GetHistoryEntryResponse(_) | EventMsg::PlanUpdate(_) | EventMsg::TurnAborted(_) - | EventMsg::ConversationPath(_) | EventMsg::UserMessage(_) | EventMsg::ShutdownComplete | EventMsg::ViewImageToolCall(_) diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 2334561e0e..3cf16bb840 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -166,10 +166,6 @@ pub enum Op { /// Request a single history entry identified by `log_id` + `offset`. GetHistoryEntryRequest { offset: usize, log_id: u64 }, - /// Request the full in-memory conversation transcript for the current session. - /// Reply is delivered via `EventMsg::ConversationHistory`. - GetPath, - /// Request the list of MCP tools available across all configured servers. /// Reply is delivered via `EventMsg::McpListToolsResponse`. ListMcpTools, @@ -519,8 +515,6 @@ pub enum EventMsg { /// Notification that the agent is shutting down. ShutdownComplete, - ConversationPath(ConversationPathResponseEvent), - /// Entered review mode. EnteredReviewMode(ReviewRequest), diff --git a/codex-rs/tui/src/app_backtrack.rs b/codex-rs/tui/src/app_backtrack.rs index b3e948ecb3..e2ded3d3ef 100644 --- a/codex-rs/tui/src/app_backtrack.rs +++ b/codex-rs/tui/src/app_backtrack.rs @@ -103,9 +103,16 @@ impl App { nth_user_message: usize, ) { self.backtrack.pending = Some((base_id, nth_user_message, prefill)); - self.app_event_tx.send(crate::app_event::AppEvent::CodexOp( - codex_core::protocol::Op::GetPath, - )); + if let Some(path) = self.chat_widget.rollout_path() { + let ev = ConversationPathResponseEvent { + conversation_id: base_id, + path, + }; + self.app_event_tx + .send(crate::app_event::AppEvent::ConversationHistory(ev)); + } else { + tracing::error!("rollout path unavailable; cannot backtrack"); + } } /// Open transcript overlay (enters alternate screen and shows full transcript). diff --git a/codex-rs/tui/src/bottom_pane/feedback_view.rs b/codex-rs/tui/src/bottom_pane/feedback_view.rs index 234dbbd253..0d42c0bebc 100644 --- a/codex-rs/tui/src/bottom_pane/feedback_view.rs +++ b/codex-rs/tui/src/bottom_pane/feedback_view.rs @@ -73,13 +73,11 @@ impl FeedbackNoteView { let rollout_path_ref = self.rollout_path.as_deref(); let classification = feedback_classification(self.category); - let cli_version = crate::version::CODEX_CLI_VERSION; let mut thread_id = self.snapshot.thread_id.clone(); let result = self.snapshot.upload_feedback( classification, reason_opt, - cli_version, self.include_logs, if self.include_logs { rollout_path_ref diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index fdebe15826..64dc89d884 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1516,10 +1516,6 @@ impl ChatWidget { self.on_user_message_event(ev); } } - EventMsg::ConversationPath(ev) => { - self.app_event_tx - .send(crate::app_event::AppEvent::ConversationHistory(ev)); - } EventMsg::EnteredReviewMode(review_request) => { self.on_entered_review_mode(review_request) } @@ -2250,6 +2246,10 @@ impl ChatWidget { self.conversation_id } + pub(crate) fn rollout_path(&self) -> Option { + self.current_rollout_path.clone() + } + /// Return a reference to the widget's current config (includes any /// runtime overrides applied via TUI, e.g., model or approval policy). pub(crate) fn config_ref(&self) -> &Config { From 5907422d6546929c8ce0dffe59f50d3bee502152 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Mon, 27 Oct 2025 02:03:30 -0700 Subject: [PATCH 25/35] feat: annotate conversations with model_provider for filtering (#5658) Because conversations that use the Responses API can have encrypted reasoning messages, trying to resume a conversation with a different provider could lead to confusing "failed to decrypt" errors. (This is reproducible by starting a conversation using ChatGPT login and resuming it as a conversation that uses OpenAI models via Azure.) This changes `ListConversationsParams` to take a `model_providers: Option>` and adds `model_provider` on each `ConversationSummary` it returns so these cases can be disambiguated. Note this ended up making changes to `codex-rs/core/src/rollout/tests.rs` because it had a number of cases where it expected `Some` for the value of `next_cursor`, but the list of rollouts was complete, so according to this docstring: https://github.com/openai/codex/blob/bcd64c7e7231d6316a2377d1525a0fa74f21b783/codex-rs/app-server-protocol/src/protocol.rs#L334-L337 If there are no more items to return, then `next_cursor` should be `None`. This PR updates that logic. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/5658). * #5803 * #5793 * __->__ #5658 --- codex-rs/app-server-protocol/src/protocol.rs | 8 + .../app-server/src/codex_message_processor.rs | 40 ++- .../app-server/tests/suite/list_resume.rs | 118 +++++++- codex-rs/core/src/rollout/list.rs | 65 ++++- codex-rs/core/src/rollout/recorder.rs | 13 +- codex-rs/core/src/rollout/tests.rs | 268 ++++++++++++++++-- codex-rs/core/tests/suite/cli_stream.rs | 14 +- codex-rs/core/tests/suite/client.rs | 3 +- codex-rs/core/tests/suite/review.rs | 3 +- .../core/tests/suite/rollout_list_find.rs | 3 +- codex-rs/exec/src/lib.rs | 12 +- codex-rs/protocol/src/protocol.rs | 2 + codex-rs/tui/src/lib.rs | 11 +- codex-rs/tui/src/resume_picker.rs | 74 ++++- 14 files changed, 560 insertions(+), 74 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol.rs b/codex-rs/app-server-protocol/src/protocol.rs index ca4be39e25..98b16a26e5 100644 --- a/codex-rs/app-server-protocol/src/protocol.rs +++ b/codex-rs/app-server-protocol/src/protocol.rs @@ -327,6 +327,12 @@ pub struct ListConversationsParams { /// Opaque pagination cursor returned by a previous call. #[serde(skip_serializing_if = "Option::is_none")] pub cursor: Option, + /// Optional model provider filter (matches against session metadata). + /// - None => filter by the server's default model provider + /// - Some([]) => no filtering, include all providers + /// - Some([...]) => only include sessions with one of the specified providers + #[serde(skip_serializing_if = "Option::is_none")] + pub model_providers: Option>, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] @@ -338,6 +344,8 @@ pub struct ConversationSummary { /// RFC3339 timestamp string for the session start, if available. #[serde(skip_serializing_if = "Option::is_none")] pub timestamp: Option, + /// Model provider recorded for the session (resolved when absent in metadata). + pub model_provider: String, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 59dd0f63e5..f6f81173b2 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -827,19 +827,38 @@ impl CodexMessageProcessor { request_id: RequestId, params: ListConversationsParams, ) { - let page_size = params.page_size.unwrap_or(25); + let ListConversationsParams { + page_size, + cursor, + model_providers: model_provider, + } = params; + let page_size = page_size.unwrap_or(25); // Decode the optional cursor string to a Cursor via serde (Cursor implements Deserialize from string) - let cursor_obj: Option = match params.cursor { + let cursor_obj: Option = match cursor { Some(s) => serde_json::from_str::(&format!("\"{s}\"")).ok(), None => None, }; let cursor_ref = cursor_obj.as_ref(); + let model_provider_filter = match model_provider { + Some(providers) => { + if providers.is_empty() { + None + } else { + Some(providers) + } + } + None => Some(vec![self.config.model_provider_id.clone()]), + }; + let model_provider_slice = model_provider_filter.as_deref(); + let fallback_provider = self.config.model_provider_id.clone(); let page = match RolloutRecorder::list_conversations( &self.config.codex_home, page_size, cursor_ref, INTERACTIVE_SESSION_SOURCES, + model_provider_slice, + fallback_provider.as_str(), ) .await { @@ -858,7 +877,7 @@ impl CodexMessageProcessor { let items = page .items .into_iter() - .filter_map(|it| extract_conversation_summary(it.path, &it.head)) + .filter_map(|it| extract_conversation_summary(it.path, &it.head, &fallback_provider)) .collect(); // Encode next_cursor as a plain string @@ -1707,6 +1726,7 @@ async fn on_exec_approval_response( fn extract_conversation_summary( path: PathBuf, head: &[serde_json::Value], + fallback_provider: &str, ) -> Option { let session_meta = match head.first() { Some(first_line) => serde_json::from_value::(first_line.clone()).ok()?, @@ -1731,12 +1751,17 @@ fn extract_conversation_summary( } else { Some(session_meta.timestamp.clone()) }; + let conversation_id = session_meta.id; + let model_provider = session_meta + .model_provider + .unwrap_or_else(|| fallback_provider.to_string()); Some(ConversationSummary { - conversation_id: session_meta.id, + conversation_id, timestamp, path, preview: preview.to_string(), + model_provider, }) } @@ -1760,7 +1785,8 @@ mod tests { "cwd": "/", "originator": "codex", "cli_version": "0.0.0", - "instructions": null + "instructions": null, + "model_provider": "test-provider" }), json!({ "type": "message", @@ -1780,7 +1806,8 @@ mod tests { }), ]; - let summary = extract_conversation_summary(path.clone(), &head).expect("summary"); + let summary = + extract_conversation_summary(path.clone(), &head, "test-provider").expect("summary"); assert_eq!(summary.conversation_id, conversation_id); assert_eq!( @@ -1789,6 +1816,7 @@ mod tests { ); assert_eq!(summary.path, path); assert_eq!(summary.preview, "Count to 5"); + assert_eq!(summary.model_provider, "test-provider"); Ok(()) } } diff --git a/codex-rs/app-server/tests/suite/list_resume.rs b/codex-rs/app-server/tests/suite/list_resume.rs index a4178b0873..85416f60bd 100644 --- a/codex-rs/app-server/tests/suite/list_resume.rs +++ b/codex-rs/app-server/tests/suite/list_resume.rs @@ -30,18 +30,21 @@ async fn test_list_and_resume_conversations() { "2025-01-02T12-00-00", "2025-01-02T12:00:00Z", "Hello A", + Some("openai"), ); create_fake_rollout( codex_home.path(), "2025-01-01T13-00-00", "2025-01-01T13:00:00Z", "Hello B", + Some("openai"), ); create_fake_rollout( codex_home.path(), "2025-01-01T12-00-00", "2025-01-01T12:00:00Z", "Hello C", + None, ); let mut mcp = McpProcess::new(codex_home.path()) @@ -57,6 +60,7 @@ async fn test_list_and_resume_conversations() { .send_list_conversations_request(ListConversationsParams { page_size: Some(2), cursor: None, + model_providers: None, }) .await .expect("send listConversations"); @@ -74,6 +78,8 @@ async fn test_list_and_resume_conversations() { // Newest first; preview text should match assert_eq!(items[0].preview, "Hello A"); assert_eq!(items[1].preview, "Hello B"); + assert_eq!(items[0].model_provider, "openai"); + assert_eq!(items[1].model_provider, "openai"); assert!(items[0].path.is_absolute()); assert!(next_cursor.is_some()); @@ -82,6 +88,7 @@ async fn test_list_and_resume_conversations() { .send_list_conversations_request(ListConversationsParams { page_size: Some(2), cursor: next_cursor, + model_providers: None, }) .await .expect("send listConversations page 2"); @@ -99,7 +106,88 @@ async fn test_list_and_resume_conversations() { } = to_response::(resp2).expect("deserialize response"); assert_eq!(items2.len(), 1); assert_eq!(items2[0].preview, "Hello C"); - assert!(next2.is_some()); + assert_eq!(items2[0].model_provider, "openai"); + assert_eq!(next2, None); + + // Add a conversation with an explicit non-OpenAI provider for filter tests. + create_fake_rollout( + codex_home.path(), + "2025-01-01T11-30-00", + "2025-01-01T11:30:00Z", + "Hello TP", + Some("test-provider"), + ); + + // Filtering by model provider should return only matching sessions. + let filter_req_id = mcp + .send_list_conversations_request(ListConversationsParams { + page_size: Some(10), + cursor: None, + model_providers: Some(vec!["test-provider".to_string()]), + }) + .await + .expect("send listConversations filtered"); + let filter_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(filter_req_id)), + ) + .await + .expect("listConversations filtered timeout") + .expect("listConversations filtered resp"); + let ListConversationsResponse { + items: filtered_items, + next_cursor: filtered_next, + } = to_response::(filter_resp).expect("deserialize filtered"); + assert_eq!(filtered_items.len(), 1); + assert_eq!(filtered_next, None); + assert_eq!(filtered_items[0].preview, "Hello TP"); + assert_eq!(filtered_items[0].model_provider, "test-provider"); + + // Empty filter should include every session regardless of provider metadata. + let unfiltered_req_id = mcp + .send_list_conversations_request(ListConversationsParams { + page_size: Some(10), + cursor: None, + model_providers: Some(Vec::new()), + }) + .await + .expect("send listConversations unfiltered"); + let unfiltered_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(unfiltered_req_id)), + ) + .await + .expect("listConversations unfiltered timeout") + .expect("listConversations unfiltered resp"); + let ListConversationsResponse { + items: unfiltered_items, + next_cursor: unfiltered_next, + } = to_response::(unfiltered_resp) + .expect("deserialize unfiltered response"); + assert_eq!(unfiltered_items.len(), 4); + assert!(unfiltered_next.is_none()); + + let empty_req_id = mcp + .send_list_conversations_request(ListConversationsParams { + page_size: Some(10), + cursor: None, + model_providers: Some(vec!["other".to_string()]), + }) + .await + .expect("send listConversations filtered empty"); + let empty_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(empty_req_id)), + ) + .await + .expect("listConversations filtered empty timeout") + .expect("listConversations filtered empty resp"); + let ListConversationsResponse { + items: empty_items, + next_cursor: empty_next, + } = to_response::(empty_resp).expect("deserialize filtered empty"); + assert!(empty_items.is_empty()); + assert!(empty_next.is_none()); // Now resume one of the sessions and expect a SessionConfigured notification and response. let resume_req_id = mcp @@ -152,7 +240,13 @@ async fn test_list_and_resume_conversations() { assert!(!conversation_id.to_string().is_empty()); } -fn create_fake_rollout(codex_home: &Path, filename_ts: &str, meta_rfc3339: &str, preview: &str) { +fn create_fake_rollout( + codex_home: &Path, + filename_ts: &str, + meta_rfc3339: &str, + preview: &str, + model_provider: Option<&str>, +) { let uuid = Uuid::new_v4(); // sessions/YYYY/MM/DD/ derived from filename_ts (YYYY-MM-DDThh-mm-ss) let year = &filename_ts[0..4]; @@ -164,18 +258,22 @@ fn create_fake_rollout(codex_home: &Path, filename_ts: &str, meta_rfc3339: &str, let file_path = dir.join(format!("rollout-{filename_ts}-{uuid}.jsonl")); let mut lines = Vec::new(); // Meta line with timestamp (flattened meta in payload for new schema) + let mut payload = json!({ + "id": uuid, + "timestamp": meta_rfc3339, + "cwd": "/", + "originator": "codex", + "cli_version": "0.0.0", + "instructions": null, + }); + if let Some(provider) = model_provider { + payload["model_provider"] = json!(provider); + } lines.push( json!({ "timestamp": meta_rfc3339, "type": "session_meta", - "payload": { - "id": uuid, - "timestamp": meta_rfc3339, - "cwd": "/", - "originator": "codex", - "cli_version": "0.0.0", - "instructions": null - } + "payload": payload }) .to_string(), ); diff --git a/codex-rs/core/src/rollout/list.rs b/codex-rs/core/src/rollout/list.rs index b142bc2d04..4a3fec7934 100644 --- a/codex-rs/core/src/rollout/list.rs +++ b/codex-rs/core/src/rollout/list.rs @@ -54,6 +54,7 @@ struct HeadTailSummary { saw_session_meta: bool, saw_user_event: bool, source: Option, + model_provider: Option, created_at: Option, updated_at: Option, } @@ -109,6 +110,8 @@ pub(crate) async fn get_conversations( page_size: usize, cursor: Option<&Cursor>, allowed_sources: &[SessionSource], + model_providers: Option<&[String]>, + default_provider: &str, ) -> io::Result { let mut root = codex_home.to_path_buf(); root.push(SESSIONS_SUBDIR); @@ -124,8 +127,17 @@ pub(crate) async fn get_conversations( let anchor = cursor.cloned(); - let result = - traverse_directories_for_paths(root.clone(), page_size, anchor, allowed_sources).await?; + let provider_matcher = + model_providers.and_then(|filters| ProviderMatcher::new(filters, default_provider)); + + let result = traverse_directories_for_paths( + root.clone(), + page_size, + anchor, + allowed_sources, + provider_matcher.as_ref(), + ) + .await?; Ok(result) } @@ -145,6 +157,7 @@ async fn traverse_directories_for_paths( page_size: usize, anchor: Option, allowed_sources: &[SessionSource], + provider_matcher: Option<&ProviderMatcher<'_>>, ) -> io::Result { let mut items: Vec = Vec::with_capacity(page_size); let mut scanned_files = 0usize; @@ -153,6 +166,7 @@ async fn traverse_directories_for_paths( Some(c) => (c.ts, c.id), None => (OffsetDateTime::UNIX_EPOCH, Uuid::nil()), }; + let mut more_matches_available = false; let year_dirs = collect_dirs_desc(&root, |s| s.parse::().ok()).await?; @@ -184,6 +198,7 @@ async fn traverse_directories_for_paths( for (ts, sid, _name_str, path) in day_files.into_iter() { scanned_files += 1; if scanned_files >= MAX_SCAN_FILES && items.len() >= page_size { + more_matches_available = true; break 'outer; } if !anchor_passed { @@ -194,6 +209,7 @@ async fn traverse_directories_for_paths( } } if items.len() == page_size { + more_matches_available = true; break 'outer; } // Read head and simultaneously detect message events within the same @@ -208,6 +224,11 @@ async fn traverse_directories_for_paths( { continue; } + if let Some(matcher) = provider_matcher + && !matcher.matches(summary.model_provider.as_deref()) + { + continue; + } // Apply filters: must have session meta and at least one user message event if summary.saw_session_meta && summary.saw_user_event { let HeadTailSummary { @@ -231,12 +252,21 @@ async fn traverse_directories_for_paths( } } - let next = build_next_cursor(&items); + let reached_scan_cap = scanned_files >= MAX_SCAN_FILES; + if reached_scan_cap && !items.is_empty() { + more_matches_available = true; + } + + let next = if more_matches_available { + build_next_cursor(&items) + } else { + None + }; Ok(ConversationsPage { items, next_cursor: next, num_scanned_files: scanned_files, - reached_scan_cap: scanned_files >= MAX_SCAN_FILES, + reached_scan_cap, }) } @@ -328,6 +358,32 @@ fn parse_timestamp_uuid_from_filename(name: &str) -> Option<(OffsetDateTime, Uui Some((ts, uuid)) } +struct ProviderMatcher<'a> { + filters: &'a [String], + matches_default_provider: bool, +} + +impl<'a> ProviderMatcher<'a> { + fn new(filters: &'a [String], default_provider: &'a str) -> Option { + if filters.is_empty() { + return None; + } + + let matches_default_provider = filters.iter().any(|provider| provider == default_provider); + Some(Self { + filters, + matches_default_provider, + }) + } + + fn matches(&self, session_provider: Option<&str>) -> bool { + match session_provider { + Some(provider) => self.filters.iter().any(|candidate| candidate == provider), + None => self.matches_default_provider, + } + } +} + async fn read_head_and_tail( path: &Path, head_limit: usize, @@ -354,6 +410,7 @@ async fn read_head_and_tail( match rollout_line.item { RolloutItem::SessionMeta(session_meta_line) => { summary.source = Some(session_meta_line.meta.source); + summary.model_provider = session_meta_line.meta.model_provider.clone(); summary.created_at = summary .created_at .clone() diff --git a/codex-rs/core/src/rollout/recorder.rs b/codex-rs/core/src/rollout/recorder.rs index 93b614f922..d575da9652 100644 --- a/codex-rs/core/src/rollout/recorder.rs +++ b/codex-rs/core/src/rollout/recorder.rs @@ -97,8 +97,18 @@ impl RolloutRecorder { page_size: usize, cursor: Option<&Cursor>, allowed_sources: &[SessionSource], + model_providers: Option<&[String]>, + default_provider: &str, ) -> std::io::Result { - get_conversations(codex_home, page_size, cursor, allowed_sources).await + get_conversations( + codex_home, + page_size, + cursor, + allowed_sources, + model_providers, + default_provider, + ) + .await } /// Attempt to create a new [`RolloutRecorder`]. If the sessions directory @@ -137,6 +147,7 @@ impl RolloutRecorder { cli_version: env!("CARGO_PKG_VERSION").to_string(), instructions, source, + model_provider: Some(config.model_provider_id.clone()), }), ) } diff --git a/codex-rs/core/src/rollout/tests.rs b/codex-rs/core/src/rollout/tests.rs index 617e5189c2..a7bc9f8c8f 100644 --- a/codex-rs/core/src/rollout/tests.rs +++ b/codex-rs/core/src/rollout/tests.rs @@ -32,6 +32,14 @@ use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::UserMessageEvent; const NO_SOURCE_FILTER: &[SessionSource] = &[]; +const TEST_PROVIDER: &str = "test-provider"; + +fn provider_vec(providers: &[&str]) -> Vec { + providers + .iter() + .map(std::string::ToString::to_string) + .collect() +} fn write_session_file( root: &Path, @@ -39,6 +47,24 @@ fn write_session_file( uuid: Uuid, num_records: usize, source: Option, +) -> std::io::Result<(OffsetDateTime, Uuid)> { + write_session_file_with_provider( + root, + ts_str, + uuid, + num_records, + source, + Some("test-provider"), + ) +} + +fn write_session_file_with_provider( + root: &Path, + ts_str: &str, + uuid: Uuid, + num_records: usize, + source: Option, + model_provider: Option<&str>, ) -> std::io::Result<(OffsetDateTime, Uuid)> { let format: &[FormatItem] = format_description!("[year]-[month]-[day]T[hour]-[minute]-[second]"); @@ -68,6 +94,9 @@ fn write_session_file( if let Some(source) = source { payload["source"] = serde_json::to_value(source).unwrap(); } + if let Some(provider) = model_provider { + payload["model_provider"] = serde_json::Value::String(provider.to_string()); + } let meta = serde_json::json!({ "timestamp": ts_str, @@ -134,9 +163,17 @@ async fn test_list_conversations_latest_first() { ) .unwrap(); - let page = get_conversations(home, 10, None, INTERACTIVE_SESSION_SOURCES) - .await - .unwrap(); + let provider_filter = provider_vec(&[TEST_PROVIDER]); + let page = get_conversations( + home, + 10, + None, + INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + TEST_PROVIDER, + ) + .await + .unwrap(); // Build expected objects let p1 = home @@ -166,6 +203,7 @@ async fn test_list_conversations_latest_first() { "originator": "test_originator", "cli_version": "test_version", "source": "vscode", + "model_provider": "test-provider", })]; let head_2 = vec![serde_json::json!({ "id": u2, @@ -175,6 +213,7 @@ async fn test_list_conversations_latest_first() { "originator": "test_originator", "cli_version": "test_version", "source": "vscode", + "model_provider": "test-provider", })]; let head_1 = vec![serde_json::json!({ "id": u1, @@ -184,11 +223,9 @@ async fn test_list_conversations_latest_first() { "originator": "test_originator", "cli_version": "test_version", "source": "vscode", + "model_provider": "test-provider", })]; - let expected_cursor: Cursor = - serde_json::from_str(&format!("\"2025-01-01T12-00-00|{u1}\"")).unwrap(); - let expected = ConversationsPage { items: vec![ ConversationItem { @@ -213,7 +250,7 @@ async fn test_list_conversations_latest_first() { updated_at: Some("2025-01-01T12-00-00".into()), }, ], - next_cursor: Some(expected_cursor), + next_cursor: None, num_scanned_files: 3, reached_scan_cap: false, }; @@ -275,9 +312,17 @@ async fn test_pagination_cursor() { ) .unwrap(); - let page1 = get_conversations(home, 2, None, INTERACTIVE_SESSION_SOURCES) - .await - .unwrap(); + let provider_filter = provider_vec(&[TEST_PROVIDER]); + let page1 = get_conversations( + home, + 2, + None, + INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + TEST_PROVIDER, + ) + .await + .unwrap(); let p5 = home .join("sessions") .join("2025") @@ -298,6 +343,7 @@ async fn test_pagination_cursor() { "originator": "test_originator", "cli_version": "test_version", "source": "vscode", + "model_provider": "test-provider", })]; let head_4 = vec![serde_json::json!({ "id": u4, @@ -307,6 +353,7 @@ async fn test_pagination_cursor() { "originator": "test_originator", "cli_version": "test_version", "source": "vscode", + "model_provider": "test-provider", })]; let expected_cursor1: Cursor = serde_json::from_str(&format!("\"2025-03-04T09-00-00|{u4}\"")).unwrap(); @@ -338,6 +385,8 @@ async fn test_pagination_cursor() { 2, page1.next_cursor.as_ref(), INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + TEST_PROVIDER, ) .await .unwrap(); @@ -361,6 +410,7 @@ async fn test_pagination_cursor() { "originator": "test_originator", "cli_version": "test_version", "source": "vscode", + "model_provider": "test-provider", })]; let head_2 = vec![serde_json::json!({ "id": u2, @@ -370,6 +420,7 @@ async fn test_pagination_cursor() { "originator": "test_originator", "cli_version": "test_version", "source": "vscode", + "model_provider": "test-provider", })]; let expected_cursor2: Cursor = serde_json::from_str(&format!("\"2025-03-02T09-00-00|{u2}\"")).unwrap(); @@ -401,6 +452,8 @@ async fn test_pagination_cursor() { 2, page2.next_cursor.as_ref(), INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + TEST_PROVIDER, ) .await .unwrap(); @@ -418,9 +471,8 @@ async fn test_pagination_cursor() { "originator": "test_originator", "cli_version": "test_version", "source": "vscode", + "model_provider": "test-provider", })]; - let expected_cursor3: Cursor = - serde_json::from_str(&format!("\"2025-03-01T09-00-00|{u1}\"")).unwrap(); let expected_page3 = ConversationsPage { items: vec![ConversationItem { path: p1, @@ -429,7 +481,7 @@ async fn test_pagination_cursor() { created_at: Some("2025-03-01T09-00-00".into()), updated_at: Some("2025-03-01T09-00-00".into()), }], - next_cursor: Some(expected_cursor3), + next_cursor: None, num_scanned_files: 5, // scanned 05, 04 (anchor), 03, 02 (anchor), 01 reached_scan_cap: false, }; @@ -445,9 +497,17 @@ async fn test_get_conversation_contents() { let ts = "2025-04-01T10-30-00"; write_session_file(home, ts, uuid, 2, Some(SessionSource::VSCode)).unwrap(); - let page = get_conversations(home, 1, None, INTERACTIVE_SESSION_SOURCES) - .await - .unwrap(); + let provider_filter = provider_vec(&[TEST_PROVIDER]); + let page = get_conversations( + home, + 1, + None, + INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + TEST_PROVIDER, + ) + .await + .unwrap(); let path = &page.items[0].path; let content = get_conversation(path).await.unwrap(); @@ -467,8 +527,8 @@ async fn test_get_conversation_contents() { "originator": "test_originator", "cli_version": "test_version", "source": "vscode", + "model_provider": "test-provider", })]; - let expected_cursor: Cursor = serde_json::from_str(&format!("\"{ts}|{uuid}\"")).unwrap(); let expected_page = ConversationsPage { items: vec![ConversationItem { path: expected_path, @@ -477,7 +537,7 @@ async fn test_get_conversation_contents() { created_at: Some(ts.into()), updated_at: Some(ts.into()), }], - next_cursor: Some(expected_cursor), + next_cursor: None, num_scanned_files: 1, reached_scan_cap: false, }; @@ -495,6 +555,7 @@ async fn test_get_conversation_contents() { "originator": "test_originator", "cli_version": "test_version", "source": "vscode", + "model_provider": "test-provider", } }); let user_event = serde_json::json!({ @@ -532,6 +593,7 @@ async fn test_tail_includes_last_response_items() -> Result<()> { originator: "test_originator".into(), cli_version: "test_version".into(), source: SessionSource::VSCode, + model_provider: Some("test-provider".into()), }, git: None, }), @@ -563,7 +625,16 @@ async fn test_tail_includes_last_response_items() -> Result<()> { } drop(file); - let page = get_conversations(home, 1, None, INTERACTIVE_SESSION_SOURCES).await?; + let provider_filter = provider_vec(&[TEST_PROVIDER]); + let page = get_conversations( + home, + 1, + None, + INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + TEST_PROVIDER, + ) + .await?; let item = page.items.first().expect("conversation item"); let tail_len = item.tail.len(); assert_eq!(tail_len, 10usize.min(total_messages)); @@ -615,6 +686,7 @@ async fn test_tail_handles_short_sessions() -> Result<()> { originator: "test_originator".into(), cli_version: "test_version".into(), source: SessionSource::VSCode, + model_provider: Some("test-provider".into()), }, git: None, }), @@ -645,7 +717,16 @@ async fn test_tail_handles_short_sessions() -> Result<()> { } drop(file); - let page = get_conversations(home, 1, None, INTERACTIVE_SESSION_SOURCES).await?; + let provider_filter = provider_vec(&[TEST_PROVIDER]); + let page = get_conversations( + home, + 1, + None, + INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + TEST_PROVIDER, + ) + .await?; let tail = &page.items.first().expect("conversation item").tail; assert_eq!(tail.len(), 3); @@ -699,6 +780,7 @@ async fn test_tail_skips_trailing_non_responses() -> Result<()> { originator: "test_originator".into(), cli_version: "test_version".into(), source: SessionSource::VSCode, + model_provider: Some("test-provider".into()), }, git: None, }), @@ -743,7 +825,16 @@ async fn test_tail_skips_trailing_non_responses() -> Result<()> { writeln!(file, "{}", serde_json::to_string(&shutdown_event)?)?; drop(file); - let page = get_conversations(home, 1, None, INTERACTIVE_SESSION_SOURCES).await?; + let provider_filter = provider_vec(&[TEST_PROVIDER]); + let page = get_conversations( + home, + 1, + None, + INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + TEST_PROVIDER, + ) + .await?; let tail = &page.items.first().expect("conversation item").tail; let expected: Vec = (0..4) @@ -785,9 +876,17 @@ async fn test_stable_ordering_same_second_pagination() { write_session_file(home, ts, u2, 0, Some(SessionSource::VSCode)).unwrap(); write_session_file(home, ts, u3, 0, Some(SessionSource::VSCode)).unwrap(); - let page1 = get_conversations(home, 2, None, INTERACTIVE_SESSION_SOURCES) - .await - .unwrap(); + let provider_filter = provider_vec(&[TEST_PROVIDER]); + let page1 = get_conversations( + home, + 2, + None, + INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + TEST_PROVIDER, + ) + .await + .unwrap(); let p3 = home .join("sessions") @@ -810,6 +909,7 @@ async fn test_stable_ordering_same_second_pagination() { "originator": "test_originator", "cli_version": "test_version", "source": "vscode", + "model_provider": "test-provider", })] }; let expected_cursor1: Cursor = serde_json::from_str(&format!("\"{ts}|{u2}\"")).unwrap(); @@ -841,6 +941,8 @@ async fn test_stable_ordering_same_second_pagination() { 2, page1.next_cursor.as_ref(), INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + TEST_PROVIDER, ) .await .unwrap(); @@ -850,7 +952,6 @@ async fn test_stable_ordering_same_second_pagination() { .join("07") .join("01") .join(format!("rollout-2025-07-01T00-00-00-{u1}.jsonl")); - let expected_cursor2: Cursor = serde_json::from_str(&format!("\"{ts}|{u1}\"")).unwrap(); let expected_page2 = ConversationsPage { items: vec![ConversationItem { path: p1, @@ -859,7 +960,7 @@ async fn test_stable_ordering_same_second_pagination() { created_at: Some(ts.to_string()), updated_at: Some(ts.to_string()), }], - next_cursor: Some(expected_cursor2), + next_cursor: None, num_scanned_files: 3, // scanned u3, u2 (anchor), u1 reached_scan_cap: false, }; @@ -891,9 +992,17 @@ async fn test_source_filter_excludes_non_matching_sessions() { ) .unwrap(); - let interactive_only = get_conversations(home, 10, None, INTERACTIVE_SESSION_SOURCES) - .await - .unwrap(); + let provider_filter = provider_vec(&[TEST_PROVIDER]); + let interactive_only = get_conversations( + home, + 10, + None, + INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + TEST_PROVIDER, + ) + .await + .unwrap(); let paths: Vec<_> = interactive_only .items .iter() @@ -905,7 +1014,7 @@ async fn test_source_filter_excludes_non_matching_sessions() { path.ends_with("rollout-2025-08-02T10-00-00-00000000-0000-0000-0000-00000000002a.jsonl") })); - let all_sessions = get_conversations(home, 10, None, NO_SOURCE_FILTER) + let all_sessions = get_conversations(home, 10, None, NO_SOURCE_FILTER, None, TEST_PROVIDER) .await .unwrap(); let all_paths: Vec<_> = all_sessions @@ -921,3 +1030,102 @@ async fn test_source_filter_excludes_non_matching_sessions() { path.ends_with("rollout-2025-08-01T10-00-00-00000000-0000-0000-0000-00000000004d.jsonl") })); } + +#[tokio::test] +async fn test_model_provider_filter_selects_only_matching_sessions() -> Result<()> { + let temp = TempDir::new().unwrap(); + let home = temp.path(); + + let openai_id = Uuid::from_u128(1); + let beta_id = Uuid::from_u128(2); + let none_id = Uuid::from_u128(3); + + write_session_file_with_provider( + home, + "2025-09-01T12-00-00", + openai_id, + 1, + Some(SessionSource::VSCode), + Some("openai"), + )?; + write_session_file_with_provider( + home, + "2025-09-01T11-00-00", + beta_id, + 1, + Some(SessionSource::VSCode), + Some("beta"), + )?; + write_session_file_with_provider( + home, + "2025-09-01T10-00-00", + none_id, + 1, + Some(SessionSource::VSCode), + None, + )?; + + let openai_id_str = openai_id.to_string(); + let none_id_str = none_id.to_string(); + let openai_filter = provider_vec(&["openai"]); + let openai_sessions = get_conversations( + home, + 10, + None, + NO_SOURCE_FILTER, + Some(openai_filter.as_slice()), + "openai", + ) + .await?; + assert_eq!(openai_sessions.items.len(), 2); + let openai_ids: Vec<_> = openai_sessions + .items + .iter() + .filter_map(|item| { + item.head + .first() + .and_then(|value| value.get("id")) + .and_then(serde_json::Value::as_str) + .map(str::to_string) + }) + .collect(); + assert!(openai_ids.contains(&openai_id_str)); + assert!(openai_ids.contains(&none_id_str)); + + let beta_filter = provider_vec(&["beta"]); + let beta_sessions = get_conversations( + home, + 10, + None, + NO_SOURCE_FILTER, + Some(beta_filter.as_slice()), + "openai", + ) + .await?; + assert_eq!(beta_sessions.items.len(), 1); + let beta_id_str = beta_id.to_string(); + let beta_head = beta_sessions + .items + .first() + .and_then(|item| item.head.first()) + .and_then(|value| value.get("id")) + .and_then(serde_json::Value::as_str); + assert_eq!(beta_head, Some(beta_id_str.as_str())); + + let unknown_filter = provider_vec(&["unknown"]); + let unknown_sessions = get_conversations( + home, + 10, + None, + NO_SOURCE_FILTER, + Some(unknown_filter.as_slice()), + "openai", + ) + .await?; + assert!(unknown_sessions.items.is_empty()); + + let all_sessions = get_conversations(home, 10, None, NO_SOURCE_FILTER, None, "openai").await?; + assert_eq!(all_sessions.items.len(), 3); + + Ok(()) +} diff --git a/codex-rs/core/tests/suite/cli_stream.rs b/codex-rs/core/tests/suite/cli_stream.rs index 497730926a..4c1f5fb8a8 100644 --- a/codex-rs/core/tests/suite/cli_stream.rs +++ b/codex-rs/core/tests/suite/cli_stream.rs @@ -75,9 +75,17 @@ async fn chat_mode_stream_cli() { server.verify().await; // Verify a new session rollout was created and is discoverable via list_conversations - let page = RolloutRecorder::list_conversations(home.path(), 10, None, &[]) - .await - .expect("list conversations"); + let provider_filter = vec!["mock".to_string()]; + let page = RolloutRecorder::list_conversations( + home.path(), + 10, + None, + &[], + Some(provider_filter.as_slice()), + "mock", + ) + .await + .expect("list conversations"); assert!( !page.items.is_empty(), "expected at least one session to be listed" diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 8730f1f38f..e302a1c114 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -154,7 +154,8 @@ async fn resume_includes_initial_messages_and_sends_prior_items() { "instructions": "be nice", "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "model_provider": "test-provider" } }) ) diff --git a/codex-rs/core/tests/suite/review.rs b/codex-rs/core/tests/suite/review.rs index 5577de7caa..fdf7669d1d 100644 --- a/codex-rs/core/tests/suite/review.rs +++ b/codex-rs/core/tests/suite/review.rs @@ -368,7 +368,8 @@ async fn review_input_isolated_from_parent_history() { "instructions": null, "cwd": ".", "originator": "test_originator", - "cli_version": "test_version" + "cli_version": "test_version", + "model_provider": "test-provider" } }); f.write_all(format!("{meta_line}\n").as_bytes()) diff --git a/codex-rs/core/tests/suite/rollout_list_find.rs b/codex-rs/core/tests/suite/rollout_list_find.rs index a38f0565c0..1d40718d4b 100644 --- a/codex-rs/core/tests/suite/rollout_list_find.rs +++ b/codex-rs/core/tests/suite/rollout_list_find.rs @@ -28,7 +28,8 @@ fn write_minimal_rollout_with_id(codex_home: &Path, id: Uuid) -> PathBuf { "instructions": null, "cwd": ".", "originator": "test", - "cli_version": "test" + "cli_version": "test", + "model_provider": "test-provider" } }) ) diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 2e615df0c6..10a4376161 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -389,8 +389,16 @@ async fn resolve_resume_path( args: &crate::cli::ResumeArgs, ) -> anyhow::Result> { if args.last { - match codex_core::RolloutRecorder::list_conversations(&config.codex_home, 1, None, &[]) - .await + let default_provider_filter = vec![config.model_provider_id.clone()]; + match codex_core::RolloutRecorder::list_conversations( + &config.codex_home, + 1, + None, + &[], + Some(default_provider_filter.as_slice()), + &config.model_provider_id, + ) + .await { Ok(page) => Ok(page.items.first().map(|it| it.path.clone())), Err(e) => { diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 3cf16bb840..1b4a6fccf1 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -935,6 +935,7 @@ pub struct SessionMeta { pub instructions: Option, #[serde(default)] pub source: SessionSource, + pub model_provider: Option, } impl Default for SessionMeta { @@ -947,6 +948,7 @@ impl Default for SessionMeta { cli_version: String::new(), instructions: None, source: SessionSource::default(), + model_provider: None, } } } diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 50f6b1a0dd..9030b7f665 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -391,11 +391,14 @@ async fn run_ratatui_app( } } } else if cli.resume_last { + let provider_filter = vec![config.model_provider_id.clone()]; match RolloutRecorder::list_conversations( &config.codex_home, 1, None, INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + &config.model_provider_id, ) .await { @@ -407,7 +410,13 @@ async fn run_ratatui_app( Err(_) => resume_picker::ResumeSelection::StartFresh, } } else if cli.resume_picker { - match resume_picker::run_resume_picker(&mut tui, &config.codex_home).await? { + match resume_picker::run_resume_picker( + &mut tui, + &config.codex_home, + &config.model_provider_id, + ) + .await? + { resume_picker::ResumeSelection::Exit => { restore(); session_log::log_session_end(); diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index b735ff9374..3104b32735 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -49,6 +49,7 @@ struct PageLoadRequest { cursor: Option, request_token: usize, search_token: Option, + default_provider: String, } type PageLoader = Arc; @@ -64,19 +65,28 @@ enum BackgroundEvent { /// Interactive session picker that lists recorded rollout files with simple /// search and pagination. Shows the first user input as the preview, relative /// time (e.g., "5 seconds ago"), and the absolute path. -pub async fn run_resume_picker(tui: &mut Tui, codex_home: &Path) -> Result { +pub async fn run_resume_picker( + tui: &mut Tui, + codex_home: &Path, + default_provider: &str, +) -> Result { let alt = AltScreenGuard::enter(tui); let (bg_tx, bg_rx) = mpsc::unbounded_channel(); + let default_provider = default_provider.to_string(); + let loader_tx = bg_tx.clone(); let page_loader: PageLoader = Arc::new(move |request: PageLoadRequest| { let tx = loader_tx.clone(); tokio::spawn(async move { + let provider_filter = vec![request.default_provider.clone()]; let page = RolloutRecorder::list_conversations( &request.codex_home, PAGE_SIZE, request.cursor.as_ref(), INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + request.default_provider.as_str(), ) .await; let _ = tx.send(BackgroundEvent::PageLoaded { @@ -91,6 +101,7 @@ pub async fn run_resume_picker(tui: &mut Tui, codex_home: &Path) -> Result, + default_provider: String, } struct PaginationState { @@ -225,7 +237,12 @@ struct Row { } impl PickerState { - fn new(codex_home: PathBuf, requester: FrameRequester, page_loader: PageLoader) -> Self { + fn new( + codex_home: PathBuf, + requester: FrameRequester, + page_loader: PageLoader, + default_provider: String, + ) -> Self { Self { codex_home, requester, @@ -246,6 +263,7 @@ impl PickerState { next_search_token: 0, page_loader, view_rows: None, + default_provider, } } @@ -324,11 +342,14 @@ impl PickerState { } async fn load_initial_page(&mut self) -> Result<()> { + let provider_filter = vec![self.default_provider.clone()]; let page = RolloutRecorder::list_conversations( &self.codex_home, PAGE_SIZE, None, INTERACTIVE_SESSION_SOURCES, + Some(provider_filter.as_slice()), + self.default_provider.as_str(), ) .await?; self.reset_pagination(); @@ -552,6 +573,7 @@ impl PickerState { cursor: Some(cursor), request_token, search_token, + default_provider: self.default_provider.clone(), }); } @@ -1061,8 +1083,12 @@ mod tests { use ratatui::layout::Layout; let loader: PageLoader = Arc::new(|_| {}); - let mut state = - PickerState::new(PathBuf::from("/tmp"), FrameRequester::test_dummy(), loader); + let mut state = PickerState::new( + PathBuf::from("/tmp"), + FrameRequester::test_dummy(), + loader, + String::from("openai"), + ); let now = Utc::now(); let rows = vec![ @@ -1117,8 +1143,12 @@ mod tests { #[test] fn pageless_scrolling_deduplicates_and_keeps_order() { let loader: PageLoader = Arc::new(|_| {}); - let mut state = - PickerState::new(PathBuf::from("/tmp"), FrameRequester::test_dummy(), loader); + let mut state = PickerState::new( + PathBuf::from("/tmp"), + FrameRequester::test_dummy(), + loader, + String::from("openai"), + ); state.reset_pagination(); state.ingest_page(page( @@ -1179,8 +1209,12 @@ mod tests { request_sink.lock().unwrap().push(req); }); - let mut state = - PickerState::new(PathBuf::from("/tmp"), FrameRequester::test_dummy(), loader); + let mut state = PickerState::new( + PathBuf::from("/tmp"), + FrameRequester::test_dummy(), + loader, + String::from("openai"), + ); state.reset_pagination(); state.ingest_page(page( vec![ @@ -1204,8 +1238,12 @@ mod tests { #[test] fn page_navigation_uses_view_rows() { let loader: PageLoader = Arc::new(|_| {}); - let mut state = - PickerState::new(PathBuf::from("/tmp"), FrameRequester::test_dummy(), loader); + let mut state = PickerState::new( + PathBuf::from("/tmp"), + FrameRequester::test_dummy(), + loader, + String::from("openai"), + ); let mut items = Vec::new(); for idx in 0..20 { @@ -1248,8 +1286,12 @@ mod tests { #[test] fn up_at_bottom_does_not_scroll_when_visible() { let loader: PageLoader = Arc::new(|_| {}); - let mut state = - PickerState::new(PathBuf::from("/tmp"), FrameRequester::test_dummy(), loader); + let mut state = PickerState::new( + PathBuf::from("/tmp"), + FrameRequester::test_dummy(), + loader, + String::from("openai"), + ); let mut items = Vec::new(); for idx in 0..10 { @@ -1288,8 +1330,12 @@ mod tests { request_sink.lock().unwrap().push(req); }); - let mut state = - PickerState::new(PathBuf::from("/tmp"), FrameRequester::test_dummy(), loader); + let mut state = PickerState::new( + PathBuf::from("/tmp"), + FrameRequester::test_dummy(), + loader, + String::from("openai"), + ); state.reset_pagination(); state.ingest_page(page( vec![make_item( From 15fa2283e7ea6d267e5e94d815ca532e29fe3ab3 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Mon, 27 Oct 2025 02:33:30 -0700 Subject: [PATCH 26/35] feat: update NewConversationParams to take an optional model_provider (#5793) An AppServer client should be able to use any (`model_provider`, `model`) in the user's config. `NewConversationParams` already supported specifying the `model`, but this PR expands it to support `model_provider`, as well. --- [//]: # (BEGIN SAPLING FOOTER) Stack created with [Sapling](https://sapling-scm.com). Best reviewed with [ReviewStack](https://reviewstack.dev/openai/codex/pull/5793). * #5803 * __->__ #5793 --- codex-rs/app-server-protocol/src/protocol.rs | 5 +++++ codex-rs/app-server/src/codex_message_processor.rs | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/codex-rs/app-server-protocol/src/protocol.rs b/codex-rs/app-server-protocol/src/protocol.rs index 98b16a26e5..74e9b6f9e2 100644 --- a/codex-rs/app-server-protocol/src/protocol.rs +++ b/codex-rs/app-server-protocol/src/protocol.rs @@ -266,6 +266,10 @@ pub struct NewConversationParams { #[serde(skip_serializing_if = "Option::is_none")] pub model: Option, + /// Override the model provider to use for this session. + #[serde(skip_serializing_if = "Option::is_none")] + pub model_provider: Option, + /// Configuration profile from config.toml to specify default options. #[serde(skip_serializing_if = "Option::is_none")] pub profile: Option, @@ -1032,6 +1036,7 @@ mod tests { request_id: RequestId::Integer(42), params: NewConversationParams { model: Some("gpt-5-codex".to_string()), + model_provider: None, profile: None, cwd: None, approval_policy: Some(AskForApproval::OnRequest), diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index f6f81173b2..9b66322047 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -1610,6 +1610,7 @@ async fn derive_config_from_params( ) -> std::io::Result { let NewConversationParams { model, + model_provider, profile, cwd, approval_policy, @@ -1625,7 +1626,7 @@ async fn derive_config_from_params( cwd: cwd.map(PathBuf::from), approval_policy, sandbox_mode, - model_provider: None, + model_provider, codex_linux_sandbox_exe, base_instructions, include_apply_patch_tool, From e92c4f65612b4fad71246b55368a7fd98fb28eef Mon Sep 17 00:00:00 2001 From: jif-oai Date: Mon, 27 Oct 2025 10:09:10 +0000 Subject: [PATCH 27/35] feat: async ghost commit (#5618) --- codex-rs/Cargo.lock | 2 + codex-rs/core/Cargo.toml | 2 + codex-rs/core/src/chat_completions.rs | 5 + codex-rs/core/src/codex.rs | 64 +++++++++- codex-rs/core/src/conversation_history.rs | 8 +- codex-rs/core/src/features.rs | 8 ++ codex-rs/core/src/rollout/policy.rs | 3 +- codex-rs/core/src/tasks/ghost_snapshot.rs | 112 ++++++++++++++++++ codex-rs/core/src/tasks/mod.rs | 2 + codex-rs/core/src/tools/parallel.rs | 5 + .../core/tests/suite/compact_resume_fork.rs | 31 ++++- codex-rs/protocol/src/models.rs | 6 + codex-rs/utils/readiness/src/lib.rs | 52 +++++++- 13 files changed, 289 insertions(+), 11 deletions(-) create mode 100644 codex-rs/core/src/tasks/ghost_snapshot.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 5025c82e7a..ecaf7df4b7 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1063,10 +1063,12 @@ dependencies = [ "codex-apply-patch", "codex-async-utils", "codex-file-search", + "codex-git-tooling", "codex-otel", "codex-protocol", "codex-rmcp-client", "codex-utils-pty", + "codex-utils-readiness", "codex-utils-string", "codex-utils-tokenizer", "core-foundation 0.9.4", diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 9b0e433972..92e63b1fe5 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -24,10 +24,12 @@ codex-apply-patch = { workspace = true } codex-file-search = { workspace = true } codex-otel = { workspace = true, features = ["otel"] } codex-protocol = { workspace = true } +codex-git-tooling = { workspace = true } codex-rmcp-client = { workspace = true } codex-async-utils = { workspace = true } codex-utils-string = { workspace = true } codex-utils-pty = { workspace = true } +codex-utils-readiness = { workspace = true } codex-utils-tokenizer = { workspace = true } dirs = { workspace = true } dunce = { workspace = true } diff --git a/codex-rs/core/src/chat_completions.rs b/codex-rs/core/src/chat_completions.rs index ac1d7f9cf5..76cbdf9f0a 100644 --- a/codex-rs/core/src/chat_completions.rs +++ b/codex-rs/core/src/chat_completions.rs @@ -76,6 +76,7 @@ pub(crate) async fn stream_chat_completions( ResponseItem::CustomToolCall { .. } => {} ResponseItem::CustomToolCallOutput { .. } => {} ResponseItem::WebSearchCall { .. } => {} + ResponseItem::GhostSnapshot { .. } => {} } } @@ -270,6 +271,10 @@ pub(crate) async fn stream_chat_completions( "content": output, })); } + ResponseItem::GhostSnapshot { .. } => { + // Ghost snapshots annotate history but are not sent to the model. + continue; + } ResponseItem::Reasoning { .. } | ResponseItem::WebSearchCall { .. } | ResponseItem::Other => { diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index a7134c9c9c..bb052d9d9a 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -104,8 +104,11 @@ use crate::state::SessionServices; use crate::state::SessionState; use crate::state::TaskKind; use crate::tasks::CompactTask; +use crate::tasks::GhostSnapshotTask; use crate::tasks::RegularTask; use crate::tasks::ReviewTask; +use crate::tasks::SessionTask; +use crate::tasks::SessionTaskContext; use crate::tools::ToolRouter; use crate::tools::context::SharedTurnDiffTracker; use crate::tools::parallel::ToolCallRuntime; @@ -128,6 +131,8 @@ use codex_protocol::models::ResponseInputItem; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::InitialHistory; use codex_protocol::user_input::UserInput; +use codex_utils_readiness::Readiness; +use codex_utils_readiness::ReadinessFlag; pub mod compact; use self::compact::build_compacted_history; @@ -178,6 +183,7 @@ impl Codex { sandbox_policy: config.sandbox_policy.clone(), cwd: config.cwd.clone(), original_config_do_not_use: Arc::clone(&config), + features: config.features.clone(), }; // Generate a unique ID for the lifetime of this Codex session. @@ -271,6 +277,7 @@ pub(crate) struct TurnContext { pub(crate) is_review_mode: bool, pub(crate) final_output_json_schema: Option, pub(crate) codex_linux_sandbox_exe: Option, + pub(crate) tool_call_gate: Arc, } impl TurnContext { @@ -312,6 +319,9 @@ pub(crate) struct SessionConfiguration { /// operate deterministically. cwd: PathBuf, + /// Set of feature flags for this session + features: Features, + // TODO(pakrym): Remove config from here original_config_do_not_use: Arc, } @@ -406,6 +416,7 @@ impl Session { is_review_mode: false, final_output_json_schema: None, codex_linux_sandbox_exe: config.codex_linux_sandbox_exe.clone(), + tool_call_gate: Arc::new(ReadinessFlag::new()), } } @@ -1096,6 +1107,43 @@ impl Session { self.send_event(turn_context, event).await; } + async fn maybe_start_ghost_snapshot( + self: &Arc, + turn_context: Arc, + cancellation_token: CancellationToken, + ) { + if turn_context.is_review_mode + || !self + .state + .lock() + .await + .session_configuration + .features + .enabled(Feature::GhostCommit) + { + return; + } + + let token = match turn_context.tool_call_gate.subscribe().await { + Ok(token) => token, + Err(err) => { + warn!("failed to subscribe to ghost snapshot readiness: {err}"); + return; + } + }; + + info!("spawning ghost snapshot task"); + let task = GhostSnapshotTask::new(token); + Arc::new(task) + .run( + Arc::new(SessionTaskContext::new(self.clone())), + turn_context.clone(), + Vec::new(), + cancellation_token, + ) + .await; + } + /// Returns the input if there was no task running to inject into pub async fn inject_input(&self, input: Vec) -> Result<(), Vec> { let mut active = self.active_turn.lock().await; @@ -1508,6 +1556,7 @@ async fn spawn_review_thread( is_review_mode: true, final_output_json_schema: None, codex_linux_sandbox_exe: parent_turn_context.codex_linux_sandbox_exe.clone(), + tool_call_gate: Arc::new(ReadinessFlag::new()), }; // Seed the child task with the review prompt as the initial user message. @@ -1571,6 +1620,8 @@ pub(crate) async fn run_task( .await; } + sess.maybe_start_ghost_snapshot(Arc::clone(&turn_context), cancellation_token.child_token()) + .await; let mut last_agent_message: Option = None; // Although from the perspective of codex.rs, TurnDiffTracker has the lifecycle of a Task which contains // many turns, from the perspective of the user, it is a single turn. @@ -1763,6 +1814,13 @@ fn parse_review_output_event(text: &str) -> ReviewOutputEvent { } } +fn filter_model_visible_history(input: Vec) -> Vec { + input + .into_iter() + .filter(|item| !matches!(item, ResponseItem::GhostSnapshot { .. })) + .collect() +} + async fn run_turn( sess: Arc, turn_context: Arc, @@ -1783,7 +1841,7 @@ async fn run_turn( .supports_parallel_tool_calls; let parallel_tool_calls = model_supports_parallel; let prompt = Prompt { - input, + input: filter_model_visible_history(input), tools: router.specs(), parallel_tool_calls, base_instructions_override: turn_context.base_instructions.clone(), @@ -2278,6 +2336,8 @@ fn is_mcp_client_startup_timeout_error(error: &anyhow::Error) -> bool { || error_message.contains("timed out handshaking with MCP server") } +use crate::features::Feature; +use crate::features::Features; #[cfg(test)] pub(crate) use tests::make_session_and_context; @@ -2594,6 +2654,7 @@ mod tests { sandbox_policy: config.sandbox_policy.clone(), cwd: config.cwd.clone(), original_config_do_not_use: Arc::clone(&config), + features: Features::default(), }; let state = SessionState::new(session_configuration.clone()); @@ -2662,6 +2723,7 @@ mod tests { sandbox_policy: config.sandbox_policy.clone(), cwd: config.cwd.clone(), original_config_do_not_use: Arc::clone(&config), + features: Features::default(), }; let state = SessionState::new(session_configuration.clone()); diff --git a/codex-rs/core/src/conversation_history.rs b/codex-rs/core/src/conversation_history.rs index b7f153d29f..08fa8cebed 100644 --- a/codex-rs/core/src/conversation_history.rs +++ b/codex-rs/core/src/conversation_history.rs @@ -2,6 +2,7 @@ use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TokenUsageInfo; +use std::ops::Deref; use tracing::error; /// Transcript of conversation history @@ -40,7 +41,9 @@ impl ConversationHistory { I::Item: std::ops::Deref, { for item in items { - if !is_api_message(&item) { + let item_ref = item.deref(); + let is_ghost_snapshot = matches!(item_ref, ResponseItem::GhostSnapshot { .. }); + if !is_api_message(item_ref) && !is_ghost_snapshot { continue; } @@ -165,6 +168,7 @@ impl ConversationHistory { | ResponseItem::WebSearchCall { .. } | ResponseItem::FunctionCallOutput { .. } | ResponseItem::CustomToolCallOutput { .. } + | ResponseItem::GhostSnapshot { .. } | ResponseItem::Other | ResponseItem::Message { .. } => { // nothing to do for these variants @@ -231,6 +235,7 @@ impl ConversationHistory { | ResponseItem::LocalShellCall { .. } | ResponseItem::Reasoning { .. } | ResponseItem::WebSearchCall { .. } + | ResponseItem::GhostSnapshot { .. } | ResponseItem::Other | ResponseItem::Message { .. } => { // nothing to do for these variants @@ -355,6 +360,7 @@ fn is_api_message(message: &ResponseItem) -> bool { | ResponseItem::LocalShellCall { .. } | ResponseItem::Reasoning { .. } | ResponseItem::WebSearchCall { .. } => true, + ResponseItem::GhostSnapshot { .. } => false, ResponseItem::Other => false, } } diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index 8e8a203062..c10305b800 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -41,6 +41,8 @@ pub enum Feature { WebSearchRequest, /// Enable the model-based risk assessments for sandboxed commands. SandboxCommandAssessment, + /// Create a ghost commit at each turn. + GhostCommit, } impl Feature { @@ -248,4 +250,10 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::Experimental, default_enabled: false, }, + FeatureSpec { + id: Feature::GhostCommit, + key: "ghost_commit", + stage: Stage::Experimental, + default_enabled: false, + }, ]; diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index 64688de9a5..746ae93bc3 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -26,7 +26,8 @@ pub(crate) fn should_persist_response_item(item: &ResponseItem) -> bool { | ResponseItem::FunctionCallOutput { .. } | ResponseItem::CustomToolCall { .. } | ResponseItem::CustomToolCallOutput { .. } - | ResponseItem::WebSearchCall { .. } => true, + | ResponseItem::WebSearchCall { .. } + | ResponseItem::GhostSnapshot { .. } => true, ResponseItem::Other => false, } } diff --git a/codex-rs/core/src/tasks/ghost_snapshot.rs b/codex-rs/core/src/tasks/ghost_snapshot.rs new file mode 100644 index 0000000000..55c64a29dc --- /dev/null +++ b/codex-rs/core/src/tasks/ghost_snapshot.rs @@ -0,0 +1,112 @@ +use crate::codex::TurnContext; +use crate::state::TaskKind; +use crate::tasks::SessionTask; +use crate::tasks::SessionTaskContext; +use async_trait::async_trait; +use codex_git_tooling::CreateGhostCommitOptions; +use codex_git_tooling::GitToolingError; +use codex_git_tooling::create_ghost_commit; +use codex_protocol::models::ResponseItem; +use codex_protocol::user_input::UserInput; +use codex_utils_readiness::Readiness; +use codex_utils_readiness::Token; +use std::borrow::ToOwned; +use std::sync::Arc; +use tokio_util::sync::CancellationToken; +use tracing::info; +use tracing::warn; + +pub(crate) struct GhostSnapshotTask { + token: Token, +} + +#[async_trait] +impl SessionTask for GhostSnapshotTask { + fn kind(&self) -> TaskKind { + TaskKind::Regular + } + + async fn run( + self: Arc, + session: Arc, + ctx: Arc, + _input: Vec, + cancellation_token: CancellationToken, + ) -> Option { + tokio::task::spawn(async move { + let token = self.token; + let ctx_for_task = Arc::clone(&ctx); + let cancelled = tokio::select! { + _ = cancellation_token.cancelled() => true, + _ = async { + let repo_path = ctx_for_task.cwd.clone(); + // Required to run in a dedicated blocking pool. + match tokio::task::spawn_blocking(move || { + let options = CreateGhostCommitOptions::new(&repo_path); + create_ghost_commit(&options) + }) + .await + { + Ok(Ok(ghost_commit)) => { + info!("ghost snapshot blocking task finished"); + session + .session + .record_conversation_items(&ctx, &[ResponseItem::GhostSnapshot { + commit_id: ghost_commit.id().to_string(), + parent: ghost_commit.parent().map(ToOwned::to_owned), + }]) + .await; + info!("ghost commit captured: {}", ghost_commit.id()); + } + Ok(Err(err)) => { + warn!( + sub_id = ctx_for_task.sub_id.as_str(), + "failed to capture ghost snapshot: {err}" + ); + let message = match err { + GitToolingError::NotAGitRepository { .. } => { + "Snapshots disabled: current directory is not a Git repository." + .to_string() + } + _ => format!("Snapshots disabled after ghost snapshot error: {err}."), + }; + session + .session + .notify_background_event(&ctx_for_task, message) + .await; + } + Err(err) => { + warn!( + sub_id = ctx_for_task.sub_id.as_str(), + "ghost snapshot task panicked: {err}" + ); + let message = + format!("Snapshots disabled after ghost snapshot panic: {err}."); + session + .session + .notify_background_event(&ctx_for_task, message) + .await; + } + } + } => false, + }; + + if cancelled { + info!("ghost snapshot task cancelled"); + } + + match ctx.tool_call_gate.mark_ready(token).await { + Ok(true) => info!("ghost snapshot gate marked ready"), + Ok(false) => warn!("ghost snapshot gate already ready"), + Err(err) => warn!("failed to mark ghost snapshot ready: {err}"), + } + }); + None + } +} + +impl GhostSnapshotTask { + pub(crate) fn new(token: Token) -> Self { + Self { token } + } +} diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 79527814e3..a5afbca2e3 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -1,4 +1,5 @@ mod compact; +mod ghost_snapshot; mod regular; mod review; @@ -25,6 +26,7 @@ use crate::state::TaskKind; use codex_protocol::user_input::UserInput; pub(crate) use compact::CompactTask; +pub(crate) use ghost_snapshot::GhostSnapshotTask; pub(crate) use regular::RegularTask; pub(crate) use review::ReviewTask; diff --git a/codex-rs/core/src/tools/parallel.rs b/codex-rs/core/src/tools/parallel.rs index 7f42bf5b05..449b8e6553 100644 --- a/codex-rs/core/src/tools/parallel.rs +++ b/codex-rs/core/src/tools/parallel.rs @@ -15,6 +15,7 @@ use crate::tools::router::ToolCall; use crate::tools::router::ToolRouter; use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseInputItem; +use codex_utils_readiness::Readiness; pub(crate) struct ToolCallRuntime { router: Arc, @@ -53,12 +54,16 @@ impl ToolCallRuntime { let tracker = Arc::clone(&self.tracker); let lock = Arc::clone(&self.parallel_execution); let aborted_response = Self::aborted_response(&call); + let readiness = self.turn_context.tool_call_gate.clone(); let handle: AbortOnDropHandle> = AbortOnDropHandle::new(tokio::spawn(async move { tokio::select! { _ = cancellation_token.cancelled() => Ok(aborted_response), res = async { + tracing::info!("waiting for tool gate"); + readiness.wait_ready().await; + tracing::info!("tool gate released"); let _guard = if supports_parallel { Either::Left(lock.read().await) } else { diff --git a/codex-rs/core/tests/suite/compact_resume_fork.rs b/codex-rs/core/tests/suite/compact_resume_fork.rs index cea03ee751..b13c6e14fd 100644 --- a/codex-rs/core/tests/suite/compact_resume_fork.rs +++ b/codex-rs/core/tests/suite/compact_resume_fork.rs @@ -41,6 +41,29 @@ fn network_disabled() -> bool { std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() } +fn filter_out_ghost_snapshot_entries(items: &[Value]) -> Vec { + items + .iter() + .filter(|item| !is_ghost_snapshot_message(item)) + .cloned() + .collect() +} + +fn is_ghost_snapshot_message(item: &Value) -> bool { + if item.get("type").and_then(Value::as_str) != Some("message") { + return false; + } + if item.get("role").and_then(Value::as_str) != Some("user") { + return false; + } + item.get("content") + .and_then(Value::as_array) + .and_then(|content| content.first()) + .and_then(|entry| entry.get("text")) + .and_then(Value::as_str) + .is_some_and(|text| text.trim_start().starts_with("")) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] /// Scenario: compact an initial conversation, resume it, fork one turn back, and /// ensure the model-visible history matches expectations at each request. @@ -556,13 +579,15 @@ async fn compact_resume_after_second_compaction_preserves_history() { let resume_input_array = input_after_resume .as_array() .expect("input after resume should be an array"); + let compact_filtered = filter_out_ghost_snapshot_entries(compact_input_array); + let resume_filtered = filter_out_ghost_snapshot_entries(resume_input_array); assert!( - compact_input_array.len() <= resume_input_array.len(), + compact_filtered.len() <= resume_filtered.len(), "after-resume input should have at least as many items as after-compact" ); assert_eq!( - compact_input_array.as_slice(), - &resume_input_array[..compact_input_array.len()] + compact_filtered.as_slice(), + &resume_filtered[..compact_filtered.len()] ); // hard coded test let prompt = requests[0]["instructions"] diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index 4e99455bd2..02d557535e 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -116,6 +116,12 @@ pub enum ResponseItem { status: Option, action: WebSearchAction, }, + // Generated by the harness but considered exactly as a model response. + GhostSnapshot { + commit_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + parent: Option, + }, #[serde(other)] Other, } diff --git a/codex-rs/utils/readiness/src/lib.rs b/codex-rs/utils/readiness/src/lib.rs index ac3a323fae..8b92f9387a 100644 --- a/codex-rs/utils/readiness/src/lib.rs +++ b/codex-rs/utils/readiness/src/lib.rs @@ -1,6 +1,7 @@ //! Readiness flag with token-based authorization and async waiting (Tokio). use std::collections::HashSet; +use std::fmt; use std::sync::atomic::AtomicBool; use std::sync::atomic::AtomicI32; use std::sync::atomic::Ordering; @@ -71,6 +72,10 @@ impl ReadinessFlag { .map_err(|_| errors::ReadinessError::TokenLockFailed)?; Ok(f(&mut guard)) } + + fn load_ready(&self) -> bool { + self.ready.load(Ordering::Acquire) + } } impl Default for ReadinessFlag { @@ -79,14 +84,37 @@ impl Default for ReadinessFlag { } } +impl fmt::Debug for ReadinessFlag { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ReadinessFlag") + .field("ready", &self.load_ready()) + .finish() + } +} + #[async_trait::async_trait] impl Readiness for ReadinessFlag { fn is_ready(&self) -> bool { - self.ready.load(Ordering::Acquire) + if self.load_ready() { + return true; + } + + if let Ok(tokens) = self.tokens.try_lock() + && tokens.is_empty() + { + let was_ready = self.ready.swap(true, Ordering::AcqRel); + drop(tokens); + if !was_ready { + let _ = self.tx.send(true); + } + return true; + } + + self.load_ready() } async fn subscribe(&self) -> Result { - if self.is_ready() { + if self.load_ready() { return Err(errors::ReadinessError::FlagAlreadyReady); } @@ -97,7 +125,7 @@ impl Readiness for ReadinessFlag { // check above and inserting the token. let inserted = self .with_tokens(|tokens| { - if self.is_ready() { + if self.load_ready() { return false; } tokens.insert(token); @@ -113,7 +141,7 @@ impl Readiness for ReadinessFlag { } async fn mark_ready(&self, token: Token) -> Result { - if self.is_ready() { + if self.load_ready() { return Ok(false); } if token.0 == 0 { @@ -202,7 +230,8 @@ mod tests { async fn mark_ready_rejects_unknown_token() -> Result<(), ReadinessError> { let flag = ReadinessFlag::new(); assert!(!flag.mark_ready(Token(42)).await?); - assert!(!flag.is_ready()); + assert!(!flag.load_ready()); + assert!(flag.is_ready()); Ok(()) } @@ -233,6 +262,19 @@ mod tests { Ok(()) } + #[tokio::test] + async fn is_ready_without_subscribers_marks_flag_ready() -> Result<(), ReadinessError> { + let flag = ReadinessFlag::new(); + + assert!(flag.is_ready()); + assert!(flag.is_ready()); + assert_matches!( + flag.subscribe().await, + Err(ReadinessError::FlagAlreadyReady) + ); + Ok(()) + } + #[tokio::test] async fn subscribe_returns_error_when_lock_is_held() { let flag = ReadinessFlag::new(); From afc4eaab8b51cf8d6340831ffcfc9ab6eb0ed4eb Mon Sep 17 00:00:00 2001 From: jif-oai Date: Mon, 27 Oct 2025 10:55:29 +0000 Subject: [PATCH 28/35] feat: TUI undo op (#5629) --- codex-rs/Cargo.lock | 17 +- codex-rs/core/src/codex.rs | 10 +- codex-rs/core/src/rollout/policy.rs | 2 + codex-rs/core/src/tasks/ghost_snapshot.rs | 4 +- codex-rs/core/src/tasks/mod.rs | 2 + codex-rs/core/src/tasks/undo.rs | 117 +++++++++ .../src/event_processor_with_human_output.rs | 45 ++-- codex-rs/git-tooling/Cargo.toml | 15 +- codex-rs/git-tooling/src/ghost_commits.rs | 226 +++++++++++++++++- codex-rs/git-tooling/src/lib.rs | 39 ++- codex-rs/git-tooling/src/operations.rs | 21 ++ codex-rs/mcp-server/src/codex_tool_runner.rs | 2 + codex-rs/protocol/Cargo.toml | 2 + codex-rs/protocol/src/models.rs | 5 +- codex-rs/protocol/src/protocol.rs | 20 ++ codex-rs/tui/Cargo.toml | 1 - codex-rs/tui/src/bottom_pane/mod.rs | 15 ++ codex-rs/tui/src/chatwidget.rs | 98 +++----- codex-rs/tui/src/chatwidget/tests.rs | 88 ++++++- codex-rs/tui/src/slash_command.rs | 13 +- 20 files changed, 604 insertions(+), 138 deletions(-) create mode 100644 codex-rs/core/src/tasks/undo.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index ecaf7df4b7..880efbbf4f 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1212,8 +1212,11 @@ version = "0.0.0" dependencies = [ "assert_matches", "pretty_assertions", + "schemars 0.8.22", + "serde", "tempfile", "thiserror 2.0.16", + "ts-rs", "walkdir", ] @@ -1331,6 +1334,7 @@ version = "0.0.0" dependencies = [ "anyhow", "base64", + "codex-git-tooling", "icu_decimal", "icu_locale_core", "mcp-types", @@ -1431,7 +1435,6 @@ dependencies = [ "codex-core", "codex-feedback", "codex-file-search", - "codex-git-tooling", "codex-login", "codex-ollama", "codex-protocol", @@ -5461,9 +5464,9 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.226" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0dca6411025b24b60bfa7ec1fe1f8e710ac09782dca409ee8237ba74b51295fd" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", "serde_derive", @@ -5471,18 +5474,18 @@ dependencies = [ [[package]] name = "serde_core" -version = "1.0.226" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba2ba63999edb9dac981fb34b3e5c0d111a69b0924e253ed29d83f7c99e966a4" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.226" +version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8db53ae22f34573731bafa1db20f04027b2d25e02d8205921b569171699cdb33" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index bb052d9d9a..65dad461fa 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -109,6 +109,7 @@ use crate::tasks::RegularTask; use crate::tasks::ReviewTask; use crate::tasks::SessionTask; use crate::tasks::SessionTaskContext; +use crate::tasks::UndoTask; use crate::tools::ToolRouter; use crate::tools::context::SharedTurnDiffTracker; use crate::tools::parallel::ToolCallRuntime; @@ -958,7 +959,7 @@ impl Session { state.record_items(items.iter()); } - async fn replace_history(&self, items: Vec) { + pub(crate) async fn replace_history(&self, items: Vec) { let mut state = self.state.lock().await; state.replace_history(items); } @@ -1420,6 +1421,13 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv }; sess.send_event_raw(event).await; } + Op::Undo => { + let turn_context = sess + .new_turn_with_sub_id(sub.id.clone(), SessionSettingsUpdate::default()) + .await; + sess.spawn_task(turn_context, Vec::new(), UndoTask::new()) + .await; + } Op::Compact => { let turn_context = sess .new_turn_with_sub_id(sub.id.clone(), SessionSettingsUpdate::default()) diff --git a/codex-rs/core/src/rollout/policy.rs b/codex-rs/core/src/rollout/policy.rs index 746ae93bc3..f1b786055e 100644 --- a/codex-rs/core/src/rollout/policy.rs +++ b/codex-rs/core/src/rollout/policy.rs @@ -43,6 +43,7 @@ pub(crate) fn should_persist_event_msg(ev: &EventMsg) -> bool { | EventMsg::TokenCount(_) | EventMsg::EnteredReviewMode(_) | EventMsg::ExitedReviewMode(_) + | EventMsg::UndoCompleted(_) | EventMsg::TurnAborted(_) => true, EventMsg::Error(_) | EventMsg::TaskStarted(_) @@ -68,6 +69,7 @@ pub(crate) fn should_persist_event_msg(ev: &EventMsg) -> bool { | EventMsg::PatchApplyEnd(_) | EventMsg::TurnDiff(_) | EventMsg::GetHistoryEntryResponse(_) + | EventMsg::UndoStarted(_) | EventMsg::McpListToolsResponse(_) | EventMsg::ListCustomPromptsResponse(_) | EventMsg::PlanUpdate(_) diff --git a/codex-rs/core/src/tasks/ghost_snapshot.rs b/codex-rs/core/src/tasks/ghost_snapshot.rs index 55c64a29dc..f421a91e4e 100644 --- a/codex-rs/core/src/tasks/ghost_snapshot.rs +++ b/codex-rs/core/src/tasks/ghost_snapshot.rs @@ -10,7 +10,6 @@ use codex_protocol::models::ResponseItem; use codex_protocol::user_input::UserInput; use codex_utils_readiness::Readiness; use codex_utils_readiness::Token; -use std::borrow::ToOwned; use std::sync::Arc; use tokio_util::sync::CancellationToken; use tracing::info; @@ -52,8 +51,7 @@ impl SessionTask for GhostSnapshotTask { session .session .record_conversation_items(&ctx, &[ResponseItem::GhostSnapshot { - commit_id: ghost_commit.id().to_string(), - parent: ghost_commit.parent().map(ToOwned::to_owned), + ghost_commit: ghost_commit.clone(), }]) .await; info!("ghost commit captured: {}", ghost_commit.id()); diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index a5afbca2e3..466bfe21a9 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -2,6 +2,7 @@ mod compact; mod ghost_snapshot; mod regular; mod review; +mod undo; use std::sync::Arc; use std::time::Duration; @@ -29,6 +30,7 @@ pub(crate) use compact::CompactTask; pub(crate) use ghost_snapshot::GhostSnapshotTask; pub(crate) use regular::RegularTask; pub(crate) use review::ReviewTask; +pub(crate) use undo::UndoTask; const GRACEFULL_INTERRUPTION_TIMEOUT_MS: u64 = 100; diff --git a/codex-rs/core/src/tasks/undo.rs b/codex-rs/core/src/tasks/undo.rs new file mode 100644 index 0000000000..e834eea02d --- /dev/null +++ b/codex-rs/core/src/tasks/undo.rs @@ -0,0 +1,117 @@ +use std::sync::Arc; + +use crate::codex::TurnContext; +use crate::protocol::EventMsg; +use crate::protocol::UndoCompletedEvent; +use crate::protocol::UndoStartedEvent; +use crate::state::TaskKind; +use crate::tasks::SessionTask; +use crate::tasks::SessionTaskContext; +use async_trait::async_trait; +use codex_git_tooling::restore_ghost_commit; +use codex_protocol::models::ResponseItem; +use codex_protocol::user_input::UserInput; +use tokio_util::sync::CancellationToken; +use tracing::error; +use tracing::info; +use tracing::warn; + +pub(crate) struct UndoTask; + +impl UndoTask { + pub(crate) fn new() -> Self { + Self + } +} + +#[async_trait] +impl SessionTask for UndoTask { + fn kind(&self) -> TaskKind { + TaskKind::Regular + } + + async fn run( + self: Arc, + session: Arc, + ctx: Arc, + _input: Vec, + cancellation_token: CancellationToken, + ) -> Option { + let sess = session.clone_session(); + sess.send_event( + ctx.as_ref(), + EventMsg::UndoStarted(UndoStartedEvent { + message: Some("Undo in progress...".to_string()), + }), + ) + .await; + + if cancellation_token.is_cancelled() { + sess.send_event( + ctx.as_ref(), + EventMsg::UndoCompleted(UndoCompletedEvent { + success: false, + message: Some("Undo cancelled.".to_string()), + }), + ) + .await; + return None; + } + + let mut history = sess.clone_history().await; + let mut items = history.get_history(); + let mut completed = UndoCompletedEvent { + success: false, + message: None, + }; + + let Some((idx, ghost_commit)) = + items + .iter() + .enumerate() + .rev() + .find_map(|(idx, item)| match item { + ResponseItem::GhostSnapshot { ghost_commit } => { + Some((idx, ghost_commit.clone())) + } + _ => None, + }) + else { + completed.message = Some("No ghost snapshot available to undo.".to_string()); + sess.send_event(ctx.as_ref(), EventMsg::UndoCompleted(completed)) + .await; + return None; + }; + + let commit_id = ghost_commit.id().to_string(); + let repo_path = ctx.cwd.clone(); + let restore_result = + tokio::task::spawn_blocking(move || restore_ghost_commit(&repo_path, &ghost_commit)) + .await; + + match restore_result { + Ok(Ok(())) => { + items.remove(idx); + sess.replace_history(items).await; + let short_id: String = commit_id.chars().take(7).collect(); + info!(commit_id = commit_id, "Undo restored ghost snapshot"); + completed.success = true; + completed.message = Some(format!("Undo restored snapshot {short_id}.")); + } + Ok(Err(err)) => { + let message = format!("Failed to restore snapshot {commit_id}: {err}"); + warn!("{message}"); + completed.message = Some(message); + } + Err(err) => { + let message = format!("Failed to restore snapshot {commit_id}: {err}"); + error!("{message}"); + completed.message = Some(message); + } + } + + sess.send_event(ctx.as_ref(), EventMsg::UndoCompleted(completed)) + .await; + None + } +} 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 bd37a438fb..2d06c881a8 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -20,7 +20,6 @@ use codex_core::protocol::StreamErrorEvent; use codex_core::protocol::TaskCompleteEvent; use codex_core::protocol::TurnAbortReason; use codex_core::protocol::TurnDiffEvent; -use codex_core::protocol::WebSearchBeginEvent; use codex_core::protocol::WebSearchEndEvent; use codex_protocol::num_format::format_with_separators; use owo_colors::OwoColorize; @@ -216,7 +215,6 @@ impl EventProcessor for EventProcessorWithHumanOutput { cwd.to_string_lossy(), ); } - EventMsg::ExecCommandOutputDelta(_) => {} EventMsg::ExecCommandEnd(ExecCommandEndEvent { aggregated_output, duration, @@ -283,7 +281,6 @@ impl EventProcessor for EventProcessorWithHumanOutput { } } } - EventMsg::WebSearchBegin(WebSearchBeginEvent { call_id: _ }) => {} EventMsg::WebSearchEnd(WebSearchEndEvent { call_id: _, query }) => { ts_msg!(self, "🌐 Searched: {query}"); } @@ -411,12 +408,6 @@ impl EventProcessor for EventProcessorWithHumanOutput { ); eprintln!("{unified_diff}"); } - EventMsg::ExecApprovalRequest(_) => { - // Should we exit? - } - EventMsg::ApplyPatchApprovalRequest(_) => { - // Should we exit? - } EventMsg::AgentReasoning(agent_reasoning_event) => { if self.show_agent_reasoning { ts_msg!( @@ -481,15 +472,6 @@ impl EventProcessor for EventProcessorWithHumanOutput { } } } - EventMsg::GetHistoryEntryResponse(_) => { - // Currently ignored in exec output. - } - EventMsg::McpListToolsResponse(_) => { - // Currently ignored in exec output. - } - EventMsg::ListCustomPromptsResponse(_) => { - // Currently ignored in exec output. - } EventMsg::ViewImageToolCall(view) => { ts_msg!( self, @@ -510,15 +492,24 @@ impl EventProcessor for EventProcessorWithHumanOutput { } }, EventMsg::ShutdownComplete => return CodexStatus::Shutdown, - EventMsg::UserMessage(_) => {} - EventMsg::EnteredReviewMode(_) => {} - EventMsg::ExitedReviewMode(_) => {} - EventMsg::AgentMessageDelta(_) => {} - EventMsg::AgentReasoningDelta(_) => {} - EventMsg::AgentReasoningRawContentDelta(_) => {} - EventMsg::ItemStarted(_) => {} - EventMsg::ItemCompleted(_) => {} - EventMsg::RawResponseItem(_) => {} + EventMsg::WebSearchBegin(_) + | EventMsg::ExecApprovalRequest(_) + | EventMsg::ApplyPatchApprovalRequest(_) + | EventMsg::ExecCommandOutputDelta(_) + | EventMsg::GetHistoryEntryResponse(_) + | EventMsg::McpListToolsResponse(_) + | EventMsg::ListCustomPromptsResponse(_) + | EventMsg::UserMessage(_) + | EventMsg::EnteredReviewMode(_) + | EventMsg::ExitedReviewMode(_) + | EventMsg::AgentMessageDelta(_) + | EventMsg::AgentReasoningDelta(_) + | EventMsg::AgentReasoningRawContentDelta(_) + | EventMsg::ItemStarted(_) + | EventMsg::ItemCompleted(_) + | EventMsg::RawResponseItem(_) + | EventMsg::UndoCompleted(_) + | EventMsg::UndoStarted(_) => {} } CodexStatus::Running } diff --git a/codex-rs/git-tooling/Cargo.toml b/codex-rs/git-tooling/Cargo.toml index 183221f3e1..c30d58de8d 100644 --- a/codex-rs/git-tooling/Cargo.toml +++ b/codex-rs/git-tooling/Cargo.toml @@ -9,13 +9,20 @@ name = "codex_git_tooling" path = "src/lib.rs" [dependencies] -tempfile = "3" -thiserror = "2" -walkdir = "2" +tempfile = { workspace = true } +thiserror = { workspace = true } +walkdir = { workspace = true } +schemars = { workspace = true } +serde = { workspace = true, features = ["derive"] } +ts-rs = { workspace = true, features = [ + "uuid-impl", + "serde-json-impl", + "no-serde-warnings", +] } [lints] workspace = true [dev-dependencies] assert_matches = { workspace = true } -pretty_assertions = "1.4.1" +pretty_assertions = { workspace = true } diff --git a/codex-rs/git-tooling/src/ghost_commits.rs b/codex-rs/git-tooling/src/ghost_commits.rs index 6c2a86166c..c5ebd7c02c 100644 --- a/codex-rs/git-tooling/src/ghost_commits.rs +++ b/codex-rs/git-tooling/src/ghost_commits.rs @@ -1,4 +1,7 @@ +use std::collections::HashSet; use std::ffi::OsString; +use std::fs; +use std::io; use std::path::Path; use std::path::PathBuf; @@ -14,6 +17,7 @@ use crate::operations::resolve_head; use crate::operations::resolve_repository_root; use crate::operations::run_git_for_status; use crate::operations::run_git_for_stdout; +use crate::operations::run_git_for_stdout_all; /// Default commit message used for ghost commits when none is provided. const DEFAULT_COMMIT_MESSAGE: &str = "codex snapshot"; @@ -69,6 +73,8 @@ pub fn create_ghost_commit( let repo_root = resolve_repository_root(options.repo_path)?; let repo_prefix = repo_subdir(repo_root.as_path(), options.repo_path); let parent = resolve_head(repo_root.as_path())?; + let existing_untracked = + capture_existing_untracked(repo_root.as_path(), repo_prefix.as_deref())?; let normalized_force = options .force_include @@ -84,6 +90,16 @@ pub fn create_ghost_commit( OsString::from(index_path.as_os_str()), )]; + // Pre-populate the temporary index with HEAD so unchanged tracked files + // are included in the snapshot tree. + if let Some(parent_sha) = parent.as_deref() { + run_git_for_status( + repo_root.as_path(), + vec![OsString::from("read-tree"), OsString::from(parent_sha)], + Some(base_env.as_slice()), + )?; + } + let mut add_args = vec![OsString::from("add"), OsString::from("--all")]; if let Some(prefix) = repo_prefix.as_deref() { add_args.extend([OsString::from("--"), prefix.as_os_str().to_os_string()]); @@ -127,12 +143,29 @@ pub fn create_ghost_commit( Some(commit_env.as_slice()), )?; - Ok(GhostCommit::new(commit_id, parent)) + Ok(GhostCommit::new( + commit_id, + parent, + existing_untracked.files, + existing_untracked.dirs, + )) } /// Restore the working tree to match the provided ghost commit. pub fn restore_ghost_commit(repo_path: &Path, commit: &GhostCommit) -> Result<(), GitToolingError> { - restore_to_commit(repo_path, commit.id()) + ensure_git_repository(repo_path)?; + + let repo_root = resolve_repository_root(repo_path)?; + let repo_prefix = repo_subdir(repo_root.as_path(), repo_path); + let current_untracked = + capture_existing_untracked(repo_root.as_path(), repo_prefix.as_deref())?; + remove_new_untracked( + repo_root.as_path(), + commit.preexisting_untracked_files(), + commit.preexisting_untracked_dirs(), + current_untracked, + )?; + restore_to_commit_inner(repo_root.as_path(), repo_prefix.as_deref(), commit.id()) } /// Restore the working tree to match the given commit ID. @@ -141,7 +174,16 @@ pub fn restore_to_commit(repo_path: &Path, commit_id: &str) -> Result<(), GitToo let repo_root = resolve_repository_root(repo_path)?; let repo_prefix = repo_subdir(repo_root.as_path(), repo_path); + restore_to_commit_inner(repo_root.as_path(), repo_prefix.as_deref(), commit_id) +} +/// Restores the working tree and index to the given commit using `git restore`. +/// The repository root and optional repository-relative prefix limit the restore scope. +fn restore_to_commit_inner( + repo_root: &Path, + repo_prefix: Option<&Path>, + commit_id: &str, +) -> Result<(), GitToolingError> { let mut restore_args = vec![ OsString::from("restore"), OsString::from("--source"), @@ -150,13 +192,143 @@ pub fn restore_to_commit(repo_path: &Path, commit_id: &str) -> Result<(), GitToo OsString::from("--staged"), OsString::from("--"), ]; - if let Some(prefix) = repo_prefix.as_deref() { + if let Some(prefix) = repo_prefix { restore_args.push(prefix.as_os_str().to_os_string()); } else { restore_args.push(OsString::from(".")); } - run_git_for_status(repo_root.as_path(), restore_args, None)?; + run_git_for_status(repo_root, restore_args, None)?; + Ok(()) +} + +#[derive(Default)] +struct UntrackedSnapshot { + files: Vec, + dirs: Vec, +} + +/// Captures the untracked and ignored entries under `repo_root`, optionally limited by `repo_prefix`. +/// Returns the result as an `UntrackedSnapshot`. +fn capture_existing_untracked( + repo_root: &Path, + repo_prefix: Option<&Path>, +) -> Result { + // Ask git for the zero-delimited porcelain status so we can enumerate + // every untracked or ignored path (including ones filtered by prefix). + let mut args = vec![ + OsString::from("status"), + OsString::from("--porcelain=2"), + OsString::from("-z"), + OsString::from("--ignored=matching"), + OsString::from("--untracked-files=all"), + ]; + if let Some(prefix) = repo_prefix { + args.push(OsString::from("--")); + args.push(prefix.as_os_str().to_os_string()); + } + + let output = run_git_for_stdout_all(repo_root, args, None)?; + if output.is_empty() { + return Ok(UntrackedSnapshot::default()); + } + + let mut snapshot = UntrackedSnapshot::default(); + // Each entry is of the form " " where code is '?' (untracked) + // or '!' (ignored); everything else is irrelevant to this snapshot. + for entry in output.split('\0') { + if entry.is_empty() { + continue; + } + let mut parts = entry.splitn(2, ' '); + let code = parts.next(); + let path_part = parts.next(); + let (Some(code), Some(path_part)) = (code, path_part) else { + continue; + }; + if code != "?" && code != "!" { + continue; + } + if path_part.is_empty() { + continue; + } + + let normalized = normalize_relative_path(Path::new(path_part))?; + let absolute = repo_root.join(&normalized); + let is_dir = absolute.is_dir(); + if is_dir { + snapshot.dirs.push(normalized); + } else { + snapshot.files.push(normalized); + } + } + + Ok(snapshot) +} + +/// Removes untracked files and directories that were not present when the snapshot was captured. +fn remove_new_untracked( + repo_root: &Path, + preserved_files: &[PathBuf], + preserved_dirs: &[PathBuf], + current: UntrackedSnapshot, +) -> Result<(), GitToolingError> { + if current.files.is_empty() && current.dirs.is_empty() { + return Ok(()); + } + + let preserved_file_set: HashSet = preserved_files.iter().cloned().collect(); + let preserved_dirs_vec: Vec = preserved_dirs.to_vec(); + + for path in current.files { + if should_preserve(&path, &preserved_file_set, &preserved_dirs_vec) { + continue; + } + remove_path(&repo_root.join(&path))?; + } + + for dir in current.dirs { + if should_preserve(&dir, &preserved_file_set, &preserved_dirs_vec) { + continue; + } + remove_path(&repo_root.join(&dir))?; + } + + Ok(()) +} + +/// Determines whether an untracked path should be kept because it existed in the snapshot. +fn should_preserve( + path: &Path, + preserved_files: &HashSet, + preserved_dirs: &[PathBuf], +) -> bool { + if preserved_files.contains(path) { + return true; + } + + preserved_dirs + .iter() + .any(|dir| path.starts_with(dir.as_path())) +} + +/// Deletes the file or directory at the provided path, ignoring if it is already absent. +fn remove_path(path: &Path) -> Result<(), GitToolingError> { + match fs::symlink_metadata(path) { + Ok(metadata) => { + if metadata.is_dir() { + fs::remove_dir_all(path)?; + } else { + fs::remove_file(path)?; + } + } + Err(err) => { + if err.kind() == io::ErrorKind::NotFound { + return Ok(()); + } + return Err(err.into()); + } + } Ok(()) } @@ -239,6 +411,9 @@ mod tests { ], ); + let preexisting_untracked = repo.join("notes.txt"); + std::fs::write(&preexisting_untracked, "notes before\n")?; + let tracked_contents = "modified contents\n"; std::fs::write(repo.join("tracked.txt"), tracked_contents)?; std::fs::remove_file(repo.join("delete-me.txt"))?; @@ -267,6 +442,7 @@ mod tests { std::fs::write(repo.join("ignored.txt"), "changed\n")?; std::fs::remove_file(repo.join("new-file.txt"))?; std::fs::write(repo.join("ephemeral.txt"), "temp data\n")?; + std::fs::write(&preexisting_untracked, "notes after\n")?; restore_ghost_commit(repo, &ghost)?; @@ -277,7 +453,9 @@ mod tests { let new_file_after = std::fs::read_to_string(repo.join("new-file.txt"))?; assert_eq!(new_file_after, new_file_contents); assert_eq!(repo.join("delete-me.txt").exists(), false); - assert!(repo.join("ephemeral.txt").exists()); + assert!(!repo.join("ephemeral.txt").exists()); + let notes_after = std::fs::read_to_string(&preexisting_untracked)?; + assert_eq!(notes_after, "notes before\n"); Ok(()) } @@ -488,7 +666,43 @@ mod tests { assert!(vscode.join("settings.json").exists()); let settings_after = std::fs::read_to_string(vscode.join("settings.json"))?; assert_eq!(settings_after, "{\n \"after\": true\n}\n"); - assert!(repo.join("temp.txt").exists()); + assert!(!repo.join("temp.txt").exists()); + + Ok(()) + } + + #[test] + /// Restoring removes ignored directories created after the snapshot. + fn restore_removes_new_ignored_directory() -> Result<(), GitToolingError> { + let temp = tempfile::tempdir()?; + let repo = temp.path(); + init_test_repo(repo); + + std::fs::write(repo.join(".gitignore"), ".vscode/\n")?; + std::fs::write(repo.join("tracked.txt"), "snapshot version\n")?; + run_git_in(repo, &["add", ".gitignore", "tracked.txt"]); + run_git_in( + repo, + &[ + "-c", + "user.name=Tester", + "-c", + "user.email=test@example.com", + "commit", + "-m", + "initial", + ], + ); + + let ghost = create_ghost_commit(&CreateGhostCommitOptions::new(repo))?; + + let vscode = repo.join(".vscode"); + std::fs::create_dir_all(&vscode)?; + std::fs::write(vscode.join("settings.json"), "{\n \"after\": true\n}\n")?; + + restore_ghost_commit(repo, &ghost)?; + + assert!(!vscode.exists()); Ok(()) } diff --git a/codex-rs/git-tooling/src/lib.rs b/codex-rs/git-tooling/src/lib.rs index f41d104385..e6e53924b6 100644 --- a/codex-rs/git-tooling/src/lib.rs +++ b/codex-rs/git-tooling/src/lib.rs @@ -1,4 +1,5 @@ use std::fmt; +use std::path::PathBuf; mod errors; mod ghost_commits; @@ -11,18 +12,36 @@ pub use ghost_commits::create_ghost_commit; pub use ghost_commits::restore_ghost_commit; pub use ghost_commits::restore_to_commit; pub use platform::create_symlink; +use schemars::JsonSchema; +use serde::Deserialize; +use serde::Serialize; +use ts_rs::TS; + +type CommitID = String; /// Details of a ghost commit created from a repository state. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema, TS)] pub struct GhostCommit { - id: String, - parent: Option, + id: CommitID, + parent: Option, + preexisting_untracked_files: Vec, + preexisting_untracked_dirs: Vec, } impl GhostCommit { /// Create a new ghost commit wrapper from a raw commit ID and optional parent. - pub fn new(id: String, parent: Option) -> Self { - Self { id, parent } + pub fn new( + id: CommitID, + parent: Option, + preexisting_untracked_files: Vec, + preexisting_untracked_dirs: Vec, + ) -> Self { + Self { + id, + parent, + preexisting_untracked_files, + preexisting_untracked_dirs, + } } /// Commit ID for the snapshot. @@ -34,6 +53,16 @@ impl GhostCommit { pub fn parent(&self) -> Option<&str> { self.parent.as_deref() } + + /// Untracked or ignored files that already existed when the snapshot was captured. + pub fn preexisting_untracked_files(&self) -> &[PathBuf] { + &self.preexisting_untracked_files + } + + /// Untracked or ignored directories that already existed when the snapshot was captured. + pub fn preexisting_untracked_dirs(&self) -> &[PathBuf] { + &self.preexisting_untracked_dirs + } } impl fmt::Display for GhostCommit { diff --git a/codex-rs/git-tooling/src/operations.rs b/codex-rs/git-tooling/src/operations.rs index 3b387f8498..415d63d568 100644 --- a/codex-rs/git-tooling/src/operations.rs +++ b/codex-rs/git-tooling/src/operations.rs @@ -161,6 +161,27 @@ where }) } +/// Executes `git` and returns the full stdout without trimming so callers +/// can parse delimiter-sensitive output, propagating UTF-8 errors with context. +pub(crate) fn run_git_for_stdout_all( + dir: &Path, + args: I, + env: Option<&[(OsString, OsString)]>, +) -> Result +where + I: IntoIterator, + S: AsRef, +{ + // Keep the raw stdout untouched so callers can parse delimiter-sensitive + // output (e.g. NUL-separated paths) without trimming artefacts. + let run = run_git(dir, args, env)?; + // Propagate UTF-8 conversion failures with the command context for debugging. + String::from_utf8(run.output.stdout).map_err(|source| GitToolingError::GitOutputUtf8 { + command: run.command, + source, + }) +} + fn run_git( dir: &Path, args: I, diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index 9f826f4e86..9ba48c018c 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -288,6 +288,8 @@ async fn run_codex_tool_session_inner( | EventMsg::EnteredReviewMode(_) | EventMsg::ItemStarted(_) | EventMsg::ItemCompleted(_) + | EventMsg::UndoStarted(_) + | EventMsg::UndoCompleted(_) | EventMsg::ExitedReviewMode(_) => { // For now, we do not do anything extra for these // events. Note that diff --git a/codex-rs/protocol/Cargo.toml b/codex-rs/protocol/Cargo.toml index 0393c85427..6249d870a3 100644 --- a/codex-rs/protocol/Cargo.toml +++ b/codex-rs/protocol/Cargo.toml @@ -11,6 +11,8 @@ path = "src/lib.rs" workspace = true [dependencies] +codex-git-tooling = { workspace = true } + base64 = { workspace = true } icu_decimal = { workspace = true } icu_locale_core = { workspace = true } diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index 02d557535e..095d7de4de 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -9,6 +9,7 @@ use serde::ser::Serializer; use ts_rs::TS; use crate::user_input::UserInput; +use codex_git_tooling::GhostCommit; use schemars::JsonSchema; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] @@ -118,9 +119,7 @@ pub enum ResponseItem { }, // Generated by the harness but considered exactly as a model response. GhostSnapshot { - commit_id: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - parent: Option, + ghost_commit: GhostCommit, }, #[serde(other)] Other, diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 1b4a6fccf1..bb14f3797b 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -178,6 +178,9 @@ pub enum Op { /// to generate a summary which will be returned as an AgentMessage event. Compact, + /// Request Codex to undo a turn (turn are stacked so it is the same effect as CMD + Z). + Undo, + /// Request a code review from the agent. Review { review_request: ReviewRequest }, @@ -486,6 +489,10 @@ pub enum EventMsg { BackgroundEvent(BackgroundEventEvent), + UndoStarted(UndoStartedEvent), + + UndoCompleted(UndoCompletedEvent), + /// Notification that a model stream experienced an error or disconnect /// and the system is handling it (e.g., retrying with backoff). StreamError(StreamErrorEvent), @@ -1135,6 +1142,19 @@ pub struct BackgroundEventEvent { pub message: String, } +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +pub struct UndoStartedEvent { + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] +pub struct UndoCompletedEvent { + pub success: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option, +} + #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct StreamErrorEvent { pub message: String, diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 824e4fee31..f087202c22 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -35,7 +35,6 @@ codex-common = { workspace = true, features = [ ] } codex-core = { workspace = true } codex-file-search = { workspace = true } -codex-git-tooling = { workspace = true } codex-login = { workspace = true } codex-ollama = { workspace = true } codex-protocol = { workspace = true } diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index cf9e354737..54d2f7912e 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -315,6 +315,11 @@ impl BottomPane { self.ctrl_c_quit_hint } + #[cfg(test)] + pub(crate) fn status_indicator_visible(&self) -> bool { + self.status.is_some() + } + pub(crate) fn show_esc_backtrack_hint(&mut self) { self.esc_backtrack_hint = true; self.composer.set_esc_backtrack_hint(true); @@ -359,6 +364,16 @@ impl BottomPane { } } + pub(crate) fn ensure_status_indicator(&mut self) { + if self.status.is_none() { + self.status = Some(StatusIndicatorWidget::new( + self.app_event_tx.clone(), + self.frame_requester.clone(), + )); + self.request_redraw(); + } + } + pub(crate) fn set_context_window_percent(&mut self, percent: Option) { if self.context_window_percent == percent { return; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 64dc89d884..7b83eedcc9 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -37,6 +37,8 @@ use codex_core::protocol::TokenUsage; use codex_core::protocol::TokenUsageInfo; use codex_core::protocol::TurnAbortReason; use codex_core::protocol::TurnDiffEvent; +use codex_core::protocol::UndoCompletedEvent; +use codex_core::protocol::UndoStartedEvent; use codex_core::protocol::UserMessageEvent; use codex_core::protocol::ViewImageToolCallEvent; use codex_core::protocol::WebSearchBeginEvent; @@ -113,16 +115,9 @@ 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 codex_git_tooling::CreateGhostCommitOptions; -use codex_git_tooling::GhostCommit; -use codex_git_tooling::GitToolingError; -use codex_git_tooling::create_ghost_commit; -use codex_git_tooling::restore_ghost_commit; use codex_protocol::plan_tool::UpdatePlanArgs; use strum::IntoEnumIterator; -const MAX_TRACKED_GHOST_COMMITS: usize = 20; - // Track information about an in-flight exec command. struct RunningCommand { command: Vec, @@ -267,9 +262,6 @@ pub(crate) struct ChatWidget { pending_notification: Option, // Simple review mode flag; used to adjust layout and banners. is_review_mode: bool, - // List of ghost commits corresponding to each turn. - ghost_snapshots: Vec, - ghost_snapshots_disabled: bool, // Whether to add a final message separator after the last message needs_final_message_separator: bool, @@ -672,6 +664,31 @@ impl ChatWidget { debug!("BackgroundEvent: {message}"); } + fn on_undo_started(&mut self, event: UndoStartedEvent) { + self.bottom_pane.ensure_status_indicator(); + let message = event + .message + .unwrap_or_else(|| "Undo in progress...".to_string()); + self.set_status_header(message); + } + + fn on_undo_completed(&mut self, event: UndoCompletedEvent) { + let UndoCompletedEvent { success, message } = event; + self.bottom_pane.hide_status_indicator(); + let message = message.unwrap_or_else(|| { + if success { + "Undo completed successfully.".to_string() + } else { + "Undo failed.".to_string() + } + }); + if success { + self.add_info_message(message, None); + } else { + self.add_error_message(message); + } + } + fn on_stream_error(&mut self, message: String) { if self.retry_status_header.is_none() { self.retry_status_header = Some(self.current_status_header.clone()); @@ -989,8 +1006,6 @@ impl ChatWidget { suppress_session_configured_redraw: false, pending_notification: None, is_review_mode: false, - ghost_snapshots: Vec::new(), - ghost_snapshots_disabled: true, needs_final_message_separator: false, last_rendered_width: std::cell::Cell::new(None), feedback, @@ -1057,8 +1072,6 @@ impl ChatWidget { suppress_session_configured_redraw: true, pending_notification: None, is_review_mode: false, - ghost_snapshots: Vec::new(), - ghost_snapshots_disabled: true, needs_final_message_separator: false, last_rendered_width: std::cell::Cell::new(None), feedback, @@ -1211,7 +1224,7 @@ impl ChatWidget { self.app_event_tx.send(AppEvent::ExitRequest); } SlashCommand::Undo => { - self.undo_last_snapshot(); + self.app_event_tx.send(AppEvent::CodexOp(Op::Undo)); } SlashCommand::Diff => { self.add_diff_in_progress(); @@ -1328,8 +1341,6 @@ impl ChatWidget { return; } - self.capture_ghost_snapshot(); - let mut items: Vec = Vec::new(); if !text.is_empty() { @@ -1362,57 +1373,6 @@ impl ChatWidget { self.needs_final_message_separator = false; } - fn capture_ghost_snapshot(&mut self) { - if self.ghost_snapshots_disabled { - return; - } - - let options = CreateGhostCommitOptions::new(&self.config.cwd); - match create_ghost_commit(&options) { - Ok(commit) => { - self.ghost_snapshots.push(commit); - if self.ghost_snapshots.len() > MAX_TRACKED_GHOST_COMMITS { - self.ghost_snapshots.remove(0); - } - } - Err(err) => { - self.ghost_snapshots_disabled = true; - let (message, hint) = match &err { - GitToolingError::NotAGitRepository { .. } => ( - "Snapshots disabled: current directory is not a Git repository." - .to_string(), - None, - ), - _ => ( - format!("Snapshots disabled after error: {err}"), - Some( - "Restart Codex after resolving the issue to re-enable snapshots." - .to_string(), - ), - ), - }; - self.add_info_message(message, hint); - tracing::warn!("failed to create ghost snapshot: {err}"); - } - } - } - - fn undo_last_snapshot(&mut self) { - let Some(commit) = self.ghost_snapshots.pop() else { - self.add_info_message("No snapshot available to undo.".to_string(), None); - return; - }; - - if let Err(err) = restore_ghost_commit(&self.config.cwd, &commit) { - self.add_error_message(format!("Failed to restore snapshot: {err}")); - self.ghost_snapshots.push(commit); - return; - } - - let short_id: String = commit.id().chars().take(8).collect(); - self.add_info_message(format!("Restored workspace to snapshot {short_id}"), None); - } - /// Replay a subset of initial events into the UI to seed the transcript when /// resuming an existing session. This approximates the live event flow and /// is intentionally conservative: only safe-to-replay items are rendered to @@ -1510,6 +1470,8 @@ impl ChatWidget { EventMsg::BackgroundEvent(BackgroundEventEvent { message }) => { self.on_background_event(message) } + EventMsg::UndoStarted(ev) => self.on_undo_started(ev), + EventMsg::UndoCompleted(ev) => self.on_undo_completed(ev), EventMsg::StreamError(StreamErrorEvent { message }) => self.on_stream_error(message), EventMsg::UserMessage(ev) => { if from_replay { diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 6ec877656c..e874c6060a 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -34,6 +34,8 @@ use codex_core::protocol::ReviewRequest; use codex_core::protocol::StreamErrorEvent; use codex_core::protocol::TaskCompleteEvent; use codex_core::protocol::TaskStartedEvent; +use codex_core::protocol::UndoCompletedEvent; +use codex_core::protocol::UndoStartedEvent; use codex_core::protocol::ViewImageToolCallEvent; use codex_protocol::ConversationId; use codex_protocol::plan_tool::PlanItemArg; @@ -294,8 +296,6 @@ fn make_chatwidget_manual() -> ( suppress_session_configured_redraw: false, pending_notification: None, is_review_mode: false, - ghost_snapshots: Vec::new(), - ghost_snapshots_disabled: false, needs_final_message_separator: false, last_rendered_width: std::cell::Cell::new(None), feedback: codex_feedback::CodexFeedback::new(), @@ -849,6 +849,90 @@ fn slash_init_skips_when_project_doc_exists() { ); } +#[test] +fn slash_undo_sends_op() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); + + chat.dispatch_command(SlashCommand::Undo); + + match rx.try_recv() { + Ok(AppEvent::CodexOp(Op::Undo)) => {} + other => panic!("expected AppEvent::CodexOp(Op::Undo), got {other:?}"), + } +} + +#[test] +fn undo_success_events_render_info_messages() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); + + chat.handle_codex_event(Event { + id: "turn-1".to_string(), + msg: EventMsg::UndoStarted(UndoStartedEvent { + message: Some("Undo requested for the last turn...".to_string()), + }), + }); + assert!( + chat.bottom_pane.status_indicator_visible(), + "status indicator should be visible during undo" + ); + + chat.handle_codex_event(Event { + id: "turn-1".to_string(), + msg: EventMsg::UndoCompleted(UndoCompletedEvent { + success: true, + message: None, + }), + }); + + let cells = drain_insert_history(&mut rx); + assert_eq!(cells.len(), 1, "expected final status only"); + assert!( + !chat.bottom_pane.status_indicator_visible(), + "status indicator should be hidden after successful undo" + ); + + let completed = lines_to_single_string(&cells[0]); + assert!( + completed.contains("Undo completed successfully."), + "expected default success message, got {completed:?}" + ); +} + +#[test] +fn undo_failure_events_render_error_message() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); + + chat.handle_codex_event(Event { + id: "turn-2".to_string(), + msg: EventMsg::UndoStarted(UndoStartedEvent { message: None }), + }); + assert!( + chat.bottom_pane.status_indicator_visible(), + "status indicator should be visible during undo" + ); + + chat.handle_codex_event(Event { + id: "turn-2".to_string(), + msg: EventMsg::UndoCompleted(UndoCompletedEvent { + success: false, + message: Some("Failed to restore workspace state.".to_string()), + }), + }); + + let cells = drain_insert_history(&mut rx); + assert_eq!(cells.len(), 1, "expected final status only"); + assert!( + !chat.bottom_pane.status_indicator_visible(), + "status indicator should be hidden after failed undo" + ); + + let completed = lines_to_single_string(&cells[0]); + assert!( + completed.contains("Failed to restore workspace state."), + "expected failure message, got {completed:?}" + ); +} + /// The commit picker shows only commit subjects (no timestamps). #[test] fn review_commit_picker_shows_subjects_without_timestamps() { diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 22da09f358..bb3be33099 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -39,7 +39,7 @@ impl SlashCommand { 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::Undo => "restore the workspace to the last Codex snapshot", + SlashCommand::Undo => "ask Codex to undo a turn", SlashCommand::Quit => "exit Codex", SlashCommand::Diff => "show git diff (including untracked files)", SlashCommand::Mention => "mention a file", @@ -85,14 +85,5 @@ impl SlashCommand { /// Return all built-in commands in a Vec paired with their command string. pub fn built_in_slash_commands() -> Vec<(&'static str, SlashCommand)> { - let show_beta_features = beta_features_enabled(); - - SlashCommand::iter() - .filter(|cmd| *cmd != SlashCommand::Undo || show_beta_features) - .map(|c| (c.command(), c)) - .collect() -} - -fn beta_features_enabled() -> bool { - std::env::var_os("BETA_FEATURE").is_some() + SlashCommand::iter().map(|c| (c.command(), c)).collect() } From 2338294b39f5af7b3b8c4c74df568654b55384d0 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Mon, 27 Oct 2025 11:43:33 +0000 Subject: [PATCH 29/35] nit: doc on session task (#5809) --- codex-rs/core/src/tasks/mod.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/codex-rs/core/src/tasks/mod.rs b/codex-rs/core/src/tasks/mod.rs index 466bfe21a9..ae22abe8cc 100644 --- a/codex-rs/core/src/tasks/mod.rs +++ b/codex-rs/core/src/tasks/mod.rs @@ -50,10 +50,28 @@ impl SessionTaskContext { } } +/// Async task that drives a [`Session`] turn. +/// +/// Implementations encapsulate a specific Codex workflow (regular chat, +/// reviews, ghost snapshots, etc.). Each task instance is owned by a +/// [`Session`] and executed on a background Tokio task. The trait is +/// intentionally small: implementers identify themselves via +/// [`SessionTask::kind`], perform their work in [`SessionTask::run`], and may +/// release resources in [`SessionTask::abort`]. #[async_trait] pub(crate) trait SessionTask: Send + Sync + 'static { + /// Describes the type of work the task performs so the session can + /// surface it in telemetry and UI. fn kind(&self) -> TaskKind; + /// Executes the task until completion or cancellation. + /// + /// Implementations typically stream protocol events using `session` and + /// `ctx`, returning an optional final agent message when finished. The + /// provided `cancellation_token` is cancelled when the session requests an + /// abort; implementers should watch for it and terminate quickly once it + /// fires. Returning [`Some`] yields a final message that + /// [`Session::on_task_finished`] will emit to the client. async fn run( self: Arc, session: Arc, @@ -62,6 +80,11 @@ pub(crate) trait SessionTask: Send + Sync + 'static { cancellation_token: CancellationToken, ) -> Option; + /// Gives the task a chance to perform cleanup after an abort. + /// + /// The default implementation is a no-op; override this if additional + /// teardown or notifications are required once + /// [`Session::abort_all_tasks`] cancels the task. async fn abort(&self, session: Arc, ctx: Arc) { let _ = (session, ctx); } From 5e8659dcbc2550e19757468b1810fa710a632cab Mon Sep 17 00:00:00 2001 From: jif-oai Date: Mon, 27 Oct 2025 11:48:01 +0000 Subject: [PATCH 30/35] chore: undo nits (#5631) --- codex-rs/core/src/codex/compact.rs | 14 ++++++-- .../src/event_processor_with_human_output.rs | 2 +- codex-rs/git-tooling/src/ghost_commits.rs | 4 +-- codex-rs/tui/src/bottom_pane/mod.rs | 8 +++++ codex-rs/tui/src/chatwidget.rs | 5 ++- codex-rs/tui/src/chatwidget/tests.rs | 19 +++++++++++ codex-rs/tui/src/status_indicator_widget.rs | 32 +++++++++++++------ 7 files changed, 66 insertions(+), 18 deletions(-) diff --git a/codex-rs/core/src/codex/compact.rs b/codex-rs/core/src/codex/compact.rs index 304452b060..236b024139 100644 --- a/codex-rs/core/src/codex/compact.rs +++ b/codex-rs/core/src/codex/compact.rs @@ -2,6 +2,7 @@ use std::sync::Arc; use super::Session; use super::TurnContext; +use super::filter_model_visible_history; use super::get_last_assistant_message_from_turn; use crate::Prompt; use crate::client_common::ResponseEvent; @@ -86,8 +87,9 @@ async fn run_compact_task_inner( loop { let turn_input = history.get_history(); + let prompt_input = filter_model_visible_history(turn_input.clone()); let prompt = Prompt { - input: turn_input.clone(), + input: prompt_input.clone(), ..Default::default() }; let attempt_result = drain_to_completed(&sess, turn_context.as_ref(), &prompt).await; @@ -109,7 +111,7 @@ async fn run_compact_task_inner( return; } Err(e @ CodexErr::ContextWindowExceeded) => { - if turn_input.len() > 1 { + if prompt_input.len() > 1 { // Trim from the beginning to preserve cache (prefix-based) and keep recent messages intact. error!( "Context window exceeded while compacting; removing oldest history item. Error: {e}" @@ -152,7 +154,13 @@ async fn run_compact_task_inner( let summary_text = get_last_assistant_message_from_turn(&history_snapshot).unwrap_or_default(); let user_messages = collect_user_messages(&history_snapshot); let initial_context = sess.build_initial_context(turn_context.as_ref()); - let new_history = build_compacted_history(initial_context, &user_messages, &summary_text); + let mut new_history = build_compacted_history(initial_context, &user_messages, &summary_text); + let ghost_snapshots: Vec = history_snapshot + .iter() + .filter(|item| matches!(item, ResponseItem::GhostSnapshot { .. })) + .cloned() + .collect(); + new_history.extend(ghost_snapshots); sess.replace_history(new_history).await; let rollout_item = RolloutItem::Compacted(CompactedItem { 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 2d06c881a8..4db6a50461 100644 --- a/codex-rs/exec/src/event_processor_with_human_output.rs +++ b/codex-rs/exec/src/event_processor_with_human_output.rs @@ -499,6 +499,7 @@ impl EventProcessor for EventProcessorWithHumanOutput { | EventMsg::GetHistoryEntryResponse(_) | EventMsg::McpListToolsResponse(_) | EventMsg::ListCustomPromptsResponse(_) + | EventMsg::RawResponseItem(_) | EventMsg::UserMessage(_) | EventMsg::EnteredReviewMode(_) | EventMsg::ExitedReviewMode(_) @@ -507,7 +508,6 @@ impl EventProcessor for EventProcessorWithHumanOutput { | EventMsg::AgentReasoningRawContentDelta(_) | EventMsg::ItemStarted(_) | EventMsg::ItemCompleted(_) - | EventMsg::RawResponseItem(_) | EventMsg::UndoCompleted(_) | EventMsg::UndoStarted(_) => {} } diff --git a/codex-rs/git-tooling/src/ghost_commits.rs b/codex-rs/git-tooling/src/ghost_commits.rs index c5ebd7c02c..ec211ac3e1 100644 --- a/codex-rs/git-tooling/src/ghost_commits.rs +++ b/codex-rs/git-tooling/src/ghost_commits.rs @@ -159,13 +159,13 @@ pub fn restore_ghost_commit(repo_path: &Path, commit: &GhostCommit) -> Result<() let repo_prefix = repo_subdir(repo_root.as_path(), repo_path); let current_untracked = capture_existing_untracked(repo_root.as_path(), repo_prefix.as_deref())?; + restore_to_commit_inner(repo_root.as_path(), repo_prefix.as_deref(), commit.id())?; remove_new_untracked( repo_root.as_path(), commit.preexisting_untracked_files(), commit.preexisting_untracked_dirs(), current_untracked, - )?; - restore_to_commit_inner(repo_root.as_path(), repo_prefix.as_deref(), commit.id()) + ) } /// Restore the working tree to match the given commit ID. diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 54d2f7912e..c23709fe07 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -348,6 +348,7 @@ impl BottomPane { )); } if let Some(status) = self.status.as_mut() { + status.set_interrupt_hint_visible(true); status.set_queued_messages(self.queued_user_messages.clone()); } self.request_redraw(); @@ -374,6 +375,13 @@ impl BottomPane { } } + pub(crate) fn set_interrupt_hint_visible(&mut self, visible: bool) { + if let Some(status) = self.status.as_mut() { + status.set_interrupt_hint_visible(visible); + self.request_redraw(); + } + } + pub(crate) fn set_context_window_percent(&mut self, percent: Option) { if self.context_window_percent == percent { return; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 7b83eedcc9..13411df404 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -304,9 +304,6 @@ impl ChatWidget { } fn set_status_header(&mut self, header: String) { - if self.current_status_header == header { - return; - } self.current_status_header = header.clone(); self.bottom_pane.update_status_header(header); } @@ -429,6 +426,7 @@ impl ChatWidget { self.bottom_pane.clear_ctrl_c_quit_hint(); self.bottom_pane.set_task_running(true); self.retry_status_header = None; + self.bottom_pane.set_interrupt_hint_visible(true); self.set_status_header(String::from("Working")); self.full_reasoning_buffer.clear(); self.reasoning_buffer.clear(); @@ -666,6 +664,7 @@ impl ChatWidget { fn on_undo_started(&mut self, event: UndoStartedEvent) { self.bottom_pane.ensure_status_indicator(); + self.bottom_pane.set_interrupt_hint_visible(false); let message = event .message .unwrap_or_else(|| "Undo in progress...".to_string()); diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index e874c6060a..75796d7d62 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -933,6 +933,25 @@ fn undo_failure_events_render_error_message() { ); } +#[test] +fn undo_started_hides_interrupt_hint() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(); + + chat.handle_codex_event(Event { + id: "turn-hint".to_string(), + msg: EventMsg::UndoStarted(UndoStartedEvent { message: None }), + }); + + let status = chat + .bottom_pane + .status_widget() + .expect("status indicator should be active"); + assert!( + !status.interrupt_hint_visible(), + "undo should hide the interrupt hint because the operation cannot be cancelled" + ); +} + /// The commit picker shows only commit subjects (no timestamps). #[test] fn review_commit_picker_shows_subjects_without_timestamps() { diff --git a/codex-rs/tui/src/status_indicator_widget.rs b/codex-rs/tui/src/status_indicator_widget.rs index 81efde71f2..cda52ffee7 100644 --- a/codex-rs/tui/src/status_indicator_widget.rs +++ b/codex-rs/tui/src/status_indicator_widget.rs @@ -25,6 +25,8 @@ pub(crate) struct StatusIndicatorWidget { header: String, /// Queued user messages to display under the status line. queued_messages: Vec, + /// Whether to show the interrupt hint (Esc). + show_interrupt_hint: bool, elapsed_running: Duration, last_resume_at: Instant, @@ -55,6 +57,7 @@ impl StatusIndicatorWidget { Self { header: String::from("Working"), queued_messages: Vec::new(), + show_interrupt_hint: true, elapsed_running: Duration::ZERO, last_resume_at: Instant::now(), is_paused: false, @@ -98,9 +101,11 @@ impl StatusIndicatorWidget { /// Update the animated header label (left of the brackets). pub(crate) fn update_header(&mut self, header: String) { - if self.header != header { - self.header = header; - } + self.header = header; + } + + pub(crate) fn set_interrupt_hint_visible(&mut self, visible: bool) { + self.show_interrupt_hint = visible; } #[cfg(test)] @@ -108,6 +113,11 @@ impl StatusIndicatorWidget { &self.header } + #[cfg(test)] + pub(crate) fn interrupt_hint_visible(&self) -> bool { + self.show_interrupt_hint + } + /// Replace the queued messages displayed beneath the header. pub(crate) fn set_queued_messages(&mut self, queued: Vec) { self.queued_messages = queued; @@ -175,12 +185,16 @@ impl WidgetRef for StatusIndicatorWidget { spans.push(spinner(Some(self.last_resume_at))); spans.push(" ".into()); spans.extend(shimmer_spans(&self.header)); - spans.extend(vec![ - " ".into(), - format!("({pretty_elapsed} • ").dim(), - key_hint::plain(KeyCode::Esc).into(), - " to interrupt)".dim(), - ]); + spans.push(" ".into()); + if self.show_interrupt_hint { + spans.extend(vec![ + format!("({pretty_elapsed} • ").dim(), + key_hint::plain(KeyCode::Esc).into(), + " to interrupt)".dim(), + ]); + } else { + spans.push(format!("({pretty_elapsed})").dim()); + } // Build lines: status, then queued messages, then spacer. let mut lines: Vec> = Vec::new(); From 81be54b22910defc99c6a64f4bb3bc8f5ea3dbf1 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Mon, 27 Oct 2025 11:57:29 +0000 Subject: [PATCH 31/35] fix: test yield time (#5811) --- codex-rs/core/tests/suite/unified_exec.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index 4a29d6ccd0..0e68ec7585 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -240,7 +240,7 @@ async fn unified_exec_emits_output_delta_for_exec_command() -> Result<()> { let call_id = "uexec-delta-1"; let args = json!({ "cmd": "printf 'HELLO-UEXEC'", - "yield_time_ms": 250, + "yield_time_ms": 1000, }); let responses = vec![ From 5ee8a17b4e8c8f7d83309666ccb46f1379db8a4c Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Mon, 27 Oct 2025 09:11:45 -0700 Subject: [PATCH 32/35] feat: introduce GetConversationSummary RPC (#5803) This adds an RPC to the app server to the the `ConversationSummary` via a rollout path. Now that the VS Code extension supports showing the Codex UI in an editor panel where the URI of the panel maps to the rollout file, we need to be able to get the `ConversationSummary` from the rollout file directly. --- codex-rs/app-server-protocol/src/protocol.rs | 16 ++ .../app-server/src/codex_message_processor.rs | 147 +++++++++++++++++- codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/rollout/list.rs | 7 + 4 files changed, 163 insertions(+), 8 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol.rs b/codex-rs/app-server-protocol/src/protocol.rs index 74e9b6f9e2..f164ce5601 100644 --- a/codex-rs/app-server-protocol/src/protocol.rs +++ b/codex-rs/app-server-protocol/src/protocol.rs @@ -147,6 +147,10 @@ client_request_definitions! { params: NewConversationParams, response: NewConversationResponse, }, + GetConversationSummary { + params: GetConversationSummaryParams, + response: GetConversationSummaryResponse, + }, /// List recorded Codex conversations (rollouts) with optional pagination and search. ListConversations { params: ListConversationsParams, @@ -322,6 +326,18 @@ pub struct ResumeConversationResponse { pub initial_messages: Option>, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +pub struct GetConversationSummaryParams { + pub rollout_path: PathBuf, +} + +#[derive(Serialize, Deserialize, Debug, Clone, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +pub struct GetConversationSummaryResponse { + pub summary: ConversationSummary, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema, TS)] #[serde(rename_all = "camelCase")] pub struct ListConversationsParams { diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 9b66322047..1dba61a524 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -21,6 +21,8 @@ use codex_app_server_protocol::ExecOneOffCommandResponse; use codex_app_server_protocol::FuzzyFileSearchParams; use codex_app_server_protocol::FuzzyFileSearchResponse; use codex_app_server_protocol::GetAccountRateLimitsResponse; +use codex_app_server_protocol::GetConversationSummaryParams; +use codex_app_server_protocol::GetConversationSummaryResponse; use codex_app_server_protocol::GetUserAgentResponse; use codex_app_server_protocol::GetUserSavedConfigResponse; use codex_app_server_protocol::GitDiffToRemoteResponse; @@ -87,6 +89,7 @@ use codex_core::protocol::EventMsg; use codex_core::protocol::ExecApprovalRequestEvent; use codex_core::protocol::Op; use codex_core::protocol::ReviewDecision; +use codex_core::read_head_for_summary; use codex_feedback::CodexFeedback; use codex_login::ServerOptions as LoginServerOptions; use codex_login::ShutdownHandle; @@ -101,6 +104,8 @@ use codex_protocol::user_input::UserInput as CoreInputItem; use codex_utils_json_to_toml::json_to_toml; use std::collections::HashMap; use std::ffi::OsStr; +use std::io::Error as IoError; +use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; @@ -176,6 +181,9 @@ impl CodexMessageProcessor { // created before processing any subsequent messages. self.process_new_conversation(request_id, params).await; } + ClientRequest::GetConversationSummary { request_id, params } => { + self.get_conversation_summary(request_id, params).await; + } ClientRequest::ListConversations { request_id, params } => { self.handle_list_conversations(request_id, params).await; } @@ -822,6 +830,39 @@ impl CodexMessageProcessor { } } + async fn get_conversation_summary( + &self, + request_id: RequestId, + params: GetConversationSummaryParams, + ) { + let GetConversationSummaryParams { rollout_path } = params; + let path = if rollout_path.is_relative() { + self.config.codex_home.join(&rollout_path) + } else { + rollout_path.clone() + }; + let fallback_provider = self.config.model_provider_id.as_str(); + + match read_summary_from_rollout(&path, fallback_provider).await { + Ok(summary) => { + let response = GetConversationSummaryResponse { summary }; + self.outgoing.send_response(request_id, response).await; + } + Err(err) => { + let error = JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: format!( + "failed to load conversation summary from {}: {}", + path.display(), + err + ), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + } + } + } + async fn handle_list_conversations( &self, request_id: RequestId, @@ -1724,6 +1765,50 @@ async fn on_exec_approval_response( } } +async fn read_summary_from_rollout( + path: &Path, + fallback_provider: &str, +) -> std::io::Result { + let head = read_head_for_summary(path).await?; + + let Some(first) = head.first() else { + return Err(IoError::other(format!( + "rollout at {} is empty", + path.display() + ))); + }; + + let session_meta = serde_json::from_value::(first.clone()).map_err(|_| { + IoError::other(format!( + "rollout at {} does not start with session metadata", + path.display() + )) + })?; + + if let Some(summary) = + extract_conversation_summary(path.to_path_buf(), &head, fallback_provider) + { + return Ok(summary); + } + + let timestamp = if session_meta.timestamp.is_empty() { + None + } else { + Some(session_meta.timestamp.clone()) + }; + let model_provider = session_meta + .model_provider + .unwrap_or_else(|| fallback_provider.to_string()); + + Ok(ConversationSummary { + conversation_id: session_meta.id, + timestamp, + path: path.to_path_buf(), + preview: String::new(), + model_provider, + }) +} + fn extract_conversation_summary( path: PathBuf, head: &[serde_json::Value], @@ -1772,6 +1857,7 @@ mod tests { use anyhow::Result; use pretty_assertions::assert_eq; use serde_json::json; + use tempfile::TempDir; #[test] fn extract_conversation_summary_prefers_plain_user_messages() -> Result<()> { @@ -1810,14 +1896,59 @@ mod tests { let summary = extract_conversation_summary(path.clone(), &head, "test-provider").expect("summary"); - assert_eq!(summary.conversation_id, conversation_id); - assert_eq!( - summary.timestamp, - Some("2025-09-05T16:53:11.850Z".to_string()) - ); - assert_eq!(summary.path, path); - assert_eq!(summary.preview, "Count to 5"); - assert_eq!(summary.model_provider, "test-provider"); + let expected = ConversationSummary { + conversation_id, + timestamp, + path, + preview: "Count to 5".to_string(), + model_provider: "test-provider".to_string(), + }; + + assert_eq!(summary, expected); + Ok(()) + } + + #[tokio::test] + async fn read_summary_from_rollout_returns_empty_preview_when_no_user_message() -> Result<()> { + use codex_protocol::protocol::RolloutItem; + use codex_protocol::protocol::RolloutLine; + use codex_protocol::protocol::SessionMetaLine; + use std::fs; + + let temp_dir = TempDir::new()?; + let path = temp_dir.path().join("rollout.jsonl"); + + let conversation_id = ConversationId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; + let timestamp = "2025-09-05T16:53:11.850Z".to_string(); + + let session_meta = SessionMeta { + id: conversation_id, + timestamp: timestamp.clone(), + model_provider: None, + ..SessionMeta::default() + }; + + let line = RolloutLine { + timestamp: timestamp.clone(), + item: RolloutItem::SessionMeta(SessionMetaLine { + meta: session_meta.clone(), + git: None, + }), + }; + + fs::write(&path, format!("{}\n", serde_json::to_string(&line)?))?; + + let summary = read_summary_from_rollout(path.as_path(), "fallback").await?; + + let expected = ConversationSummary { + conversation_id, + timestamp: Some(timestamp), + path: path.clone(), + preview: String::new(), + model_provider: "fallback".to_string(), + }; + + assert_eq!(summary, expected); Ok(()) } } diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 34b6df4a5a..f7d86c41a5 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -77,6 +77,7 @@ pub use rollout::find_conversation_path_by_id_str; pub use rollout::list::ConversationItem; pub use rollout::list::ConversationsPage; pub use rollout::list::Cursor; +pub use rollout::list::read_head_for_summary; mod function_tool; mod state; mod tasks; diff --git a/codex-rs/core/src/rollout/list.rs b/codex-rs/core/src/rollout/list.rs index 4a3fec7934..13663beb29 100644 --- a/codex-rs/core/src/rollout/list.rs +++ b/codex-rs/core/src/rollout/list.rs @@ -451,6 +451,13 @@ async fn read_head_and_tail( Ok(summary) } +/// Read up to `HEAD_RECORD_LIMIT` records from the start of the rollout file at `path`. +/// This should be enough to produce a summary including the session meta line. +pub async fn read_head_for_summary(path: &Path) -> io::Result> { + let summary = read_head_and_tail(path, HEAD_RECORD_LIMIT, 0).await?; + Ok(summary.head) +} + async fn read_tail_records( path: &Path, max_records: usize, From 775fbba6e0b14d124a056165efa141d3732dbd68 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Mon, 27 Oct 2025 16:53:00 +0000 Subject: [PATCH 33/35] feat: return an error if unknown enabled/disabled feature (#5817) --- codex-rs/cli/src/main.rs | 57 +++++++++++++++++++++++++++++------ codex-rs/core/src/features.rs | 5 +++ 2 files changed, 53 insertions(+), 9 deletions(-) diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index 940e1e536d..90d6440cf4 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -29,6 +29,7 @@ mod mcp_cmd; use crate::mcp_cmd::McpCli; use codex_core::config::Config; use codex_core::config::ConfigOverrides; +use codex_core::features::is_known_feature_key; /// Codex CLI /// @@ -286,15 +287,25 @@ struct FeatureToggles { } impl FeatureToggles { - fn to_overrides(&self) -> Vec { + fn to_overrides(&self) -> anyhow::Result> { let mut v = Vec::new(); - for k in &self.enable { - v.push(format!("features.{k}=true")); + for feature in &self.enable { + Self::validate_feature(feature)?; + v.push(format!("features.{feature}=true")); } - for k in &self.disable { - v.push(format!("features.{k}=false")); + for feature in &self.disable { + Self::validate_feature(feature)?; + v.push(format!("features.{feature}=false")); + } + Ok(v) + } + + fn validate_feature(feature: &str) -> anyhow::Result<()> { + if is_known_feature_key(feature) { + Ok(()) + } else { + anyhow::bail!("Unknown feature flag: {feature}") } - v } } @@ -345,9 +356,8 @@ async fn cli_main(codex_linux_sandbox_exe: Option) -> anyhow::Result<() } = MultitoolCli::parse(); // Fold --enable/--disable into config overrides so they flow to all subcommands. - root_config_overrides - .raw_overrides - .extend(feature_toggles.to_overrides()); + let toggle_overrides = feature_toggles.to_overrides()?; + root_config_overrides.raw_overrides.extend(toggle_overrides); match subcommand { None => { @@ -605,6 +615,7 @@ mod tests { use assert_matches::assert_matches; use codex_core::protocol::TokenUsage; use codex_protocol::ConversationId; + use pretty_assertions::assert_eq; fn finalize_from_args(args: &[&str]) -> TuiCli { let cli = MultitoolCli::try_parse_from(args).expect("parse"); @@ -781,4 +792,32 @@ mod tests { assert!(!interactive.resume_last); assert_eq!(interactive.resume_session_id, None); } + + #[test] + fn feature_toggles_known_features_generate_overrides() { + let toggles = FeatureToggles { + enable: vec!["web_search_request".to_string()], + disable: vec!["unified_exec".to_string()], + }; + let overrides = toggles.to_overrides().expect("valid features"); + assert_eq!( + overrides, + vec![ + "features.web_search_request=true".to_string(), + "features.unified_exec=false".to_string(), + ] + ); + } + + #[test] + fn feature_toggles_unknown_feature_errors() { + let toggles = FeatureToggles { + enable: vec!["does_not_exist".to_string()], + disable: Vec::new(), + }; + let err = toggles + .to_overrides() + .expect_err("feature should be rejected"); + assert_eq!(err.to_string(), "Unknown feature flag: does_not_exist"); + } } diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index c10305b800..269a445203 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -191,6 +191,11 @@ fn feature_for_key(key: &str) -> Option { legacy::feature_for_key(key) } +/// Returns `true` if the provided string matches a known feature toggle key. +pub fn is_known_feature_key(key: &str) -> bool { + feature_for_key(key).is_some() +} + /// Deserializable features table for TOML. #[derive(Deserialize, Debug, Clone, Default, PartialEq)] pub struct FeaturesToml { From aea7610c761df45863d7b36287ed0c3604f1a349 Mon Sep 17 00:00:00 2001 From: jif-oai Date: Mon, 27 Oct 2025 16:58:10 +0000 Subject: [PATCH 34/35] feat: image resizing (#5446) Add image resizing on the client side to reduce load on the API --- codex-rs/Cargo.lock | 23 +++ codex-rs/Cargo.toml | 7 +- codex-rs/core/Cargo.toml | 1 + codex-rs/core/tests/suite/view_image.rs | 109 +++++++++- codex-rs/protocol/Cargo.toml | 1 + codex-rs/protocol/src/models.rs | 102 ++++++++-- codex-rs/utils/cache/Cargo.toml | 15 ++ codex-rs/utils/cache/src/lib.rs | 159 +++++++++++++++ codex-rs/utils/image/Cargo.toml | 18 ++ codex-rs/utils/image/src/error.rs | 25 +++ codex-rs/utils/image/src/lib.rs | 252 ++++++++++++++++++++++++ 11 files changed, 684 insertions(+), 28 deletions(-) create mode 100644 codex-rs/utils/cache/Cargo.toml create mode 100644 codex-rs/utils/cache/src/lib.rs create mode 100644 codex-rs/utils/image/Cargo.toml create mode 100644 codex-rs/utils/image/src/error.rs create mode 100644 codex-rs/utils/image/src/lib.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 880efbbf4f..7940e4cbeb 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1080,6 +1080,7 @@ dependencies = [ "eventsource-stream", "futures", "http", + "image", "indexmap 2.10.0", "landlock", "libc", @@ -1335,6 +1336,7 @@ dependencies = [ "anyhow", "base64", "codex-git-tooling", + "codex-utils-image", "icu_decimal", "icu_locale_core", "mcp-types", @@ -1479,6 +1481,27 @@ dependencies = [ "vt100", ] +[[package]] +name = "codex-utils-cache" +version = "0.0.0" +dependencies = [ + "lru", + "sha1", + "tokio", +] + +[[package]] +name = "codex-utils-image" +version = "0.0.0" +dependencies = [ + "base64", + "codex-utils-cache", + "image", + "tempfile", + "thiserror 2.0.16", + "tokio", +] + [[package]] name = "codex-utils-json-to-toml" version = "0.0.0" diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 46a46e23e8..1d6c937e8a 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -32,9 +32,11 @@ members = [ "otel", "tui", "git-apply", + "utils/cache", + "utils/image", "utils/json-to-toml", - "utils/readiness", "utils/pty", + "utils/readiness", "utils/string", "utils/tokenizer", ] @@ -77,6 +79,8 @@ codex-responses-api-proxy = { path = "responses-api-proxy" } codex-rmcp-client = { path = "rmcp-client" } codex-stdio-to-uds = { path = "stdio-to-uds" } codex-tui = { path = "tui" } +codex-utils-cache = { path = "utils/cache" } +codex-utils-image = { path = "utils/image" } codex-utils-json-to-toml = { path = "utils/json-to-toml" } codex-utils-pty = { path = "utils/pty" } codex-utils-readiness = { path = "utils/readiness" } @@ -129,6 +133,7 @@ landlock = "0.4.1" lazy_static = "1" libc = "0.2.175" log = "0.4" +lru = "0.12.5" maplit = "1.0.2" mime_guess = "2.0.5" multimap = "0.10.0" diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 92e63b1fe5..8ab7ffe827 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -97,6 +97,7 @@ assert_cmd = { workspace = true } assert_matches = { workspace = true } core_test_support = { workspace = true } escargot = { workspace = true } +image = { workspace = true, features = ["jpeg", "png"] } maplit = { workspace = true } predicates = { workspace = true } pretty_assertions = { workspace = true } diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index e0dd2ab051..f50a5a5cc9 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -19,6 +19,10 @@ use core_test_support::skip_if_no_network; use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; +use image::GenericImageView; +use image::ImageBuffer; +use image::Rgba; +use image::load_from_memory; use serde_json::Value; use wiremock::matchers::any; @@ -49,6 +53,88 @@ fn extract_output_text(item: &Value) -> Option<&str> { }) } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn user_turn_with_local_image_attaches_image() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + + let TestCodex { + codex, + cwd, + session_configured, + .. + } = test_codex().build(&server).await?; + + let rel_path = "user-turn/example.png"; + let abs_path = cwd.path().join(rel_path); + if let Some(parent) = abs_path.parent() { + std::fs::create_dir_all(parent)?; + } + let image = ImageBuffer::from_pixel(4096, 1024, Rgba([20u8, 40, 60, 255])); + image.save(&abs_path)?; + + let response = sse(vec![ + ev_response_created("resp-1"), + ev_assistant_message("msg-1", "done"), + ev_completed("resp-1"), + ]); + let mock = responses::mount_sse_once_match(&server, any(), response).await; + + let session_model = session_configured.model.clone(); + + codex + .submit(Op::UserTurn { + items: vec![UserInput::LocalImage { + path: abs_path.clone(), + }], + final_output_json_schema: None, + cwd: cwd.path().to_path_buf(), + approval_policy: AskForApproval::Never, + sandbox_policy: SandboxPolicy::DangerFullAccess, + model: session_model, + effort: None, + summary: ReasoningSummary::Auto, + }) + .await?; + + wait_for_event(&codex, |event| matches!(event, EventMsg::TaskComplete(_))).await; + + let body = mock.single_request().body_json(); + let image_message = + find_image_message(&body).expect("pending input image message not included in request"); + let image_url = image_message + .get("content") + .and_then(Value::as_array) + .and_then(|content| { + content.iter().find_map(|span| { + if span.get("type").and_then(Value::as_str) == Some("input_image") { + span.get("image_url").and_then(Value::as_str) + } else { + None + } + }) + }) + .expect("image_url present"); + + let (prefix, encoded) = image_url + .split_once(',') + .expect("image url contains data prefix"); + assert_eq!(prefix, "data:image/png;base64"); + + let decoded = BASE64_STANDARD + .decode(encoded) + .expect("image data decodes from base64 for request"); + let resized = load_from_memory(&decoded).expect("load resized image"); + let (width, height) = resized.dimensions(); + assert!(width <= 2048); + assert!(height <= 768); + assert!(width < 4096); + assert!(height < 1024); + + Ok(()) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); @@ -67,8 +153,8 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> { if let Some(parent) = abs_path.parent() { std::fs::create_dir_all(parent)?; } - let image_bytes = b"fake_png_bytes".to_vec(); - std::fs::write(&abs_path, &image_bytes)?; + let image = ImageBuffer::from_pixel(4096, 1024, Rgba([255u8, 0, 0, 255])); + image.save(&abs_path)?; let call_id = "view-image-call"; let arguments = serde_json::json!({ "path": rel_path }).to_string(); @@ -143,11 +229,20 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> { }) .expect("image_url present"); - let expected_image_url = format!( - "data:image/png;base64,{}", - BASE64_STANDARD.encode(&image_bytes) - ); - assert_eq!(image_url, expected_image_url); + let (prefix, encoded) = image_url + .split_once(',') + .expect("image url contains data prefix"); + assert_eq!(prefix, "data:image/png;base64"); + + let decoded = BASE64_STANDARD + .decode(encoded) + .expect("image data decodes from base64 for request"); + let resized = load_from_memory(&decoded).expect("load resized image"); + let (resized_width, resized_height) = resized.dimensions(); + assert!(resized_width <= 2048); + assert!(resized_height <= 768); + assert!(resized_width < 4096); + assert!(resized_height < 1024); Ok(()) } diff --git a/codex-rs/protocol/Cargo.toml b/codex-rs/protocol/Cargo.toml index 6249d870a3..3258a984b3 100644 --- a/codex-rs/protocol/Cargo.toml +++ b/codex-rs/protocol/Cargo.toml @@ -14,6 +14,7 @@ workspace = true codex-git-tooling = { workspace = true } base64 = { workspace = true } +codex-utils-image = { workspace = true } icu_decimal = { workspace = true } icu_locale_core = { workspace = true } mcp-types = { workspace = true } diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index 095d7de4de..4430a0998a 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use base64::Engine; +use codex_utils_image::load_and_resize_to_fit; use mcp_types::CallToolResult; use serde::Deserialize; use serde::Deserializer; @@ -10,6 +11,7 @@ use ts_rs::TS; use crate::user_input::UserInput; use codex_git_tooling::GhostCommit; +use codex_utils_image::error::ImageProcessingError; use schemars::JsonSchema; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema, TS)] @@ -134,6 +136,19 @@ fn should_serialize_reasoning_content(content: &Option } } +fn local_image_error_placeholder( + path: &std::path::Path, + error: impl std::fmt::Display, +) -> ContentItem { + ContentItem::InputText { + text: format!( + "Codex could not read the local image at `{}`: {}", + path.display(), + error + ), + } +} + impl From for ResponseItem { fn from(item: ResponseInputItem) -> Self { match item { @@ -217,27 +232,40 @@ impl From> for ResponseInputItem { role: "user".to_string(), content: items .into_iter() - .filter_map(|c| match c { - UserInput::Text { text } => Some(ContentItem::InputText { text }), - UserInput::Image { image_url } => Some(ContentItem::InputImage { image_url }), - UserInput::LocalImage { path } => match std::fs::read(&path) { - Ok(bytes) => { - let mime = mime_guess::from_path(&path) - .first() - .map(|m| m.essence_str().to_owned()) - .unwrap_or_else(|| "image".to_string()); - let encoded = base64::engine::general_purpose::STANDARD.encode(bytes); - Some(ContentItem::InputImage { - image_url: format!("data:{mime};base64,{encoded}"), - }) - } + .map(|c| match c { + UserInput::Text { text } => ContentItem::InputText { text }, + UserInput::Image { image_url } => ContentItem::InputImage { image_url }, + UserInput::LocalImage { path } => match load_and_resize_to_fit(&path) { + Ok(image) => ContentItem::InputImage { + image_url: image.into_data_url(), + }, Err(err) => { - tracing::warn!( - "Skipping image {} – could not read file: {}", - path.display(), - err - ); - None + tracing::warn!("Failed to resize image {}: {}", path.display(), err); + if matches!(&err, ImageProcessingError::Read { .. }) { + local_image_error_placeholder(&path, &err) + } else { + match std::fs::read(&path) { + Ok(bytes) => { + let mime = mime_guess::from_path(&path) + .first() + .map(|m| m.essence_str().to_owned()) + .unwrap_or_else(|| "image".to_string()); + let encoded = + base64::engine::general_purpose::STANDARD.encode(bytes); + ContentItem::InputImage { + image_url: format!("data:{mime};base64,{encoded}"), + } + } + Err(read_err) => { + tracing::warn!( + "Skipping image {} – could not read file: {}", + path.display(), + read_err + ); + local_image_error_placeholder(&path, &read_err) + } + } + } } }, }) @@ -326,6 +354,7 @@ impl std::ops::Deref for FunctionCallOutputPayload { mod tests { use super::*; use anyhow::Result; + use tempfile::tempdir; #[test] fn serializes_success_as_plain_string() -> Result<()> { @@ -383,4 +412,37 @@ mod tests { ); Ok(()) } + + #[test] + fn local_image_read_error_adds_placeholder() -> Result<()> { + let dir = tempdir()?; + let missing_path = dir.path().join("missing-image.png"); + + let item = ResponseInputItem::from(vec![UserInput::LocalImage { + path: missing_path.clone(), + }]); + + match item { + ResponseInputItem::Message { content, .. } => { + assert_eq!(content.len(), 1); + match &content[0] { + ContentItem::InputText { text } => { + let display_path = missing_path.display().to_string(); + assert!( + text.contains(&display_path), + "placeholder should mention missing path: {text}" + ); + assert!( + text.contains("could not read"), + "placeholder should mention read issue: {text}" + ); + } + other => panic!("expected placeholder text but found {other:?}"), + } + } + other => panic!("expected message response but got {other:?}"), + } + + Ok(()) + } } diff --git a/codex-rs/utils/cache/Cargo.toml b/codex-rs/utils/cache/Cargo.toml new file mode 100644 index 0000000000..d100071530 --- /dev/null +++ b/codex-rs/utils/cache/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "codex-utils-cache" +version.workspace = true +edition.workspace = true + +[lints] +workspace = true + +[dependencies] +lru = { workspace = true } +sha1 = { workspace = true } +tokio = { workspace = true, features = ["sync", "rt"] } + +[dev-dependencies] +tokio = { workspace = true, features = ["macros", "rt", "rt-multi-thread"] } diff --git a/codex-rs/utils/cache/src/lib.rs b/codex-rs/utils/cache/src/lib.rs new file mode 100644 index 0000000000..38d07e52e9 --- /dev/null +++ b/codex-rs/utils/cache/src/lib.rs @@ -0,0 +1,159 @@ +use std::borrow::Borrow; +use std::hash::Hash; +use std::num::NonZeroUsize; + +use lru::LruCache; +use sha1::Digest; +use sha1::Sha1; +use tokio::sync::Mutex; +use tokio::sync::MutexGuard; + +/// A minimal LRU cache protected by a Tokio mutex. +pub struct BlockingLruCache { + inner: Mutex>, +} + +impl BlockingLruCache +where + K: Eq + Hash, +{ + /// Creates a cache with the provided non-zero capacity. + #[must_use] + pub fn new(capacity: NonZeroUsize) -> Self { + Self { + inner: Mutex::new(LruCache::new(capacity)), + } + } + + /// Returns a clone of the cached value for `key`, or computes and inserts it. + pub fn get_or_insert_with(&self, key: K, value: impl FnOnce() -> V) -> V + where + V: Clone, + { + let mut guard = lock_blocking(&self.inner); + if let Some(v) = guard.get(&key) { + return v.clone(); + } + let v = value(); + // Insert and return a clone to keep ownership in the cache. + guard.put(key, v.clone()); + v + } + + /// Like `get_or_insert_with`, but the value factory may fail. + pub fn get_or_try_insert_with( + &self, + key: K, + value: impl FnOnce() -> Result, + ) -> Result + where + V: Clone, + { + let mut guard = lock_blocking(&self.inner); + if let Some(v) = guard.get(&key) { + return Ok(v.clone()); + } + let v = value()?; + guard.put(key, v.clone()); + Ok(v) + } + + /// Builds a cache if `capacity` is non-zero, returning `None` otherwise. + #[must_use] + pub fn try_with_capacity(capacity: usize) -> Option { + NonZeroUsize::new(capacity).map(Self::new) + } + + /// Returns a clone of the cached value corresponding to `key`, if present. + pub fn get(&self, key: &Q) -> Option + where + K: Borrow, + Q: Hash + Eq + ?Sized, + V: Clone, + { + lock_blocking(&self.inner).get(key).cloned() + } + + /// Inserts `value` for `key`, returning the previous entry if it existed. + pub fn insert(&self, key: K, value: V) -> Option { + lock_blocking(&self.inner).put(key, value) + } + + /// Removes the entry for `key` if it exists, returning it. + pub fn remove(&self, key: &Q) -> Option + where + K: Borrow, + Q: Hash + Eq + ?Sized, + { + lock_blocking(&self.inner).pop(key) + } + + /// Clears all entries from the cache. + pub fn clear(&self) { + lock_blocking(&self.inner).clear(); + } + + /// Executes `callback` with a mutable reference to the underlying cache. + pub fn with_mut(&self, callback: impl FnOnce(&mut LruCache) -> R) -> R { + let mut guard = lock_blocking(&self.inner); + callback(&mut guard) + } + + /// Provides direct access to the cache guard for advanced use cases. + pub fn blocking_lock(&self) -> MutexGuard<'_, LruCache> { + lock_blocking(&self.inner) + } +} + +fn lock_blocking(m: &Mutex>) -> MutexGuard<'_, LruCache> +where + K: Eq + Hash, +{ + match tokio::runtime::Handle::try_current() { + Ok(_) => tokio::task::block_in_place(|| m.blocking_lock()), + Err(_) => m.blocking_lock(), + } +} + +/// Computes the SHA-1 digest of `bytes`. +/// +/// Useful for content-based cache keys when you want to avoid staleness +/// caused by path-only keys. +#[must_use] +pub fn sha1_digest(bytes: &[u8]) -> [u8; 20] { + let mut hasher = Sha1::new(); + hasher.update(bytes); + let result = hasher.finalize(); + let mut out = [0; 20]; + out.copy_from_slice(&result); + out +} + +#[cfg(test)] +mod tests { + use super::BlockingLruCache; + use std::num::NonZeroUsize; + + #[tokio::test(flavor = "multi_thread")] + async fn stores_and_retrieves_values() { + let cache = BlockingLruCache::new(NonZeroUsize::new(2).expect("capacity")); + + assert!(cache.get(&"first").is_none()); + cache.insert("first", 1); + assert_eq!(cache.get(&"first"), Some(1)); + } + + #[tokio::test(flavor = "multi_thread")] + async fn evicts_least_recently_used() { + let cache = BlockingLruCache::new(NonZeroUsize::new(2).expect("capacity")); + cache.insert("a", 1); + cache.insert("b", 2); + assert_eq!(cache.get(&"a"), Some(1)); + + cache.insert("c", 3); + + assert!(cache.get(&"b").is_none()); + assert_eq!(cache.get(&"a"), Some(1)); + assert_eq!(cache.get(&"c"), Some(3)); + } +} diff --git a/codex-rs/utils/image/Cargo.toml b/codex-rs/utils/image/Cargo.toml new file mode 100644 index 0000000000..6e83d4d0df --- /dev/null +++ b/codex-rs/utils/image/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "codex-utils-image" +version.workspace = true +edition.workspace = true + +[lints] +workspace = true + +[dependencies] +base64 = { workspace = true } +image = { workspace = true, features = ["jpeg", "png"] } +codex-utils-cache = { workspace = true } +thiserror = { workspace = true } +tokio = { workspace = true, features = ["fs", "rt", "rt-multi-thread", "macros"] } + +[dev-dependencies] +image = { workspace = true, features = ["jpeg", "png"] } +tempfile = { workspace = true } diff --git a/codex-rs/utils/image/src/error.rs b/codex-rs/utils/image/src/error.rs new file mode 100644 index 0000000000..ffd0a7850e --- /dev/null +++ b/codex-rs/utils/image/src/error.rs @@ -0,0 +1,25 @@ +use image::ImageFormat; +use std::path::PathBuf; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum ImageProcessingError { + #[error("failed to read image at {path}: {source}")] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("failed to decode image at {path}: {source}")] + Decode { + path: PathBuf, + #[source] + source: image::ImageError, + }, + #[error("failed to encode image as {format:?}: {source}")] + Encode { + format: ImageFormat, + #[source] + source: image::ImageError, + }, +} diff --git a/codex-rs/utils/image/src/lib.rs b/codex-rs/utils/image/src/lib.rs new file mode 100644 index 0000000000..0950bf176e --- /dev/null +++ b/codex-rs/utils/image/src/lib.rs @@ -0,0 +1,252 @@ +use std::num::NonZeroUsize; +use std::path::Path; +use std::sync::LazyLock; + +use crate::error::ImageProcessingError; +use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; +use codex_utils_cache::BlockingLruCache; +use codex_utils_cache::sha1_digest; +use image::ColorType; +use image::DynamicImage; +use image::GenericImageView; +use image::ImageEncoder; +use image::ImageFormat; +use image::codecs::jpeg::JpegEncoder; +use image::codecs::png::PngEncoder; +use image::imageops::FilterType; +/// Maximum width used when resizing images before uploading. +pub const MAX_WIDTH: u32 = 2048; +/// Maximum height used when resizing images before uploading. +pub const MAX_HEIGHT: u32 = 768; + +pub mod error; + +#[derive(Debug, Clone)] +pub struct EncodedImage { + pub bytes: Vec, + pub mime: String, + pub width: u32, + pub height: u32, +} + +impl EncodedImage { + pub fn into_data_url(self) -> String { + let encoded = BASE64_STANDARD.encode(&self.bytes); + format!("data:{};base64,{}", self.mime, encoded) + } +} + +static IMAGE_CACHE: LazyLock> = + LazyLock::new(|| BlockingLruCache::new(NonZeroUsize::new(32).unwrap_or(NonZeroUsize::MIN))); + +pub fn load_and_resize_to_fit(path: &Path) -> Result { + let path_buf = path.to_path_buf(); + + let file_bytes = read_file_bytes(path, &path_buf)?; + + let key = sha1_digest(&file_bytes); + + IMAGE_CACHE.get_or_try_insert_with(key, move || { + let format = match image::guess_format(&file_bytes) { + Ok(ImageFormat::Png) => Some(ImageFormat::Png), + Ok(ImageFormat::Jpeg) => Some(ImageFormat::Jpeg), + _ => None, + }; + + let dynamic = image::load_from_memory(&file_bytes).map_err(|source| { + ImageProcessingError::Decode { + path: path_buf.clone(), + source, + } + })?; + + let (width, height) = dynamic.dimensions(); + + let encoded = if width <= MAX_WIDTH && height <= MAX_HEIGHT { + if let Some(format) = format { + let mime = format_to_mime(format); + EncodedImage { + bytes: file_bytes, + mime, + width, + height, + } + } else { + let (bytes, output_format) = encode_image(&dynamic, ImageFormat::Png)?; + let mime = format_to_mime(output_format); + EncodedImage { + bytes, + mime, + width, + height, + } + } + } else { + let resized = dynamic.resize(MAX_WIDTH, MAX_HEIGHT, FilterType::Triangle); + let target_format = format.unwrap_or(ImageFormat::Png); + let (bytes, output_format) = encode_image(&resized, target_format)?; + let mime = format_to_mime(output_format); + EncodedImage { + bytes, + mime, + width: resized.width(), + height: resized.height(), + } + }; + + Ok(encoded) + }) +} + +fn read_file_bytes(path: &Path, path_for_error: &Path) -> Result, ImageProcessingError> { + match tokio::runtime::Handle::try_current() { + // If we're inside a Tokio runtime, avoid block_on (it panics on worker threads). + // Use block_in_place and do a standard blocking read safely. + Ok(_) => tokio::task::block_in_place(|| std::fs::read(path)).map_err(|source| { + ImageProcessingError::Read { + path: path_for_error.to_path_buf(), + source, + } + }), + // Outside a runtime, just read synchronously. + Err(_) => std::fs::read(path).map_err(|source| ImageProcessingError::Read { + path: path_for_error.to_path_buf(), + source, + }), + } +} + +fn encode_image( + image: &DynamicImage, + preferred_format: ImageFormat, +) -> Result<(Vec, ImageFormat), ImageProcessingError> { + let target_format = match preferred_format { + ImageFormat::Jpeg => ImageFormat::Jpeg, + _ => ImageFormat::Png, + }; + + let mut buffer = Vec::new(); + + match target_format { + ImageFormat::Png => { + let rgba = image.to_rgba8(); + let encoder = PngEncoder::new(&mut buffer); + encoder + .write_image( + rgba.as_raw(), + image.width(), + image.height(), + ColorType::Rgba8.into(), + ) + .map_err(|source| ImageProcessingError::Encode { + format: target_format, + source, + })?; + } + ImageFormat::Jpeg => { + let mut encoder = JpegEncoder::new_with_quality(&mut buffer, 85); + encoder + .encode_image(image) + .map_err(|source| ImageProcessingError::Encode { + format: target_format, + source, + })?; + } + _ => unreachable!("unsupported target_format should have been handled earlier"), + } + + Ok((buffer, target_format)) +} + +fn format_to_mime(format: ImageFormat) -> String { + match format { + ImageFormat::Jpeg => "image/jpeg".to_string(), + _ => "image/png".to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use image::GenericImageView; + use image::ImageBuffer; + use image::Rgba; + use tempfile::NamedTempFile; + + #[tokio::test(flavor = "multi_thread")] + async fn returns_original_image_when_within_bounds() { + let temp_file = NamedTempFile::new().expect("temp file"); + let image = ImageBuffer::from_pixel(64, 32, Rgba([10u8, 20, 30, 255])); + image + .save_with_format(temp_file.path(), ImageFormat::Png) + .expect("write png to temp file"); + + let original_bytes = std::fs::read(temp_file.path()).expect("read written image"); + + let encoded = load_and_resize_to_fit(temp_file.path()).expect("process image"); + + assert_eq!(encoded.width, 64); + assert_eq!(encoded.height, 32); + assert_eq!(encoded.mime, "image/png"); + assert_eq!(encoded.bytes, original_bytes); + } + + #[tokio::test(flavor = "multi_thread")] + async fn downscales_large_image() { + let temp_file = NamedTempFile::new().expect("temp file"); + let image = ImageBuffer::from_pixel(4096, 2048, Rgba([200u8, 10, 10, 255])); + image + .save_with_format(temp_file.path(), ImageFormat::Png) + .expect("write png to temp file"); + + let processed = load_and_resize_to_fit(temp_file.path()).expect("process image"); + + assert!(processed.width <= MAX_WIDTH); + assert!(processed.height <= MAX_HEIGHT); + + let loaded = + image::load_from_memory(&processed.bytes).expect("read resized bytes back into image"); + assert_eq!(loaded.dimensions(), (processed.width, processed.height)); + } + + #[tokio::test(flavor = "multi_thread")] + async fn fails_cleanly_for_invalid_images() { + let temp_file = NamedTempFile::new().expect("temp file"); + std::fs::write(temp_file.path(), b"not an image").expect("write bytes"); + + let err = load_and_resize_to_fit(temp_file.path()).expect_err("invalid image should fail"); + match err { + ImageProcessingError::Decode { .. } => {} + _ => panic!("unexpected error variant"), + } + } + + #[tokio::test(flavor = "multi_thread")] + async fn reprocesses_updated_file_contents() { + { + IMAGE_CACHE.clear(); + } + + let temp_file = NamedTempFile::new().expect("temp file"); + let first_image = ImageBuffer::from_pixel(32, 16, Rgba([20u8, 120, 220, 255])); + first_image + .save_with_format(temp_file.path(), ImageFormat::Png) + .expect("write initial image"); + + let first = load_and_resize_to_fit(temp_file.path()).expect("process first image"); + + let second_image = ImageBuffer::from_pixel(96, 48, Rgba([50u8, 60, 70, 255])); + second_image + .save_with_format(temp_file.path(), ImageFormat::Png) + .expect("write updated image"); + + let second = load_and_resize_to_fit(temp_file.path()).expect("process updated image"); + + assert_eq!(first.width, 32); + assert_eq!(first.height, 16); + assert_eq!(second.width, 96); + assert_eq!(second.height, 48); + assert_ne!(second.bytes, first.bytes); + } +} From 0c1ff1d3fd84d6aa6f3235856f873808144f4a67 Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Mon, 27 Oct 2025 12:09:53 -0500 Subject: [PATCH 35/35] Made token refresh code resilient to missing `id_token` (#5782) This PR does the following: 1. Changes `try_refresh_token` to handle the case where the endpoint returns a response without an `id_token`. The OpenID spec indicates that this field is optional and clients should not assume it's present. 2. Changes the `attempt_stream_responses` to propagate token refresh errors rather than silently ignoring them. 3. Fixes a typo in a couple of error messages (unrelated to the above, but something I noticed in passing) - "reconnect" should be spelled without a hyphen. This PR does not implement the additional suggestion from @pakrym-oai that we should sign out when receiving `refresh_token_expired` from the refresh endpoint. Leaving this as a follow-on because I'm undecided on whether this should be implemented in `try_refresh_token` or its callers. --- codex-rs/core/src/auth.rs | 37 +++++++++++++++++++++++++--- codex-rs/core/src/client.rs | 9 +++++-- codex-rs/core/src/codex.rs | 2 +- codex-rs/core/src/codex/compact.rs | 2 +- codex-rs/tui/src/chatwidget/tests.rs | 2 +- 5 files changed, 44 insertions(+), 8 deletions(-) diff --git a/codex-rs/core/src/auth.rs b/codex-rs/core/src/auth.rs index 55386ca5ec..d122d338e8 100644 --- a/codex-rs/core/src/auth.rs +++ b/codex-rs/core/src/auth.rs @@ -382,14 +382,16 @@ pub fn write_auth_json(auth_file: &Path, auth_dot_json: &AuthDotJson) -> std::io async fn update_tokens( auth_file: &Path, - id_token: String, + id_token: Option, access_token: Option, refresh_token: Option, ) -> std::io::Result { let mut auth_dot_json = try_read_auth_json(auth_file)?; let tokens = auth_dot_json.tokens.get_or_insert_with(TokenData::default); - tokens.id_token = parse_id_token(&id_token).map_err(std::io::Error::other)?; + if let Some(id_token) = id_token { + tokens.id_token = parse_id_token(&id_token).map_err(std::io::Error::other)?; + } if let Some(access_token) = access_token { tokens.access_token = access_token; } @@ -445,7 +447,7 @@ struct RefreshRequest { #[derive(Deserialize, Clone)] struct RefreshResponse { - id_token: String, + id_token: Option, access_token: Option, refresh_token: Option, } @@ -511,6 +513,35 @@ mod tests { assert_eq!(auth_dot_json, same_auth_dot_json); } + #[tokio::test] + async fn refresh_without_id_token() { + let codex_home = tempdir().unwrap(); + let fake_jwt = write_auth_file( + AuthFileParams { + openai_api_key: None, + chatgpt_plan_type: "pro".to_string(), + chatgpt_account_id: None, + }, + codex_home.path(), + ) + .expect("failed to write auth file"); + + let auth_file = super::get_auth_file(codex_home.path()); + let updated = super::update_tokens( + auth_file.as_path(), + None, + Some("new-access-token".to_string()), + Some("new-refresh-token".to_string()), + ) + .await + .expect("update_tokens should succeed"); + + let tokens = updated.tokens.expect("tokens should exist"); + assert_eq!(tokens.id_token.raw_jwt, fake_jwt); + assert_eq!(tokens.access_token, "new-access-token"); + assert_eq!(tokens.refresh_token, "new-refresh-token"); + } + #[test] fn login_with_api_key_overwrites_existing_auth_json() { let dir = tempdir().unwrap(); diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index de10d6406f..cc40ef4261 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -389,9 +389,14 @@ impl ModelClient { if status == StatusCode::UNAUTHORIZED && let Some(manager) = auth_manager.as_ref() - && manager.auth().is_some() + && let Some(auth) = auth.as_ref() + && auth.mode == AuthMode::ChatGPT { - let _ = manager.refresh_token().await; + manager.refresh_token().await.map_err(|err| { + StreamAttemptError::Fatal(CodexErr::Fatal(format!( + "Failed to refresh ChatGPT credentials: {err}" + ))) + })?; } // The OpenAI Responses endpoint returns structured JSON bodies even for 4xx/5xx diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 65dad461fa..f811211c4f 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -1911,7 +1911,7 @@ async fn run_turn( // at a seemingly frozen screen. sess.notify_stream_error( turn_context.as_ref(), - format!("Re-connecting... {retries}/{max_retries}"), + format!("Reconnecting... {retries}/{max_retries}"), ) .await; diff --git a/codex-rs/core/src/codex/compact.rs b/codex-rs/core/src/codex/compact.rs index 236b024139..dc7a6aa5c6 100644 --- a/codex-rs/core/src/codex/compact.rs +++ b/codex-rs/core/src/codex/compact.rs @@ -134,7 +134,7 @@ async fn run_compact_task_inner( let delay = backoff(retries); sess.notify_stream_error( turn_context.as_ref(), - format!("Re-connecting... {retries}/{max_retries}"), + format!("Reconnecting... {retries}/{max_retries}"), ) .await; tokio::time::sleep(delay).await; diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 75796d7d62..a9c1d58c67 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -2325,7 +2325,7 @@ fn plan_update_renders_history_cell() { fn stream_error_updates_status_indicator() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(); chat.bottom_pane.set_task_running(true); - let msg = "Re-connecting... 2/5"; + let msg = "Reconnecting... 2/5"; chat.handle_codex_event(Event { id: "sub-1".into(), msg: EventMsg::StreamError(StreamErrorEvent {