diff --git a/.github/ISSUE_TEMPLATE/4-feature-request.yml b/.github/ISSUE_TEMPLATE/4-feature-request.yml new file mode 100644 index 0000000000..fc95a67ec2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/4-feature-request.yml @@ -0,0 +1,31 @@ +name: 🎁 Feature Request +description: Propose a new feature for Codex +labels: + - enhancement + - needs triage +body: + - type: markdown + attributes: + value: | + Is Codex missing a feature that you'd like to see? Feel free to propose it here. + + Before you submit a feature: + 1. Search existing issues for similar features. If you find one, πŸ‘ it rather than opening a new one. + 2. The Codex team will try to balance the varying needs of the community when prioritizing or rejecting new features. Not all features will be accepted. See [Contributing](https://github.com/openai/codex#contributing) for more details. + + - type: textarea + id: feature + attributes: + label: What feature would you like to see? + validations: + required: true + - type: textarea + id: author + attributes: + label: Are you interested in implementing this feature? + description: Please wait for acknowledgement before implementing or opening a PR. + - type: textarea + id: notes + attributes: + label: Additional information + description: Is there anything else you think we should know? diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..03cedab29c --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,6 @@ +# External (non-OpenAI) Pull Request Requirements + +Before opening this Pull Request, please read the "Contributing" section of the README or your PR may be closed: +https://github.com/openai/codex#contributing + +If your PR conforms to our contribution guidelines, replace this text with a detailed and high quality description of your changes. diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index 0fd67175a9..735a187a78 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -53,15 +53,9 @@ jobs: - runner: macos-14 target: x86_64-apple-darwin profile: dev - - runner: macos-14 - target: aarch64-apple-darwin - profile: release - runner: ubuntu-24.04 target: x86_64-unknown-linux-musl profile: dev - - runner: ubuntu-24.04 - target: x86_64-unknown-linux-musl - profile: release - runner: ubuntu-24.04 target: x86_64-unknown-linux-gnu profile: dev @@ -75,6 +69,15 @@ jobs: target: x86_64-pc-windows-msvc profile: dev + # Also run representative release builds on Mac and Linux because + # there could be release-only build errors we want to catch. + - runner: macos-14 + target: aarch64-apple-darwin + profile: release + - runner: ubuntu-24.04 + target: x86_64-unknown-linux-musl + profile: release + steps: - uses: actions/checkout@v4 - uses: dtolnay/rust-toolchain@1.88 @@ -108,12 +111,14 @@ jobs: # slower, we only do this for the x86_64-unknown-linux-gnu target. - name: cargo build individual crates id: build - if: ${{ matrix.target == 'x86_64-unknown-linux-gnu' }} + if: ${{ matrix.target == 'x86_64-unknown-linux-gnu' && matrix.profile != 'release' }} continue-on-error: true run: find . -name Cargo.toml -mindepth 2 -maxdepth 2 -print0 | xargs -0 -n1 -I{} bash -c 'cd "$(dirname "{}")" && cargo build --profile ${{ matrix.profile }}' - name: cargo test id: test + # `cargo test` takes too long for release builds to run them on every PR + if: ${{ matrix.profile != 'release' }} continue-on-error: true run: cargo test --all-features --target ${{ matrix.target }} --profile ${{ matrix.profile }} env: diff --git a/README.md b/README.md index 0c01654d66..596362a30a 100644 --- a/README.md +++ b/README.md @@ -566,9 +566,13 @@ We're excited to launch a **$1 million initiative** supporting open source proje ## Contributing -This project is under active development and the code will likely change pretty significantly. We'll update this message once that's complete! +This project is under active development and the code will likely change pretty significantly. -More broadly we welcome contributions - whether you are opening your very first pull request or you're a seasoned maintainer. At the same time we care about reliability and long-term maintainability, so the bar for merging code is intentionally **high**. The guidelines below spell out what "high-quality" means in practice and should make the whole process transparent and friendly. +**At the moment, we only plan to prioritize reviewing external contributions for bugs or security fixes.** + +If you want to add a new feature or change the behavior of an existing one, please open an issue proposing the feature and get approval from an OpenAI team member before spending time building it. + +**New contributions that don't go through this process may be closed** if they aren't aligned with our current roadmap or conflict with other priorities/upcoming features. ### Development workflow @@ -593,8 +597,9 @@ More broadly we welcome contributions - whether you are opening your very first ### Review process 1. One maintainer will be assigned as a primary reviewer. -2. We may ask for changes - please do not take this personally. We value the work, we just also value consistency and long-term maintainability. -3. When there is consensus that the PR meets the bar, a maintainer will squash-and-merge. +2. If your PR adds a new feature that was not previously discussed and approved, we may choose to close your PR (see [Contributing](#contributing)). +3. We may ask for changes - please do not take this personally. We value the work, but we also value consistency and long-term maintainability. +5. When there is consensus that the PR meets the bar, a maintainer will squash-and-merge. ### Community values diff --git a/codex-rs/arg0/src/lib.rs b/codex-rs/arg0/src/lib.rs index c097ebc11c..b7766fe70a 100644 --- a/codex-rs/arg0/src/lib.rs +++ b/codex-rs/arg0/src/lib.rs @@ -82,10 +82,34 @@ where }) } +const ILLEGAL_ENV_VAR_PREFIX: &str = "CODEX_"; + /// Load env vars from ~/.codex/.env and `$(pwd)/.env`. +/// +/// Security: Do not allow `.env` files to create or modify any variables +/// with names starting with `CODEX_`. fn load_dotenv() { if let Ok(codex_home) = codex_core::config::find_codex_home() { - dotenvy::from_path(codex_home.join(".env")).ok(); + if let Ok(iter) = dotenvy::from_path_iter(codex_home.join(".env")) { + set_filtered(iter); + } + } + + if let Ok(iter) = dotenvy::dotenv_iter() { + set_filtered(iter); + } +} + +/// Helper to set vars from a dotenvy iterator while filtering out `CODEX_` keys. +fn set_filtered(iter: I) +where + I: IntoIterator>, +{ + for (key, value) in iter.into_iter().flatten() { + if !key.to_ascii_uppercase().starts_with(ILLEGAL_ENV_VAR_PREFIX) { + // It is safe to call set_var() because our process is + // single-threaded at this point in its execution. + unsafe { std::env::set_var(&key, &value) }; + } } - dotenvy::dotenv().ok(); } diff --git a/codex-rs/cli/src/debug_sandbox.rs b/codex-rs/cli/src/debug_sandbox.rs index 7f0983cbc6..30e144ed34 100644 --- a/codex-rs/cli/src/debug_sandbox.rs +++ b/codex-rs/cli/src/debug_sandbox.rs @@ -4,8 +4,8 @@ use codex_common::CliConfigOverrides; use codex_core::config::Config; use codex_core::config::ConfigOverrides; use codex_core::config_types::SandboxMode; -use codex_core::exec::spawn_command_under_linux_sandbox; use codex_core::exec_env::create_env; +use codex_core::landlock::spawn_command_under_linux_sandbox; use codex_core::seatbelt::spawn_command_under_seatbelt; use codex_core::spawn::StdioPolicy; diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 1ea1422bd4..3fb99d1f7f 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -29,6 +29,7 @@ mcp-types = { path = "../mcp-types" } mime_guess = "2.0" os_info = "3.12.0" rand = "0.9" +regex-lite = "0.1.6" reqwest = { version = "0.12", features = ["json", "stream"] } serde = { version = "1", features = ["derive"] } serde_bytes = "0.11" @@ -76,7 +77,6 @@ core_test_support = { path = "tests/common" } maplit = "1.0.2" predicates = "3" pretty_assertions = "1.4.1" -regex-lite = "0.1.6" tempfile = "3" tokio-test = "0.4" walkdir = "2.5.0" diff --git a/codex-rs/core/src/apply_patch.rs b/codex-rs/core/src/apply_patch.rs index dc11aed023..21e80406e5 100644 --- a/codex-rs/core/src/apply_patch.rs +++ b/codex-rs/core/src/apply_patch.rs @@ -45,17 +45,13 @@ pub(crate) async fn apply_patch( call_id: &str, action: ApplyPatchAction, ) -> InternalApplyPatchInvocation { - let writable_roots_snapshot = { - #[allow(clippy::unwrap_used)] - let guard = sess.writable_roots.lock().unwrap(); - guard.clone() - }; + let writable_roots_snapshot = sess.get_writable_roots().to_vec(); match assess_patch_safety( &action, - sess.approval_policy, + sess.get_approval_policy(), &writable_roots_snapshot, - &sess.cwd, + sess.get_cwd(), ) { SafetyCheck::AutoApprove { .. } => { InternalApplyPatchInvocation::DelegateToExec(ApplyPatchExec { diff --git a/codex-rs/core/src/chat_completions.rs b/codex-rs/core/src/chat_completions.rs index 840e808fc7..fc0ceca5ad 100644 --- a/codex-rs/core/src/chat_completions.rs +++ b/codex-rs/core/src/chat_completions.rs @@ -213,7 +213,9 @@ async fn process_chat_sse( let sse = match timeout(idle_timeout, stream.next()).await { Ok(Some(Ok(ev))) => ev, Ok(Some(Err(e))) => { - let _ = tx_event.send(Err(CodexErr::Stream(e.to_string()))).await; + let _ = tx_event + .send(Err(CodexErr::Stream(e.to_string(), None))) + .await; return; } Ok(None) => { @@ -228,7 +230,10 @@ async fn process_chat_sse( } Err(_) => { let _ = tx_event - .send(Err(CodexErr::Stream("idle timeout waiting for SSE".into()))) + .send(Err(CodexErr::Stream( + "idle timeout waiting for SSE".into(), + None, + ))) .await; return; } diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index f0229d45ae..135782bc31 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -1,5 +1,6 @@ use std::io::BufRead; use std::path::Path; +use std::sync::OnceLock; use std::time::Duration; use bytes::Bytes; @@ -7,6 +8,7 @@ use codex_login::AuthMode; use codex_login::CodexAuth; use eventsource_stream::Eventsource; use futures::prelude::*; +use regex_lite::Regex; use reqwest::StatusCode; use serde::Deserialize; use serde::Serialize; @@ -49,7 +51,9 @@ struct ErrorResponse { #[derive(Debug, Deserialize)] struct Error { - r#type: String, + r#type: Option, + code: Option, + message: Option, } #[derive(Clone)] @@ -263,14 +267,18 @@ impl ModelClient { if status == StatusCode::TOO_MANY_REQUESTS { let body = res.json::().await.ok(); if let Some(ErrorResponse { - error: Error { r#type, .. }, + error: + Error { + r#type: Some(error_type), + .. + }, }) = body { - if r#type == "usage_limit_reached" { + if error_type == "usage_limit_reached" { return Err(CodexErr::UsageLimitReached(UsageLimitReachedError { plan_type: auth.and_then(|a| a.get_plan_type()), })); - } else if r#type == "usage_not_included" { + } else if error_type == "usage_not_included" { return Err(CodexErr::UsageNotIncluded); } } @@ -366,13 +374,14 @@ async fn process_sse( // If the stream stays completely silent for an extended period treat it as disconnected. // The response id returned from the "complete" message. let mut response_completed: Option = None; + let mut response_error: Option = None; loop { let sse = match timeout(idle_timeout, stream.next()).await { Ok(Some(Ok(sse))) => sse, Ok(Some(Err(e))) => { debug!("SSE Error: {e:#}"); - let event = CodexErr::Stream(e.to_string()); + let event = CodexErr::Stream(e.to_string(), None); let _ = tx_event.send(Err(event)).await; return; } @@ -390,9 +399,10 @@ async fn process_sse( } None => { let _ = tx_event - .send(Err(CodexErr::Stream( + .send(Err(response_error.unwrap_or(CodexErr::Stream( "stream closed before response.completed".into(), - ))) + None, + )))) .await; } } @@ -400,7 +410,10 @@ async fn process_sse( } Err(_) => { let _ = tx_event - .send(Err(CodexErr::Stream("idle timeout waiting for SSE".into()))) + .send(Err(CodexErr::Stream( + "idle timeout waiting for SSE".into(), + None, + ))) .await; return; } @@ -478,15 +491,25 @@ async fn process_sse( } "response.failed" => { if let Some(resp_val) = event.response { - let error = resp_val - .get("error") - .and_then(|v| v.get("message")) - .and_then(|v| v.as_str()) - .unwrap_or("response.failed event received"); + response_error = Some(CodexErr::Stream( + "response.failed event received".to_string(), + None, + )); - let _ = tx_event - .send(Err(CodexErr::Stream(error.to_string()))) - .await; + let error = resp_val.get("error"); + + if let Some(error) = error { + match serde_json::from_value::(error.clone()) { + Ok(error) => { + let delay = try_parse_retry_after(&error); + let message = error.message.unwrap_or_default(); + response_error = Some(CodexErr::Stream(message, delay)); + } + Err(e) => { + debug!("failed to parse ErrorResponse: {e}"); + } + } + } } } // Final response completed – includes array of output items & id @@ -550,6 +573,40 @@ async fn stream_from_fixture( Ok(ResponseStream { rx_event }) } +fn rate_limit_regex() -> &'static Regex { + static RE: OnceLock = OnceLock::new(); + + #[expect(clippy::unwrap_used)] + RE.get_or_init(|| Regex::new(r"Please try again in (\d+(?:\.\d+)?)(s|ms)").unwrap()) +} + +fn try_parse_retry_after(err: &Error) -> Option { + if err.code != Some("rate_limit_exceeded".to_string()) { + return None; + } + + // parse the Please try again in 1.898s format using regex + let re = rate_limit_regex(); + if let Some(message) = &err.message + && let Some(captures) = re.captures(message) + { + let seconds = captures.get(1); + let unit = captures.get(2); + + if let (Some(value), Some(unit)) = (seconds, unit) { + let value = value.as_str().parse::().ok()?; + let unit = unit.as_str(); + + if unit == "s" { + return Some(Duration::from_secs_f64(value)); + } else if unit == "ms" { + return Some(Duration::from_millis(value as u64)); + } + } + } + None +} + #[cfg(test)] mod tests { #![allow(clippy::expect_used, clippy::unwrap_used)] @@ -735,13 +792,49 @@ mod tests { matches!(events[0], Ok(ResponseEvent::OutputItemDone(_))); match &events[1] { - Err(CodexErr::Stream(msg)) => { + Err(CodexErr::Stream(msg, _)) => { assert_eq!(msg, "stream closed before response.completed") } other => panic!("unexpected second event: {other:?}"), } } + #[tokio::test] + async fn error_when_error_event() { + let raw_error = r#"{"type":"response.failed","sequence_number":3,"response":{"id":"resp_689bcf18d7f08194bf3440ba62fe05d803fee0cdac429894","object":"response","created_at":1755041560,"status":"failed","background":false,"error":{"code":"rate_limit_exceeded","message":"Rate limit reached for gpt-5 in organization org-AAA on tokens per min (TPM): Limit 30000, Used 22999, Requested 12528. Please try again in 11.054s. Visit https://platform.openai.com/account/rate-limits to learn more."}, "usage":null,"user":null,"metadata":{}}}"#; + + let sse1 = format!("event: response.failed\ndata: {raw_error}\n\n"); + let provider = ModelProviderInfo { + name: "test".to_string(), + base_url: Some("https://test.com".to_string()), + env_key: Some("TEST_API_KEY".to_string()), + env_key_instructions: None, + wire_api: WireApi::Responses, + query_params: None, + http_headers: None, + env_http_headers: None, + request_max_retries: Some(0), + stream_max_retries: Some(0), + stream_idle_timeout_ms: Some(1000), + requires_openai_auth: false, + }; + + let events = collect_events(&[sse1.as_bytes()], provider).await; + + assert_eq!(events.len(), 1); + + match &events[0] { + Err(CodexErr::Stream(msg, delay)) => { + assert_eq!( + msg, + "Rate limit reached for gpt-5 in organization org-AAA on tokens per min (TPM): Limit 30000, Used 22999, Requested 12528. Please try again in 11.054s. Visit https://platform.openai.com/account/rate-limits to learn more." + ); + assert_eq!(*delay, Some(Duration::from_secs_f64(11.054))); + } + other => panic!("unexpected second event: {other:?}"), + } + } + // ──────────────────────────── // Table-driven test from `main` // ──────────────────────────── @@ -840,4 +933,27 @@ mod tests { ); } } + + #[test] + fn test_try_parse_retry_after() { + let err = Error { + r#type: None, + message: Some("Rate limit reached for gpt-5 in organization org- on tokens per min (TPM): Limit 1, Used 1, Requested 19304. Please try again in 28ms. Visit https://platform.openai.com/account/rate-limits to learn more.".to_string()), + code: Some("rate_limit_exceeded".to_string()), + }; + + let delay = try_parse_retry_after(&err); + assert_eq!(delay, Some(Duration::from_millis(28))); + } + + #[test] + fn test_try_parse_retry_after_no_delay() { + let err = Error { + r#type: None, + message: Some("Rate limit reached for gpt-5 in organization on tokens per min (TPM): Limit 30000, Used 6899, Requested 24050. Please try again in 1.898s. Visit https://platform.openai.com/account/rate-limits to learn more.".to_string()), + code: Some("rate_limit_exceeded".to_string()), + }; + let delay = try_parse_retry_after(&err); + assert_eq!(delay, Some(Duration::from_secs_f64(1.898))); + } } diff --git a/codex-rs/core/src/client_common.rs b/codex-rs/core/src/client_common.rs index 440d250b62..d8684648f8 100644 --- a/codex-rs/core/src/client_common.rs +++ b/codex-rs/core/src/client_common.rs @@ -5,15 +5,11 @@ use crate::model_family::ModelFamily; use crate::models::ContentItem; use crate::models::ResponseItem; use crate::openai_tools::OpenAiTool; -use crate::protocol::AskForApproval; -use crate::protocol::SandboxPolicy; use crate::protocol::TokenUsage; use codex_apply_patch::APPLY_PATCH_TOOL_INSTRUCTIONS; use futures::Stream; use serde::Serialize; use std::borrow::Cow; -use std::fmt::Display; -use std::path::PathBuf; use std::pin::Pin; use std::task::Context; use std::task::Poll; @@ -23,62 +19,19 @@ use tokio::sync::mpsc; /// with this content. const BASE_INSTRUCTIONS: &str = include_str!("../prompt.md"); -/// wraps environment context message in a tag for the model to parse more easily. -const ENVIRONMENT_CONTEXT_START: &str = "\n\n"; -const ENVIRONMENT_CONTEXT_END: &str = "\n\n"; - /// wraps user instructions message in a tag for the model to parse more easily. const USER_INSTRUCTIONS_START: &str = "\n\n"; const USER_INSTRUCTIONS_END: &str = "\n\n"; -#[derive(Debug, Clone)] -pub(crate) struct EnvironmentContext { - pub cwd: PathBuf, - pub approval_policy: AskForApproval, - pub sandbox_policy: SandboxPolicy, -} - -impl Display for EnvironmentContext { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - writeln!( - f, - "Current working directory: {}", - self.cwd.to_string_lossy() - )?; - writeln!(f, "Approval policy: {}", self.approval_policy)?; - writeln!(f, "Sandbox policy: {}", self.sandbox_policy)?; - - let network_access = match self.sandbox_policy.clone() { - SandboxPolicy::DangerFullAccess => "enabled", - SandboxPolicy::ReadOnly => "restricted", - SandboxPolicy::WorkspaceWrite { network_access, .. } => { - if network_access { - "enabled" - } else { - "restricted" - } - } - }; - writeln!(f, "Network access: {network_access}")?; - Ok(()) - } -} - -/// API request payload for a single model turn. +/// API request payload for a single model turn #[derive(Default, Debug, Clone)] pub struct Prompt { /// Conversation context input items. pub input: Vec, - /// Optional instructions from the user to amend to the built-in agent - /// instructions. - pub user_instructions: Option, + /// Whether to store response on server side (disable_response_storage = !store). pub store: bool, - /// A list of key-value pairs that will be added as a developer message - /// for the model to use - pub environment_context: Option, - /// Tools available to the model, including additional tools sourced from /// external MCP servers. pub tools: Vec, @@ -100,36 +53,19 @@ impl Prompt { Cow::Owned(sections.join("\n")) } - fn get_formatted_user_instructions(&self) -> Option { - self.user_instructions - .as_ref() - .map(|ui| format!("{USER_INSTRUCTIONS_START}{ui}{USER_INSTRUCTIONS_END}")) - } - - fn get_formatted_environment_context(&self) -> Option { - self.environment_context - .as_ref() - .map(|ec| format!("{ENVIRONMENT_CONTEXT_START}{ec}{ENVIRONMENT_CONTEXT_END}")) - } - pub(crate) fn get_formatted_input(&self) -> Vec { - let mut input_with_instructions = Vec::with_capacity(self.input.len() + 2); - if let Some(ec) = self.get_formatted_environment_context() { - input_with_instructions.push(ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { text: ec }], - }); + self.input.clone() + } + + /// Creates a formatted user instructions message from a string + pub(crate) fn format_user_instructions_message(ui: &str) -> ResponseItem { + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: format!("{USER_INSTRUCTIONS_START}{ui}{USER_INSTRUCTIONS_END}"), + }], } - if let Some(ui) = self.get_formatted_user_instructions() { - input_with_instructions.push(ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { text: ui }], - }); - } - input_with_instructions.extend(self.input.clone()); - input_with_instructions } } @@ -259,7 +195,6 @@ mod tests { #[test] fn get_full_instructions_no_user_content() { let prompt = Prompt { - user_instructions: Some("custom instruction".to_string()), ..Default::default() }; let expected = format!("{BASE_INSTRUCTIONS}\n{APPLY_PATCH_TOOL_INSTRUCTIONS}"); diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 5ac1392bee..098ff115fa 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -4,6 +4,7 @@ use std::borrow::Cow; use std::collections::HashMap; use std::collections::HashSet; +use std::path::Path; use std::path::PathBuf; use std::sync::Arc; use std::sync::Mutex; @@ -29,6 +30,7 @@ use tracing::trace; use tracing::warn; use uuid::Uuid; +use crate::ModelProviderInfo; use crate::apply_patch::ApplyPatchExec; use crate::apply_patch::CODEX_APPLY_PATCH_ARG1; use crate::apply_patch::InternalApplyPatchInvocation; @@ -36,12 +38,14 @@ use crate::apply_patch::convert_apply_patch_to_protocol; use crate::apply_patch::get_writable_roots; use crate::apply_patch::{self}; use crate::client::ModelClient; -use crate::client_common::EnvironmentContext; use crate::client_common::Prompt; use crate::client_common::ResponseEvent; use crate::config::Config; +use crate::config_types::ReasoningEffort as ReasoningEffortConfig; +use crate::config_types::ReasoningSummary as ReasoningSummaryConfig; use crate::config_types::ShellEnvironmentPolicy; use crate::conversation_history::ConversationHistory; +use crate::environment_context::EnvironmentContext; use crate::error::CodexErr; use crate::error::Result as CodexResult; use crate::error::SandboxErr; @@ -117,22 +121,23 @@ pub struct Codex { /// unique session id. pub struct CodexSpawnOk { pub codex: Codex, - pub init_id: String, pub session_id: Uuid, } +pub(crate) const INITIAL_SUBMIT_ID: &str = ""; + impl Codex { /// Spawn a new [`Codex`] and initialize the session. pub async fn spawn(config: Config, auth: Option) -> CodexResult { - // experimental resume path (undocumented) - let resume_path = config.experimental_resume.clone(); - info!("resume_path: {resume_path:?}"); let (tx_sub, rx_sub) = async_channel::bounded(64); let (tx_event, rx_event) = async_channel::unbounded(); let user_instructions = get_user_instructions(&config).await; - let configure_session = Op::ConfigureSession { + let config = Arc::new(config); + let resume_path = config.experimental_resume.clone(); + + let configure_session = ConfigureSession { provider: config.model_provider.clone(), model: config.model.clone(), model_reasoning_effort: config.model_reasoning_effort, @@ -144,28 +149,27 @@ impl Codex { disable_response_storage: config.disable_response_storage, notify: config.notify.clone(), cwd: config.cwd.clone(), - resume_path: resume_path.clone(), + resume_path, }; - let config = Arc::new(config); - // Generate a unique ID for the lifetime of this Codex session. - let session_id = Uuid::new_v4(); + let session = Session::new(configure_session, config.clone(), auth, tx_event.clone()) + .await + .map_err(|e| { + error!("Failed to create session: {e:#}"); + CodexErr::InternalAgentDied + })?; + let session_id = session.session_id; // This task will run until Op::Shutdown is received. - tokio::spawn(submission_loop(session_id, config, auth, rx_sub, tx_event)); + tokio::spawn(submission_loop(session, config, rx_sub)); let codex = Codex { next_id: AtomicU64::new(0), tx_sub, rx_event, }; - let init_id = codex.submit(configure_session).await?; - Ok(CodexSpawnOk { - codex, - init_id, - session_id, - }) + Ok(CodexSpawnOk { codex, session_id }) } /// Submit the `op` wrapped in a `Submission` with a unique ID. @@ -199,23 +203,34 @@ impl Codex { } } +/// Mutable state of the agent +#[derive(Default)] +struct State { + approved_commands: HashSet>, + current_task: Option, + pending_approvals: HashMap>, + pending_input: Vec, + history: ConversationHistory, +} + /// Context for an initialized model agent /// /// A session has at most 1 running task at a time, and can be interrupted by user input. pub(crate) struct Session { + session_id: Uuid, client: ModelClient, - pub(crate) tx_event: Sender, + tx_event: Sender, /// The session's current working directory. All relative paths provided by /// the model as well as sandbox policies are resolved against this path /// instead of `std::env::current_dir()`. - pub(crate) cwd: PathBuf, + cwd: PathBuf, base_instructions: Option, user_instructions: Option, - pub(crate) approval_policy: AskForApproval, + approval_policy: AskForApproval, sandbox_policy: SandboxPolicy, shell_environment_policy: ShellEnvironmentPolicy, - pub(crate) writable_roots: Mutex>, + writable_roots: Vec, disable_response_storage: bool, tools_config: ToolsConfig, @@ -235,25 +250,281 @@ pub(crate) struct Session { show_raw_agent_reasoning: bool, } +/// Configure the model session. +struct ConfigureSession { + /// Provider identifier ("openai", "openrouter", ...). + provider: ModelProviderInfo, + + /// If not specified, server will use its default model. + model: String, + + model_reasoning_effort: ReasoningEffortConfig, + model_reasoning_summary: ReasoningSummaryConfig, + + /// Model instructions that are appended to the base instructions. + user_instructions: Option, + + /// Base instructions override. + base_instructions: Option, + + /// When to escalate for approval for execution + approval_policy: AskForApproval, + /// How to sandbox commands executed in the system + sandbox_policy: SandboxPolicy, + /// Disable server-side response storage (send full context each request) + disable_response_storage: bool, + + /// Optional external notifier command tokens. Present only when the + /// client wants the agent to spawn a program after each completed + /// turn. + notify: Option>, + + /// Working directory that should be treated as the *root* of the + /// session. All relative paths supplied by the model as well as the + /// execution sandbox are resolved against this directory **instead** + /// of the process-wide current working directory. CLI front-ends are + /// expected to expand this to an absolute path before sending the + /// `ConfigureSession` operation so that the business-logic layer can + /// operate deterministically. + cwd: PathBuf, + + resume_path: Option, +} + impl Session { + async fn new( + configure_session: ConfigureSession, + config: Arc, + auth: Option, + tx_event: Sender, + ) -> anyhow::Result> { + let ConfigureSession { + provider, + model, + model_reasoning_effort, + model_reasoning_summary, + user_instructions, + base_instructions, + approval_policy, + sandbox_policy, + disable_response_storage, + notify, + cwd, + resume_path, + } = configure_session; + debug!("Configuring session: model={model}; provider={provider:?}"); + if !cwd.is_absolute() { + return Err(anyhow::anyhow!("cwd is not absolute: {cwd:?}")); + } + + // Error messages to dispatch after SessionConfigured is sent. + let mut post_session_configured_error_events = Vec::::new(); + + // Kick off independent async setup tasks in parallel to reduce startup latency. + // + // - initialize RolloutRecorder with new or resumed session info + // - spin up MCP connection manager + // - perform default shell discovery + // - load history metadata + let rollout_fut = async { + match resume_path.as_ref() { + Some(path) => RolloutRecorder::resume(path, cwd.clone()) + .await + .map(|(rec, saved)| (saved.session_id, Some(saved), rec)), + None => { + let session_id = Uuid::new_v4(); + RolloutRecorder::new(&config, session_id, user_instructions.clone()) + .await + .map(|rec| (session_id, None, rec)) + } + } + }; + + let mcp_fut = McpConnectionManager::new(config.mcp_servers.clone()); + let default_shell_fut = shell::default_user_shell(); + let history_meta_fut = crate::message_history::history_metadata(&config); + + // Join all independent futures. + let (rollout_res, mcp_res, default_shell, (history_log_id, history_entry_count)) = + tokio::join!(rollout_fut, mcp_fut, default_shell_fut, history_meta_fut); + + // Handle rollout result, which determines the session_id. + struct RolloutResult { + session_id: Uuid, + rollout_recorder: Option, + restored_items: Option>, + } + let rollout_result = match rollout_res { + Ok((session_id, maybe_saved, recorder)) => { + let restored_items: Option> = + maybe_saved.and_then(|saved_session| { + if saved_session.items.is_empty() { + None + } else { + Some(saved_session.items) + } + }); + RolloutResult { + session_id, + rollout_recorder: Some(recorder), + restored_items, + } + } + Err(e) => { + if let Some(path) = resume_path.as_ref() { + return Err(anyhow::anyhow!( + "failed to resume rollout from {path:?}: {e}" + )); + } + + let message = format!("failed to initialize rollout recorder: {e}"); + post_session_configured_error_events.push(Event { + id: INITIAL_SUBMIT_ID.to_owned(), + msg: EventMsg::Error(ErrorEvent { + message: message.clone(), + }), + }); + warn!("{message}"); + + RolloutResult { + session_id: Uuid::new_v4(), + rollout_recorder: None, + restored_items: None, + } + } + }; + + let RolloutResult { + session_id, + rollout_recorder, + restored_items, + } = rollout_result; + + // Create the mutable state for the Session. + let mut state = State { + history: ConversationHistory::new(), + ..Default::default() + }; + if let Some(restored_items) = restored_items { + state.history.record_items(&restored_items); + } + + let writable_roots = get_writable_roots(&cwd); + + // Handle MCP manager result and record any startup failures. + let (mcp_connection_manager, failed_clients) = match mcp_res { + Ok((mgr, failures)) => (mgr, failures), + Err(e) => { + let message = format!("Failed to create MCP connection manager: {e:#}"); + error!("{message}"); + post_session_configured_error_events.push(Event { + id: INITIAL_SUBMIT_ID.to_owned(), + msg: EventMsg::Error(ErrorEvent { message }), + }); + (McpConnectionManager::default(), Default::default()) + } + }; + + // Surface individual client start-up failures to the user. + if !failed_clients.is_empty() { + for (server_name, err) in failed_clients { + let message = format!("MCP client for `{server_name}` failed to start: {err:#}"); + error!("{message}"); + post_session_configured_error_events.push(Event { + id: INITIAL_SUBMIT_ID.to_owned(), + msg: EventMsg::Error(ErrorEvent { message }), + }); + } + } + + // Now that `session_id` is final (may have been updated by resume), + // construct the model client. + let client = ModelClient::new( + config.clone(), + auth.clone(), + provider.clone(), + model_reasoning_effort, + model_reasoning_summary, + session_id, + ); + let sess = Arc::new(Session { + session_id, + client, + tools_config: ToolsConfig::new( + &config.model_family, + approval_policy, + sandbox_policy.clone(), + config.include_plan_tool, + ), + tx_event: tx_event.clone(), + user_instructions, + base_instructions, + approval_policy, + sandbox_policy, + shell_environment_policy: config.shell_environment_policy.clone(), + cwd, + writable_roots, + mcp_connection_manager, + notify, + state: Mutex::new(state), + rollout: Mutex::new(rollout_recorder), + codex_linux_sandbox_exe: config.codex_linux_sandbox_exe.clone(), + disable_response_storage, + user_shell: default_shell, + show_raw_agent_reasoning: config.show_raw_agent_reasoning, + }); + + // record the initial user instructions and environment context, + // regardless of whether we restored items. + let mut conversation_items = Vec::::with_capacity(2); + if let Some(user_instructions) = sess.user_instructions.as_deref() { + conversation_items.push(Prompt::format_user_instructions_message(user_instructions)); + } + conversation_items.push(ResponseItem::from(EnvironmentContext::new( + sess.get_cwd().to_path_buf(), + sess.get_approval_policy(), + sess.sandbox_policy.clone(), + ))); + sess.record_conversation_items(&conversation_items).await; + + // Dispatch the SessionConfiguredEvent first and then report any errors. + let events = std::iter::once(Event { + id: INITIAL_SUBMIT_ID.to_owned(), + msg: EventMsg::SessionConfigured(SessionConfiguredEvent { + session_id, + model, + history_log_id, + history_entry_count, + }), + }) + .chain(post_session_configured_error_events.into_iter()); + for event in events { + if let Err(e) = tx_event.send(event).await { + error!("failed to send event: {e:?}"); + } + } + + Ok(sess) + } + + pub(crate) fn get_writable_roots(&self) -> &[PathBuf] { + &self.writable_roots + } + + pub(crate) fn get_approval_policy(&self) -> AskForApproval { + self.approval_policy + } + + pub(crate) fn get_cwd(&self) -> &Path { + &self.cwd + } + fn resolve_path(&self, path: Option) -> PathBuf { path.as_ref() .map(PathBuf::from) .map_or_else(|| self.cwd.clone(), |p| self.cwd.join(p)) } -} -/// Mutable state of the agent -#[derive(Default)] -struct State { - approved_commands: HashSet>, - current_task: Option, - pending_approvals: HashMap>, - pending_input: Vec, - history: ConversationHistory, -} - -impl Session { pub fn set_task(&self, task: AgentTask) { let mut state = self.state.lock().unwrap(); if let Some(current_task) = state.current_task.take() { @@ -617,16 +888,6 @@ impl Drop for Session { } } -impl State { - pub fn partial_clone(&self) -> Self { - Self { - approved_commands: self.approved_commands.clone(), - history: self.history.clone(), - ..Default::default() - } - } -} - #[derive(Clone, Debug)] pub(crate) struct ExecCommandContext { pub(crate) sub_id: String, @@ -659,6 +920,7 @@ impl AgentTask { handle, } } + fn compact( sess: Arc, sub_id: String, @@ -696,262 +958,36 @@ impl AgentTask { } } -async fn submission_loop( - mut session_id: Uuid, - config: Arc, - auth: Option, - rx_sub: Receiver, - tx_event: Sender, -) { - let mut sess: Option> = None; - // shorthand - send an event when there is no active session - let send_no_session_event = |sub_id: String| async { - let event = Event { - id: sub_id, - msg: EventMsg::Error(ErrorEvent { - message: "No session initialized, expected 'ConfigureSession' as first Op" - .to_string(), - }), - }; - tx_event.send(event).await.ok(); - }; - +async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiver) { // To break out of this loop, send Op::Shutdown. while let Ok(sub) = rx_sub.recv().await { debug!(?sub, "Submission"); match sub.op { Op::Interrupt => { - let sess = match sess.as_ref() { - Some(sess) => sess, - None => { - send_no_session_event(sub.id).await; - continue; - } - }; sess.abort(); } - Op::ConfigureSession { - provider, - model, - model_reasoning_effort, - model_reasoning_summary, - user_instructions, - base_instructions, - approval_policy, - sandbox_policy, - disable_response_storage, - notify, - cwd, - resume_path, - } => { - debug!( - "Configuring session: model={model}; provider={provider:?}; resume={resume_path:?}" - ); - if !cwd.is_absolute() { - let message = format!("cwd is not absolute: {cwd:?}"); - error!(message); - let event = Event { - id: sub.id, - msg: EventMsg::Error(ErrorEvent { message }), - }; - if let Err(e) = tx_event.send(event).await { - error!("failed to send error message: {e:?}"); - } - return; - } - // Optionally resume an existing rollout. - let mut restored_items: Option> = None; - let rollout_recorder: Option = - if let Some(path) = resume_path.as_ref() { - match RolloutRecorder::resume(path, cwd.clone()).await { - Ok((rec, saved)) => { - session_id = saved.session_id; - if !saved.items.is_empty() { - restored_items = Some(saved.items); - } - Some(rec) - } - Err(e) => { - warn!("failed to resume rollout from {path:?}: {e}"); - None - } - } - } else { - None - }; - - let rollout_recorder = match rollout_recorder { - Some(rec) => Some(rec), - None => { - match RolloutRecorder::new(&config, session_id, user_instructions.clone()) - .await - { - Ok(r) => Some(r), - Err(e) => { - warn!("failed to initialise rollout recorder: {e}"); - None - } - } - } - }; - - let client = ModelClient::new( - config.clone(), - auth.clone(), - provider.clone(), - model_reasoning_effort, - model_reasoning_summary, - session_id, - ); - - // abort any current running session and clone its state - let state = match sess.take() { - Some(sess) => { - sess.abort(); - sess.state.lock().unwrap().partial_clone() - } - None => State { - history: ConversationHistory::new(), - ..Default::default() - }, - }; - - let writable_roots = Mutex::new(get_writable_roots(&cwd)); - - // Error messages to dispatch after SessionConfigured is sent. - let mut mcp_connection_errors = Vec::::new(); - let (mcp_connection_manager, failed_clients) = - match McpConnectionManager::new(config.mcp_servers.clone()).await { - Ok((mgr, failures)) => (mgr, failures), - Err(e) => { - let message = format!("Failed to create MCP connection manager: {e:#}"); - error!("{message}"); - mcp_connection_errors.push(Event { - id: sub.id.clone(), - msg: EventMsg::Error(ErrorEvent { message }), - }); - (McpConnectionManager::default(), Default::default()) - } - }; - - // Surface individual client start-up failures to the user. - if !failed_clients.is_empty() { - for (server_name, err) in failed_clients { - let message = - format!("MCP client for `{server_name}` failed to start: {err:#}"); - error!("{message}"); - mcp_connection_errors.push(Event { - id: sub.id.clone(), - msg: EventMsg::Error(ErrorEvent { message }), - }); - } - } - let default_shell = shell::default_user_shell().await; - sess = Some(Arc::new(Session { - client, - tools_config: ToolsConfig::new( - &config.model_family, - approval_policy, - sandbox_policy.clone(), - config.include_plan_tool, - ), - tx_event: tx_event.clone(), - user_instructions, - base_instructions, - approval_policy, - sandbox_policy, - shell_environment_policy: config.shell_environment_policy.clone(), - cwd, - writable_roots, - mcp_connection_manager, - notify, - state: Mutex::new(state), - rollout: Mutex::new(rollout_recorder), - codex_linux_sandbox_exe: config.codex_linux_sandbox_exe.clone(), - disable_response_storage, - user_shell: default_shell, - show_raw_agent_reasoning: config.show_raw_agent_reasoning, - })); - - // Patch restored state into the newly created session. - if let Some(sess_arc) = &sess { - if restored_items.is_some() { - let mut st = sess_arc.state.lock().unwrap(); - st.history.record_items(restored_items.unwrap().iter()); - } - } - - // Gather history metadata for SessionConfiguredEvent. - let (history_log_id, history_entry_count) = - crate::message_history::history_metadata(&config).await; - - // ack - let events = std::iter::once(Event { - id: sub.id.clone(), - msg: EventMsg::SessionConfigured(SessionConfiguredEvent { - session_id, - model, - history_log_id, - history_entry_count, - }), - }) - .chain(mcp_connection_errors.into_iter()); - for event in events { - if let Err(e) = tx_event.send(event).await { - error!("failed to send event: {e:?}"); - } - } - } Op::UserInput { items } => { - let sess = match sess.as_ref() { - Some(sess) => sess, - None => { - send_no_session_event(sub.id).await; - continue; - } - }; - // attempt to inject input into current task if let Err(items) = sess.inject_input(items) { // no current task, spawn a new one - let task = AgentTask::spawn(Arc::clone(sess), sub.id, items); + let task = AgentTask::spawn(sess.clone(), sub.id, items); sess.set_task(task); } } - Op::ExecApproval { id, decision } => { - let sess = match sess.as_ref() { - Some(sess) => sess, - None => { - send_no_session_event(sub.id).await; - continue; - } - }; - match decision { - ReviewDecision::Abort => { - sess.abort(); - } - other => sess.notify_approval(&id, other), + Op::ExecApproval { id, decision } => match decision { + ReviewDecision::Abort => { + sess.abort(); } - } - Op::PatchApproval { id, decision } => { - let sess = match sess.as_ref() { - Some(sess) => sess, - None => { - send_no_session_event(sub.id).await; - continue; - } - }; - match decision { - ReviewDecision::Abort => { - sess.abort(); - } - other => sess.notify_approval(&id, other), + other => sess.notify_approval(&id, other), + }, + Op::PatchApproval { id, decision } => match decision { + ReviewDecision::Abort => { + sess.abort(); } - } + other => sess.notify_approval(&id, other), + }, Op::AddToHistory { text } => { - // TODO: What should we do if we got AddToHistory before ConfigureSession? - // currently, if ConfigureSession has resume path, this history will be ignored - let id = session_id; + let id = sess.session_id; let config = config.clone(); tokio::spawn(async move { if let Err(e) = crate::message_history::append_entry(&text, &id, &config).await @@ -963,7 +999,7 @@ async fn submission_loop( Op::GetHistoryEntryRequest { offset, log_id } => { let config = config.clone(); - let tx_event = tx_event.clone(); + let tx_event = sess.tx_event.clone(); let sub_id = sub.id.clone(); tokio::spawn(async move { @@ -991,14 +1027,6 @@ async fn submission_loop( }); } Op::Compact => { - let sess = match sess.as_ref() { - Some(sess) => sess, - None => { - send_no_session_event(sub.id).await; - continue; - } - }; - // Create a summarization request as user input const SUMMARIZATION_PROMPT: &str = include_str!("prompt_for_compact_command.md"); @@ -1020,28 +1048,27 @@ async fn submission_loop( // Gracefully flush and shutdown rollout recorder on session end so tests // that inspect the rollout file do not race with the background writer. - if let Some(sess_arc) = sess { - let recorder_opt = sess_arc.rollout.lock().unwrap().take(); - if let Some(rec) = recorder_opt { - if let Err(e) = rec.shutdown().await { - warn!("failed to shutdown rollout recorder: {e}"); - let event = Event { - id: sub.id.clone(), - msg: EventMsg::Error(ErrorEvent { - message: "Failed to shutdown rollout recorder".to_string(), - }), - }; - if let Err(e) = tx_event.send(event).await { - warn!("failed to send error message: {e:?}"); - } + let recorder_opt = sess.rollout.lock().unwrap().take(); + if let Some(rec) = recorder_opt { + if let Err(e) = rec.shutdown().await { + warn!("failed to shutdown rollout recorder: {e}"); + let event = Event { + id: sub.id.clone(), + msg: EventMsg::Error(ErrorEvent { + message: "Failed to shutdown rollout recorder".to_string(), + }), + }; + if let Err(e) = sess.tx_event.send(event).await { + warn!("failed to send error message: {e:?}"); } } } + let event = Event { id: sub.id.clone(), msg: EventMsg::ShutdownComplete, }; - if let Err(e) = tx_event.send(event).await { + if let Err(e) = sess.tx_event.send(event).await { warn!("failed to send Shutdown event: {e}"); } break; @@ -1256,15 +1283,9 @@ async fn run_turn( let prompt = Prompt { input, - user_instructions: sess.user_instructions.clone(), store: !sess.disable_response_storage, tools, base_instructions_override: sess.base_instructions.clone(), - environment_context: Some(EnvironmentContext { - cwd: sess.cwd.clone(), - approval_policy: sess.approval_policy, - sandbox_policy: sess.sandbox_policy.clone(), - }), }; let mut retries = 0; @@ -1281,7 +1302,10 @@ async fn run_turn( let max_retries = sess.client.get_provider().stream_max_retries(); if retries < max_retries { retries += 1; - let delay = backoff(retries); + let delay = match e { + CodexErr::Stream(_, Some(delay)) => delay, + _ => backoff(retries), + }; warn!( "stream disconnected - retrying turn ({retries}/{max_retries} in {delay:?})...", ); @@ -1391,6 +1415,7 @@ async fn try_run_turn( // Treat as a disconnected stream so the caller can retry. return Err(CodexErr::Stream( "stream closed before response.completed".into(), + None, )); }; @@ -1498,9 +1523,7 @@ async fn run_compact_task( let prompt = Prompt { input: turn_input, - user_instructions: None, store: !sess.disable_response_storage, - environment_context: None, tools: Vec::new(), base_instructions_override: Some(compact_instructions.clone()), }; @@ -1602,6 +1625,7 @@ async fn handle_response_item( for item in content { let text = match item { ReasoningItemContent::ReasoningText { text } => text, + ReasoningItemContent::Text { text } => text, }; let event = Event { id: sub_id.to_string(), @@ -2201,6 +2225,7 @@ async fn drain_to_completed(sess: &Session, sub_id: &str, prompt: &Prompt) -> Co let Some(event) = maybe_event else { return Err(CodexErr::Stream( "stream closed before response.completed".into(), + None, )); }; match event { @@ -2218,6 +2243,7 @@ async fn drain_to_completed(sess: &Session, sub_id: &str, prompt: &Prompt) -> Co None => { return Err(CodexErr::Stream( "token_usage was None in ResponseEvent::Completed".into(), + None, )); } }; diff --git a/codex-rs/core/src/config_types.rs b/codex-rs/core/src/config_types.rs index 291dcb6422..cbbc6b4923 100644 --- a/codex-rs/core/src/config_types.rs +++ b/codex-rs/core/src/config_types.rs @@ -78,8 +78,9 @@ pub enum HistoryPersistence { #[derive(Deserialize, Debug, Clone, PartialEq, Default)] pub struct Tui {} -#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Default, Serialize)] +#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Default, Serialize, Display)] #[serde(rename_all = "kebab-case")] +#[strum(serialize_all = "kebab-case")] pub enum SandboxMode { #[serde(rename = "read-only")] #[default] diff --git a/codex-rs/core/src/conversation_manager.rs b/codex-rs/core/src/conversation_manager.rs index 4a6cdc1bf1..48ccdddf35 100644 --- a/codex-rs/core/src/conversation_manager.rs +++ b/codex-rs/core/src/conversation_manager.rs @@ -7,6 +7,7 @@ use uuid::Uuid; use crate::codex::Codex; use crate::codex::CodexSpawnOk; +use crate::codex::INITIAL_SUBMIT_ID; use crate::codex_conversation::CodexConversation; use crate::config::Config; use crate::error::CodexErr; @@ -52,7 +53,6 @@ impl ConversationManager { ) -> CodexResult { let CodexSpawnOk { codex, - init_id, session_id: conversation_id, } = Codex::spawn(config, auth).await?; @@ -64,7 +64,7 @@ impl ConversationManager { Event { id, msg: EventMsg::SessionConfigured(session_configured), - } if id == init_id => session_configured, + } if id == INITIAL_SUBMIT_ID => session_configured, _ => { return Err(CodexErr::SessionConfiguredNotFirstEvent); } diff --git a/codex-rs/core/src/environment_context.rs b/codex-rs/core/src/environment_context.rs new file mode 100644 index 0000000000..d31ddbc15e --- /dev/null +++ b/codex-rs/core/src/environment_context.rs @@ -0,0 +1,86 @@ +use serde::Deserialize; +use serde::Serialize; +use strum_macros::Display as DeriveDisplay; + +use crate::config_types::SandboxMode; +use crate::models::ContentItem; +use crate::models::ResponseItem; +use crate::protocol::AskForApproval; +use crate::protocol::SandboxPolicy; +use std::fmt::Display; +use std::path::PathBuf; + +/// wraps environment context message in a tag for the model to parse more easily. +pub(crate) const ENVIRONMENT_CONTEXT_START: &str = "\n"; +pub(crate) const ENVIRONMENT_CONTEXT_END: &str = ""; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, DeriveDisplay)] +#[serde(rename_all = "kebab-case")] +#[strum(serialize_all = "kebab-case")] +pub enum NetworkAccess { + Restricted, + Enabled, +} +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename = "environment_context", rename_all = "snake_case")] +pub(crate) struct EnvironmentContext { + pub cwd: PathBuf, + pub approval_policy: AskForApproval, + pub sandbox_mode: SandboxMode, + pub network_access: NetworkAccess, +} + +impl EnvironmentContext { + pub fn new( + cwd: PathBuf, + approval_policy: AskForApproval, + sandbox_policy: SandboxPolicy, + ) -> Self { + Self { + cwd, + approval_policy, + sandbox_mode: match sandbox_policy { + SandboxPolicy::DangerFullAccess => SandboxMode::DangerFullAccess, + SandboxPolicy::ReadOnly => SandboxMode::ReadOnly, + SandboxPolicy::WorkspaceWrite { .. } => SandboxMode::WorkspaceWrite, + }, + network_access: match sandbox_policy { + SandboxPolicy::DangerFullAccess => NetworkAccess::Enabled, + SandboxPolicy::ReadOnly => NetworkAccess::Restricted, + SandboxPolicy::WorkspaceWrite { network_access, .. } => { + if network_access { + NetworkAccess::Enabled + } else { + NetworkAccess::Restricted + } + } + }, + } + } +} + +impl Display for EnvironmentContext { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + writeln!( + f, + "Current working directory: {}", + self.cwd.to_string_lossy() + )?; + writeln!(f, "Approval policy: {}", self.approval_policy)?; + writeln!(f, "Sandbox mode: {}", self.sandbox_mode)?; + writeln!(f, "Network access: {}", self.network_access)?; + Ok(()) + } +} + +impl From for ResponseItem { + fn from(ec: EnvironmentContext) -> Self { + ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { + text: format!("{ENVIRONMENT_CONTEXT_START}{ec}{ENVIRONMENT_CONTEXT_END}"), + }], + } + } +} diff --git a/codex-rs/core/src/error.rs b/codex-rs/core/src/error.rs index 4df6663394..356c23011c 100644 --- a/codex-rs/core/src/error.rs +++ b/codex-rs/core/src/error.rs @@ -1,6 +1,7 @@ use reqwest::StatusCode; use serde_json; use std::io; +use std::time::Duration; use thiserror::Error; use tokio::task::JoinError; use uuid::Uuid; @@ -42,8 +43,10 @@ pub enum CodexErr { /// handshake has succeeded but **before** it finished emitting `response.completed`. /// /// The Session loop treats this as a transient error and will automatically retry the turn. + /// + /// Optionally includes the requested delay before retrying the turn. #[error("stream disconnected before completion: {0}")] - Stream(String), + Stream(String, Option), #[error("no conversation with id: {0}")] ConversationNotFound(Uuid), diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index 50bba1b4b7..9430433c11 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -3,7 +3,6 @@ use std::os::unix::process::ExitStatusExt; use std::collections::HashMap; use std::io; -use std::path::Path; use std::path::PathBuf; use std::process::ExitStatus; use std::time::Duration; @@ -18,6 +17,7 @@ use tokio::process::Child; use crate::error::CodexErr; use crate::error::Result; use crate::error::SandboxErr; +use crate::landlock::spawn_command_under_linux_sandbox; use crate::protocol::Event; use crate::protocol::EventMsg; use crate::protocol::ExecCommandOutputDeltaEvent; @@ -163,65 +163,6 @@ pub async fn process_exec_tool_call( } } -/// Spawn a shell tool command under the Linux Landlock+seccomp sandbox helper -/// (codex-linux-sandbox). -/// -/// Unlike macOS Seatbelt where we directly embed the policy text, the Linux -/// helper accepts a list of `--sandbox-permission`/`-s` flags mirroring the -/// public CLI. We convert the internal [`SandboxPolicy`] representation into -/// the equivalent CLI options. -pub async fn spawn_command_under_linux_sandbox

( - codex_linux_sandbox_exe: P, - command: Vec, - sandbox_policy: &SandboxPolicy, - cwd: PathBuf, - stdio_policy: StdioPolicy, - env: HashMap, -) -> std::io::Result -where - P: AsRef, -{ - let args = create_linux_sandbox_command_args(command, sandbox_policy, &cwd); - let arg0 = Some("codex-linux-sandbox"); - spawn_child_async( - codex_linux_sandbox_exe.as_ref().to_path_buf(), - args, - arg0, - cwd, - sandbox_policy, - stdio_policy, - env, - ) - .await -} - -/// Converts the sandbox policy into the CLI invocation for `codex-linux-sandbox`. -fn create_linux_sandbox_command_args( - command: Vec, - sandbox_policy: &SandboxPolicy, - cwd: &Path, -) -> Vec { - #[expect(clippy::expect_used)] - let sandbox_policy_cwd = cwd.to_str().expect("cwd must be valid UTF-8").to_string(); - - #[expect(clippy::expect_used)] - let sandbox_policy_json = - serde_json::to_string(sandbox_policy).expect("Failed to serialize SandboxPolicy to JSON"); - - let mut linux_cmd: Vec = vec![ - sandbox_policy_cwd, - sandbox_policy_json, - // Separator so that command arguments starting with `-` are not parsed as - // options of the helper itself. - "--".to_string(), - ]; - - // Append the original tool command. - linux_cmd.extend(command); - - linux_cmd -} - /// We don't have a fully deterministic way to tell if our command failed /// because of the sandbox - a command in the user's zshrc file might hit an /// error, but the command itself might fail or succeed for other reasons. diff --git a/codex-rs/core/src/landlock.rs b/codex-rs/core/src/landlock.rs new file mode 100644 index 0000000000..8c8840c269 --- /dev/null +++ b/codex-rs/core/src/landlock.rs @@ -0,0 +1,66 @@ +use crate::protocol::SandboxPolicy; +use crate::spawn::StdioPolicy; +use crate::spawn::spawn_child_async; +use std::collections::HashMap; +use std::path::Path; +use std::path::PathBuf; +use tokio::process::Child; + +/// Spawn a shell tool command under the Linux Landlock+seccomp sandbox helper +/// (codex-linux-sandbox). +/// +/// Unlike macOS Seatbelt where we directly embed the policy text, the Linux +/// helper accepts a list of `--sandbox-permission`/`-s` flags mirroring the +/// public CLI. We convert the internal [`SandboxPolicy`] representation into +/// the equivalent CLI options. +pub async fn spawn_command_under_linux_sandbox

( + codex_linux_sandbox_exe: P, + command: Vec, + sandbox_policy: &SandboxPolicy, + cwd: PathBuf, + stdio_policy: StdioPolicy, + env: HashMap, +) -> std::io::Result +where + P: AsRef, +{ + let args = create_linux_sandbox_command_args(command, sandbox_policy, &cwd); + let arg0 = Some("codex-linux-sandbox"); + spawn_child_async( + codex_linux_sandbox_exe.as_ref().to_path_buf(), + args, + arg0, + cwd, + sandbox_policy, + stdio_policy, + env, + ) + .await +} + +/// Converts the sandbox policy into the CLI invocation for `codex-linux-sandbox`. +fn create_linux_sandbox_command_args( + command: Vec, + sandbox_policy: &SandboxPolicy, + cwd: &Path, +) -> Vec { + #[expect(clippy::expect_used)] + let sandbox_policy_cwd = cwd.to_str().expect("cwd must be valid UTF-8").to_string(); + + #[expect(clippy::expect_used)] + let sandbox_policy_json = + serde_json::to_string(sandbox_policy).expect("Failed to serialize SandboxPolicy to JSON"); + + let mut linux_cmd: Vec = vec![ + sandbox_policy_cwd, + sandbox_policy_json, + // Separator so that command arguments starting with `-` are not parsed as + // options of the helper itself. + "--".to_string(), + ]; + + // Append the original tool command. + linux_cmd.extend(command); + + linux_cmd +} diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 1fc404062d..725df4d0a6 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -17,12 +17,14 @@ pub mod config; pub mod config_profile; pub mod config_types; mod conversation_history; +mod environment_context; pub mod error; pub mod exec; pub mod exec_env; mod flags; pub mod git_info; mod is_safe_command; +pub mod landlock; mod mcp_connection_manager; mod mcp_tool_call; mod message_history; diff --git a/codex-rs/core/src/model_family.rs b/codex-rs/core/src/model_family.rs index 1245a030c6..fa4826d76f 100644 --- a/codex-rs/core/src/model_family.rs +++ b/codex-rs/core/src/model_family.rs @@ -78,6 +78,11 @@ pub fn find_family_for_model(slug: &str) -> Option { supports_reasoning_summaries: true, uses_local_shell_tool: true, ) + } else if slug.starts_with("codex-") { + model_family!( + slug, slug, + supports_reasoning_summaries: true, + ) } else if slug.starts_with("gpt-4.1") { model_family!( slug, "gpt-4.1", diff --git a/codex-rs/core/src/models.rs b/codex-rs/core/src/models.rs index e052bc43a4..da1e31b706 100644 --- a/codex-rs/core/src/models.rs +++ b/codex-rs/core/src/models.rs @@ -45,7 +45,7 @@ pub enum ResponseItem { Reasoning { id: String, summary: Vec, - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(default, skip_serializing_if = "should_serialize_reasoning_content")] content: Option>, encrypted_content: Option, }, @@ -81,6 +81,15 @@ pub enum ResponseItem { Other, } +fn should_serialize_reasoning_content(content: &Option>) -> bool { + match content { + Some(content) => !content + .iter() + .any(|c| matches!(c, ReasoningItemContent::ReasoningText { .. })), + None => false, + } +} + impl From for ResponseItem { fn from(item: ResponseInputItem) -> Self { match item { @@ -142,6 +151,7 @@ pub enum ReasoningItemReasoningSummary { #[serde(tag = "type", rename_all = "snake_case")] pub enum ReasoningItemContent { ReasoningText { text: String }, + Text { text: String }, } impl From> for ResponseInputItem { diff --git a/codex-rs/core/src/openai_model_info.rs b/codex-rs/core/src/openai_model_info.rs index a072d409c6..66f3c626ea 100644 --- a/codex-rs/core/src/openai_model_info.rs +++ b/codex-rs/core/src/openai_model_info.rs @@ -15,7 +15,8 @@ pub(crate) struct ModelInfo { } pub(crate) fn get_model_info(model_family: &ModelFamily) -> Option { - match model_family.slug.as_str() { + let slug = model_family.slug.as_str(); + match slug { // OSS models have a 128k shared token pool. // Arbitrarily splitting it: 3/4 input context, 1/4 output. // https://openai.com/index/gpt-oss-model-card/ @@ -82,6 +83,11 @@ pub(crate) fn get_model_info(model_family: &ModelFamily) -> Option { max_output_tokens: 100_000, }), + _ if slug.starts_with("codex-") => Some(ModelInfo { + context_window: 200_000, + max_output_tokens: 100_000, + }), + _ => None, } } diff --git a/codex-rs/core/src/parse_command.rs b/codex-rs/core/src/parse_command.rs index 01dc6e3227..6436ce4039 100644 --- a/codex-rs/core/src/parse_command.rs +++ b/codex-rs/core/src/parse_command.rs @@ -3,38 +3,47 @@ use crate::bash::try_parse_word_only_commands_sequence; use serde::Deserialize; use serde::Serialize; use shlex::split as shlex_split; +use shlex::try_join as shlex_try_join; #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub enum ParsedCommand { Read { - cmd: Vec, + cmd: String, name: String, }, ListFiles { - cmd: Vec, + cmd: String, path: Option, }, Search { - cmd: Vec, + cmd: String, query: Option, path: Option, }, Format { - cmd: Vec, + cmd: String, tool: Option, targets: Option>, }, Test { - cmd: Vec, + cmd: String, }, Lint { - cmd: Vec, + cmd: String, tool: Option, targets: Option>, }, - Unknown { - cmd: Vec, + Noop { + cmd: String, }, + Unknown { + cmd: String, + }, +} + +fn shlex_join(tokens: &[String]) -> String { + shlex_try_join(tokens.iter().map(|s| s.as_str())) + .unwrap_or_else(|_| "".to_string()) } /// DO NOT REVIEW THIS CODE BY HAND @@ -84,7 +93,29 @@ mod tests { assert_parsed( &vec_str(&["git", "status"]), vec![ParsedCommand::Unknown { - cmd: vec_str(&["git", "status"]), + cmd: "git status".to_string(), + }], + ); + } + + #[test] + fn handles_git_pipe_wc() { + let inner = "git status | wc -l"; + assert_parsed( + &vec_str(&["bash", "-lc", inner]), + vec![ParsedCommand::Unknown { + cmd: "git status | wc -l".to_string(), + }], + ); + } + + #[test] + fn bash_lc_redirect_not_quoted() { + let inner = "echo foo > bar"; + assert_parsed( + &vec_str(&["bash", "-lc", inner]), + vec![ParsedCommand::Unknown { + cmd: "echo foo > bar".to_string(), }], ); } @@ -98,23 +129,23 @@ mod tests { vec![ // Expect commands in left-to-right execution order ParsedCommand::Search { - cmd: vec_str(&["rg", "--version"]), + cmd: "rg --version".to_string(), query: None, path: None, }, ParsedCommand::Unknown { - cmd: vec_str(&["node", "-v"]), + cmd: "node -v".to_string(), }, ParsedCommand::Unknown { - cmd: vec_str(&["pnpm", "-v"]), + cmd: "pnpm -v".to_string(), }, ParsedCommand::Search { - cmd: vec_str(&["rg", "--files"]), + cmd: "rg --files".to_string(), query: None, path: None, }, ParsedCommand::Unknown { - cmd: vec_str(&["head", "-n", "40"]), + cmd: "head -n 40".to_string(), }, ], ); @@ -126,7 +157,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Search { - cmd: shlex_split_safe(inner), + cmd: "rg -n navigate-to-route -S".to_string(), query: Some("navigate-to-route".to_string()), path: None, }], @@ -141,12 +172,12 @@ mod tests { &vec_str(&["bash", "-lc", inner]), vec![ ParsedCommand::Search { - cmd: vec_str(&["rg", "-n", "BUG|FIXME|TODO|XXX|HACK", "-S"]), + cmd: "rg -n 'BUG|FIXME|TODO|XXX|HACK' -S".to_string(), query: Some("BUG|FIXME|TODO|XXX|HACK".to_string()), path: None, }, ParsedCommand::Unknown { - cmd: vec_str(&["head", "-n", "200"]), + cmd: "head -n 200".to_string(), }, ], ); @@ -158,7 +189,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Search { - cmd: vec_str(&["rg", "--files", "webview/src"]), + cmd: "rg --files webview/src".to_string(), query: None, path: Some("webview".to_string()), }], @@ -172,12 +203,12 @@ mod tests { &vec_str(&["bash", "-lc", inner]), vec![ ParsedCommand::Search { - cmd: vec_str(&["rg", "--files"]), + cmd: "rg --files".to_string(), query: None, path: None, }, ParsedCommand::Unknown { - cmd: vec_str(&["head", "-n", "50"]), + cmd: "head -n 50".to_string(), }, ], ); @@ -189,7 +220,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "README.md".to_string(), }], ); @@ -201,7 +232,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::ListFiles { - cmd: vec_str(&["ls", "-la"]), + cmd: "ls -la".to_string(), path: None, }], ); @@ -213,7 +244,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "Cargo.toml".to_string(), }], ); @@ -225,7 +256,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "Cargo.toml".to_string(), }], ); @@ -237,7 +268,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "README.md".to_string(), }], ); @@ -250,7 +281,7 @@ mod tests { assert_eq!( out, vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "README.md".to_string(), }] ); @@ -261,7 +292,7 @@ mod tests { assert_parsed( &vec_str(&["npm", "run", "build"]), vec![ParsedCommand::Unknown { - cmd: vec_str(&["npm", "run", "build"]), + cmd: "npm run build".to_string(), }], ); } @@ -280,16 +311,7 @@ mod tests { "json", ]), vec![ParsedCommand::Lint { - cmd: vec_str(&[ - "npm", - "run", - "lint", - "--", - "--max-warnings", - "0", - "--format", - "json", - ]), + cmd: "npm run lint -- --max-warnings 0 --format json".to_string(), tool: Some("npm-script:lint".to_string()), targets: None, }], @@ -301,7 +323,7 @@ mod tests { assert_parsed( &vec_str(&["grep", "-R", "CODEX_SANDBOX_ENV_VAR", "-n", "."]), vec![ParsedCommand::Search { - cmd: vec_str(&["grep", "-R", "CODEX_SANDBOX_ENV_VAR", "-n", "."]), + cmd: "grep -R CODEX_SANDBOX_ENV_VAR -n .".to_string(), query: Some("CODEX_SANDBOX_ENV_VAR".to_string()), path: Some(".".to_string()), }], @@ -319,13 +341,7 @@ mod tests { "core/src/spawn.rs", ]), vec![ParsedCommand::Search { - cmd: vec_str(&[ - "grep", - "-R", - "CODEX_SANDBOX_ENV_VAR", - "-n", - "core/src/spawn.rs", - ]), + cmd: "grep -R CODEX_SANDBOX_ENV_VAR -n core/src/spawn.rs".to_string(), query: Some("CODEX_SANDBOX_ENV_VAR".to_string()), path: Some("spawn.rs".to_string()), }], @@ -339,7 +355,7 @@ mod tests { assert_parsed( &shlex_split_safe("grep -R src/main.rs -n ."), vec![ParsedCommand::Search { - cmd: vec_str(&["grep", "-R", "src/main.rs", "-n", "."]), + cmd: "grep -R src/main.rs -n .".to_string(), query: Some("src/main.rs".to_string()), path: Some(".".to_string()), }], @@ -351,7 +367,7 @@ mod tests { assert_parsed( &shlex_split_safe("grep -R COD`EX_SANDBOX -n"), vec![ParsedCommand::Search { - cmd: vec_str(&["grep", "-R", "COD`EX_SANDBOX", "-n"]), + cmd: "grep -R 'COD`EX_SANDBOX' -n".to_string(), query: Some("COD`EX_SANDBOX".to_string()), path: None, }], @@ -364,10 +380,10 @@ mod tests { &shlex_split_safe("cd codex-rs && rg --files"), vec![ ParsedCommand::Unknown { - cmd: vec_str(&["cd", "codex-rs"]), + cmd: "cd codex-rs".to_string(), }, ParsedCommand::Search { - cmd: vec_str(&["rg", "--files"]), + cmd: "rg --files".to_string(), query: None, path: None, }, @@ -380,7 +396,7 @@ mod tests { assert_parsed( &shlex_split_safe("echo Running tests... && cargo test --all-features --quiet"), vec![ParsedCommand::Test { - cmd: vec_str(&["cargo", "test", "--all-features", "--quiet"]), + cmd: "cargo test --all-features --quiet".to_string(), }], ); } @@ -393,12 +409,12 @@ mod tests { ), vec![ ParsedCommand::Format { - cmd: shlex_split_safe("cargo fmt -- --config imports_granularity=Item"), + cmd: "cargo fmt -- --config 'imports_granularity=Item'".to_string(), tool: Some("cargo fmt".to_string()), targets: None, }, ParsedCommand::Test { - cmd: vec_str(&["cargo", "test", "-p", "core", "--all-features"]), + cmd: "cargo test -p core --all-features".to_string(), }, ], ); @@ -409,7 +425,7 @@ mod tests { assert_parsed( &shlex_split_safe("rustfmt src/main.rs"), vec![ParsedCommand::Format { - cmd: vec_str(&["rustfmt", "src/main.rs"]), + cmd: "rustfmt src/main.rs".to_string(), tool: Some("rustfmt".to_string()), targets: Some(vec!["src/main.rs".to_string()]), }], @@ -418,16 +434,7 @@ mod tests { assert_parsed( &shlex_split_safe("cargo clippy -p core --all-features -- -D warnings"), vec![ParsedCommand::Lint { - cmd: vec_str(&[ - "cargo", - "clippy", - "-p", - "core", - "--all-features", - "--", - "-D", - "warnings", - ]), + cmd: "cargo clippy -p core --all-features -- -D warnings".to_string(), tool: Some("cargo clippy".to_string()), targets: None, }], @@ -441,19 +448,15 @@ mod tests { "pytest -k 'Login and not slow' tests/test_login.py::TestLogin::test_ok", ), vec![ParsedCommand::Test { - cmd: vec_str(&[ - "pytest", - "-k", - "Login and not slow", - "tests/test_login.py::TestLogin::test_ok", - ]), + cmd: "pytest -k 'Login and not slow' tests/test_login.py::TestLogin::test_ok" + .to_string(), }], ); assert_parsed( &shlex_split_safe("go fmt ./..."), vec![ParsedCommand::Format { - cmd: vec_str(&["go", "fmt", "./..."]), + cmd: "go fmt ./...".to_string(), tool: Some("go fmt".to_string()), targets: Some(vec!["./...".to_string()]), }], @@ -462,14 +465,14 @@ mod tests { assert_parsed( &shlex_split_safe("go test ./pkg -run TestThing"), vec![ParsedCommand::Test { - cmd: vec_str(&["go", "test", "./pkg", "-run", "TestThing"]), + cmd: "go test ./pkg -run TestThing".to_string(), }], ); assert_parsed( &shlex_split_safe("eslint . --max-warnings 0"), vec![ParsedCommand::Lint { - cmd: vec_str(&["eslint", ".", "--max-warnings", "0"]), + cmd: "eslint . --max-warnings 0".to_string(), tool: Some("eslint".to_string()), targets: Some(vec![".".to_string()]), }], @@ -478,7 +481,7 @@ mod tests { assert_parsed( &shlex_split_safe("prettier -w ."), vec![ParsedCommand::Format { - cmd: vec_str(&["prettier", "-w", "."]), + cmd: "prettier -w .".to_string(), tool: Some("prettier".to_string()), targets: Some(vec![".".to_string()]), }], @@ -490,14 +493,14 @@ mod tests { assert_parsed( &shlex_split_safe("jest -t 'should work' src/foo.test.ts"), vec![ParsedCommand::Test { - cmd: vec_str(&["jest", "-t", "should work", "src/foo.test.ts"]), + cmd: "jest -t 'should work' src/foo.test.ts".to_string(), }], ); assert_parsed( &shlex_split_safe("vitest -t 'runs' src/foo.test.tsx"), vec![ParsedCommand::Test { - cmd: vec_str(&["vitest", "-t", "runs", "src/foo.test.tsx"]), + cmd: "vitest -t runs src/foo.test.tsx".to_string(), }], ); } @@ -507,7 +510,7 @@ mod tests { assert_parsed( &shlex_split_safe("npx eslint src"), vec![ParsedCommand::Lint { - cmd: vec_str(&["npx", "eslint", "src"]), + cmd: "npx eslint src".to_string(), tool: Some("eslint".to_string()), targets: Some(vec!["src".to_string()]), }], @@ -516,7 +519,7 @@ mod tests { assert_parsed( &shlex_split_safe("npx prettier -c ."), vec![ParsedCommand::Format { - cmd: vec_str(&["npx", "prettier", "-c", "."]), + cmd: "npx prettier -c .".to_string(), tool: Some("prettier".to_string()), targets: Some(vec![".".to_string()]), }], @@ -525,7 +528,7 @@ mod tests { assert_parsed( &shlex_split_safe("pnpm run lint -- --max-warnings 0"), vec![ParsedCommand::Lint { - cmd: vec_str(&["pnpm", "run", "lint", "--", "--max-warnings", "0"]), + cmd: "pnpm run lint -- --max-warnings 0".to_string(), tool: Some("pnpm-script:lint".to_string()), targets: None, }], @@ -534,14 +537,14 @@ mod tests { assert_parsed( &shlex_split_safe("npm test"), vec![ParsedCommand::Test { - cmd: vec_str(&["npm", "test"]), + cmd: "npm test".to_string(), }], ); assert_parsed( &shlex_split_safe("yarn test"), vec![ParsedCommand::Test { - cmd: vec_str(&["yarn", "test"]), + cmd: "yarn test".to_string(), }], ); } @@ -631,7 +634,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "parse_command.rs".to_string(), }], ); @@ -643,7 +646,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe(inner), + cmd: inner.to_string(), name: "history_cell.rs".to_string(), }], ); @@ -656,7 +659,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Read { - cmd: shlex_split_safe("cat -- ansi-escape/Cargo.toml"), + cmd: "cat -- ansi-escape/Cargo.toml".to_string(), name: "Cargo.toml".to_string(), }], ); @@ -669,7 +672,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Search { - cmd: vec_str(&["rg", "--files"]), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -685,9 +688,7 @@ mod tests { assert_parsed( &args, vec![ParsedCommand::Read { - cmd: shlex_split_safe( - "sed -n '260,640p' exec/src/event_processor_with_human_output.rs", - ), + cmd: "sed -n '260,640p' exec/src/event_processor_with_human_output.rs".to_string(), name: "event_processor_with_human_output.rs".to_string(), }], ); @@ -698,7 +699,7 @@ mod tests { assert_parsed( &shlex_split_safe("yes | rg -n 'foo bar' -S"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg -n 'foo bar' -S"), + cmd: "rg -n 'foo bar' -S".to_string(), query: Some("foo bar".to_string()), path: None, }], @@ -710,7 +711,7 @@ mod tests { assert_parsed( &shlex_split_safe("ls -I '*.test.js'"), vec![ParsedCommand::ListFiles { - cmd: shlex_split_safe("ls -I '*.test.js'"), + cmd: "ls -I '*.test.js'".to_string(), path: None, }], ); @@ -722,12 +723,12 @@ mod tests { &shlex_split_safe("rg foo ; echo done"), vec![ ParsedCommand::Search { - cmd: shlex_split_safe("rg foo"), + cmd: "rg foo".to_string(), query: Some("foo".to_string()), path: None, }, ParsedCommand::Unknown { - cmd: shlex_split_safe("echo done"), + cmd: "echo done".to_string(), }, ], ); @@ -740,12 +741,12 @@ mod tests { &shlex_split_safe("rg foo || echo done"), vec![ ParsedCommand::Search { - cmd: shlex_split_safe("rg foo"), + cmd: "rg foo".to_string(), query: Some("foo".to_string()), path: None, }, ParsedCommand::Unknown { - cmd: shlex_split_safe("echo done"), + cmd: "echo done".to_string(), }, ], ); @@ -757,7 +758,7 @@ mod tests { assert_parsed( &shlex_split_safe("true && rg --files"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -766,7 +767,7 @@ mod tests { assert_parsed( &shlex_split_safe("rg --files && true"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -779,7 +780,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner]), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -789,7 +790,7 @@ mod tests { assert_parsed( &vec_str(&["bash", "-lc", inner2]), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -801,7 +802,7 @@ mod tests { assert_parsed( &shlex_split_safe(r#"cat "pkg\src\main.rs""#), vec![ParsedCommand::Read { - cmd: shlex_split_safe(r#"cat "pkg\src\main.rs""#), + cmd: r#"cat "pkg\\src\\main.rs""#.to_string(), name: "main.rs".to_string(), }], ); @@ -812,7 +813,7 @@ mod tests { assert_parsed( &shlex_split_safe("bash -lc 'head -n50 Cargo.toml'"), vec![ParsedCommand::Read { - cmd: shlex_split_safe("head -n50 Cargo.toml"), + cmd: "head -n50 Cargo.toml".to_string(), name: "Cargo.toml".to_string(), }], ); @@ -826,12 +827,12 @@ mod tests { &shlex_split_safe(inner), vec![ ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }, ParsedCommand::Unknown { - cmd: shlex_split_safe("head -n 1"), + cmd: "head -n 1".to_string(), }, ], ); @@ -842,7 +843,7 @@ mod tests { assert_parsed( &shlex_split_safe("bash -lc 'tail -n+10 README.md'"), vec![ParsedCommand::Read { - cmd: shlex_split_safe("tail -n+10 README.md"), + cmd: "tail -n+10 README.md".to_string(), name: "README.md".to_string(), }], ); @@ -853,7 +854,7 @@ mod tests { assert_parsed( &shlex_split_safe("pnpm test"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("pnpm test"), + cmd: "pnpm test".to_string(), }], ); } @@ -866,12 +867,10 @@ mod tests { &shlex_split_safe(inner), vec![ ParsedCommand::Unknown { - cmd: shlex_split_safe("cd codex-cli"), + cmd: "cd codex-cli".to_string(), }, ParsedCommand::Unknown { - cmd: shlex_split_safe( - "pnpm exec vitest run tests/file-tag-utils.test.ts --threads=false --passWithNoTests", - ), + cmd: "pnpm exec vitest run tests/file-tag-utils.test.ts '--threads=false' --passWithNoTests".to_string(), }, ], ); @@ -882,7 +881,7 @@ mod tests { assert_parsed( &shlex_split_safe("cargo test -p codex-core parse_command::"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("cargo test -p codex-core parse_command::"), + cmd: "cargo test -p codex-core parse_command::".to_string(), }], ); } @@ -894,9 +893,7 @@ mod tests { "cd core && cargo test -q parse_command::tests::bash_dash_c_pipeline_parsing parse_command::tests::fd_file_finder_variants", ), vec![ParsedCommand::Test { - cmd: shlex_split_safe( - "cargo test -q parse_command::tests::bash_dash_c_pipeline_parsing parse_command::tests::fd_file_finder_variants", - ), + cmd: "cargo test -q parse_command::tests::bash_dash_c_pipeline_parsing parse_command::tests::fd_file_finder_variants".to_string(), }], ); } @@ -906,7 +903,7 @@ mod tests { assert_parsed( &shlex_split_safe("cd core && cargo test -q parse_command::tests"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("cargo test -q parse_command::tests"), + cmd: "cargo test -q parse_command::tests".to_string(), }], ); } @@ -916,7 +913,7 @@ mod tests { assert_parsed( &shlex_split_safe("cd core && cargo test --all-features parse_command -- --nocapture"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("cargo test --all-features parse_command -- --nocapture"), + cmd: "cargo test --all-features parse_command -- --nocapture".to_string(), }], ); } @@ -928,7 +925,7 @@ mod tests { assert_parsed( &shlex_split_safe("black src"), vec![ParsedCommand::Format { - cmd: shlex_split_safe("black src"), + cmd: "black src".to_string(), tool: Some("black".to_string()), targets: Some(vec!["src".to_string()]), }], @@ -938,7 +935,7 @@ mod tests { assert_parsed( &shlex_split_safe("ruff check ."), vec![ParsedCommand::Lint { - cmd: shlex_split_safe("ruff check ."), + cmd: "ruff check .".to_string(), tool: Some("ruff".to_string()), targets: Some(vec![".".to_string()]), }], @@ -948,7 +945,7 @@ mod tests { assert_parsed( &shlex_split_safe("ruff format pkg/"), vec![ParsedCommand::Format { - cmd: shlex_split_safe("ruff format pkg/"), + cmd: "ruff format pkg/".to_string(), tool: Some("ruff".to_string()), targets: Some(vec!["pkg/".to_string()]), }], @@ -961,7 +958,7 @@ mod tests { assert_parsed( &shlex_split_safe("pnpm -r test"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("pnpm -r test"), + cmd: "pnpm -r test".to_string(), }], ); @@ -969,7 +966,7 @@ mod tests { assert_parsed( &shlex_split_safe("npm run format -- -w ."), vec![ParsedCommand::Format { - cmd: shlex_split_safe("npm run format -- -w ."), + cmd: "npm run format -- -w .".to_string(), tool: Some("npm-script:format".to_string()), targets: None, }], @@ -981,7 +978,7 @@ mod tests { assert_parsed( &shlex_split_safe("yarn test"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("yarn test"), + cmd: "yarn test".to_string(), }], ); } @@ -992,7 +989,7 @@ mod tests { assert_parsed( &shlex_split_safe("pytest tests/test_example.py"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("pytest tests/test_example.py"), + cmd: "pytest tests/test_example.py".to_string(), }], ); @@ -1000,7 +997,7 @@ mod tests { assert_parsed( &shlex_split_safe("go test ./... -run '^TestFoo$'"), vec![ParsedCommand::Test { - cmd: shlex_split_safe("go test ./... -run '^TestFoo$'"), + cmd: "go test ./... -run '^TestFoo$'".to_string(), }], ); } @@ -1010,7 +1007,7 @@ mod tests { assert_parsed( &shlex_split_safe("grep -R TODO src"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("grep -R TODO src"), + cmd: "grep -R TODO src".to_string(), query: Some("TODO".to_string()), path: Some("src".to_string()), }], @@ -1022,7 +1019,7 @@ mod tests { assert_parsed( &shlex_split_safe("rg --colors=never -n foo src"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --colors=never -n foo src"), + cmd: "rg '--colors=never' -n foo src".to_string(), query: Some("foo".to_string()), path: Some("src".to_string()), }], @@ -1035,7 +1032,7 @@ mod tests { assert_parsed( &shlex_split_safe("cat -- ./-strange-file-name"), vec![ParsedCommand::Read { - cmd: shlex_split_safe("cat -- ./-strange-file-name"), + cmd: "cat -- ./-strange-file-name".to_string(), name: "-strange-file-name".to_string(), }], ); @@ -1044,7 +1041,7 @@ mod tests { assert_parsed( &shlex_split_safe("sed -n '12,20p' Cargo.toml"), vec![ParsedCommand::Read { - cmd: shlex_split_safe("sed -n '12,20p' Cargo.toml"), + cmd: "sed -n '12,20p' Cargo.toml".to_string(), name: "Cargo.toml".to_string(), }], ); @@ -1056,7 +1053,7 @@ mod tests { assert_parsed( &shlex_split_safe("rg --files | nl -ba"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("rg --files"), + cmd: "rg --files".to_string(), query: None, path: None, }], @@ -1068,7 +1065,7 @@ mod tests { assert_parsed( &shlex_split_safe("ls --time-style=long-iso ./dist"), vec![ParsedCommand::ListFiles { - cmd: shlex_split_safe("ls --time-style=long-iso ./dist"), + cmd: "ls '--time-style=long-iso' ./dist".to_string(), // short_display_path drops "dist" and shows "." as the last useful segment path: Some(".".to_string()), }], @@ -1080,7 +1077,7 @@ mod tests { assert_parsed( &shlex_split_safe("eslint -c .eslintrc.json src"), vec![ParsedCommand::Lint { - cmd: shlex_split_safe("eslint -c .eslintrc.json src"), + cmd: "eslint -c .eslintrc.json src".to_string(), tool: Some("eslint".to_string()), targets: Some(vec!["src".to_string()]), }], @@ -1092,7 +1089,7 @@ mod tests { assert_parsed( &shlex_split_safe("npx eslint -c .eslintrc src"), vec![ParsedCommand::Lint { - cmd: shlex_split_safe("npx eslint -c .eslintrc src"), + cmd: "npx eslint -c .eslintrc src".to_string(), tool: Some("eslint".to_string()), targets: Some(vec!["src".to_string()]), }], @@ -1104,7 +1101,7 @@ mod tests { assert_parsed( &shlex_split_safe("fd -t f src/"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("fd -t f src/"), + cmd: "fd -t f src/".to_string(), query: None, path: Some("src".to_string()), }], @@ -1114,7 +1111,7 @@ mod tests { assert_parsed( &shlex_split_safe("fd main src"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("fd main src"), + cmd: "fd main src".to_string(), query: Some("main".to_string()), path: Some("src".to_string()), }], @@ -1126,7 +1123,7 @@ mod tests { assert_parsed( &shlex_split_safe("find . -name '*.rs'"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("find . -name '*.rs'"), + cmd: "find . -name '*.rs'".to_string(), query: Some("*.rs".to_string()), path: Some(".".to_string()), }], @@ -1138,7 +1135,7 @@ mod tests { assert_parsed( &shlex_split_safe("find src -type f"), vec![ParsedCommand::Search { - cmd: shlex_split_safe("find src -type f"), + cmd: "find src -type f".to_string(), query: None, path: Some("src".to_string()), }], @@ -1147,12 +1144,12 @@ mod tests { } pub fn parse_command_impl(command: &[String]) -> Vec { - let normalized = normalize_tokens(command); - - if let Some(commands) = parse_bash_lc_commands(command, &normalized) { + if let Some(commands) = parse_bash_lc_commands(command) { return commands; } + let normalized = normalize_tokens(command); + let parts = if contains_connectors(&normalized) { split_on_connectors(&normalized) } else { @@ -1163,55 +1160,79 @@ pub fn parse_command_impl(command: &[String]) -> Vec { // so summaries reflect the order they will run. // Map each pipeline segment to its parsed summary. - let mut parsed: Vec = parts + let mut commands: Vec = parts .iter() .map(|tokens| summarize_main_tokens(tokens)) .collect(); - // If a pipeline ends with `nl` using only flags (e.g., `| nl -ba`), drop it so the - // main action (e.g., a sed range over a file) is surfaced cleanly. - if parsed.len() >= 2 { - let has_and_and = normalized.iter().any(|t| t == "&&"); - let contains_test = parsed - .iter() - .any(|pc| matches!(pc, ParsedCommand::Test { .. })); - parsed.retain(|pc| match pc { - ParsedCommand::Unknown { cmd } => { - if let Some(first) = cmd.first() { - // Drop cosmetic echo segments in chained commands - if has_and_and && first == "echo" { - return false; - } - // In non-bash chained commands, ignore directory changes like `cd foo` - // when the sequence includes a recognized test command. Preserve `cd` - // for other sequences (e.g., followed by a search command). - if has_and_and && contains_test && first == "cd" { - return false; - } - // Drop no-op commands like `true` - if cmd.len() == 1 && first == "true" { - return false; - } - if first == "nl" { - // Treat `nl` without an explicit file operand as formatting-only. - return cmd.iter().skip(1).any(|a| !a.starts_with('-')); - } - } - true - } - _ => true, - }); + while let Some(next) = simplify_once(&commands) { + commands = next; } - // Also drop standalone `true` commands when not part of a chained `&&` context above - parsed.retain(|pc| match pc { - ParsedCommand::Unknown { cmd } => { - !(cmd.len() == 1 && cmd.first().is_some_and(|s| s == "true")) - } - _ => true, - }); + commands +} - parsed +fn simplify_once(commands: &[ParsedCommand]) -> Option> { + if commands.len() <= 1 { + return None; + } + + // echo ... && ...rest => ...rest + if let ParsedCommand::Unknown { cmd } = &commands[0] { + if shlex_split(cmd).is_some_and(|t| t.first().map(|s| s.as_str()) == Some("echo")) { + return Some(commands[1..].to_vec()); + } + } + + // cd foo && [any Test command] => [any Test command] + if let Some(idx) = commands.iter().position(|pc| match pc { + ParsedCommand::Unknown { cmd } => { + shlex_split(cmd).is_some_and(|t| t.first().map(|s| s.as_str()) == Some("cd")) + } + _ => false, + }) { + if commands + .iter() + .skip(idx + 1) + .any(|pc| matches!(pc, ParsedCommand::Test { .. })) + { + let mut out = Vec::with_capacity(commands.len() - 1); + out.extend_from_slice(&commands[..idx]); + out.extend_from_slice(&commands[idx + 1..]); + return Some(out); + } + } + + // cmd || true => cmd + if let Some(idx) = commands.iter().position(|pc| match pc { + ParsedCommand::Noop { cmd } => cmd == "true", + _ => false, + }) { + let mut out = Vec::with_capacity(commands.len() - 1); + out.extend_from_slice(&commands[..idx]); + out.extend_from_slice(&commands[idx + 1..]); + return Some(out); + } + + // nl -[any_flags] && ...rest => ...rest + if let Some(idx) = commands.iter().position(|pc| match pc { + ParsedCommand::Unknown { cmd } => { + if let Some(tokens) = shlex_split(cmd) { + tokens.first().is_some_and(|s| s.as_str() == "nl") + && tokens.iter().skip(1).all(|t| t.starts_with('-')) + } else { + false + } + } + _ => false, + }) { + let mut out = Vec::with_capacity(commands.len() - 1); + out.extend_from_slice(&commands[..idx]); + out.extend_from_slice(&commands[idx + 1..]); + return Some(out); + } + + None } /// Validates that this is a `sed -n 123,123p` command. @@ -1497,19 +1518,19 @@ fn classify_npm_like(tool: &str, tail: &[String], full_cmd: &[String]) -> Option let lname = name.to_lowercase(); if lname == "test" || lname == "unit" || lname == "jest" || lname == "vitest" { return Some(ParsedCommand::Test { - cmd: full_cmd.to_vec(), + cmd: shlex_join(full_cmd), }); } if lname == "lint" || lname == "eslint" { return Some(ParsedCommand::Lint { - cmd: full_cmd.to_vec(), + cmd: shlex_join(full_cmd), tool: Some(format!("{tool}-script:{name}")), targets: None, }); } if lname == "format" || lname == "fmt" || lname == "prettier" { return Some(ParsedCommand::Format { - cmd: full_cmd.to_vec(), + cmd: shlex_join(full_cmd), tool: Some(format!("{tool}-script:{name}")), targets: None, }); @@ -1518,10 +1539,7 @@ fn classify_npm_like(tool: &str, tail: &[String], full_cmd: &[String]) -> Option None } -fn parse_bash_lc_commands( - original: &[String], - normalized: &[String], -) -> Option> { +fn parse_bash_lc_commands(original: &[String]) -> Option> { let [bash, flag, script] = original else { return None; }; @@ -1543,21 +1561,16 @@ fn parse_bash_lc_commands( filtered_commands.reverse(); if filtered_commands.is_empty() { return Some(vec![ParsedCommand::Unknown { - cmd: normalized.to_vec(), + cmd: script.clone(), }]); } let mut commands: Vec = filtered_commands .into_iter() .map(|tokens| summarize_main_tokens(&tokens)) .collect(); - // Drop no-op `true` commands - commands.retain(|pc| match pc { - ParsedCommand::Unknown { cmd } => { - !(cmd.len() == 1 && cmd.first().is_some_and(|s| s == "true")) - } - _ => true, - }); - commands = maybe_collapse_cat_sed(commands, &script_tokens); + if commands.len() > 1 { + commands.retain(|pc| !matches!(pc, ParsedCommand::Noop { .. })); + } if commands.len() == 1 { // If we reduced to a single command, attribute the full original script // for clearer UX in file-reading and listing scenarios, or when there were @@ -1570,7 +1583,7 @@ fn parse_bash_lc_commands( commands = commands .into_iter() .map(|pc| match pc { - ParsedCommand::Read { name, cmd } => { + ParsedCommand::Read { name, cmd, .. } => { if had_connectors { let has_pipe = script_tokens.iter().any(|t| t == "|"); let has_sed_n = script_tokens.windows(2).any(|w| { @@ -1579,55 +1592,74 @@ fn parse_bash_lc_commands( }); if has_pipe && has_sed_n { ParsedCommand::Read { - cmd: script_tokens.clone(), + cmd: script.clone(), name, } } else { - ParsedCommand::Read { cmd, name } + ParsedCommand::Read { + cmd: cmd.clone(), + name, + } } } else { ParsedCommand::Read { - cmd: script_tokens.clone(), + cmd: shlex_join(&script_tokens), name, } } } - ParsedCommand::ListFiles { path, cmd } => { + ParsedCommand::ListFiles { path, cmd, .. } => { if had_connectors { - ParsedCommand::ListFiles { cmd, path } + ParsedCommand::ListFiles { + cmd: cmd.clone(), + path, + } } else { ParsedCommand::ListFiles { - cmd: script_tokens.clone(), + cmd: shlex_join(&script_tokens), path, } } } - ParsedCommand::Search { cmd, query, path } => { + ParsedCommand::Search { + query, path, cmd, .. + } => { if had_connectors { - ParsedCommand::Search { cmd, query, path } + ParsedCommand::Search { + cmd: cmd.clone(), + query, + path, + } } else { ParsedCommand::Search { - cmd: script_tokens.clone(), + cmd: shlex_join(&script_tokens), query, path, } } } - ParsedCommand::Format { tool, targets, .. } => ParsedCommand::Format { - cmd: script_tokens.clone(), + ParsedCommand::Format { + tool, targets, cmd, .. + } => ParsedCommand::Format { + cmd: cmd.clone(), tool, targets, }, - ParsedCommand::Test { .. } => ParsedCommand::Test { - cmd: script_tokens.clone(), - }, - ParsedCommand::Lint { tool, targets, .. } => ParsedCommand::Lint { - cmd: script_tokens.clone(), + ParsedCommand::Test { cmd, .. } => { + ParsedCommand::Test { cmd: cmd.clone() } + } + ParsedCommand::Lint { + tool, targets, cmd, .. + } => ParsedCommand::Lint { + cmd: cmd.clone(), tool, targets, }, ParsedCommand::Unknown { .. } => ParsedCommand::Unknown { - cmd: script_tokens.clone(), + cmd: script.clone(), + }, + ParsedCommand::Noop { .. } => ParsedCommand::Noop { + cmd: script.clone(), }, }) .collect(); @@ -1637,7 +1669,7 @@ fn parse_bash_lc_commands( } } Some(vec![ParsedCommand::Unknown { - cmd: normalized.to_vec(), + cmd: script.clone(), }]) } @@ -1681,44 +1713,17 @@ fn drop_small_formatting_commands(mut commands: Vec>) -> Vec, - script_tokens: &[String], -) -> Vec { - if commands.len() < 2 { - return commands; - } - let drop_leading_sed = match (&commands[0], &commands[1]) { - (ParsedCommand::Unknown { cmd: sed_cmd }, ParsedCommand::Read { cmd: cat_cmd, .. }) => { - let is_sed_n = sed_cmd.first().map(|s| s.as_str()) == Some("sed") - && sed_cmd.get(1).map(|s| s.as_str()) == Some("-n") - && is_valid_sed_n_arg(sed_cmd.get(2).map(|s| s.as_str())) - && sed_cmd.len() == 3; - let is_cat_file = - cat_cmd.first().map(|s| s.as_str()) == Some("cat") && cat_cmd.len() == 2; - is_sed_n && is_cat_file - } - _ => false, - }; - if drop_leading_sed { - if let ParsedCommand::Read { name, .. } = &commands[1] { - return vec![ParsedCommand::Read { - cmd: script_tokens.to_vec(), - name: name.clone(), - }]; - } - } - commands -} - fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { match main_cmd.split_first() { + Some((head, tail)) if head == "true" && tail.is_empty() => ParsedCommand::Noop { + cmd: shlex_join(main_cmd), + }, // (sed-specific logic handled below in dedicated arm returning Read) Some((head, tail)) if head == "cargo" && tail.first().map(|s| s.as_str()) == Some("fmt") => { ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("cargo fmt".to_string()), targets: collect_non_flag_targets(&tail[1..]), } @@ -1727,7 +1732,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if head == "cargo" && tail.first().map(|s| s.as_str()) == Some("clippy") => { ParsedCommand::Lint { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("cargo clippy".to_string()), targets: collect_non_flag_targets(&tail[1..]), } @@ -1736,45 +1741,45 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if head == "cargo" && tail.first().map(|s| s.as_str()) == Some("test") => { ParsedCommand::Test { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } Some((head, tail)) if head == "rustfmt" => ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("rustfmt".to_string()), targets: collect_non_flag_targets(tail), }, Some((head, tail)) if head == "go" && tail.first().map(|s| s.as_str()) == Some("fmt") => { ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("go fmt".to_string()), targets: collect_non_flag_targets(&tail[1..]), } } Some((head, tail)) if head == "go" && tail.first().map(|s| s.as_str()) == Some("test") => { ParsedCommand::Test { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } Some((head, _)) if head == "pytest" => ParsedCommand::Test { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), }, Some((head, tail)) if head == "eslint" => { // Treat configuration flags with values (e.g. `-c .eslintrc`) as non-targets. let targets = collect_non_flag_targets_with_flags(tail, ESLINT_FLAGS_WITH_VALUES); ParsedCommand::Lint { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("eslint".to_string()), targets, } } Some((head, tail)) if head == "prettier" => ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("prettier".to_string()), targets: collect_non_flag_targets(tail), }, Some((head, tail)) if head == "black" => ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("black".to_string()), targets: collect_non_flag_targets(tail), }, @@ -1782,7 +1787,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if head == "ruff" && tail.first().map(|s| s.as_str()) == Some("check") => { ParsedCommand::Lint { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("ruff".to_string()), targets: collect_non_flag_targets(&tail[1..]), } @@ -1791,20 +1796,20 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if head == "ruff" && tail.first().map(|s| s.as_str()) == Some("format") => { ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("ruff".to_string()), targets: collect_non_flag_targets(&tail[1..]), } } Some((head, _)) if (head == "jest" || head == "vitest") => ParsedCommand::Test { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), }, Some((head, tail)) if head == "npx" && tail.first().map(|s| s.as_str()) == Some("eslint") => { let targets = collect_non_flag_targets_with_flags(&tail[1..], ESLINT_FLAGS_WITH_VALUES); ParsedCommand::Lint { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("eslint".to_string()), targets, } @@ -1813,7 +1818,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if head == "npx" && tail.first().map(|s| s.as_str()) == Some("prettier") => { ParsedCommand::Format { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), tool: Some("prettier".to_string()), targets: collect_non_flag_targets(&tail[1..]), } @@ -1824,7 +1829,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { cmd } else { ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } } @@ -1847,7 +1852,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { .find(|p| !p.starts_with('-')) .map(|p| short_display_path(p)); ParsedCommand::ListFiles { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), path, } } @@ -1867,7 +1872,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { ) }; ParsedCommand::Search { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), query, path, } @@ -1875,7 +1880,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { Some((head, tail)) if head == "fd" => { let (query, path) = parse_fd_query_and_path(tail); ParsedCommand::Search { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), query, path, } @@ -1884,7 +1889,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { // Basic find support: capture path and common name filter let (query, path) = parse_find_query_and_path(tail); ParsedCommand::Search { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), query, path, } @@ -1900,7 +1905,7 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { let query = non_flags.first().cloned().map(|s| s.to_string()); let path = non_flags.get(1).map(|s| short_display_path(s)); ParsedCommand::Search { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), query, path, } @@ -1915,12 +1920,12 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if effective_tail.len() == 1 { let name = short_display_path(&effective_tail[0]); ParsedCommand::Read { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), name, } } else { ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } } @@ -1953,13 +1958,13 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if let Some(p) = candidates.into_iter().find(|p| !p.starts_with('-')) { let name = short_display_path(p); return ParsedCommand::Read { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), name, }; } } ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } Some((head, tail)) if head == "tail" => { @@ -1995,13 +2000,13 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if let Some(p) = candidates.into_iter().find(|p| !p.starts_with('-')) { let name = short_display_path(p); return ParsedCommand::Read { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), name, }; } } ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } Some((head, tail)) if head == "nl" => { @@ -2010,12 +2015,12 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if let Some(p) = candidates.into_iter().find(|p| !p.starts_with('-')) { let name = short_display_path(p); ParsedCommand::Read { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), name, } } else { ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } } @@ -2028,18 +2033,18 @@ fn summarize_main_tokens(main_cmd: &[String]) -> ParsedCommand { if let Some(path) = tail.get(2) { let name = short_display_path(path); ParsedCommand::Read { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), name, } } else { ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), } } } // Other commands _ => ParsedCommand::Unknown { - cmd: main_cmd.to_vec(), + cmd: shlex_join(main_cmd), }, } } diff --git a/codex-rs/core/src/protocol.rs b/codex-rs/core/src/protocol.rs index e984b95f98..f32d9ccf53 100644 --- a/codex-rs/core/src/protocol.rs +++ b/codex-rs/core/src/protocol.rs @@ -17,10 +17,7 @@ use serde_bytes::ByteBuf; use strum_macros::Display; use uuid::Uuid; -use crate::config_types::ReasoningEffort as ReasoningEffortConfig; -use crate::config_types::ReasoningSummary as ReasoningSummaryConfig; use crate::message_history::HistoryEntry; -use crate::model_provider_info::ModelProviderInfo; use crate::parse_command::ParsedCommand; use crate::plan_tool::UpdatePlanArgs; @@ -39,52 +36,6 @@ pub struct Submission { #[allow(clippy::large_enum_variant)] #[non_exhaustive] pub enum Op { - /// Configure the model session. - ConfigureSession { - /// Provider identifier ("openai", "openrouter", ...). - provider: ModelProviderInfo, - - /// If not specified, server will use its default model. - model: String, - - model_reasoning_effort: ReasoningEffortConfig, - model_reasoning_summary: ReasoningSummaryConfig, - - /// Model instructions that are appended to the base instructions. - user_instructions: Option, - - /// Base instructions override. - base_instructions: Option, - - /// When to escalate for approval for execution - approval_policy: AskForApproval, - /// How to sandbox commands executed in the system - sandbox_policy: SandboxPolicy, - /// Disable server-side response storage (send full context each request) - #[serde(default)] - disable_response_storage: bool, - - /// Optional external notifier command tokens. Present only when the - /// client wants the agent to spawn a program after each completed - /// turn. - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(default)] - notify: Option>, - - /// Working directory that should be treated as the *root* of the - /// session. All relative paths supplied by the model as well as the - /// execution sandbox are resolved against this directory **instead** - /// of the process-wide current working directory. CLI front-ends are - /// expected to expand this to an absolute path before sending the - /// `ConfigureSession` operation so that the business-logic layer can - /// operate deterministically. - cwd: std::path::PathBuf, - - /// Path to a rollout file to resume from. - #[serde(skip_serializing_if = "Option::is_none")] - resume_path: Option, - }, - /// Abort current task. /// This server sends no corresponding Event Interrupt, @@ -723,7 +674,7 @@ pub enum ReviewDecision { Abort, } -#[derive(Debug, Clone, Deserialize, Serialize)] +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum FileChange { Add { diff --git a/codex-rs/core/tests/client.rs b/codex-rs/core/tests/client.rs index 1bcddf0796..10c6c66fb5 100644 --- a/codex-rs/core/tests/client.rs +++ b/codex-rs/core/tests/client.rs @@ -373,11 +373,11 @@ async fn includes_user_instructions_message_in_request() { .contains("be nice") ); assert_message_role(&request_body["input"][0], "user"); - assert_message_starts_with(&request_body["input"][0], "\n\n"); - assert_message_ends_with(&request_body["input"][0], ""); + assert_message_starts_with(&request_body["input"][0], ""); + assert_message_ends_with(&request_body["input"][0], ""); assert_message_role(&request_body["input"][1], "user"); - assert_message_starts_with(&request_body["input"][1], "\n\n"); - assert_message_ends_with(&request_body["input"][1], ""); + assert_message_starts_with(&request_body["input"][1], ""); + assert_message_ends_with(&request_body["input"][1], ""); } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] diff --git a/codex-rs/core/tests/prompt_caching.rs b/codex-rs/core/tests/prompt_caching.rs index 8df7ea353d..0c2552ee05 100644 --- a/codex-rs/core/tests/prompt_caching.rs +++ b/codex-rs/core/tests/prompt_caching.rs @@ -85,7 +85,7 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests assert_eq!(requests.len(), 2, "expected two POST requests"); let expected_env_text = format!( - "\n\nCurrent working directory: {}\nApproval policy: on-request\nSandbox policy: read-only\nNetwork access: restricted\n\n\n", + "\nCurrent working directory: {}\nApproval policy: on-request\nSandbox mode: read-only\nNetwork access: restricted\n", cwd.path().to_string_lossy() ); let expected_ui_text = @@ -113,7 +113,7 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests let body1 = requests[0].body_json::().unwrap(); assert_eq!( body1["input"], - serde_json::json!([expected_env_msg, expected_ui_msg, expected_user_message_1]) + serde_json::json!([expected_ui_msg, expected_env_msg, expected_user_message_1]) ); let expected_user_message_2 = serde_json::json!({ diff --git a/codex-rs/core/tests/sandbox.rs b/codex-rs/core/tests/seatbelt.rs similarity index 97% rename from codex-rs/core/tests/sandbox.rs rename to codex-rs/core/tests/seatbelt.rs index ae5bdc44a6..fb2e7452f1 100644 --- a/codex-rs/core/tests/sandbox.rs +++ b/codex-rs/core/tests/seatbelt.rs @@ -1,6 +1,9 @@ #![cfg(target_os = "macos")] #![expect(clippy::expect_used)] +//! Tests for the macOS sandboxing that are specific to Seatbelt. +//! Tests that apply to both Mac and Linux sandboxing should go in sandbox.rs. + use std::collections::HashMap; use std::path::Path; use std::path::PathBuf; diff --git a/codex-rs/exec/tests/sandbox.rs b/codex-rs/exec/tests/sandbox.rs new file mode 100644 index 0000000000..8cc31bba58 --- /dev/null +++ b/codex-rs/exec/tests/sandbox.rs @@ -0,0 +1,92 @@ +#![cfg(unix)] +#![expect(clippy::expect_used)] + +use codex_core::protocol::SandboxPolicy; +use codex_core::spawn::StdioPolicy; +use std::collections::HashMap; +use std::path::PathBuf; +use tokio::process::Child; + +#[cfg(target_os = "macos")] +async fn spawn_command_under_sandbox( + command: Vec, + sandbox_policy: &SandboxPolicy, + cwd: PathBuf, + stdio_policy: StdioPolicy, + env: HashMap, +) -> std::io::Result { + use codex_core::seatbelt::spawn_command_under_seatbelt; + spawn_command_under_seatbelt(command, sandbox_policy, cwd, stdio_policy, env).await +} + +#[cfg(target_os = "linux")] +async fn spawn_command_under_sandbox( + command: Vec, + sandbox_policy: &SandboxPolicy, + cwd: PathBuf, + stdio_policy: StdioPolicy, + env: HashMap, +) -> std::io::Result { + use codex_core::landlock::spawn_command_under_linux_sandbox; + let codex_linux_sandbox_exe = assert_cmd::cargo::cargo_bin("codex-exec"); + spawn_command_under_linux_sandbox( + codex_linux_sandbox_exe, + command, + sandbox_policy, + cwd, + stdio_policy, + env, + ) + .await +} + +#[tokio::test] +async fn python_multiprocessing_lock_works_under_sandbox() { + #[cfg(target_os = "macos")] + let writable_roots = Vec::::new(); + + // From https://man7.org/linux/man-pages/man7/sem_overview.7.html + // + // > On Linux, named semaphores are created in a virtual filesystem, + // > normally mounted under /dev/shm. + #[cfg(target_os = "linux")] + let writable_roots = vec![PathBuf::from("/dev/shm")]; + + let policy = SandboxPolicy::WorkspaceWrite { + writable_roots, + network_access: false, + exclude_tmpdir_env_var: false, + exclude_slash_tmp: false, + }; + + let python_code = r#"import multiprocessing +from multiprocessing import Lock, Process + +def f(lock): + with lock: + print("Lock acquired in child process") + +if __name__ == '__main__': + lock = Lock() + p = Process(target=f, args=(lock,)) + p.start() + p.join() +"#; + + let mut child = spawn_command_under_sandbox( + vec![ + "python3".to_string(), + "-c".to_string(), + python_code.to_string(), + ], + &policy, + std::env::current_dir().expect("should be able to get current dir"), + StdioPolicy::Inherit, + HashMap::new(), + ) + .await + .expect("should be able to spawn python under sandbox"); + + let status = child.wait().await.expect("should wait for child process"); + assert!(status.success(), "python exited with {status:?}"); +} diff --git a/codex-rs/mcp-server/src/codex_message_processor.rs b/codex-rs/mcp-server/src/codex_message_processor.rs new file mode 100644 index 0000000000..2495feb9e0 --- /dev/null +++ b/codex-rs/mcp-server/src/codex_message_processor.rs @@ -0,0 +1,470 @@ +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::Arc; + +use codex_core::CodexConversation; +use codex_core::ConversationManager; +use codex_core::NewConversation; +use codex_core::config::Config; +use codex_core::config::ConfigOverrides; +use codex_core::protocol::ApplyPatchApprovalRequestEvent; +use codex_core::protocol::Event; +use codex_core::protocol::EventMsg; +use codex_core::protocol::ExecApprovalRequestEvent; +use codex_core::protocol::ReviewDecision; +use mcp_types::JSONRPCErrorError; +use mcp_types::RequestId; +use tokio::sync::oneshot; +use tracing::error; +use uuid::Uuid; + +use crate::error_code::INTERNAL_ERROR_CODE; +use crate::error_code::INVALID_REQUEST_ERROR_CODE; +use crate::json_to_toml::json_to_toml; +use crate::outgoing_message::OutgoingMessageSender; +use crate::outgoing_message::OutgoingNotification; +use crate::wire_format::APPLY_PATCH_APPROVAL_METHOD; +use crate::wire_format::AddConversationListenerParams; +use crate::wire_format::AddConversationSubscriptionResponse; +use crate::wire_format::ApplyPatchApprovalParams; +use crate::wire_format::ApplyPatchApprovalResponse; +use crate::wire_format::ClientRequest; +use crate::wire_format::ConversationId; +use crate::wire_format::EXEC_COMMAND_APPROVAL_METHOD; +use crate::wire_format::ExecCommandApprovalParams; +use crate::wire_format::ExecCommandApprovalResponse; +use crate::wire_format::InputItem as WireInputItem; +use crate::wire_format::InterruptConversationParams; +use crate::wire_format::InterruptConversationResponse; +use crate::wire_format::NewConversationParams; +use crate::wire_format::NewConversationResponse; +use crate::wire_format::RemoveConversationListenerParams; +use crate::wire_format::RemoveConversationSubscriptionResponse; +use crate::wire_format::SendUserMessageParams; +use crate::wire_format::SendUserMessageResponse; +use codex_core::protocol::InputItem as CoreInputItem; +use codex_core::protocol::Op; + +/// Handles JSON-RPC messages for Codex conversations. +pub(crate) struct CodexMessageProcessor { + conversation_manager: Arc, + outgoing: Arc, + codex_linux_sandbox_exe: Option, + conversation_listeners: HashMap>, +} + +impl CodexMessageProcessor { + pub fn new( + conversation_manager: Arc, + outgoing: Arc, + codex_linux_sandbox_exe: Option, + ) -> Self { + Self { + conversation_manager, + outgoing, + codex_linux_sandbox_exe, + conversation_listeners: HashMap::new(), + } + } + + pub async fn process_request(&mut self, request: ClientRequest) { + match request { + ClientRequest::NewConversation { request_id, params } => { + // Do not tokio::spawn() to process new_conversation() + // asynchronously because we need to ensure the conversation is + // created before processing any subsequent messages. + self.process_new_conversation(request_id, params).await; + } + ClientRequest::SendUserMessage { request_id, params } => { + self.send_user_message(request_id, params).await; + } + ClientRequest::InterruptConversation { request_id, params } => { + self.interrupt_conversation(request_id, params).await; + } + ClientRequest::AddConversationListener { request_id, params } => { + self.add_conversation_listener(request_id, params).await; + } + ClientRequest::RemoveConversationListener { request_id, params } => { + self.remove_conversation_listener(request_id, params).await; + } + } + } + + async fn process_new_conversation(&self, request_id: RequestId, params: NewConversationParams) { + let config = match derive_config_from_params(params, self.codex_linux_sandbox_exe.clone()) { + Ok(config) => config, + Err(err) => { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("error deriving config: {err}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + } + }; + + match self.conversation_manager.new_conversation(config).await { + Ok(conversation_id) => { + let NewConversation { + conversation_id, + session_configured, + .. + } = conversation_id; + let response = NewConversationResponse { + conversation_id: ConversationId(conversation_id), + model: session_configured.model, + }; + self.outgoing.send_response(request_id, response).await; + } + Err(err) => { + let error = JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: format!("error creating conversation: {err}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + } + } + } + + async fn send_user_message(&self, request_id: RequestId, params: SendUserMessageParams) { + let SendUserMessageParams { + conversation_id, + items, + } = params; + let Ok(conversation) = self + .conversation_manager + .get_conversation(conversation_id.0) + .await + else { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("conversation not found: {conversation_id}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + }; + + let mapped_items: Vec = items + .into_iter() + .map(|item| match item { + WireInputItem::Text { text } => CoreInputItem::Text { text }, + WireInputItem::Image { image_url } => CoreInputItem::Image { image_url }, + WireInputItem::LocalImage { path } => CoreInputItem::LocalImage { path }, + }) + .collect(); + + // Submit user input to the conversation. + let _ = conversation + .submit(Op::UserInput { + items: mapped_items, + }) + .await; + + // Acknowledge with an empty result. + self.outgoing + .send_response(request_id, SendUserMessageResponse {}) + .await; + } + + async fn interrupt_conversation( + &mut self, + request_id: RequestId, + params: InterruptConversationParams, + ) { + let InterruptConversationParams { conversation_id } = params; + let Ok(conversation) = self + .conversation_manager + .get_conversation(conversation_id.0) + .await + else { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("conversation not found: {conversation_id}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + }; + + let _ = conversation.submit(Op::Interrupt).await; + + // Apparently CodexConversation does not send an ack for Op::Interrupt, + // so we can reply to the request right away. + self.outgoing + .send_response(request_id, InterruptConversationResponse {}) + .await; + } + + async fn add_conversation_listener( + &mut self, + request_id: RequestId, + params: AddConversationListenerParams, + ) { + let AddConversationListenerParams { conversation_id } = params; + let Ok(conversation) = self + .conversation_manager + .get_conversation(conversation_id.0) + .await + else { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("conversation not found: {}", conversation_id.0), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + return; + }; + + let subscription_id = Uuid::new_v4(); + let (cancel_tx, mut cancel_rx) = oneshot::channel(); + self.conversation_listeners + .insert(subscription_id, cancel_tx); + let outgoing_for_task = self.outgoing.clone(); + tokio::spawn(async move { + loop { + tokio::select! { + _ = &mut cancel_rx => { + // User has unsubscribed, so exit this task. + break; + } + event = conversation.next_event() => { + let event = match event { + Ok(event) => event, + Err(err) => { + tracing::warn!("conversation.next_event() failed with: {err}"); + break; + } + }; + + // For now, we send a notification for every event, + // JSON-serializing the `Event` as-is, but we will move + // to creating a special enum for notifications with a + // stable wire format. + let method = format!("codex/event/{}", event.msg); + let mut params = match serde_json::to_value(event.clone()) { + Ok(serde_json::Value::Object(map)) => map, + Ok(_) => { + tracing::error!("event did not serialize to an object"); + continue; + } + Err(err) => { + tracing::error!("failed to serialize event: {err}"); + continue; + } + }; + params.insert("conversationId".to_string(), conversation_id.to_string().into()); + + outgoing_for_task.send_notification(OutgoingNotification { + method, + params: Some(params.into()), + }) + .await; + + apply_bespoke_event_handling(event, conversation_id, conversation.clone(), outgoing_for_task.clone()).await; + } + } + } + }); + let response = AddConversationSubscriptionResponse { subscription_id }; + self.outgoing.send_response(request_id, response).await; + } + + async fn remove_conversation_listener( + &mut self, + request_id: RequestId, + params: RemoveConversationListenerParams, + ) { + let RemoveConversationListenerParams { subscription_id } = params; + match self.conversation_listeners.remove(&subscription_id) { + Some(sender) => { + // Signal the spawned task to exit and acknowledge. + let _ = sender.send(()); + let response = RemoveConversationSubscriptionResponse {}; + self.outgoing.send_response(request_id, response).await; + } + None => { + let error = JSONRPCErrorError { + code: INVALID_REQUEST_ERROR_CODE, + message: format!("subscription not found: {subscription_id}"), + data: None, + }; + self.outgoing.send_error(request_id, error).await; + } + } + } +} + +async fn apply_bespoke_event_handling( + event: Event, + conversation_id: ConversationId, + conversation: Arc, + outgoing: Arc, +) { + let Event { id: event_id, msg } = event; + match msg { + EventMsg::ApplyPatchApprovalRequest(ApplyPatchApprovalRequestEvent { + call_id, + changes, + reason, + grant_root, + }) => { + let params = ApplyPatchApprovalParams { + conversation_id, + call_id, + file_changes: changes, + reason, + grant_root, + }; + let value = serde_json::to_value(¶ms).unwrap_or_default(); + let rx = outgoing + .send_request(APPLY_PATCH_APPROVAL_METHOD, Some(value)) + .await; + // TODO(mbolin): Enforce a timeout so this task does not live indefinitely? + tokio::spawn(async move { + on_patch_approval_response(event_id, rx, conversation).await; + }); + } + EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent { + call_id, + command, + cwd, + reason, + }) => { + let params = ExecCommandApprovalParams { + conversation_id, + call_id, + command, + cwd, + reason, + }; + let value = serde_json::to_value(¶ms).unwrap_or_default(); + let rx = outgoing + .send_request(EXEC_COMMAND_APPROVAL_METHOD, Some(value)) + .await; + + // TODO(mbolin): Enforce a timeout so this task does not live indefinitely? + tokio::spawn(async move { + on_exec_approval_response(event_id, rx, conversation).await; + }); + } + _ => {} + } +} + +fn derive_config_from_params( + params: NewConversationParams, + codex_linux_sandbox_exe: Option, +) -> std::io::Result { + let NewConversationParams { + model, + profile, + cwd, + approval_policy, + sandbox, + config: cli_overrides, + base_instructions, + include_plan_tool, + } = params; + let overrides = ConfigOverrides { + model, + config_profile: profile, + cwd: cwd.map(PathBuf::from), + approval_policy: approval_policy.map(Into::into), + sandbox_mode: sandbox.map(Into::into), + model_provider: None, + codex_linux_sandbox_exe, + base_instructions, + include_plan_tool, + disable_response_storage: None, + show_raw_agent_reasoning: None, + }; + + let cli_overrides = cli_overrides + .unwrap_or_default() + .into_iter() + .map(|(k, v)| (k, json_to_toml(v))) + .collect(); + + Config::load_with_cli_overrides(cli_overrides, overrides) +} + +async fn on_patch_approval_response( + event_id: String, + receiver: tokio::sync::oneshot::Receiver, + codex: Arc, +) { + let response = receiver.await; + let value = match response { + Ok(value) => value, + Err(err) => { + error!("request failed: {err:?}"); + if let Err(submit_err) = codex + .submit(Op::PatchApproval { + id: event_id.clone(), + decision: ReviewDecision::Denied, + }) + .await + { + error!("failed to submit denied PatchApproval after request failure: {submit_err}"); + } + return; + } + }; + + let response = + serde_json::from_value::(value).unwrap_or_else(|err| { + error!("failed to deserialize ApplyPatchApprovalResponse: {err}"); + ApplyPatchApprovalResponse { + decision: ReviewDecision::Denied, + } + }); + + if let Err(err) = codex + .submit(Op::PatchApproval { + id: event_id, + decision: response.decision, + }) + .await + { + error!("failed to submit PatchApproval: {err}"); + } +} + +async fn on_exec_approval_response( + event_id: String, + receiver: tokio::sync::oneshot::Receiver, + conversation: Arc, +) { + let response = receiver.await; + let value = match response { + Ok(value) => value, + Err(err) => { + tracing::error!("request failed: {err:?}"); + return; + } + }; + + // Try to deserialize `value` and then make the appropriate call to `codex`. + let response = + serde_json::from_value::(value).unwrap_or_else(|err| { + error!("failed to deserialize ExecCommandApprovalResponse: {err}"); + // If we cannot deserialize the response, we deny the request to be + // conservative. + ExecCommandApprovalResponse { + decision: ReviewDecision::Denied, + } + }); + + if let Err(err) = conversation + .submit(Op::ExecApproval { + id: event_id, + decision: response.decision, + }) + .await + { + error!("failed to submit ExecApproval: {err}"); + } +} diff --git a/codex-rs/mcp-server/src/codex_tool_config.rs b/codex-rs/mcp-server/src/codex_tool_config.rs index 4af3e29c48..1d77eb4b82 100644 --- a/codex-rs/mcp-server/src/codex_tool_config.rs +++ b/codex-rs/mcp-server/src/codex_tool_config.rs @@ -58,7 +58,7 @@ pub struct CodexToolCallParam { /// Custom enum mirroring [`AskForApproval`], but has an extra dependency on /// [`JsonSchema`]. -#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)] #[serde(rename_all = "kebab-case")] pub enum CodexToolCallApprovalPolicy { Untrusted, @@ -80,7 +80,7 @@ impl From for AskForApproval { /// Custom enum mirroring [`SandboxMode`] from config_types.rs, but with /// `JsonSchema` support. -#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)] #[serde(rename_all = "kebab-case")] pub enum CodexToolCallSandboxMode { ReadOnly, diff --git a/codex-rs/mcp-server/src/codex_tool_runner.rs b/codex-rs/mcp-server/src/codex_tool_runner.rs index ced01539bb..ff660167d5 100644 --- a/codex-rs/mcp-server/src/codex_tool_runner.rs +++ b/codex-rs/mcp-server/src/codex_tool_runner.rs @@ -61,7 +61,7 @@ pub async fn run_codex_tool_session( is_error: Some(true), structured_content: None, }; - outgoing.send_response(id.clone(), result.into()).await; + outgoing.send_response(id.clone(), result).await; return; } }; @@ -235,9 +235,7 @@ async fn run_codex_tool_session_inner( is_error: None, structured_content: None, }; - outgoing - .send_response(request_id.clone(), result.into()) - .await; + outgoing.send_response(request_id.clone(), result).await; // unregister the id so we don't keep it in the map running_requests_id_to_codex_uuid .lock() @@ -296,9 +294,7 @@ async fn run_codex_tool_session_inner( // structured way. structured_content: None, }; - outgoing - .send_response(request_id.clone(), result.into()) - .await; + outgoing.send_response(request_id.clone(), result).await; break; } } diff --git a/codex-rs/mcp-server/src/error_code.rs b/codex-rs/mcp-server/src/error_code.rs new file mode 100644 index 0000000000..1ffd889d40 --- /dev/null +++ b/codex-rs/mcp-server/src/error_code.rs @@ -0,0 +1,2 @@ +pub(crate) const INVALID_REQUEST_ERROR_CODE: i64 = -32600; +pub(crate) const INTERNAL_ERROR_CODE: i64 = -32603; diff --git a/codex-rs/mcp-server/src/lib.rs b/codex-rs/mcp-server/src/lib.rs index f6d0838efc..b6dcf8246d 100644 --- a/codex-rs/mcp-server/src/lib.rs +++ b/codex-rs/mcp-server/src/lib.rs @@ -15,9 +15,11 @@ use tracing::error; use tracing::info; use tracing_subscriber::EnvFilter; +mod codex_message_processor; mod codex_tool_config; mod codex_tool_runner; mod conversation_loop; +mod error_code; mod exec_approval; mod json_to_toml; pub mod mcp_protocol; @@ -25,6 +27,7 @@ pub(crate) mod message_processor; mod outgoing_message; mod patch_approval; pub(crate) mod tool_handlers; +pub mod wire_format; use crate::message_processor::MessageProcessor; use crate::outgoing_message::OutgoingMessage; diff --git a/codex-rs/mcp-server/src/message_processor.rs b/codex-rs/mcp-server/src/message_processor.rs index a3349aeb35..763e51bf81 100644 --- a/codex-rs/mcp-server/src/message_processor.rs +++ b/codex-rs/mcp-server/src/message_processor.rs @@ -3,16 +3,19 @@ use std::collections::HashSet; use std::path::PathBuf; use std::sync::Arc; +use crate::codex_message_processor::CodexMessageProcessor; use crate::codex_tool_config::CodexToolCallParam; use crate::codex_tool_config::CodexToolCallReplyParam; use crate::codex_tool_config::create_tool_for_codex_tool_call_param; use crate::codex_tool_config::create_tool_for_codex_tool_call_reply_param; +use crate::error_code::INVALID_REQUEST_ERROR_CODE; use crate::mcp_protocol::ToolCallRequestParams; use crate::mcp_protocol::ToolCallResponse; use crate::mcp_protocol::ToolCallResponseResult; use crate::outgoing_message::OutgoingMessageSender; use crate::tool_handlers::create_conversation::handle_create_conversation; use crate::tool_handlers::send_message::handle_send_message; +use crate::wire_format::ClientRequest; use codex_core::ConversationManager; use codex_core::config::Config as CodexConfig; @@ -20,7 +23,7 @@ use codex_core::protocol::Submission; use mcp_types::CallToolRequest; use mcp_types::CallToolRequestParams; use mcp_types::CallToolResult; -use mcp_types::ClientRequest; +use mcp_types::ClientRequest as McpClientRequest; use mcp_types::ContentBlock; use mcp_types::JSONRPCError; use mcp_types::JSONRPCErrorError; @@ -39,6 +42,7 @@ use tokio::task; use uuid::Uuid; pub(crate) struct MessageProcessor { + codex_message_processor: CodexMessageProcessor, outgoing: Arc, initialized: bool, codex_linux_sandbox_exe: Option, @@ -54,11 +58,19 @@ impl MessageProcessor { outgoing: OutgoingMessageSender, codex_linux_sandbox_exe: Option, ) -> Self { + let outgoing = Arc::new(outgoing); + let conversation_manager = Arc::new(ConversationManager::default()); + let codex_message_processor = CodexMessageProcessor::new( + conversation_manager.clone(), + outgoing.clone(), + codex_linux_sandbox_exe.clone(), + ); Self { - outgoing: Arc::new(outgoing), + codex_message_processor, + outgoing, initialized: false, codex_linux_sandbox_exe, - conversation_manager: Arc::new(ConversationManager::default()), + conversation_manager, running_requests_id_to_codex_uuid: Arc::new(Mutex::new(HashMap::new())), running_session_ids: Arc::new(Mutex::new(HashSet::new())), } @@ -77,10 +89,21 @@ impl MessageProcessor { } pub(crate) async fn process_request(&mut self, request: JSONRPCRequest) { + if let Ok(request_json) = serde_json::to_value(request.clone()) + && let Ok(codex_request) = serde_json::from_value::(request_json) + { + // If the request is a Codex request, handle it with the Codex + // message processor. + self.codex_message_processor + .process_request(codex_request) + .await; + return; + } + // Hold on to the ID so we can respond. let request_id = request.id.clone(); - let client_request = match ClientRequest::try_from(request) { + let client_request = match McpClientRequest::try_from(request) { Ok(client_request) => client_request, Err(e) => { tracing::warn!("Failed to convert request: {e}"); @@ -90,43 +113,43 @@ impl MessageProcessor { // Dispatch to a dedicated handler for each request type. match client_request { - ClientRequest::InitializeRequest(params) => { + McpClientRequest::InitializeRequest(params) => { self.handle_initialize(request_id, params).await; } - ClientRequest::PingRequest(params) => { + McpClientRequest::PingRequest(params) => { self.handle_ping(request_id, params).await; } - ClientRequest::ListResourcesRequest(params) => { + McpClientRequest::ListResourcesRequest(params) => { self.handle_list_resources(params); } - ClientRequest::ListResourceTemplatesRequest(params) => { + McpClientRequest::ListResourceTemplatesRequest(params) => { self.handle_list_resource_templates(params); } - ClientRequest::ReadResourceRequest(params) => { + McpClientRequest::ReadResourceRequest(params) => { self.handle_read_resource(params); } - ClientRequest::SubscribeRequest(params) => { + McpClientRequest::SubscribeRequest(params) => { self.handle_subscribe(params); } - ClientRequest::UnsubscribeRequest(params) => { + McpClientRequest::UnsubscribeRequest(params) => { self.handle_unsubscribe(params); } - ClientRequest::ListPromptsRequest(params) => { + McpClientRequest::ListPromptsRequest(params) => { self.handle_list_prompts(params); } - ClientRequest::GetPromptRequest(params) => { + McpClientRequest::GetPromptRequest(params) => { self.handle_get_prompt(params); } - ClientRequest::ListToolsRequest(params) => { + McpClientRequest::ListToolsRequest(params) => { self.handle_list_tools(request_id, params).await; } - ClientRequest::CallToolRequest(params) => { + McpClientRequest::CallToolRequest(params) => { self.handle_call_tool(request_id, params).await; } - ClientRequest::SetLevelRequest(params) => { + McpClientRequest::SetLevelRequest(params) => { self.handle_set_level(params); } - ClientRequest::CompleteRequest(params) => { + McpClientRequest::CompleteRequest(params) => { self.handle_complete(params); } } @@ -191,7 +214,7 @@ impl MessageProcessor { if self.initialized { // Already initialised: send JSON-RPC error response. let error = JSONRPCErrorError { - code: -32600, // Invalid Request + code: INVALID_REQUEST_ERROR_CODE, message: "initialize called more than once".to_string(), data: None, }; @@ -230,9 +253,6 @@ impl MessageProcessor { where T: ModelContextProtocolRequest, { - // result has `Serialized` instance so should never fail - #[expect(clippy::unwrap_used)] - let result = serde_json::to_value(result).unwrap(); self.outgoing.send_response(id, result).await; } @@ -533,9 +553,7 @@ impl MessageProcessor { is_error: Some(true), structured_content: None, }; - outgoing - .send_response(request_id, serde_json::to_value(result).unwrap_or_default()) - .await; + outgoing.send_response(request_id, result).await; return; } }; diff --git a/codex-rs/mcp-server/src/outgoing_message.rs b/codex-rs/mcp-server/src/outgoing_message.rs index e7b0b9b63c..f13b8b324f 100644 --- a/codex-rs/mcp-server/src/outgoing_message.rs +++ b/codex-rs/mcp-server/src/outgoing_message.rs @@ -18,6 +18,8 @@ use tokio::sync::mpsc; use tokio::sync::oneshot; use tracing::warn; +use crate::error_code::INTERNAL_ERROR_CODE; + /// Sends messages to the client and manages request callbacks. pub(crate) struct OutgoingMessageSender { next_request_id: AtomicI64, @@ -74,9 +76,24 @@ impl OutgoingMessageSender { } } - pub(crate) async fn send_response(&self, id: RequestId, result: Result) { - let outgoing_message = OutgoingMessage::Response(OutgoingResponse { id, result }); - let _ = self.sender.send(outgoing_message).await; + pub(crate) async fn send_response(&self, id: RequestId, response: T) { + match serde_json::to_value(response) { + Ok(result) => { + let outgoing_message = OutgoingMessage::Response(OutgoingResponse { id, result }); + let _ = self.sender.send(outgoing_message).await; + } + Err(err) => { + self.send_error( + id, + JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: format!("failed to serialize response: {err}"), + data: None, + }, + ) + .await; + } + } } pub(crate) async fn send_event_as_notification( @@ -97,16 +114,21 @@ impl OutgoingMessageSender { event_json }; - let outgoing_message = OutgoingMessage::Notification(OutgoingNotification { + self.send_notification(OutgoingNotification { method: "codex/event".to_string(), params: Some(params.clone()), - }); - let _ = self.sender.send(outgoing_message).await; + }) + .await; self.send_event_as_notification_new_schema(event, Some(params.clone())) .await; } + pub(crate) async fn send_notification(&self, notification: OutgoingNotification) { + let outgoing_message = OutgoingMessage::Notification(notification); + let _ = self.sender.send(outgoing_message).await; + } + // should be backwards compatible. // it will replace send_event_as_notification eventually. async fn send_event_as_notification_new_schema( diff --git a/codex-rs/mcp-server/src/wire_format.rs b/codex-rs/mcp-server/src/wire_format.rs new file mode 100644 index 0000000000..95d55e8bf5 --- /dev/null +++ b/codex-rs/mcp-server/src/wire_format.rs @@ -0,0 +1,259 @@ +use std::collections::HashMap; +use std::fmt::Display; +use std::path::PathBuf; + +use codex_core::protocol::FileChange; +use codex_core::protocol::ReviewDecision; +use mcp_types::RequestId; +use serde::Deserialize; +use serde::Serialize; + +use crate::codex_tool_config::CodexToolCallApprovalPolicy; +use crate::codex_tool_config::CodexToolCallSandboxMode; +use uuid::Uuid; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ConversationId(pub Uuid); + +impl Display for ConversationId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +/// Request from the client to the server. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(tag = "method", rename_all = "camelCase")] +pub enum ClientRequest { + NewConversation { + #[serde(rename = "id")] + request_id: RequestId, + params: NewConversationParams, + }, + SendUserMessage { + #[serde(rename = "id")] + request_id: RequestId, + params: SendUserMessageParams, + }, + InterruptConversation { + #[serde(rename = "id")] + request_id: RequestId, + params: InterruptConversationParams, + }, + AddConversationListener { + #[serde(rename = "id")] + request_id: RequestId, + params: AddConversationListenerParams, + }, + RemoveConversationListener { + #[serde(rename = "id")] + request_id: RequestId, + params: RemoveConversationListenerParams, + }, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)] +#[serde(rename_all = "camelCase")] +pub struct NewConversationParams { + /// Optional override for the model name (e.g. "o3", "o4-mini"). + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option, + + /// Configuration profile from config.toml to specify default options. + #[serde(skip_serializing_if = "Option::is_none")] + pub profile: Option, + + /// Working directory for the session. If relative, it is resolved against + /// the server process's current working directory. + #[serde(skip_serializing_if = "Option::is_none")] + pub cwd: Option, + + /// Approval policy for shell commands generated by the model: + /// `untrusted`, `on-failure`, `on-request`, `never`. + #[serde(skip_serializing_if = "Option::is_none")] + pub approval_policy: Option, + + /// Sandbox mode: `read-only`, `workspace-write`, or `danger-full-access`. + #[serde(skip_serializing_if = "Option::is_none")] + pub sandbox: Option, + + /// Individual config settings that will override what is in + /// CODEX_HOME/config.toml. + #[serde(skip_serializing_if = "Option::is_none")] + pub config: Option>, + + /// The set of instructions to use instead of the default ones. + #[serde(skip_serializing_if = "Option::is_none")] + pub base_instructions: Option, + + /// Whether to include the plan tool in the conversation. + #[serde(skip_serializing_if = "Option::is_none")] + pub include_plan_tool: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct NewConversationResponse { + pub conversation_id: ConversationId, + pub model: String, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct AddConversationSubscriptionResponse { + pub subscription_id: Uuid, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct RemoveConversationSubscriptionResponse {} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SendUserMessageParams { + pub conversation_id: ConversationId, + pub items: Vec, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct InterruptConversationParams { + pub conversation_id: ConversationId, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct InterruptConversationResponse {} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct SendUserMessageResponse {} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct AddConversationListenerParams { + pub conversation_id: ConversationId, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct RemoveConversationListenerParams { + pub subscription_id: Uuid, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +#[serde(tag = "type", content = "data")] +pub enum InputItem { + Text { + text: String, + }, + /// Pre‑encoded data: URI image. + Image { + image_url: String, + }, + + /// Local image path provided by the user. This will be converted to an + /// `Image` variant (base64 data URL) during request serialization. + LocalImage { + path: PathBuf, + }, +} + +// TODO(mbolin): Need test to ensure these constants match the enum variants. + +pub const APPLY_PATCH_APPROVAL_METHOD: &str = "applyPatchApproval"; +pub const EXEC_COMMAND_APPROVAL_METHOD: &str = "execCommandApproval"; + +/// Request initiated from the server and sent to the client. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +#[serde(tag = "method", rename_all = "camelCase")] +pub enum ServerRequest { + /// Request to approve a patch. + ApplyPatchApproval { + #[serde(rename = "id")] + request_id: RequestId, + params: ApplyPatchApprovalParams, + }, + /// Request to exec a command. + ExecCommandApproval { + #[serde(rename = "id")] + request_id: RequestId, + params: ExecCommandApprovalParams, + }, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub struct ApplyPatchApprovalParams { + pub conversation_id: ConversationId, + /// Use to correlate this with [codex_core::protocol::PatchApplyBeginEvent] + /// and [codex_core::protocol::PatchApplyEndEvent]. + pub call_id: String, + pub file_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 (unclear if this is honored today). + #[serde(skip_serializing_if = "Option::is_none")] + pub grant_root: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub struct ExecCommandApprovalParams { + pub conversation_id: ConversationId, + /// Use to correlate this with [codex_core::protocol::ExecCommandBeginEvent] + /// and [codex_core::protocol::ExecCommandEndEvent]. + pub call_id: String, + pub command: Vec, + pub cwd: PathBuf, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub struct ExecCommandApprovalResponse { + pub decision: ReviewDecision, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)] +pub struct ApplyPatchApprovalResponse { + pub decision: ReviewDecision, +} + +#[allow(clippy::unwrap_used)] +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + use serde_json::json; + + #[test] + fn serialize_new_conversation() { + let request = ClientRequest::NewConversation { + request_id: RequestId::Integer(42), + params: NewConversationParams { + model: Some("gpt-5".to_string()), + profile: None, + cwd: None, + approval_policy: Some(CodexToolCallApprovalPolicy::OnRequest), + sandbox: None, + config: None, + base_instructions: None, + include_plan_tool: None, + }, + }; + assert_eq!( + json!({ + "method": "newConversation", + "id": 42, + "params": { + "model": "gpt-5", + "approvalPolicy": "on-request" + } + }), + serde_json::to_value(&request).unwrap(), + ); + } +} diff --git a/codex-rs/mcp-server/tests/codex_message_processor_flow.rs b/codex-rs/mcp-server/tests/codex_message_processor_flow.rs new file mode 100644 index 0000000000..7b7845609e --- /dev/null +++ b/codex-rs/mcp-server/tests/codex_message_processor_flow.rs @@ -0,0 +1,193 @@ +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use std::path::Path; + +use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; +use codex_mcp_server::wire_format::AddConversationListenerParams; +use codex_mcp_server::wire_format::AddConversationSubscriptionResponse; +use codex_mcp_server::wire_format::NewConversationParams; +use codex_mcp_server::wire_format::NewConversationResponse; +use codex_mcp_server::wire_format::RemoveConversationListenerParams; +use codex_mcp_server::wire_format::RemoveConversationSubscriptionResponse; +use codex_mcp_server::wire_format::SendUserMessageParams; +use codex_mcp_server::wire_format::SendUserMessageResponse; +use mcp_test_support::McpProcess; +use mcp_test_support::create_final_assistant_message_sse_response; +use mcp_test_support::create_mock_chat_completions_server; +use mcp_test_support::create_shell_sse_response; +use mcp_types::JSONRPCNotification; +use mcp_types::JSONRPCResponse; +use mcp_types::RequestId; +use pretty_assertions::assert_eq; +use serde::de::DeserializeOwned; +use std::env; +use tempfile::TempDir; +use tokio::time::timeout; + +const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn test_codex_jsonrpc_conversation_flow() { + if env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() { + println!( + "Skipping test because it cannot execute when network is disabled in a Codex sandbox." + ); + return; + } + + let tmp = TempDir::new().expect("tmp dir"); + // Temporary Codex home with config pointing at the mock server. + let codex_home = tmp.path().join("codex_home"); + std::fs::create_dir(&codex_home).expect("create codex home dir"); + let working_directory = tmp.path().join("workdir"); + std::fs::create_dir(&working_directory).expect("create working directory"); + + // Create a mock model server that immediately ends each turn. + // Two turns are expected: initial session configure + one user message. + let responses = vec![ + create_shell_sse_response( + vec!["ls".to_string()], + Some(&working_directory), + Some(5000), + "call1234", + ) + .expect("create shell sse response"), + create_final_assistant_message_sse_response("Enjoy your new git repo!") + .expect("create final assistant message"), + ]; + let server = create_mock_chat_completions_server(responses).await; + create_config_toml(&codex_home, &server.uri()).expect("write config"); + + // Start MCP server and initialize. + let mut mcp = McpProcess::new(&codex_home).await.expect("spawn mcp"); + timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()) + .await + .expect("init timeout") + .expect("init error"); + + // 1) newConversation + let new_conv_id = mcp + .send_new_conversation_request(NewConversationParams { + cwd: Some(working_directory.to_string_lossy().into_owned()), + ..Default::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 new_conv_resp = to_response::(new_conv_resp) + .expect("deserialize newConversation response"); + let NewConversationResponse { + conversation_id, + model, + } = new_conv_resp; + assert_eq!(model, "mock-model"); + + // 2) addConversationListener + let add_listener_id = mcp + .send_add_conversation_listener_request(AddConversationListenerParams { conversation_id }) + .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"); + + // 3) sendUserMessage (should trigger notifications; we only validate an OK response) + let send_user_id = mcp + .send_send_user_message_request(SendUserMessageParams { + conversation_id, + items: vec![codex_mcp_server::wire_format::InputItem::Text { + text: "text".to_string(), + }], + }) + .await + .expect("send sendUserMessage"); + let send_user_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(send_user_id)), + ) + .await + .expect("sendUserMessage timeout") + .expect("sendUserMessage resp"); + let SendUserMessageResponse {} = to_response::(send_user_resp) + .expect("deserialize sendUserMessage response"); + + // Verify the task_finished notification is received. + // Note this also ensures that the final request to the server was made. + let task_finished_notification: JSONRPCNotification = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_notification_message("codex/event/task_complete"), + ) + .await + .expect("task_finished_notification timeout") + .expect("task_finished_notification resp"); + let serde_json::Value::Object(map) = task_finished_notification + .params + .expect("notification should have params") + else { + panic!("task_finished_notification should have params"); + }; + assert_eq!( + map.get("conversationId") + .expect("should have conversationId"), + &serde_json::Value::String(conversation_id.to_string()) + ); + + // 4) removeConversationListener + let remove_listener_id = mcp + .send_remove_conversation_listener_request(RemoveConversationListenerParams { + subscription_id, + }) + .await + .expect("send removeConversationListener"); + let remove_listener_resp: JSONRPCResponse = timeout( + DEFAULT_READ_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(remove_listener_id)), + ) + .await + .expect("removeConversationListener timeout") + .expect("removeConversationListener resp"); + let RemoveConversationSubscriptionResponse {} = + to_response(remove_listener_resp).expect("deserialize removeConversationListener response"); +} + +fn to_response(response: JSONRPCResponse) -> anyhow::Result { + let value = serde_json::to_value(response.result)?; + let codex_response = serde_json::from_value(value)?; + Ok(codex_response) +} + +// Helper: minimal config.toml pointing at mock provider. +fn create_config_toml(codex_home: &Path, server_uri: &str) -> std::io::Result<()> { + let config_toml = codex_home.join("config.toml"); + std::fs::write( + config_toml, + format!( + r#" +model = "mock-model" +approval_policy = "never" + +model_provider = "mock_provider" + +[model_providers.mock_provider] +name = "Mock provider for test" +base_url = "{server_uri}/v1" +wire_api = "chat" +request_max_retries = 0 +stream_max_retries = 0 +"# + ), + ) +} diff --git a/codex-rs/mcp-server/tests/common/mcp_process.rs b/codex-rs/mcp-server/tests/common/mcp_process.rs index 83cf085cd4..a659b1d950 100644 --- a/codex-rs/mcp-server/tests/common/mcp_process.rs +++ b/codex-rs/mcp-server/tests/common/mcp_process.rs @@ -18,6 +18,10 @@ use codex_mcp_server::mcp_protocol::ConversationCreateArgs; use codex_mcp_server::mcp_protocol::ConversationId; use codex_mcp_server::mcp_protocol::ConversationSendMessageArgs; use codex_mcp_server::mcp_protocol::ToolCallRequestParams; +use codex_mcp_server::wire_format::AddConversationListenerParams; +use codex_mcp_server::wire_format::NewConversationParams; +use codex_mcp_server::wire_format::RemoveConversationListenerParams; +use codex_mcp_server::wire_format::SendUserMessageParams; use mcp_types::CallToolRequestParams; use mcp_types::ClientCapabilities; @@ -236,6 +240,47 @@ impl McpProcess { .await } + // --------------------------------------------------------------------- + // Codex JSON-RPC (non-tool) helpers + // --------------------------------------------------------------------- + /// Send a `newConversation` JSON-RPC request. + pub async fn send_new_conversation_request( + &mut self, + params: NewConversationParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("newConversation", params).await + } + + /// Send an `addConversationListener` JSON-RPC request. + pub async fn send_add_conversation_listener_request( + &mut self, + params: AddConversationListenerParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("addConversationListener", params).await + } + + /// Send a `sendUserMessage` JSON-RPC request with a single text item. + pub async fn send_send_user_message_request( + &mut self, + params: SendUserMessageParams, + ) -> anyhow::Result { + // Wire format expects variants in camelCase; text item uses external tagging. + let params = Some(serde_json::to_value(params)?); + self.send_request("sendUserMessage", params).await + } + + /// Send a `removeConversationListener` JSON-RPC request. + pub async fn send_remove_conversation_listener_request( + &mut self, + params: RemoveConversationListenerParams, + ) -> anyhow::Result { + let params = Some(serde_json::to_value(params)?); + self.send_request("removeConversationListener", params) + .await + } + async fn send_request( &mut self, method: &str, @@ -329,6 +374,33 @@ impl McpProcess { } } + pub async fn read_stream_until_notification_message( + &mut self, + method: &str, + ) -> anyhow::Result { + loop { + let message = self.read_jsonrpc_message().await?; + eprint!("message: {message:?}"); + + match message { + JSONRPCMessage::Notification(notification) => { + if notification.method == method { + return Ok(notification); + } + } + JSONRPCMessage::Request(_) => { + anyhow::bail!("unexpected JSONRPCMessage::Request: {message:?}"); + } + JSONRPCMessage::Error(_) => { + anyhow::bail!("unexpected JSONRPCMessage::Error: {message:?}"); + } + JSONRPCMessage::Response(_) => { + anyhow::bail!("unexpected JSONRPCMessage::Response: {message:?}"); + } + } + } + } + pub async fn read_stream_until_configured_response_message( &mut self, ) -> anyhow::Result { diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index fb45ecfd19..2bef9fb925 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -30,6 +30,7 @@ use std::sync::mpsc::Receiver; use std::sync::mpsc::channel; use std::thread; use std::time::Duration; +use std::time::Instant; /// Time window for debouncing redraw requests. const REDRAW_DEBOUNCE: Duration = Duration::from_millis(1); @@ -59,15 +60,16 @@ pub(crate) struct App<'a> { file_search: FileSearchManager, - /// True when a redraw has been scheduled but not yet executed. - pending_redraw: Arc, - pending_history_lines: Vec>, enhanced_keys_supported: bool, /// Controls the animation thread that sends CommitTick events. commit_anim_running: Arc, + + /// Channel to schedule one-shot animation frames; coalesced by a single + /// scheduler thread. + frame_schedule_tx: std::sync::mpsc::Sender, } /// Aggregate parameters needed to create a `ChatWidget`, as creation may be @@ -91,7 +93,6 @@ impl App<'_> { let (app_event_tx, app_event_rx) = channel(); let app_event_tx = AppEventSender::new(app_event_tx); - let pending_redraw = Arc::new(AtomicBool::new(false)); let enhanced_keys_supported = supports_keyboard_enhancement().unwrap_or(false); @@ -169,6 +170,47 @@ impl App<'_> { }; let file_search = FileSearchManager::new(config.cwd.clone(), app_event_tx.clone()); + + // Spawn a single scheduler thread that coalesces both debounced redraw + // requests and animation frame requests, and emits a single Redraw event + // at the earliest requested time. + let (frame_tx, frame_rx) = channel::(); + { + let app_event_tx = app_event_tx.clone(); + std::thread::spawn(move || { + use std::sync::mpsc::RecvTimeoutError; + let mut next_deadline: Option = None; + loop { + if next_deadline.is_none() { + match frame_rx.recv() { + Ok(deadline) => next_deadline = Some(deadline), + Err(_) => break, + } + } + + #[allow(clippy::expect_used)] + let deadline = next_deadline.expect("deadline set"); + let now = Instant::now(); + let timeout = if deadline > now { + deadline - now + } else { + Duration::from_millis(0) + }; + + match frame_rx.recv_timeout(timeout) { + Ok(new_deadline) => { + next_deadline = + Some(next_deadline.map_or(new_deadline, |d| d.min(new_deadline))); + } + Err(RecvTimeoutError::Timeout) => { + app_event_tx.send(AppEvent::Redraw); + next_deadline = None; + } + Err(RecvTimeoutError::Disconnected) => break, + } + } + }); + } Self { server: conversation_manager, app_event_tx, @@ -177,44 +219,19 @@ impl App<'_> { app_state, config, file_search, - pending_redraw, enhanced_keys_supported, commit_anim_running: Arc::new(AtomicBool::new(false)), + frame_schedule_tx: frame_tx, } } - /// Clone of the internal event sender so external tasks (e.g. log bridge) - /// can inject `AppEvent`s. - pub fn event_sender(&self) -> AppEventSender { - self.app_event_tx.clone() - } - - /// Schedule a redraw if one is not already pending. - #[allow(clippy::unwrap_used)] - fn schedule_redraw(&self) { - // Attempt to set the flag to `true`. If it was already `true`, another - // redraw is already pending so we can return early. - if self - .pending_redraw - .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) - .is_err() - { - return; - } - - let tx = self.app_event_tx.clone(); - let pending_redraw = self.pending_redraw.clone(); - thread::spawn(move || { - thread::sleep(REDRAW_DEBOUNCE); - tx.send(AppEvent::Redraw); - pending_redraw.store(false, Ordering::Release); - }); + fn schedule_frame_in(&self, dur: Duration) { + let _ = self.frame_schedule_tx.send(Instant::now() + dur); } pub(crate) fn run(&mut self, terminal: &mut tui::Tui) -> Result<()> { - // Insert an event to trigger the first render. - let app_event_tx = self.app_event_tx.clone(); - app_event_tx.send(AppEvent::RequestRedraw); + // Schedule the first render immediately. + let _ = self.frame_schedule_tx.send(Instant::now()); while let Ok(event) = self.app_event_rx.recv() { match event { @@ -223,7 +240,10 @@ impl App<'_> { self.app_event_tx.send(AppEvent::RequestRedraw); } AppEvent::RequestRedraw => { - self.schedule_redraw(); + self.schedule_frame_in(REDRAW_DEBOUNCE); + } + AppEvent::ScheduleFrameIn(dur) => { + self.schedule_frame_in(dur); } AppEvent::Redraw => { std::io::stdout().sync_update(|_| self.draw_next_frame(terminal))??; @@ -325,10 +345,6 @@ impl App<'_> { AppState::Chat { widget } => widget.submit_op(op), AppState::Onboarding { .. } => {} }, - AppEvent::LatestLog(line) => match &mut self.app_state { - AppState::Chat { widget } => widget.update_latest_log(line), - AppState::Onboarding { .. } => {} - }, AppEvent::DispatchCommand(command) => match command { SlashCommand::New => { // User accepted – switch to chat view. @@ -457,7 +473,7 @@ impl App<'_> { widget: Box::new(ChatWidget::new( config, self.server.clone(), - app_event_tx.clone(), + self.app_event_tx.clone(), initial_prompt, initial_images, enhanced_keys_supported, diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index a52f8baf39..6b9999848c 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -2,6 +2,7 @@ use codex_core::protocol::Event; use codex_file_search::FileMatch; use crossterm::event::KeyEvent; use ratatui::text::Line; +use std::time::Duration; use crate::app::ChatWidgetArgs; use crate::slash_command::SlashCommand; @@ -17,6 +18,10 @@ pub(crate) enum AppEvent { /// Actually draw the next frame. Redraw, + /// Schedule a one-shot animation frame roughly after the given duration. + /// Multiple requests are coalesced by the central frame scheduler. + ScheduleFrameIn(Duration), + KeyEvent(KeyEvent), /// Text pasted from the terminal clipboard. @@ -29,9 +34,6 @@ pub(crate) enum AppEvent { /// bubbling channels through layers of widgets. CodexOp(codex_core::protocol::Op), - /// Latest formatted log line emitted by `tracing`. - LatestLog(String), - /// Dispatch a recognized slash command from the UI (composer) to the app /// layer so it can be handled centrally. DispatchCommand(SlashCommand), diff --git a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs index a5616371d2..c86dad3183 100644 --- a/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs +++ b/codex-rs/tui/src/bottom_pane/bottom_pane_view.rs @@ -6,12 +6,6 @@ use ratatui::layout::Rect; use super::BottomPane; use super::CancellationEvent; -/// Type to use for a method that may require a redraw of the UI. -pub(crate) enum ConditionalUpdate { - NeedsRedraw, - NoRedraw, -} - /// Trait implemented by every view that can be shown in the bottom pane. pub(crate) trait BottomPaneView<'a> { /// Handle a key event while the view is active. A redraw is always @@ -34,11 +28,6 @@ pub(crate) trait BottomPaneView<'a> { /// Render the view: this will be displayed in place of the composer. fn render(&self, area: Rect, buf: &mut Buffer); - /// Update the status indicator text. - fn update_status_text(&mut self, _text: String) -> ConditionalUpdate { - ConditionalUpdate::NoRedraw - } - /// Called when task completes to check if the view should be hidden. fn should_hide_when_task_is_done(&mut self) -> bool { false diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 78506f572c..601f4d4843 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -166,7 +166,7 @@ impl ChatComposer { let char_count = pasted.chars().count(); if char_count > LARGE_PASTE_CHAR_THRESHOLD { let placeholder = format!("[Pasted Content {char_count} chars]"); - self.textarea.insert_str(&placeholder); + self.textarea.insert_element(&placeholder); self.pending_pastes.push((placeholder, pasted)); } else { self.textarea.insert_str(&pasted); @@ -532,17 +532,6 @@ impl ChatComposer { /// Handle generic Input events that modify the textarea content. fn handle_input_basic(&mut self, input: KeyEvent) -> (InputResult, bool) { - // Special handling for backspace on placeholders - if let KeyEvent { - code: KeyCode::Backspace, - .. - } = input - { - if self.try_remove_placeholder_at_cursor() { - return (InputResult::None, true); - } - } - // Normal input handling self.textarea.input(input); let text_after = self.textarea.text(); @@ -554,34 +543,6 @@ impl ChatComposer { (InputResult::None, true) } - /// Attempts to remove a placeholder if the cursor is at the end of one. - /// Returns true if a placeholder was removed. - fn try_remove_placeholder_at_cursor(&mut self) -> bool { - let p = self.textarea.cursor(); - let text = self.textarea.text(); - - // Find any placeholder that ends at the cursor position - let placeholder_to_remove = self.pending_pastes.iter().find_map(|(ph, _)| { - if p < ph.len() { - return None; - } - let potential_ph_start = p - ph.len(); - if text[potential_ph_start..p] == *ph { - Some(ph.clone()) - } else { - None - } - }); - - if let Some(placeholder) = placeholder_to_remove { - self.textarea.replace_range(p - placeholder.len()..p, ""); - self.pending_pastes.retain(|(ph, _)| ph != &placeholder); - true - } else { - false - } - } - /// Synchronize `self.command_popup` with the current text in the /// textarea. This must be called after every modification that can change /// the text so the popup is shown/updated/hidden as appropriate. @@ -731,15 +692,15 @@ impl WidgetRef for &ChatComposer { .render_ref(bottom_line_rect, buf); } } + let border_style = if self.has_focus { + Style::default().fg(Color::Cyan) + } else { + Style::default().add_modifier(Modifier::DIM) + }; Block::default() - .border_style(Style::default().dim()) .borders(Borders::LEFT) .border_type(BorderType::QuadrantOutside) - .border_style(Style::default().fg(if self.has_focus { - Color::Cyan - } else { - Color::Gray - })) + .border_style(border_style) .render_ref( Rect::new(textarea_rect.x, textarea_rect.y, 1, textarea_rect.height), buf, diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 69f174f148..b2da8d28a6 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -32,7 +32,6 @@ pub(crate) enum CancellationEvent { pub(crate) use chat_composer::ChatComposer; pub(crate) use chat_composer::InputResult; -use crate::status_indicator_widget::StatusIndicatorWidget; use approval_modal_view::ApprovalModalView; use status_indicator_view::StatusIndicatorView; @@ -50,11 +49,6 @@ pub(crate) struct BottomPane<'a> { is_task_running: bool, ctrl_c_quit_hint: bool, - /// Optional live, multi‑line status/"live cell" rendered directly above - /// the composer while a task is running. Unlike `active_view`, this does - /// not replace the composer; it augments it. - live_status: Option, - /// True if the active view is the StatusIndicatorView that replaces the /// composer during a running task. status_view_active: bool, @@ -81,27 +75,18 @@ impl BottomPane<'_> { has_input_focus: params.has_input_focus, is_task_running: false, ctrl_c_quit_hint: false, - live_status: None, status_view_active: false, } } pub fn desired_height(&self, width: u16) -> u16 { - let overlay_status_h = self - .live_status - .as_ref() - .map(|s| s.desired_height(width)) - .unwrap_or(0); - let view_height = if let Some(view) = self.active_view.as_ref() { view.desired_height(width) } else { self.composer.desired_height(width) }; - overlay_status_h - .saturating_add(view_height) - .saturating_add(Self::BOTTOM_PAD_LINES) + view_height.saturating_add(Self::BOTTOM_PAD_LINES) } pub fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> { @@ -182,44 +167,6 @@ impl BottomPane<'_> { self.request_redraw(); } - /// Update the status indicator text. Prefer replacing the composer with - /// the StatusIndicatorView so the input pane shows a single-line status - /// like: `β–Œ Working waiting for model`. - pub(crate) fn update_status_text(&mut self, text: String) { - let mut handled_by_view = false; - if let Some(view) = self.active_view.as_mut() { - if matches!( - view.update_status_text(text.clone()), - bottom_pane_view::ConditionalUpdate::NeedsRedraw - ) { - handled_by_view = true; - } - } else { - let mut v = StatusIndicatorView::new(self.app_event_tx.clone()); - v.update_text(text.clone()); - self.active_view = Some(Box::new(v)); - self.status_view_active = true; - handled_by_view = true; - } - - // Fallback: if the current active view did not consume status updates - // and no modal view is active, present an overlay above the composer. - // If a modal is active, do NOT render the overlay to avoid drawing - // over the dialog. - if !handled_by_view && self.active_view.is_none() { - if self.live_status.is_none() { - self.live_status = Some(StatusIndicatorWidget::new(self.app_event_tx.clone())); - } - if let Some(status) = &mut self.live_status { - status.update_text(text); - } - } else if !handled_by_view { - // Ensure any previous overlay is cleared when a modal becomes active. - self.live_status = None; - } - self.request_redraw(); - } - pub(crate) fn show_ctrl_c_quit_hint(&mut self) { self.ctrl_c_quit_hint = true; self.composer @@ -252,7 +199,6 @@ impl BottomPane<'_> { } self.request_redraw(); } else { - self.live_status = None; // Drop the status view when a task completes, but keep other // modal views (e.g. approval dialogs). if let Some(mut view) = self.active_view.take() { @@ -302,8 +248,6 @@ impl BottomPane<'_> { // Otherwise create a new approval modal overlay. let modal = ApprovalModalView::new(request, self.app_event_tx.clone()); self.active_view = Some(Box::new(modal)); - // Hide any overlay status while a modal is visible. - self.live_status = None; self.status_view_active = false; self.request_redraw() } @@ -342,46 +286,31 @@ impl BottomPane<'_> { impl WidgetRef for &BottomPane<'_> { fn render_ref(&self, area: Rect, buf: &mut Buffer) { - let mut y_offset = 0u16; - if let Some(status) = &self.live_status { - let live_h = status - .desired_height(area.width) - .min(area.height.saturating_sub(y_offset)); - if live_h > 0 { - let live_rect = Rect { - x: area.x, - y: area.y + y_offset, - width: area.width, - height: live_h, - }; - status.render_ref(live_rect, buf); - y_offset = y_offset.saturating_add(live_h); - } - } - if let Some(view) = &self.active_view { - if y_offset < area.height { - // Reserve bottom padding lines; keep at least 1 line for the view. - let avail = area.height - y_offset; + // Reserve bottom padding lines; keep at least 1 line for the view. + let avail = area.height; + if avail > 0 { let pad = BottomPane::BOTTOM_PAD_LINES.min(avail.saturating_sub(1)); let view_rect = Rect { x: area.x, - y: area.y + y_offset, + y: area.y, width: area.width, height: avail - pad, }; view.render(view_rect, buf); } - } else if y_offset < area.height { - let composer_rect = Rect { - x: area.x, - y: area.y + y_offset, - width: area.width, - // Reserve bottom padding - height: (area.height - y_offset) - - BottomPane::BOTTOM_PAD_LINES.min((area.height - y_offset).saturating_sub(1)), - }; - (&self.composer).render_ref(composer_rect, buf); + } else { + let avail = area.height; + if avail > 0 { + let composer_rect = Rect { + x: area.x, + y: area.y, + width: area.width, + // Reserve bottom padding + height: avail - BottomPane::BOTTOM_PAD_LINES.min(avail.saturating_sub(1)), + }; + (&self.composer).render_ref(composer_rect, buf); + } } } } @@ -431,10 +360,8 @@ mod tests { // Create an approval modal (active view). pane.push_approval_request(exec_request()); - // Attempt to update status; this should NOT create an overlay while modal is visible. - pane.update_status_text("running command".to_string()); - // Render and verify the top row does not include the Working header overlay. + // Render and verify the top row does not include an overlay. let area = Rect::new(0, 0, 60, 6); let mut buf = Buffer::empty(area); (&pane).render_ref(area, &mut buf); @@ -445,7 +372,7 @@ mod tests { } assert!( !r0.contains("Working"), - "overlay Working header should not render above modal" + "overlay should not render above modal" ); } @@ -461,7 +388,6 @@ mod tests { // Start a running task so the status indicator replaces the composer. pane.set_task_running(true); - pane.update_status_text("waiting for model".to_string()); // Push an approval modal (e.g., command approval) which should hide the status view. pane.push_approval_request(exec_request()); @@ -511,11 +437,6 @@ mod tests { // Begin a task: show initial status. pane.set_task_running(true); - pane.update_status_text("waiting for model".to_string()); - - // As a long-running command begins (post-approval), ensure the status - // indicator is visible while we wait for the command to run. - pane.update_status_text("running command".to_string()); // Allow some frames so the animation thread ticks. std::thread::sleep(std::time::Duration::from_millis(120)); @@ -547,7 +468,6 @@ mod tests { // Activate spinner (status view replaces composer) with no live ring. pane.set_task_running(true); - pane.update_status_text("waiting for model".to_string()); // Use height == desired_height; expect 1 status row at top and 2 bottom padding rows. let height = pane.desired_height(30); @@ -598,7 +518,6 @@ mod tests { }); pane.set_task_running(true); - pane.update_status_text("waiting for model".to_string()); // Height=2 β†’ pad shrinks to 1; bottom row is blank, top row has spinner. let area2 = Rect::new(0, 0, 20, 2); diff --git a/codex-rs/tui/src/bottom_pane/selection_popup_common.rs b/codex-rs/tui/src/bottom_pane/selection_popup_common.rs index 1a31115d77..0a0574c600 100644 --- a/codex-rs/tui/src/bottom_pane/selection_popup_common.rs +++ b/codex-rs/tui/src/bottom_pane/selection_popup_common.rs @@ -93,9 +93,7 @@ pub(crate) fn render_rows( spans.push(Span::raw(" ")); spans.push(Span::styled( desc.clone(), - Style::default() - .fg(Color::DarkGray) - .add_modifier(Modifier::DIM), + Style::default().add_modifier(Modifier::DIM), )); } @@ -118,7 +116,7 @@ pub(crate) fn render_rows( Block::default() .borders(Borders::LEFT) .border_type(BorderType::QuadrantOutside) - .border_style(Style::default().fg(Color::DarkGray)), + .border_style(Style::default().add_modifier(Modifier::DIM)), ) .widths([Constraint::Percentage(100)]); diff --git a/codex-rs/tui/src/bottom_pane/status_indicator_view.rs b/codex-rs/tui/src/bottom_pane/status_indicator_view.rs index cad4f0f272..b0f64a972e 100644 --- a/codex-rs/tui/src/bottom_pane/status_indicator_view.rs +++ b/codex-rs/tui/src/bottom_pane/status_indicator_view.rs @@ -8,7 +8,6 @@ use crate::bottom_pane::BottomPane; use crate::status_indicator_widget::StatusIndicatorWidget; use super::BottomPaneView; -use super::bottom_pane_view::ConditionalUpdate; pub(crate) struct StatusIndicatorView { view: StatusIndicatorWidget, @@ -27,11 +26,6 @@ impl StatusIndicatorView { } impl BottomPaneView<'_> for StatusIndicatorView { - fn update_status_text(&mut self, text: String) -> ConditionalUpdate { - self.update_text(text); - ConditionalUpdate::NeedsRedraw - } - fn should_hide_when_task_is_done(&mut self) -> bool { true } diff --git a/codex-rs/tui/src/bottom_pane/textarea.rs b/codex-rs/tui/src/bottom_pane/textarea.rs index dabc276a37..f0cfa614f9 100644 --- a/codex-rs/tui/src/bottom_pane/textarea.rs +++ b/codex-rs/tui/src/bottom_pane/textarea.rs @@ -3,6 +3,7 @@ use crossterm::event::KeyEvent; use crossterm::event::KeyModifiers; use ratatui::buffer::Buffer; use ratatui::layout::Rect; +use ratatui::style::Color; use ratatui::style::Style; use ratatui::widgets::StatefulWidgetRef; use ratatui::widgets::WidgetRef; @@ -13,12 +14,18 @@ use textwrap::Options; use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; +#[derive(Debug, Clone)] +struct TextElement { + range: Range, +} + #[derive(Debug)] pub(crate) struct TextArea { text: String, cursor_pos: usize, wrap_cache: RefCell>, preferred_col: Option, + elements: Vec, } #[derive(Debug, Clone)] @@ -40,6 +47,7 @@ impl TextArea { cursor_pos: 0, wrap_cache: RefCell::new(None), preferred_col: None, + elements: Vec::new(), } } @@ -48,6 +56,7 @@ impl TextArea { self.cursor_pos = self.cursor_pos.clamp(0, self.text.len()); self.wrap_cache.replace(None); self.preferred_col = None; + self.elements.clear(); } pub fn text(&self) -> &str { @@ -59,15 +68,22 @@ impl TextArea { } pub fn insert_str_at(&mut self, pos: usize, text: &str) { + let pos = self.clamp_pos_for_insertion(pos); self.text.insert_str(pos, text); self.wrap_cache.replace(None); if pos <= self.cursor_pos { self.cursor_pos += text.len(); } + self.shift_elements(pos, 0, text.len()); self.preferred_col = None; } pub fn replace_range(&mut self, range: std::ops::Range, text: &str) { + let range = self.expand_range_to_element_boundaries(range); + self.replace_range_raw(range, text); + } + + fn replace_range_raw(&mut self, range: std::ops::Range, text: &str) { assert!(range.start <= range.end); let start = range.start.clamp(0, self.text.len()); let end = range.end.clamp(0, self.text.len()); @@ -81,6 +97,7 @@ impl TextArea { self.text.replace_range(range, text); self.wrap_cache.replace(None); self.preferred_col = None; + self.update_elements_after_replace(start, end, inserted_len); // Update the cursor position to account for the edit. self.cursor_pos = if self.cursor_pos < start { @@ -94,6 +111,9 @@ impl TextArea { ((self.cursor_pos as isize) + diff) as usize } .min(self.text.len()); + + // Ensure cursor is not inside an element + self.cursor_pos = self.clamp_pos_to_nearest_boundary(self.cursor_pos); } pub fn cursor(&self) -> usize { @@ -102,6 +122,7 @@ impl TextArea { pub fn set_cursor(&mut self, pos: usize) { self.cursor_pos = pos.clamp(0, self.text.len()); + self.cursor_pos = self.clamp_pos_to_nearest_boundary(self.cursor_pos); self.preferred_col = None; } @@ -155,10 +176,13 @@ impl TextArea { width_so_far += g.width(); if width_so_far > target_col { self.cursor_pos = line_start + i; + // Avoid landing inside an element; round to nearest boundary + self.cursor_pos = self.clamp_pos_to_nearest_boundary(self.cursor_pos); return; } } self.cursor_pos = line_end; + self.cursor_pos = self.clamp_pos_to_nearest_boundary(self.cursor_pos); } fn beginning_of_line(&self, pos: usize) -> usize { @@ -178,30 +202,6 @@ impl TextArea { self.end_of_line(self.cursor_pos) } - pub(crate) fn beginning_of_previous_word(&self) -> usize { - if let Some(first_non_ws) = self.text[..self.cursor_pos].rfind(|c: char| !c.is_whitespace()) - { - self.text[..first_non_ws] - .rfind(|c: char| c.is_whitespace()) - .map(|i| i + 1) - .unwrap_or(0) - } else { - 0 - } - } - - pub(crate) fn end_of_next_word(&self) -> usize { - let Some(first_non_ws) = self.text[self.cursor_pos..].find(|c: char| !c.is_whitespace()) - else { - return self.text.len(); - }; - let word_start = self.cursor_pos + first_non_ws; - match self.text[word_start..].find(|c: char| c.is_whitespace()) { - Some(rel_idx) => word_start + rel_idx, - None => self.text.len(), - } - } - pub fn input(&mut self, event: KeyEvent) { match event { KeyEvent { @@ -385,19 +385,11 @@ impl TextArea { if n == 0 || self.cursor_pos == 0 { return; } - let mut gc = - unicode_segmentation::GraphemeCursor::new(self.cursor_pos, self.text.len(), false); let mut target = self.cursor_pos; for _ in 0..n { - match gc.prev_boundary(&self.text, 0) { - Ok(Some(b)) => target = b, - Ok(None) => { - target = 0; - break; - } - Err(_) => { - target = target.saturating_sub(1); - } + target = self.prev_atomic_boundary(target); + if target == 0 { + break; } } self.replace_range(target..self.cursor_pos, ""); @@ -407,26 +399,19 @@ impl TextArea { if n == 0 || self.cursor_pos >= self.text.len() { return; } - let mut gc = - unicode_segmentation::GraphemeCursor::new(self.cursor_pos, self.text.len(), false); let mut target = self.cursor_pos; for _ in 0..n { - match gc.next_boundary(&self.text, 0) { - Ok(Some(b)) => target = b, - Ok(None) => { - target = self.text.len(); - break; - } - Err(_) => { - target = target.saturating_add(1); - } + target = self.next_atomic_boundary(target); + if target >= self.text.len() { + break; } } self.replace_range(self.cursor_pos..target, ""); } pub fn delete_backward_word(&mut self) { - self.replace_range(self.beginning_of_previous_word()..self.cursor_pos, ""); + let start = self.beginning_of_previous_word(); + self.replace_range(start..self.cursor_pos, ""); } pub fn kill_to_end_of_line(&mut self) { @@ -453,25 +438,13 @@ impl TextArea { /// Move the cursor left by a single grapheme cluster. pub fn move_cursor_left(&mut self) { - let mut gc = - unicode_segmentation::GraphemeCursor::new(self.cursor_pos, self.text.len(), false); - match gc.prev_boundary(&self.text, 0) { - Ok(Some(boundary)) => self.cursor_pos = boundary, - Ok(None) => self.cursor_pos = 0, // Already at start. - Err(_) => self.cursor_pos = self.cursor_pos.saturating_sub(1), - } + self.cursor_pos = self.prev_atomic_boundary(self.cursor_pos); self.preferred_col = None; } /// Move the cursor right by a single grapheme cluster. pub fn move_cursor_right(&mut self) { - let mut gc = - unicode_segmentation::GraphemeCursor::new(self.cursor_pos, self.text.len(), false); - match gc.next_boundary(&self.text, 0) { - Ok(Some(boundary)) => self.cursor_pos = boundary, - Ok(None) => self.cursor_pos = self.text.len(), // Already at end. - Err(_) => self.cursor_pos = self.cursor_pos.saturating_add(1), - } + self.cursor_pos = self.next_atomic_boundary(self.cursor_pos); self.preferred_col = None; } @@ -626,6 +599,208 @@ impl TextArea { } } + // ===== Text elements support ===== + + pub fn insert_element(&mut self, text: &str) { + let start = self.clamp_pos_for_insertion(self.cursor_pos); + self.insert_str_at(start, text); + let end = start + text.len(); + self.add_element(start..end); + // Place cursor at end of inserted element + self.set_cursor(end); + } + + fn add_element(&mut self, range: Range) { + let elem = TextElement { + range: range.clone(), + }; + self.elements.push(elem); + self.elements.sort_by_key(|e| e.range.start); + } + + fn find_element_containing(&self, pos: usize) -> Option { + self.elements + .iter() + .position(|e| pos > e.range.start && pos < e.range.end) + } + + fn clamp_pos_to_nearest_boundary(&self, mut pos: usize) -> usize { + if pos > self.text.len() { + pos = self.text.len(); + } + if let Some(idx) = self.find_element_containing(pos) { + let e = &self.elements[idx]; + let dist_start = pos.saturating_sub(e.range.start); + let dist_end = e.range.end.saturating_sub(pos); + if dist_start <= dist_end { + e.range.start + } else { + e.range.end + } + } else { + pos + } + } + + fn clamp_pos_for_insertion(&self, pos: usize) -> usize { + // Do not allow inserting into the middle of an element + if let Some(idx) = self.find_element_containing(pos) { + let e = &self.elements[idx]; + // Choose closest edge for insertion + let dist_start = pos.saturating_sub(e.range.start); + let dist_end = e.range.end.saturating_sub(pos); + if dist_start <= dist_end { + e.range.start + } else { + e.range.end + } + } else { + pos + } + } + + fn expand_range_to_element_boundaries(&self, mut range: Range) -> Range { + // Expand to include any intersecting elements fully + loop { + let mut changed = false; + for e in &self.elements { + if e.range.start < range.end && e.range.end > range.start { + let new_start = range.start.min(e.range.start); + let new_end = range.end.max(e.range.end); + if new_start != range.start || new_end != range.end { + range.start = new_start; + range.end = new_end; + changed = true; + } + } + } + if !changed { + break; + } + } + range + } + + fn shift_elements(&mut self, at: usize, removed: usize, inserted: usize) { + // Generic shift: for pure insert, removed = 0; for delete, inserted = 0. + let end = at + removed; + let diff = inserted as isize - removed as isize; + // Remove elements fully deleted by the operation and shift the rest + self.elements + .retain(|e| !(e.range.start >= at && e.range.end <= end)); + for e in &mut self.elements { + if e.range.end <= at { + // before edit + } else if e.range.start >= end { + // after edit + e.range.start = ((e.range.start as isize) + diff) as usize; + e.range.end = ((e.range.end as isize) + diff) as usize; + } else { + // Overlap with element but not fully contained (shouldn't happen when using + // element-aware replace, but degrade gracefully by snapping element to new bounds) + let new_start = at.min(e.range.start); + let new_end = at + inserted.max(e.range.end.saturating_sub(end)); + e.range.start = new_start; + e.range.end = new_end; + } + } + } + + fn update_elements_after_replace(&mut self, start: usize, end: usize, inserted_len: usize) { + self.shift_elements(start, end.saturating_sub(start), inserted_len); + } + + fn prev_atomic_boundary(&self, pos: usize) -> usize { + if pos == 0 { + return 0; + } + // If currently at an element end or inside, jump to start of that element. + if let Some(idx) = self + .elements + .iter() + .position(|e| pos > e.range.start && pos <= e.range.end) + { + return self.elements[idx].range.start; + } + let mut gc = unicode_segmentation::GraphemeCursor::new(pos, self.text.len(), false); + match gc.prev_boundary(&self.text, 0) { + Ok(Some(b)) => { + if let Some(idx) = self.find_element_containing(b) { + self.elements[idx].range.start + } else { + b + } + } + Ok(None) => 0, + Err(_) => pos.saturating_sub(1), + } + } + + fn next_atomic_boundary(&self, pos: usize) -> usize { + if pos >= self.text.len() { + return self.text.len(); + } + // If currently at an element start or inside, jump to end of that element. + if let Some(idx) = self + .elements + .iter() + .position(|e| pos >= e.range.start && pos < e.range.end) + { + return self.elements[idx].range.end; + } + let mut gc = unicode_segmentation::GraphemeCursor::new(pos, self.text.len(), false); + match gc.next_boundary(&self.text, 0) { + Ok(Some(b)) => { + if let Some(idx) = self.find_element_containing(b) { + self.elements[idx].range.end + } else { + b + } + } + Ok(None) => self.text.len(), + Err(_) => pos.saturating_add(1), + } + } + + pub(crate) fn beginning_of_previous_word(&self) -> usize { + if let Some(first_non_ws) = self.text[..self.cursor_pos].rfind(|c: char| !c.is_whitespace()) + { + let candidate = self.text[..first_non_ws] + .rfind(|c: char| c.is_whitespace()) + .map(|i| i + 1) + .unwrap_or(0); + self.adjust_pos_out_of_elements(candidate, true) + } else { + 0 + } + } + + pub(crate) fn end_of_next_word(&self) -> usize { + let Some(first_non_ws) = self.text[self.cursor_pos..].find(|c: char| !c.is_whitespace()) + else { + return self.text.len(); + }; + let word_start = self.cursor_pos + first_non_ws; + let candidate = match self.text[word_start..].find(|c: char| c.is_whitespace()) { + Some(rel_idx) => word_start + rel_idx, + None => self.text.len(), + }; + self.adjust_pos_out_of_elements(candidate, false) + } + + fn adjust_pos_out_of_elements(&self, pos: usize, prefer_start: bool) -> usize { + if let Some(idx) = self.find_element_containing(pos) { + let e = &self.elements[idx]; + if prefer_start { + e.range.start + } else { + e.range.end + } + } else { + pos + } + } + #[allow(clippy::unwrap_used)] fn wrapped_lines(&self, width: u16) -> Ref<'_, Vec>> { // Ensure cache is ready (potentially mutably borrow, then drop) @@ -700,10 +875,7 @@ impl TextArea { impl WidgetRef for &TextArea { fn render_ref(&self, area: Rect, buf: &mut Buffer) { let lines = self.wrapped_lines(area.width); - for (i, ls) in lines.iter().enumerate() { - let s = &self.text[ls.start..ls.end - 1]; - buf.set_string(area.x, area.y + i as u16, s, Style::default()); - } + self.render_lines(area, buf, &lines, 0..lines.len()); } } @@ -717,10 +889,38 @@ impl StatefulWidgetRef for &TextArea { let start = scroll as usize; let end = (scroll + area.height).min(lines.len() as u16) as usize; - for (row, ls) in (start..end).enumerate() { - let r = &lines[ls]; - let s = &self.text[r.start..r.end - 1]; - buf.set_string(area.x, area.y + row as u16, s, Style::default()); + self.render_lines(area, buf, &lines, start..end); + } +} + +impl TextArea { + fn render_lines( + &self, + area: Rect, + buf: &mut Buffer, + lines: &[Range], + range: std::ops::Range, + ) { + for (row, idx) in range.enumerate() { + let r = &lines[idx]; + let y = area.y + row as u16; + let line_range = r.start..r.end - 1; + // Draw base line with default style. + buf.set_string(area.x, y, &self.text[line_range.clone()], Style::default()); + + // Overlay styled segments for elements that intersect this line. + for elem in &self.elements { + // Compute overlap with displayed slice. + let overlap_start = elem.range.start.max(line_range.start); + let overlap_end = elem.range.end.min(line_range.end); + if overlap_start >= overlap_end { + continue; + } + let styled = &self.text[overlap_start..overlap_end]; + let x_off = self.text[line_range.start..overlap_start].width() as u16; + let style = Style::default().fg(Color::Cyan); + buf.set_string(area.x + x_off, y, styled, style); + } } } } @@ -1244,6 +1444,10 @@ mod tests { for _case in 0..10_000 { let mut ta = TextArea::new(); let mut state = TextAreaState::default(); + // Track element payloads we insert. Payloads use characters '[' and ']' which + // are not produced by rand_grapheme(), avoiding accidental collisions. + let mut elem_texts: Vec = Vec::new(); + let mut next_elem_id: usize = 0; // Start with a random base string let base_len = rng.gen_range(0..30); let mut base = String::new(); @@ -1271,7 +1475,7 @@ mod tests { } // Pick an operation - match rng.gen_range(0..14) { + match rng.gen_range(0..18) { 0 => { // insert small random string at cursor let len = rng.gen_range(0..6); @@ -1299,12 +1503,24 @@ mod tests { s.push_str(&rand_grapheme(&mut rng)); } let before = ta.text().len(); + // If the chosen range intersects an element, replace_range will expand to + // element boundaries, so the naive size delta assertion does not hold. + let intersects_element = elem_texts.iter().any(|payload| { + if let Some(pstart) = ta.text().find(payload) { + let pend = pstart + payload.len(); + pstart < end && pend > start + } else { + false + } + }); ta.replace_range(start..end, &s); - let after = ta.text().len(); - assert_eq!( - after as isize, - before as isize + (s.len() as isize) - ((end - start) as isize) - ); + if !intersects_element { + let after = ta.text().len(); + assert_eq!( + after as isize, + before as isize + (s.len() as isize) - ((end - start) as isize) + ); + } } 2 => ta.delete_backward(rng.gen_range(0..=3)), 3 => ta.delete_forward(rng.gen_range(0..=3)), @@ -1317,6 +1533,66 @@ mod tests { 10 => ta.move_cursor_down(), 11 => ta.move_cursor_to_beginning_of_line(true), 12 => ta.move_cursor_to_end_of_line(true), + 13 => { + // Insert an element with a unique sentinel payload + let payload = + format!("[[EL#{}:{}]]", next_elem_id, rng.gen_range(1000..9999)); + next_elem_id += 1; + ta.insert_element(&payload); + elem_texts.push(payload); + } + 14 => { + // Try inserting inside an existing element (should clamp to boundary) + if let Some(payload) = elem_texts.choose(&mut rng).cloned() { + if let Some(start) = ta.text().find(&payload) { + let end = start + payload.len(); + if end - start > 2 { + let pos = rng.gen_range(start + 1..end - 1); + let ins = rand_grapheme(&mut rng); + ta.insert_str_at(pos, &ins); + } + } + } + } + 15 => { + // Replace a range that intersects an element -> whole element should be replaced + if let Some(payload) = elem_texts.choose(&mut rng).cloned() { + if let Some(start) = ta.text().find(&payload) { + let end = start + payload.len(); + // Create an intersecting range [start-Ξ΄, end-Ξ΄2) + let mut s = start.saturating_sub(rng.gen_range(0..=2)); + let mut e = (end + rng.gen_range(0..=2)).min(ta.text().len()); + // Align to char boundaries to satisfy String::replace_range contract + let txt = ta.text(); + while s > 0 && !txt.is_char_boundary(s) { + s -= 1; + } + while e < txt.len() && !txt.is_char_boundary(e) { + e += 1; + } + if s < e { + // Small replacement text + let mut srep = String::new(); + for _ in 0..rng.gen_range(0..=2) { + srep.push_str(&rand_grapheme(&mut rng)); + } + ta.replace_range(s..e, &srep); + } + } + } + } + 16 => { + // Try setting the cursor to a position inside an element; it should clamp out + if let Some(payload) = elem_texts.choose(&mut rng).cloned() { + if let Some(start) = ta.text().find(&payload) { + let end = start + payload.len(); + if end - start > 2 { + let pos = rng.gen_range(start + 1..end - 1); + ta.set_cursor(pos); + } + } + } + } _ => { // Jump to word boundaries if rng.gen_bool(0.5) { @@ -1332,6 +1608,21 @@ mod tests { // Sanity invariants assert!(ta.cursor() <= ta.text().len()); + // Element invariants + for payload in &elem_texts { + if let Some(start) = ta.text().find(payload) { + let end = start + payload.len(); + // 1) Text inside elements matches the initially set payload + assert_eq!(&ta.text()[start..end], payload); + // 2) Cursor is never strictly inside an element + let c = ta.cursor(); + assert!( + c <= start || c >= end, + "cursor inside element: {start}..{end} at {c}" + ); + } + } + // Render and compute cursor positions; ensure they are in-bounds and do not panic let area = Rect::new(0, 0, width, height); // Stateless render into an area tall enough for all wrapped lines diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 517a9a35f5..3fa78279ec 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -44,7 +44,9 @@ use crate::bottom_pane::BottomPaneParams; use crate::bottom_pane::CancellationEvent; use crate::bottom_pane::InputResult; use crate::exec_command::strip_bash_lc_and_escape; +use crate::history_cell; use crate::history_cell::CommandOutput; +use crate::history_cell::ExecCell; use crate::history_cell::HistoryCell; use crate::history_cell::PatchEventType; // streaming internals are provided by crate::streaming and crate::markdown_stream @@ -68,7 +70,7 @@ pub(crate) struct ChatWidget<'a> { app_event_tx: AppEventSender, codex_op_tx: UnboundedSender, bottom_pane: BottomPane<'a>, - active_exec_cell: Option, + active_exec_cell: Option, config: Config, initial_user_message: Option, total_token_usage: TokenUsage, @@ -123,7 +125,7 @@ impl ChatWidget<'_> { fn on_session_configured(&mut self, event: codex_core::protocol::SessionConfiguredEvent) { self.bottom_pane .set_history_metadata(event.history_log_id, event.history_entry_count); - self.add_to_history(HistoryCell::new_session_info(&self.config, event, true)); + self.add_to_history(&history_cell::new_session_info(&self.config, event, true)); if let Some(user_message) = self.initial_user_message.take() { self.submit_user_message(user_message); } @@ -133,6 +135,7 @@ impl ChatWidget<'_> { fn on_agent_message(&mut self, message: String) { let sink = AppEventHistorySink(self.app_event_tx.clone()); let finished = self.stream.apply_final_answer(&message, &sink); + self.last_stream_kind = Some(StreamKind::Answer); self.handle_if_stream_finished(finished); self.mark_needs_redraw(); } @@ -145,9 +148,10 @@ impl ChatWidget<'_> { self.handle_streaming_delta(StreamKind::Reasoning, delta); } - fn on_agent_reasoning_final(&mut self) { + fn on_agent_reasoning_final(&mut self, text: String) { let sink = AppEventHistorySink(self.app_event_tx.clone()); - let finished = self.stream.finalize(StreamKind::Reasoning, false, &sink); + let finished = self.stream.apply_final_reasoning(&text, &sink); + self.last_stream_kind = Some(StreamKind::Reasoning); self.handle_if_stream_finished(finished); self.mark_needs_redraw(); } @@ -162,7 +166,6 @@ impl ChatWidget<'_> { fn on_task_started(&mut self) { self.bottom_pane.clear_ctrl_c_quit_hint(); self.bottom_pane.set_task_running(true); - self.set_waiting_for_model_status(); self.stream.reset_headers_for_new_turn(); self.last_stream_kind = None; self.mark_needs_redraw(); @@ -193,14 +196,14 @@ impl ChatWidget<'_> { } fn on_error(&mut self, message: String) { - self.add_to_history(HistoryCell::new_error_event(message)); + self.add_to_history(&history_cell::new_error_event(message)); self.bottom_pane.set_task_running(false); self.stream.clear_all(); self.mark_needs_redraw(); } fn on_plan_update(&mut self, update: codex_core::plan_tool::UpdatePlanArgs) { - self.add_to_history(HistoryCell::new_plan_update(update)); + self.add_to_history(&history_cell::new_plan_update(update)); } fn on_exec_approval_request(&mut self, id: String, ev: ExecApprovalRequestEvent) { @@ -235,7 +238,7 @@ impl ChatWidget<'_> { } fn on_patch_apply_begin(&mut self, event: PatchApplyBeginEvent) { - self.add_to_history(HistoryCell::new_patch_event( + self.add_to_history(&history_cell::new_patch_event( PatchEventType::ApplyBegin { auto_approved: event.auto_approved, }, @@ -334,16 +337,9 @@ impl ChatWidget<'_> { } } - #[inline] - fn set_waiting_for_model_status(&mut self) { - self.bottom_pane - .update_status_text("waiting for model".to_string()); - } - #[inline] fn handle_streaming_delta(&mut self, kind: StreamKind, delta: String) { let sink = AppEventHistorySink(self.app_event_tx.clone()); - self.set_waiting_for_model_status(); self.stream.begin(kind, &sink); self.last_stream_kind = Some(kind); self.stream.push_and_maybe_commit(&delta, &sink); @@ -370,7 +366,7 @@ impl ChatWidget<'_> { self.active_exec_cell = None; let pending = std::mem::take(&mut self.pending_exec_completions); for (command, parsed, output) in pending { - self.add_to_history(HistoryCell::new_completed_exec_command( + self.add_to_history(&history_cell::new_completed_exec_command( command, parsed, output, )); } @@ -382,9 +378,9 @@ impl ChatWidget<'_> { event: codex_core::protocol::PatchApplyEndEvent, ) { if event.success { - self.add_to_history(HistoryCell::new_patch_apply_success(event.stdout)); + self.add_to_history(&history_cell::new_patch_apply_success(event.stdout)); } else { - self.add_to_history(HistoryCell::new_patch_apply_failure(event.stderr)); + self.add_to_history(&history_cell::new_patch_apply_failure(event.stderr)); } } @@ -400,7 +396,7 @@ impl ChatWidget<'_> { .map(|r| format!("\n{r}")) .unwrap_or_default() ); - self.add_to_history(HistoryCell::new_background_event(text)); + self.add_to_history(&history_cell::new_background_event(text)); let request = ApprovalRequest::Exec { id, @@ -417,7 +413,7 @@ impl ChatWidget<'_> { ev: ApplyPatchApprovalRequestEvent, ) { self.flush_answer_stream_with_separator(); - self.add_to_history(HistoryCell::new_patch_event( + self.add_to_history(&history_cell::new_patch_event( PatchEventType::ApprovalRequest, ev.changes.clone(), )); @@ -433,8 +429,6 @@ impl ChatWidget<'_> { pub(crate) fn handle_exec_begin_now(&mut self, ev: ExecCommandBeginEvent) { // Ensure the status indicator is visible while the command runs. - self.bottom_pane - .update_status_text("running command".to_string()); self.running_commands.insert( ev.call_id.clone(), RunningCommand { @@ -444,11 +438,11 @@ impl ChatWidget<'_> { ); // Accumulate parsed commands into a single active Exec cell so they stack match self.active_exec_cell.as_mut() { - Some(HistoryCell::Exec(exec)) => { + Some(exec) => { exec.parsed.extend(ev.parsed_cmd); } _ => { - self.active_exec_cell = Some(HistoryCell::new_active_exec_command( + self.active_exec_cell = Some(history_cell::new_active_exec_command( ev.command, ev.parsed_cmd, )); @@ -461,11 +455,11 @@ impl ChatWidget<'_> { pub(crate) fn handle_mcp_begin_now(&mut self, ev: McpToolCallBeginEvent) { self.flush_answer_stream_with_separator(); - self.add_to_history(HistoryCell::new_active_mcp_tool_call(ev.invocation)); + self.add_to_history(&history_cell::new_active_mcp_tool_call(ev.invocation)); } pub(crate) fn handle_mcp_end_now(&mut self, ev: McpToolCallEndEvent) { self.flush_answer_stream_with_separator(); - self.add_to_history(HistoryCell::new_completed_mcp_tool_call( + self.add_to_history(&*history_cell::new_completed_mcp_tool_call( 80, ev.invocation, ev.duration, @@ -562,14 +556,14 @@ impl ChatWidget<'_> { fn flush_active_exec_cell(&mut self) { if let Some(active) = self.active_exec_cell.take() { self.app_event_tx - .send(AppEvent::InsertHistory(active.plain_lines())); + .send(AppEvent::InsertHistory(active.display_lines())); } } - fn add_to_history(&mut self, cell: HistoryCell) { + fn add_to_history(&mut self, cell: &dyn HistoryCell) { self.flush_active_exec_cell(); self.app_event_tx - .send(AppEvent::InsertHistory(cell.plain_lines())); + .send(AppEvent::InsertHistory(cell.display_lines())); } fn submit_user_message(&mut self, user_message: UserMessage) { @@ -605,7 +599,7 @@ impl ChatWidget<'_> { // Only show the text portion in conversation history. if !text.is_empty() { - self.add_to_history(HistoryCell::new_user_prompt(text.clone())); + self.add_to_history(&history_cell::new_user_prompt(text.clone())); } } @@ -619,7 +613,7 @@ impl ChatWidget<'_> { | EventMsg::AgentReasoningDelta(_) | EventMsg::ExecCommandOutputDelta(_) => {} _ => { - tracing::info!("handle_codex_event: {:?}", msg); + tracing::trace!("handle_codex_event: {:?}", msg); } } @@ -633,9 +627,9 @@ impl ChatWidget<'_> { | EventMsg::AgentReasoningRawContentDelta(AgentReasoningRawContentDeltaEvent { delta, }) => self.on_agent_reasoning_delta(delta), - EventMsg::AgentReasoning(AgentReasoningEvent { .. }) - | EventMsg::AgentReasoningRawContent(AgentReasoningRawContentEvent { .. }) => { - self.on_agent_reasoning_final() + EventMsg::AgentReasoning(AgentReasoningEvent { text }) + | EventMsg::AgentReasoningRawContent(AgentReasoningRawContentEvent { text }) => { + self.on_agent_reasoning_final(text) } EventMsg::AgentReasoningSectionBreak(_) => self.on_reasoning_section_break(), EventMsg::TaskStarted => self.on_task_started(), @@ -666,30 +660,23 @@ impl ChatWidget<'_> { } } - /// Update the live log preview while a task is running. - pub(crate) fn update_latest_log(&mut self, line: String) { - if self.bottom_pane.is_task_running() { - self.bottom_pane.update_status_text(line); - } - } - fn request_redraw(&mut self) { self.app_event_tx.send(AppEvent::RequestRedraw); } pub(crate) fn add_diff_output(&mut self, diff_output: String) { - self.add_to_history(HistoryCell::new_diff_output(diff_output.clone())); + self.add_to_history(&history_cell::new_diff_output(diff_output.clone())); } pub(crate) fn add_status_output(&mut self) { - self.add_to_history(HistoryCell::new_status_output( + self.add_to_history(&history_cell::new_status_output( &self.config, &self.total_token_usage, )); } pub(crate) fn add_prompts_output(&mut self) { - self.add_to_history(HistoryCell::new_prompts_output()); + self.add_to_history(&history_cell::new_prompts_output()); } /// Forward file-search results to the bottom pane. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap new file mode 100644 index 0000000000..8258ea0b28 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__deltas_then_same_final_message_are_rendered_snapshot.snap @@ -0,0 +1,10 @@ +--- +source: tui/src/chatwidget/tests.rs +assertion_line: 886 +expression: combined +--- +thinking +I will first analyze the request. + +codex +Here is the result. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__final_reasoning_then_message_without_deltas_are_rendered.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__final_reasoning_then_message_without_deltas_are_rendered.snap new file mode 100644 index 0000000000..c90ec2733d --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__final_reasoning_then_message_without_deltas_are_rendered.snap @@ -0,0 +1,9 @@ +--- +source: tui/src/chatwidget/tests.rs +expression: combined +--- +thinking +I will first analyze the request. + +codex +Here is the result. diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 0a7dd93368..3336024272 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -12,6 +12,7 @@ use codex_core::plan_tool::UpdatePlanArgs; use codex_core::protocol::AgentMessageDeltaEvent; use codex_core::protocol::AgentMessageEvent; use codex_core::protocol::AgentReasoningDeltaEvent; +use codex_core::protocol::AgentReasoningEvent; use codex_core::protocol::ApplyPatchApprovalRequestEvent; use codex_core::protocol::Event; use codex_core::protocol::EventMsg; @@ -24,6 +25,7 @@ use codex_core::protocol::TaskCompleteEvent; use crossterm::event::KeyCode; use crossterm::event::KeyEvent; use crossterm::event::KeyModifiers; +use insta::assert_snapshot; use pretty_assertions::assert_eq; use std::fs::File; use std::io::BufRead; @@ -204,7 +206,7 @@ fn exec_history_cell_shows_working_then_completed() { command: vec!["bash".into(), "-lc".into(), "echo done".into()], cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), parsed_cmd: vec![codex_core::parse_command::ParsedCommand::Unknown { - cmd: vec!["echo".into(), "done".into()], + cmd: "echo done".into(), }], }), }); @@ -246,7 +248,7 @@ fn exec_history_cell_shows_working_then_failed() { command: vec!["bash".into(), "-lc".into(), "false".into()], cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")), parsed_cmd: vec![codex_core::parse_command::ParsedCommand::Unknown { - cmd: vec!["false".into()], + cmd: "false".into(), }], }), }); @@ -413,46 +415,6 @@ async fn binary_size_transcript_matches_ideal_fixture() { assert_eq!(visible_after, ideal); } -#[test] -fn final_longer_answer_after_single_char_delta_is_complete() { - let (mut chat, rx, _op_rx) = make_chatwidget_manual(); - - // Simulate a stray delta without newline (e.g., punctuation). - chat.handle_codex_event(Event { - id: "sub-x".into(), - msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { delta: "?".into() }), - }); - - // Now send the full final answer with no newline. - let full = "Hi! How can I help with codex-rs today? Want me to explore the repo, run tests, or work on a specific change?"; - chat.handle_codex_event(Event { - id: "sub-x".into(), - msg: EventMsg::AgentMessage(AgentMessageEvent { - message: full.into(), - }), - }); - - // Drain and assert the full message appears in history. - let cells = drain_insert_history(&rx); - let mut found = false; - for lines in &cells { - let s = lines - .iter() - .flat_map(|l| l.spans.iter()) - .map(|sp| sp.content.clone()) - .collect::(); - if s.contains(full) { - found = true; - break; - } - } - assert!( - found, - "expected full final message to be flushed to history, cells={:?}", - cells.len() - ); -} - #[test] fn apply_patch_events_emit_history_cells() { let (mut chat, rx, _op_rx) = make_chatwidget_manual(); @@ -923,3 +885,91 @@ fn multiple_agent_messages_in_single_turn_emit_multiple_headers() { let second_idx = combined.find("Second message").unwrap(); assert!(first_idx < second_idx, "messages out of order: {combined}"); } + +#[test] +fn final_reasoning_then_message_without_deltas_are_rendered() { + let (mut chat, rx, _op_rx) = make_chatwidget_manual(); + + // No deltas; only final reasoning followed by final message. + chat.handle_codex_event(Event { + id: "s1".into(), + msg: EventMsg::AgentReasoning(AgentReasoningEvent { + text: "I will first analyze the request.".into(), + }), + }); + chat.handle_codex_event(Event { + id: "s1".into(), + msg: EventMsg::AgentMessage(AgentMessageEvent { + message: "Here is the result.".into(), + }), + }); + + // Drain history and snapshot the combined visible content. + let cells = drain_insert_history(&rx); + let combined = cells + .iter() + .map(|lines| lines_to_single_string(lines)) + .collect::(); + assert_snapshot!(combined); +} + +#[test] +fn deltas_then_same_final_message_are_rendered_snapshot() { + let (mut chat, rx, _op_rx) = make_chatwidget_manual(); + + // Stream some reasoning deltas first. + chat.handle_codex_event(Event { + id: "s1".into(), + msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent { + delta: "I will ".into(), + }), + }); + chat.handle_codex_event(Event { + id: "s1".into(), + msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent { + delta: "first analyze the ".into(), + }), + }); + chat.handle_codex_event(Event { + id: "s1".into(), + msg: EventMsg::AgentReasoningDelta(AgentReasoningDeltaEvent { + delta: "request.".into(), + }), + }); + chat.handle_codex_event(Event { + id: "s1".into(), + msg: EventMsg::AgentReasoning(AgentReasoningEvent { + text: "request.".into(), + }), + }); + + // Then stream answer deltas, followed by the exact same final message. + chat.handle_codex_event(Event { + id: "s1".into(), + msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { + delta: "Here is the ".into(), + }), + }); + chat.handle_codex_event(Event { + id: "s1".into(), + msg: EventMsg::AgentMessageDelta(AgentMessageDeltaEvent { + delta: "result.".into(), + }), + }); + + chat.handle_codex_event(Event { + id: "s1".into(), + msg: EventMsg::AgentMessage(AgentMessageEvent { + message: "Here is the result.".into(), + }), + }); + + // Snapshot the combined visible content to ensure we render as expected + // when deltas are followed by the identical final message. + let cells = drain_insert_history(&rx); + let combined = cells + .iter() + .map(|lines| lines_to_single_string(lines)) + .collect::(); + assert_snapshot!(combined); +} diff --git a/codex-rs/tui/src/diff_render.rs b/codex-rs/tui/src/diff_render.rs index ada84b89d6..5a3199c04b 100644 --- a/codex-rs/tui/src/diff_render.rs +++ b/codex-rs/tui/src/diff_render.rs @@ -143,7 +143,7 @@ pub(crate) fn create_diff_summary( spans.push(RtSpan::raw(")")); let mut line = RtLine::from(spans); - let prefix = if idx == 0 { " ⎿ " } else { " " }; + let prefix = if idx == 0 { " β”” " } else { " " }; line.spans.insert(0, prefix.into()); line.spans .iter_mut() @@ -270,13 +270,14 @@ fn push_wrapped_diff_line( // Reserve a fixed number of spaces after the line number so that content starts // at a consistent column. The sign ("+"/"-") is rendered as part of the content - // with the same background as the edit, not as a separate dimmed column. + // and colored with the same foreground as the edited text, not as a separate + // dimmed column. let gap_after_ln = SPACES_AFTER_LINE_NUMBER.saturating_sub(ln_str.len()); let first_prefix_cols = indent.len() + ln_str.len() + gap_after_ln; let cont_prefix_cols = indent.len() + ln_str.len() + gap_after_ln; let mut first = true; - let (sign_opt, bg_style) = match kind { + let (sign_opt, line_style) = match kind { DiffLineType::Insert => (Some('+'), Some(style_add())), DiffLineType::Delete => (Some('-'), Some(style_del())), DiffLineType::Context => (None, None), @@ -307,18 +308,22 @@ fn push_wrapped_diff_line( spans.push(RtSpan::raw(" ".repeat(gap_after_ln))); // Prefix the content with the sign if it is an insertion or deletion, and color - // the sign with the same background as the edited text. + // the sign and content with the same foreground as the edited text. let display_chunk = match sign_opt { Some(sign_char) => format!("{sign_char}{chunk}"), None => chunk.to_string(), }; - let content_span = match bg_style { + let content_span = match line_style { Some(style) => RtSpan::styled(display_chunk, style), None => RtSpan::raw(display_chunk), }; spans.push(content_span); - lines.push(RtLine::from(spans)); + let mut line = RtLine::from(spans); + if let Some(style) = line_style { + line.style = line.style.patch(style); + } + lines.push(line); first = false; } else { let hang_prefix = format!( @@ -326,11 +331,15 @@ fn push_wrapped_diff_line( " ".repeat(ln_str.len()), " ".repeat(gap_after_ln) ); - let content_span = match bg_style { + let content_span = match line_style { Some(style) => RtSpan::styled(chunk.to_string(), style), None => RtSpan::raw(chunk.to_string()), }; - lines.push(RtLine::from(vec![RtSpan::raw(hang_prefix), content_span])); + let mut line = RtLine::from(vec![RtSpan::raw(hang_prefix), content_span]); + if let Some(style) = line_style { + line.style = line.style.patch(style); + } + lines.push(line); } } lines @@ -341,30 +350,33 @@ fn style_dim() -> Style { } fn style_add() -> Style { - Style::default().bg(Color::Green) + Style::default().fg(Color::Green) } fn style_del() -> Style { - Style::default().bg(Color::Red) + Style::default().fg(Color::Red) } #[allow(clippy::expect_used)] #[cfg(test)] mod tests { use super::*; - use crate::history_cell::HistoryCell; - use crate::text_block::TextBlock; use insta::assert_snapshot; use ratatui::Terminal; use ratatui::backend::TestBackend; + use ratatui::text::Text; + use ratatui::widgets::Paragraph; + use ratatui::widgets::WidgetRef; + use ratatui::widgets::Wrap; fn snapshot_lines(name: &str, lines: Vec>, width: u16, height: u16) { let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("terminal"); - let cell = HistoryCell::PendingPatch { - view: TextBlock::new(lines), - }; terminal - .draw(|f| f.render_widget_ref(&cell, f.area())) + .draw(|f| { + Paragraph::new(Text::from(lines)) + .wrap(Wrap { trim: false }) + .render_ref(f.area(), f.buffer_mut()) + }) .expect("draw"); assert_snapshot!(name, terminal.backend()); } diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 865a97a5f0..a56f2998fd 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -3,7 +3,6 @@ use crate::diff_render::create_diff_summary; use crate::exec_command::relativize_to_home; use crate::exec_command::strip_bash_lc_and_escape; use crate::slash_command::SlashCommand; -use crate::text_block::TextBlock; use crate::text_formatting::format_and_truncate_tool_result; use base64::Engine; use codex_ansi_escape::ansi_escape_line; @@ -38,6 +37,7 @@ use std::collections::HashMap; use std::io::Cursor; use std::path::PathBuf; use std::time::Duration; +use std::time::Instant; use tracing::error; #[derive(Clone)] @@ -52,18 +52,28 @@ pub(crate) enum PatchEventType { ApplyBegin { auto_approved: bool }, } -fn span_to_static(span: &Span) -> Span<'static> { - Span { - style: span.style, - content: std::borrow::Cow::Owned(span.content.clone().into_owned()), +/// Represents an event to display in the conversation history. Returns its +/// `Vec>` representation to make it easier to display in a +/// scrollable list. +pub(crate) trait HistoryCell { + fn display_lines(&self) -> Vec>; + + fn desired_height(&self, width: u16) -> u16 { + Paragraph::new(Text::from(self.display_lines())) + .wrap(Wrap { trim: false }) + .line_count(width) + .try_into() + .unwrap_or(0) } } -fn line_to_static(line: &Line) -> Line<'static> { - Line { - style: line.style, - alignment: line.alignment, - spans: line.spans.iter().map(span_to_static).collect(), +pub(crate) struct PlainHistoryCell { + lines: Vec>, +} + +impl HistoryCell for PlainHistoryCell { + fn display_lines(&self) -> Vec> { + self.lines.clone() } } @@ -71,93 +81,37 @@ pub(crate) struct ExecCell { pub(crate) command: Vec, pub(crate) parsed: Vec, pub(crate) output: Option, + start_time: Option, +} +impl HistoryCell for ExecCell { + fn display_lines(&self) -> Vec> { + exec_command_lines( + &self.command, + &self.parsed, + self.output.as_ref(), + self.start_time, + ) + } } -/// Represents an event to display in the conversation history. Returns its -/// `Vec>` representation to make it easier to display in a -/// scrollable list. -pub(crate) enum HistoryCell { - /// Welcome message. - WelcomeMessage { - view: TextBlock, - }, +impl WidgetRef for &ExecCell { + fn render_ref(&self, area: Rect, buf: &mut Buffer) { + Paragraph::new(Text::from(self.display_lines())) + .wrap(Wrap { trim: false }) + .render(area, buf); + } +} - /// Message from the user. - UserPrompt { - view: TextBlock, - }, - - Exec(ExecCell), - - /// An MCP tool call that has not finished yet. - ActiveMcpToolCall { - view: TextBlock, - }, - - /// Completed MCP tool call where we show the result serialized as JSON. - CompletedMcpToolCall { - view: TextBlock, - }, - - /// Completed MCP tool call where the result is an image. - /// Admittedly, [mcp_types::CallToolResult] can have multiple content types, - /// which could be a mix of text and images, so we need to tighten this up. - // NOTE: For image output we keep the *original* image around and lazily - // compute a resized copy that fits the available cell width. Caching the - // resized version avoids doing the potentially expensive rescale twice - // because the scroll-view first calls `height()` for layouting and then - // `render_window()` for painting. - CompletedMcpToolCallWithImageOutput { - _image: DynamicImage, - }, - - /// Background event. - BackgroundEvent { - view: TextBlock, - }, - - /// Output from the `/diff` command. - GitDiffOutput { - view: TextBlock, - }, - - /// Output from the `/status` command. - StatusOutput { - view: TextBlock, - }, - - /// Output from the `/prompts` command. - PromptsOutput { - view: TextBlock, - }, - - /// Error event from the backend. - ErrorEvent { - view: TextBlock, - }, - - /// Info describing the newly-initialized session. - SessionInfo { - view: TextBlock, - }, - - /// A pending code patch that is awaiting user approval. Mirrors the - /// behaviour of `ExecCell` so the user sees *what* patch the - /// model wants to apply before being prompted to approve or deny it. - PendingPatch { - view: TextBlock, - }, - - /// A human‑friendly rendering of the model's current plan and step - /// statuses provided via the `update_plan` tool. - PlanUpdate { - view: TextBlock, - }, - - /// Result of applying a patch (success or failure) with optional output. - PatchApplyResult { - view: TextBlock, - }, +struct CompletedMcpToolCallWithImageOutput { + _image: DynamicImage, +} +impl HistoryCell for CompletedMcpToolCallWithImageOutput { + fn display_lines(&self) -> Vec> { + vec![ + Line::from("tool result (image output omitted)"), + Line::from(""), + ] + } } const TOOL_CALL_MAX_LINES: usize = 5; @@ -183,771 +137,705 @@ fn pretty_provider_name(id: &str) -> String { } } -impl HistoryCell { - /// Return a cloned, plain representation of the cell's lines suitable for - /// one‑shot insertion into the terminal scrollback. Image cells are - /// represented with a simple placeholder. - /// These lines are also rendered directly by ratatui wrapped in a Paragraph. - pub(crate) fn plain_lines(&self) -> Vec> { - match self { - HistoryCell::WelcomeMessage { view } - | HistoryCell::UserPrompt { view } - | HistoryCell::BackgroundEvent { view } - | HistoryCell::GitDiffOutput { view } - | HistoryCell::StatusOutput { view } - | HistoryCell::PromptsOutput { view } - | HistoryCell::ErrorEvent { view } - | HistoryCell::SessionInfo { view } - | HistoryCell::CompletedMcpToolCall { view } - | HistoryCell::PendingPatch { view } - | HistoryCell::PlanUpdate { view } - | HistoryCell::PatchApplyResult { view } - | HistoryCell::ActiveMcpToolCall { view, .. } => { - view.lines.iter().map(line_to_static).collect() - } - HistoryCell::Exec(ExecCell { - command, - parsed, - output, - }) => HistoryCell::exec_command_lines(command, parsed, output.as_ref()), - HistoryCell::CompletedMcpToolCallWithImageOutput { .. } => vec![ - Line::from("tool result (image output omitted)"), - Line::from(""), - ], - } - } +pub(crate) fn new_background_event(message: String) -> PlainHistoryCell { + let mut lines: Vec> = Vec::new(); + lines.push(Line::from("event".dim())); + lines.extend(message.lines().map(|line| ansi_escape_line(line).dim())); + lines.push(Line::from("")); + PlainHistoryCell { lines } +} - pub(crate) fn new_background_event(message: String) -> Self { - let mut lines: Vec> = Vec::new(); - lines.push(Line::from("event".dim())); - lines.extend(message.lines().map(|line| ansi_escape_line(line).dim())); - lines.push(Line::from("")); - HistoryCell::BackgroundEvent { - view: TextBlock::new(lines), - } - } - - pub(crate) fn desired_height(&self, width: u16) -> u16 { - Paragraph::new(Text::from(self.plain_lines())) - .wrap(Wrap { trim: false }) - .line_count(width) - .try_into() - .unwrap_or(0) - } - - pub(crate) fn new_session_info( - config: &Config, - event: SessionConfiguredEvent, - is_first_event: bool, - ) -> Self { - let SessionConfiguredEvent { - model, - session_id: _, - history_log_id: _, - history_entry_count: _, - } = event; - if is_first_event { - let cwd_str = match relativize_to_home(&config.cwd) { - Some(rel) if !rel.as_os_str().is_empty() => format!("~/{}", rel.display()), - Some(_) => "~".to_string(), - None => config.cwd.display().to_string(), - }; - - let agents_path = find_project_doc_sync(&config.cwd).unwrap_or_default(); - - let mut lines: Vec> = vec![ - Line::from(vec![ - Span::raw(">_ ").dim(), - Span::styled( - "You are using OpenAI Codex in", - Style::default().add_modifier(Modifier::BOLD), - ), - Span::raw(format!(" {cwd_str}")).dim(), - ]), - Line::from(""), - ]; - if let Some(p) = &agents_path { - let instructions_display_path = diff_paths(p, &config.cwd) - .map(|rel| rel.display().to_string()) - .unwrap_or_else(|| p.display().to_string()); - lines.push(Line::from(vec![ - " Found ".dim(), - instructions_display_path.into(), - ".".dim(), - ])); - lines.push(Line::from("")); - } - lines.push(Line::from( - " To get started, describe a task or try one of these commands:".dim(), - )); - lines.push(Line::from("")); - if agents_path.is_none() { - lines.push(Line::from( - format!(" /init - {}", SlashCommand::Init.description()).dim(), - )); - } - lines.push(Line::from( - format!(" /status - {}", SlashCommand::Status.description()).dim(), - )); - lines.push(Line::from( - format!(" /diff - {}", SlashCommand::Diff.description()).dim(), - )); - lines.push(Line::from( - format!(" /prompts - {}", SlashCommand::Prompts.description()).dim(), - )); - lines.push(Line::from("".dim())); - HistoryCell::WelcomeMessage { - view: TextBlock::new(lines), - } - } else if config.model == model { - HistoryCell::SessionInfo { - view: TextBlock::new(Vec::new()), - } - } else { - let lines = vec![ - Line::from("model changed:".magenta().bold()), - Line::from(format!("requested: {}", config.model)), - Line::from(format!("used: {model}")), - Line::from(""), - ]; - HistoryCell::SessionInfo { - view: TextBlock::new(lines), - } - } - } - - pub(crate) fn new_user_prompt(message: String) -> Self { - let mut lines: Vec> = Vec::new(); - lines.push(Line::from("user".cyan().bold())); - lines.extend(message.lines().map(|l| Line::from(l.to_string()))); - lines.push(Line::from("")); - - HistoryCell::UserPrompt { - view: TextBlock::new(lines), - } - } - - pub(crate) fn new_active_exec_command( - command: Vec, - parsed: Vec, - ) -> Self { - HistoryCell::new_exec_cell(command, parsed, None) - } - - pub(crate) fn new_completed_exec_command( - command: Vec, - parsed: Vec, - output: CommandOutput, - ) -> Self { - HistoryCell::new_exec_cell(command, parsed, Some(output)) - } - - fn new_exec_cell( - command: Vec, - parsed: Vec, - output: Option, - ) -> Self { - HistoryCell::Exec(ExecCell { - command, - parsed, - output, - }) - } - - fn exec_command_lines( - command: &[String], - parsed: &[ParsedCommand], - output: Option<&CommandOutput>, - ) -> Vec> { - match parsed.is_empty() { - true => HistoryCell::new_exec_command_generic(command, output), - false => HistoryCell::new_parsed_command(parsed, output), - } - } - - fn new_parsed_command( - parsed_commands: &[ParsedCommand], - output: Option<&CommandOutput>, - ) -> Vec> { - let mut lines: Vec = vec![match output { - None => Line::from("βš™οΈŽ Working".magenta().bold()), - Some(o) if o.exit_code == 0 => Line::from("βœ“ Completed".green().bold()), - Some(o) => Line::from(format!("βœ— Failed (exit {})", o.exit_code).red().bold()), - }]; - - for (i, parsed) in parsed_commands.iter().enumerate() { - let text = match parsed { - ParsedCommand::Read { name, .. } => format!("πŸ“– {name}"), - ParsedCommand::ListFiles { cmd, path } => match path { - Some(p) => format!("πŸ“‚ {p}"), - None => format!("πŸ“‚ {}", shlex_join_safe(cmd)), - }, - ParsedCommand::Search { query, path, cmd } => match (query, path) { - (Some(q), Some(p)) => format!("πŸ”Ž {q} in {p}"), - (Some(q), None) => format!("πŸ”Ž {q}"), - (None, Some(p)) => format!("πŸ”Ž {p}"), - (None, None) => format!("πŸ”Ž {}", shlex_join_safe(cmd)), - }, - ParsedCommand::Format { .. } => "✨ Formatting".to_string(), - ParsedCommand::Test { cmd } => format!("πŸ§ͺ {}", shlex_join_safe(cmd)), - ParsedCommand::Lint { cmd, .. } => format!("🧹 {}", shlex_join_safe(cmd)), - ParsedCommand::Unknown { cmd } => format!("⌨️ {}", shlex_join_safe(cmd)), - }; - - let first_prefix = if i == 0 { " L " } else { " " }; - for (j, line_text) in text.lines().enumerate() { - let prefix = if j == 0 { first_prefix } else { " " }; - lines.push(Line::from(vec![ - Span::styled(prefix, Style::default().add_modifier(Modifier::DIM)), - Span::styled(line_text.to_string(), Style::default().fg(LIGHT_BLUE)), - ])); - } - } - - lines.extend(output_lines(output, true, false)); - lines.push(Line::from("")); - - lines - } - - fn new_exec_command_generic( - command: &[String], - output: Option<&CommandOutput>, - ) -> Vec> { - let mut lines: Vec> = Vec::new(); - let command_escaped = strip_bash_lc_and_escape(command); - let mut cmd_lines = command_escaped.lines(); - if let Some(first) = cmd_lines.next() { - lines.push(Line::from(vec![ - "⚑ Running ".to_string().magenta(), - first.to_string().into(), - ])); - } else { - lines.push(Line::from("⚑ Running".to_string().magenta())); - } - for cont in cmd_lines { - lines.push(Line::from(cont.to_string())); - } - - lines.extend(output_lines(output, false, true)); - - lines - } - - pub(crate) fn new_active_mcp_tool_call(invocation: McpInvocation) -> Self { - let title_line = Line::from(vec!["tool".magenta(), " running...".dim()]); - let lines: Vec = vec![ - title_line, - format_mcp_invocation(invocation.clone()), - Line::from(""), - ]; - - HistoryCell::ActiveMcpToolCall { - view: TextBlock::new(lines), - } - } - - /// If the first content is an image, return a new cell with the image. - /// TODO(rgwood-dd): Handle images properly even if they're not the first result. - fn try_new_completed_mcp_tool_call_with_image_output( - result: &Result, - ) -> Option { - match result { - Ok(mcp_types::CallToolResult { content, .. }) => { - if let Some(mcp_types::ContentBlock::ImageContent(image)) = content.first() { - let raw_data = - match base64::engine::general_purpose::STANDARD.decode(&image.data) { - Ok(data) => data, - Err(e) => { - error!("Failed to decode image data: {e}"); - return None; - } - }; - let reader = match ImageReader::new(Cursor::new(raw_data)).with_guessed_format() - { - Ok(reader) => reader, - Err(e) => { - error!("Failed to guess image format: {e}"); - return None; - } - }; - - let image = match reader.decode() { - Ok(image) => image, - Err(e) => { - error!("Image decoding failed: {e}"); - return None; - } - }; - - Some(HistoryCell::CompletedMcpToolCallWithImageOutput { _image: image }) - } else { - None - } - } - _ => None, - } - } - - pub(crate) fn new_completed_mcp_tool_call( - num_cols: usize, - invocation: McpInvocation, - duration: Duration, - success: bool, - result: Result, - ) -> Self { - if let Some(cell) = Self::try_new_completed_mcp_tool_call_with_image_output(&result) { - return cell; - } - - let duration = format_duration(duration); - let status_str = if success { "success" } else { "failed" }; - let title_line = Line::from(vec![ - "tool".magenta(), - " ".into(), - if success { - status_str.green() - } else { - status_str.red() - }, - format!(", duration: {duration}").gray(), - ]); - - let mut lines: Vec> = Vec::new(); - lines.push(title_line); - lines.push(format_mcp_invocation(invocation)); - - match result { - Ok(mcp_types::CallToolResult { content, .. }) => { - if !content.is_empty() { - lines.push(Line::from("")); - - for tool_call_result in content { - let line_text = match tool_call_result { - mcp_types::ContentBlock::TextContent(text) => { - format_and_truncate_tool_result( - &text.text, - TOOL_CALL_MAX_LINES, - num_cols, - ) - } - mcp_types::ContentBlock::ImageContent(_) => { - // TODO show images even if they're not the first result, will require a refactor of `CompletedMcpToolCall` - "".to_string() - } - mcp_types::ContentBlock::AudioContent(_) => { - "