From 8dcbd29edd5f204d47efa06560981cd089d21f7b Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Thu, 13 Nov 2025 07:51:28 -0800 Subject: [PATCH 01/20] chore(core) Update prompt for gpt-5.1 (#6588) ## Summary Updates the prompt for GPT-5.1 --- codex-rs/core/gpt_5_1_prompt.md | 132 +++++++++++++++++++++++--------- 1 file changed, 96 insertions(+), 36 deletions(-) diff --git a/codex-rs/core/gpt_5_1_prompt.md b/codex-rs/core/gpt_5_1_prompt.md index e4590c386d..5a424dd0f6 100644 --- a/codex-rs/core/gpt_5_1_prompt.md +++ b/codex-rs/core/gpt_5_1_prompt.md @@ -1,4 +1,4 @@ -You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful. +You are GPT-5.1 running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful. Your capabilities: @@ -26,17 +26,28 @@ Your default personality and tone is concise, direct, and friendly. You communic - Direct system/developer/user instructions (as part of a prompt) take precedence over AGENTS.md instructions. - The contents of the AGENTS.md file at the root of the repo and any directories from the CWD up to the root are included with the developer message and don't need to be re-read. When working in a subdirectory of CWD, or a directory outside the CWD, check for any AGENTS.md files that may be applicable. +## Autonomy and Persistence +Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you. + +Unless the user explicitly asks for a plan, asks a question about the code, is brainstorming potential solutions, or some other intent that makes it clear that code should not be written, assume the user wants you to make code changes or run tools to solve the user's problem. In these cases, it's bad to output your proposed solution in a message, you should go ahead and actually implement the change. If you encounter challenges or blockers, you should attempt to resolve them yourself. + ## Responsiveness -### Preamble messages +### User Updates Spec +You'll work for stretches with tool calls — it's critical to keep the user updated as you work. -Before making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples: +Frequency & Length: +- Send short updates (1–2 sentences) whenever there is a meaningful, important insight you need to share with the user to keep them informed. +- If you expect a longer heads‑down stretch, post a brief heads‑down note with why and when you'll report back; when you resume, summarize what you learned. +- Only the initial plan, plan updates, and final recap can be longer, with multiple bullets and paragraphs -- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each. -- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words for quick updates). -- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions. -- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging. -- **Exception**: Avoid adding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action. +Tone: +- Friendly, confident, senior-engineer energy. Positive, collaborative, humble; fix mistakes quickly. + +Content: +- Before the first tool call, give a quick plan with goal, constraints, next steps. +- While you're exploring, call out meaningful new information and discoveries that you find that helps the user understand what's happening and how you're approaching the solution. +- If you change the plan (e.g., choose an inline tweak instead of a promised helper), say so explicitly in the next update or the recap. **Examples:** @@ -59,6 +70,8 @@ Do not repeat the full contents of the plan after an `update_plan` call — the Before running a command, consider whether or not you have completed the previous step, and make sure to mark it as completed before moving on to the next step. It may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. Sometimes, you may need to change plans in the middle of a task: call `update_plan` with the updated plan and make sure to provide an `explanation` of the rationale when doing so. +Maintain statuses in the tool: exactly one item in_progress at a time; mark items complete when done; post timely status transitions. Do not jump an item from pending to completed: always set it to in_progress first. Do not batch-complete multiple items after the fact. Finish with all items completed or explicitly canceled/deferred before ending the turn. Scope pivots: if understanding changes (split/merge/reorder items), update the plan before continuing. Do not let the plan go stale while coding. + Use a plan when: - The task is non-trivial and will require multiple actions over a long time horizon. @@ -122,14 +135,14 @@ If you need to write a plan, only write high quality plans, not low quality ones ## Task execution -You are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer. +You are a coding agent. You must keep going until the query or task is completely resolved, before ending your turn and yielding back to the user. Persist until the task is fully handled end-to-end within the current turn whenever feasible and persevere even when function calls fail. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer. You MUST adhere to the following criteria when solving queries: - Working on the repo(s) in the current environment is allowed, even if they are proprietary. - Analyzing code for vulnerabilities is allowed. - Showing user code and tool call details is allowed. -- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`): {"command":["apply_patch","*** Begin Patch\\n*** Update File: path/to/file.py\\n@@ def example():\\n- pass\\n+ return 123\\n*** End Patch"]} +- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`). This is a FREEFORM tool, so do not wrap the patch in JSON. If completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines: @@ -146,44 +159,46 @@ If completing the user's task requires writing or modifying files, your code and - Do not use one-letter variable names unless explicitly requested. - NEVER output inline citations like "【F:README.md†L5-L14】" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor. -## Sandbox and approvals +## Codex CLI harness, sandboxing, and approvals -The Codex CLI harness supports several different sandboxing, and approval configurations that the user can choose from. +The Codex CLI harness supports several different configurations for sandboxing and escalation approvals that the user can choose from. -Filesystem sandboxing prevents you from editing files without user approval. The options are: +Filesystem sandboxing defines which files can be read or written. The options for `sandbox_mode` are: +- **read-only**: The sandbox only permits reading files. +- **workspace-write**: The sandbox permits reading files, and editing files in `cwd` and `writable_roots`. Editing files in other directories requires approval. +- **danger-full-access**: No filesystem sandboxing - all commands are permitted. -- **read-only**: You can only read files. -- **workspace-write**: You can read files. You can write to files in your workspace folder, but not outside it. -- **danger-full-access**: No filesystem sandboxing. - -Network sandboxing prevents you from accessing network without approval. Options are - -- **restricted** -- **enabled** - -Approvals are your mechanism to get user consent to perform more privileged actions. Although they introduce friction to the user because your work is paused until the user responds, you should leverage them to accomplish your important work. Do not let these settings or the sandbox deter you from attempting to accomplish the user's task. Approval options are +Network sandboxing defines whether network can be accessed without approval. Options for `network_access` are: +- **restricted**: Requires approval +- **enabled**: No approval needed +Approvals are your mechanism to get user consent to run shell commands without the sandbox. Possible configuration options for `approval_policy` are - **untrusted**: The harness will escalate most commands for user approval, apart from a limited allowlist of safe "read" commands. - **on-failure**: The harness will allow all commands to run in the sandbox (if enabled), and failures will be escalated to the user for approval to run again without the sandbox. -- **on-request**: Commands will be run in the sandbox by default, and you can specify in your tool call if you want to escalate a command to run without sandboxing. (Note that this mode is not always available. If it is, you'll see parameters for it in the `shell` command description.) -- **never**: This is a non-interactive mode where you may NEVER ask the user for approval to run commands. Instead, you must always persist and work around constraints to solve the task for the user. You MUST do your utmost best to finish the task and validate your work before yielding. If this mode is pared with `danger-full-access`, take advantage of it to deliver the best outcome for the user. Further, in this mode, your default testing philosophy is overridden: Even if you don't see local patterns for testing, you may add tests and scripts to validate your work. Just remove them before yielding. +- **on-request**: Commands will be run in the sandbox by default, and you can specify in your tool call if you want to escalate a command to run without sandboxing. (Note that this mode is not always available. If it is, you'll see parameters for escalating in the tool definition.) +- **never**: This is a non-interactive mode where you may NEVER ask the user for approval to run commands. Instead, you must always persist and work around constraints to solve the task for the user. You MUST do your utmost best to finish the task and validate your work before yielding. If this mode is paired with `danger-full-access`, take advantage of it to deliver the best outcome for the user. Further, in this mode, your default testing philosophy is overridden: Even if you don't see local patterns for testing, you may add tests and scripts to validate your work. Just remove them before yielding. -When you are running with approvals `on-request`, and sandboxing enabled, here are scenarios where you'll need to request approval: - -- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /tmp) +When you are running with `approval_policy == on-request`, and sandboxing enabled, here are scenarios where you'll need to request approval: +- You need to run a command that writes to a directory that requires it (e.g. running tests that write to /var) - You need to run a GUI app (e.g., open/xdg-open/osascript) to open browsers or files. - You are running sandboxed and need to run a command that requires network access (e.g. installing packages) -- If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with approval. +- If you run a command that is important to solving the user's query, but it fails because of sandboxing, rerun the command with approval. ALWAYS proceed to use the `with_escalated_permissions` and `justification` parameters. Within this harness, prefer requesting approval via the tool over asking in natural language. - You are about to take a potentially destructive action such as an `rm` or `git reset` that the user did not explicitly ask for -- (For all of these, you should weigh alternative paths that do not require approval.) +- (for all of these, you should weigh alternative paths that do not require approval) -Note that when sandboxing is set to read-only, you'll need to request approval for any command that isn't a read. +When `sandbox_mode` is set to read-only, you'll need to request approval for any command that isn't a read. -You will be told what filesystem sandboxing, network sandboxing, and approval mode are active in a developer or user message. If you are not told about this, assume that you are running with workspace-write, network sandboxing ON, and approval on-failure. +You will be told what filesystem sandboxing, network sandboxing, and approval mode are active in a developer or user message. If you are not told about this, assume that you are running with workspace-write, network sandboxing enabled, and approval on-failure. + +Although they introduce friction to the user because your work is paused until the user responds, you should leverage them when necessary to accomplish important work. If the completing the task requires escalated permissions, Do not let these settings or the sandbox deter you from attempting to accomplish the user's task unless it is set to "never", in which case never ask for approvals. + +When requesting approval to execute a command that will require escalated privileges: + - Provide the `with_escalated_permissions` parameter with the boolean value true + - Include a short, 1 sentence explanation for why you need to enable `with_escalated_permissions` in the justification parameter ## Validating your work -If the codebase has tests or the ability to build or run, consider using them to verify that your work is complete. +If the codebase has tests or the ability to build or run, consider using them to verify changes once your work is complete. When testing, your philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests. @@ -193,7 +208,7 @@ For all of testing, running, building, and formatting, do not attempt to fix unr Be mindful of whether to run validation commands proactively. In the absence of behavioral guidance: -- When running in non-interactive approval modes like **never** or **on-failure**, proactively run tests, lint and do whatever you need to ensure you've completed the task. +- When running in non-interactive approval modes like **never** or **on-failure**, you can proactively run tests, lint and do whatever you need to ensure you've completed the task. If you are unable to run tests, you must still do your utmost best to complete the task. - When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first. - When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task. @@ -219,7 +234,7 @@ Your final message should read naturally, like an update from a concise teammate You can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation. -The user is working on the same computer as you, and has access to your work. As such there's no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using `apply_patch`, there's no need to tell users to "save the file" or "copy the code into a file"—just reference the file path. +The user is working on the same computer as you, and has access to your work. As such there's no need to show the contents of files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using `apply_patch`, there's no need to tell users to "save the file" or "copy the code into a file"—just reference the file path. If there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly. @@ -247,7 +262,7 @@ You are producing plain text that will later be styled by the CLI. Follow these **Monospace** -- Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``). +- Wrap all commands, file paths, env vars, code identifiers, and code samples in backticks (`` `...` ``). - Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command. - Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``). @@ -278,6 +293,13 @@ When referencing files in your response, make sure to include the relevant start - Keep descriptions self-contained; don’t refer to “above” or “below”. - Use parallel structure in lists for consistency. +**Verbosity** +- Final answer compactness rules (enforced): + - Tiny/small single-file change (≤ ~10 lines): 2–5 sentences or ≤3 bullets. No headings. 0–1 short snippet (≤3 lines) only if essential. + - Medium change (single area or a few files): ≤6 bullets or 6–10 sentences. At most 1–2 short snippets total (≤8 lines each). + - Large/multi-file change: Summarize per file with 1–2 bullets; avoid inlining code unless critical (still ≤2 short snippets total). + - Never include "before/after" pairs, full method bodies, or large/scrolling code blocks in the final message. Prefer referencing file/symbol names instead. + **Don’t** - Don’t use literal words “bold” or “monospace” in the content. @@ -296,9 +318,47 @@ For casual greetings, acknowledgements, or other one-off conversational messages When using the shell, you must adhere to the following guidelines: +- The arguments to `shell` will be passed to execvp(). +- Always set the `workdir` param when using the shell function. Do not use `cd` unless absolutely necessary. - When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.) - Read files in chunks with a max chunk size of 250 lines. Do not use python scripts to attempt to output larger chunks of a file. Command line output will be truncated after 10 kilobytes or 256 lines of output, regardless of the command used. +## apply_patch + +Use the `apply_patch` tool to edit files. Your patch language is a stripped‑down, file‑oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high‑level envelope: + +*** Begin Patch +[ one or more file sections ] +*** End Patch + +Within that envelope, you get a sequence of file operations. +You MUST include a header to specify the action you are taking. +Each operation starts with one of three headers: + +*** Add File: - create a new file. Every following line is a + line (the initial contents). +*** Delete File: - remove an existing file. Nothing follows. +*** Update File: - patch an existing file in place (optionally with a rename). + +Example patch: + +``` +*** Begin Patch +*** Add File: hello.txt ++Hello world +*** Update File: src/app.py +*** Move to: src/main.py +@@ def greet(): +-print("Hi") ++print("Hello, world!") +*** Delete File: obsolete.txt +*** End Patch +``` + +It is important to remember: + +- You must include a header with your intended action (Add/Delete/Update) +- You must prefix new lines with `+` even when creating a new file + ## `update_plan` A tool named `update_plan` is available to you. You can use it to keep an up‑to‑date, step‑by‑step plan for the task. From 2a417c47ac79b55d9eabfd95781cf08386d5c22d Mon Sep 17 00:00:00 2001 From: jif-oai Date: Thu, 13 Nov 2025 15:54:03 +0000 Subject: [PATCH 02/20] feat: proxy context left after compaction (#6597) --- codex-rs/core/src/codex.rs | 31 +++++++++ codex-rs/core/src/compact.rs | 9 +++ codex-rs/core/src/context_manager/history.rs | 35 ++++++++-- codex-rs/core/src/state/session.rs | 4 ++ codex-rs/core/tests/suite/compact.rs | 67 ++++++++++++++++++++ 5 files changed, 142 insertions(+), 4 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index c3573a99ae..273f7a4975 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -96,6 +96,7 @@ use crate::protocol::StreamErrorEvent; use crate::protocol::Submission; use crate::protocol::TokenCountEvent; use crate::protocol::TokenUsage; +use crate::protocol::TokenUsageInfo; use crate::protocol::TurnDiffEvent; use crate::protocol::WarningEvent; use crate::rollout::RolloutRecorder; @@ -1082,6 +1083,36 @@ impl Session { self.send_token_count_event(turn_context).await; } + pub(crate) async fn override_last_token_usage_estimate( + &self, + turn_context: &TurnContext, + estimated_total_tokens: i64, + ) { + { + let mut state = self.state.lock().await; + let mut info = state.token_info().unwrap_or(TokenUsageInfo { + total_token_usage: TokenUsage::default(), + last_token_usage: TokenUsage::default(), + model_context_window: None, + }); + + info.last_token_usage = TokenUsage { + input_tokens: 0, + cached_input_tokens: 0, + output_tokens: 0, + reasoning_output_tokens: 0, + total_tokens: estimated_total_tokens.max(0), + }; + + if info.model_context_window.is_none() { + info.model_context_window = turn_context.client.get_model_context_window(); + } + + state.set_token_info(Some(info)); + } + self.send_token_count_event(turn_context).await; + } + pub(crate) async fn update_rate_limits( &self, turn_context: &TurnContext, diff --git a/codex-rs/core/src/compact.rs b/codex-rs/core/src/compact.rs index baee20f0f9..a1c0533047 100644 --- a/codex-rs/core/src/compact.rs +++ b/codex-rs/core/src/compact.rs @@ -153,6 +153,15 @@ async fn run_compact_task_inner( new_history.extend(ghost_snapshots); sess.replace_history(new_history).await; + if let Some(estimated_tokens) = sess + .clone_history() + .await + .estimate_token_count(&turn_context) + { + sess.override_last_token_usage_estimate(&turn_context, estimated_tokens) + .await; + } + let rollout_item = RolloutItem::Compacted(CompactedItem { message: summary_text.clone(), }); diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index da9157124b..07ff54ad1c 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -1,13 +1,14 @@ +use crate::codex::TurnContext; +use crate::context_manager::normalize; +use crate::context_manager::truncate::format_output_for_model_body; +use crate::context_manager::truncate::globally_truncate_function_output_items; use codex_protocol::models::FunctionCallOutputPayload; use codex_protocol::models::ResponseItem; use codex_protocol::protocol::TokenUsage; use codex_protocol::protocol::TokenUsageInfo; +use codex_utils_tokenizer::Tokenizer; use std::ops::Deref; -use crate::context_manager::normalize; -use crate::context_manager::truncate::format_output_for_model_body; -use crate::context_manager::truncate::globally_truncate_function_output_items; - /// Transcript of conversation history #[derive(Debug, Clone, Default)] pub(crate) struct ContextManager { @@ -28,6 +29,10 @@ impl ContextManager { self.token_info.clone() } + pub(crate) fn set_token_info(&mut self, info: Option) { + self.token_info = info; + } + pub(crate) fn set_token_usage_full(&mut self, context_window: i64) { match &mut self.token_info { Some(info) => info.fill_to_context_window(context_window), @@ -68,6 +73,28 @@ impl ContextManager { history } + // Estimate the number of tokens in the history. Return None if no tokenizer + // is available. This does not consider the reasoning traces. + // /!\ The value is a lower bound estimate and does not represent the exact + // context length. + pub(crate) fn estimate_token_count(&self, turn_context: &TurnContext) -> Option { + let model = turn_context.client.get_model(); + let tokenizer = Tokenizer::for_model(model.as_str()).ok()?; + let model_family = turn_context.client.get_model_family(); + + Some( + self.items + .iter() + .map(|item| { + serde_json::to_string(&item) + .map(|item| tokenizer.count(&item)) + .unwrap_or_default() + }) + .sum::() + + tokenizer.count(model_family.base_instructions.as_str()), + ) + } + pub(crate) fn remove_first_item(&mut self) { if !self.items.is_empty() { // Remove the oldest item (front of the list). Items are ordered from diff --git a/codex-rs/core/src/state/session.rs b/codex-rs/core/src/state/session.rs index 054d485b0f..5b630d5ce9 100644 --- a/codex-rs/core/src/state/session.rs +++ b/codex-rs/core/src/state/session.rs @@ -42,6 +42,10 @@ impl SessionState { self.history.replace(items); } + pub(crate) fn set_token_info(&mut self, info: Option) { + self.history.set_token_info(info); + } + // Token/rate limit helpers pub(crate) fn update_token_info_from_usage( &mut self, diff --git a/codex-rs/core/tests/suite/compact.rs b/codex-rs/core/tests/suite/compact.rs index 7b2fd6a217..9560a3ee9e 100644 --- a/codex-rs/core/tests/suite/compact.rs +++ b/codex-rs/core/tests/suite/compact.rs @@ -14,6 +14,7 @@ use codex_protocol::user_input::UserInput; use core_test_support::load_default_config_for_test; use core_test_support::skip_if_no_network; use core_test_support::wait_for_event; +use core_test_support::wait_for_event_match; use std::collections::VecDeque; use tempfile::TempDir; @@ -366,6 +367,72 @@ async fn manual_compact_uses_custom_prompt() { assert!(!found_default_prompt, "default prompt should be replaced"); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn manual_compact_emits_estimated_token_usage_event() { + skip_if_no_network!(); + + let server = start_mock_server().await; + + // Compact run where the API reports zero tokens in usage. Our local + // estimator should still compute a non-zero context size for the compacted + // history. + let sse_compact = sse(vec![ + ev_assistant_message("m1", SUMMARY_TEXT), + ev_completed_with_tokens("r1", 0), + ]); + mount_sse_once(&server, sse_compact).await; + + let model_provider = ModelProviderInfo { + base_url: Some(format!("{}/v1", server.uri())), + ..built_in_model_providers()["openai"].clone() + }; + let home = TempDir::new().unwrap(); + let mut config = load_default_config_for_test(&home); + config.model_provider = model_provider; + set_test_compact_prompt(&mut config); + + let conversation_manager = ConversationManager::with_auth(CodexAuth::from_api_key("dummy")); + let NewConversation { + conversation: codex, + .. + } = conversation_manager.new_conversation(config).await.unwrap(); + + // Trigger manual compact and collect TokenCount events for the compact turn. + codex.submit(Op::Compact).await.unwrap(); + + // First TokenCount: from the compact API call (usage.total_tokens = 0). + let first = wait_for_event_match(&codex, |ev| match ev { + EventMsg::TokenCount(tc) => tc + .info + .as_ref() + .map(|info| info.last_token_usage.total_tokens), + _ => None, + }) + .await; + + // Second TokenCount: from the local post-compaction estimate. + let last = wait_for_event_match(&codex, |ev| match ev { + EventMsg::TokenCount(tc) => tc + .info + .as_ref() + .map(|info| info.last_token_usage.total_tokens), + _ => None, + }) + .await; + + // Ensure the compact task itself completes. + wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; + + assert_eq!( + first, 0, + "expected first TokenCount from compact API usage to be zero" + ); + assert!( + last > 0, + "second TokenCount should reflect a non-zero estimated context size after compaction" + ); +} + // Windows CI only: bump to 4 workers to prevent SSE/event starvation and test timeouts. #[cfg_attr(windows, tokio::test(flavor = "multi_thread", worker_threads = 4))] #[cfg_attr(not(windows), tokio::test(flavor = "multi_thread", worker_threads = 2))] From ba74cee6f7d057fecba024aedb22a17f673bbf3f Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 13 Nov 2025 08:09:13 -0800 Subject: [PATCH 03/20] fix model picker wrapping (#6589) Previously the popup measured rows using the full content width while the renderer drew them with 2 columns of padding, so at certain widths the layout allocated too little vertical space and hid the third option. Now both desired_height and render call a shared helper that subtracts the padding before measuring, so the height we reserve always matches what we draw and the menu doesn't drops entries. https://github.com/user-attachments/assets/59058fd9-1e34-4325-b5fe-fc888dfcb6bc --- .../src/bottom_pane/list_selection_view.rs | 193 +++++++++++++++++- ..._list_selection_model_picker_width_80.snap | 13 ++ ...selection_narrow_width_preserves_rows.snap | 16 ++ 3 files changed, 212 insertions(+), 10 deletions(-) create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_model_picker_width_80.snap create mode 100644 codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_narrow_width_preserves_rows.snap diff --git a/codex-rs/tui/src/bottom_pane/list_selection_view.rs b/codex-rs/tui/src/bottom_pane/list_selection_view.rs index 44d7b26402..88fbaf5b53 100644 --- a/codex-rs/tui/src/bottom_pane/list_selection_view.rs +++ b/codex-rs/tui/src/bottom_pane/list_selection_view.rs @@ -250,6 +250,10 @@ impl ListSelectionView { pub(crate) fn take_last_selected_index(&mut self) -> Option { self.last_selected_actual_idx.take() } + + fn rows_width(total_width: u16) -> u16 { + total_width.saturating_sub(2) + } } impl BottomPaneView for ListSelectionView { @@ -327,8 +331,13 @@ impl Renderable for ListSelectionView { // Measure wrapped height for up to MAX_POPUP_ROWS items at the given width. // Build the same display rows used by the renderer so wrapping math matches. let rows = self.build_rows(); - - let rows_height = measure_rows_height(&rows, &self.state, MAX_POPUP_ROWS, width); + let rows_width = Self::rows_width(width); + let rows_height = measure_rows_height( + &rows, + &self.state, + MAX_POPUP_ROWS, + rows_width.saturating_add(1), + ); // Subtract 4 for the padding on the left and right of the header. let mut height = self.header.desired_height(width.saturating_sub(4)); @@ -362,8 +371,13 @@ impl Renderable for ListSelectionView { // Subtract 4 for the padding on the left and right of the header. .desired_height(content_area.width.saturating_sub(4)); let rows = self.build_rows(); - let rows_height = - measure_rows_height(&rows, &self.state, MAX_POPUP_ROWS, content_area.width); + let rows_width = Self::rows_width(content_area.width); + let rows_height = measure_rows_height( + &rows, + &self.state, + MAX_POPUP_ROWS, + rows_width.saturating_add(1), + ); let [header_area, _, search_area, list_area] = Layout::vertical([ Constraint::Max(header_height), Constraint::Max(1), @@ -398,18 +412,18 @@ impl Renderable for ListSelectionView { } if list_area.height > 0 { - let list_area = Rect { - x: list_area.x - 2, + let render_area = Rect { + x: list_area.x.saturating_sub(2), y: list_area.y, - width: list_area.width + 2, + width: rows_width.max(1), height: list_area.height, }; render_rows( - list_area, + render_area, buf, &rows, &self.state, - list_area.height as usize, + render_area.height as usize, "no matches", ); } @@ -467,7 +481,10 @@ mod tests { } fn render_lines(view: &ListSelectionView) -> String { - let width = 48; + render_lines_with_width(view, 48) + } + + fn render_lines_with_width(view: &ListSelectionView, width: u16) -> String { let height = view.desired_height(width); let area = Rect::new(0, 0, width, height); let mut buf = Buffer::empty(area); @@ -535,4 +552,160 @@ mod tests { "expected search query line to include rendered query, got {lines:?}" ); } + + #[test] + fn width_changes_do_not_hide_rows() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let items = vec![ + SelectionItem { + name: "gpt-5.1-codex".to_string(), + description: Some( + "Optimized for Codex. Balance of reasoning quality and coding ability." + .to_string(), + ), + is_current: true, + dismiss_on_select: true, + ..Default::default() + }, + SelectionItem { + name: "gpt-5.1-codex-mini".to_string(), + description: Some( + "Optimized for Codex. Cheaper, faster, but less capable.".to_string(), + ), + dismiss_on_select: true, + ..Default::default() + }, + SelectionItem { + name: "gpt-4.1-codex".to_string(), + description: Some( + "Legacy model. Use when you need compatibility with older automations." + .to_string(), + ), + dismiss_on_select: true, + ..Default::default() + }, + ]; + let view = ListSelectionView::new( + SelectionViewParams { + title: Some("Select Model and Effort".to_string()), + items, + ..Default::default() + }, + tx, + ); + let mut missing: Vec = Vec::new(); + for width in 60..=90 { + let rendered = render_lines_with_width(&view, width); + if !rendered.contains("3.") { + missing.push(width); + } + } + assert!( + missing.is_empty(), + "third option missing at widths {missing:?}" + ); + } + + #[test] + fn narrow_width_keeps_all_rows_visible() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let desc = "x".repeat(10); + let items: Vec = (1..=3) + .map(|idx| SelectionItem { + name: format!("Item {idx}"), + description: Some(desc.clone()), + dismiss_on_select: true, + ..Default::default() + }) + .collect(); + let view = ListSelectionView::new( + SelectionViewParams { + title: Some("Debug".to_string()), + items, + ..Default::default() + }, + tx, + ); + let rendered = render_lines_with_width(&view, 24); + assert!( + rendered.contains("3."), + "third option missing for width 24:\n{rendered}" + ); + } + + #[test] + fn snapshot_model_picker_width_80() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let items = vec![ + SelectionItem { + name: "gpt-5.1-codex".to_string(), + description: Some( + "Optimized for Codex. Balance of reasoning quality and coding ability." + .to_string(), + ), + is_current: true, + dismiss_on_select: true, + ..Default::default() + }, + SelectionItem { + name: "gpt-5.1-codex-mini".to_string(), + description: Some( + "Optimized for Codex. Cheaper, faster, but less capable.".to_string(), + ), + dismiss_on_select: true, + ..Default::default() + }, + SelectionItem { + name: "gpt-4.1-codex".to_string(), + description: Some( + "Legacy model. Use when you need compatibility with older automations." + .to_string(), + ), + dismiss_on_select: true, + ..Default::default() + }, + ]; + let view = ListSelectionView::new( + SelectionViewParams { + title: Some("Select Model and Effort".to_string()), + items, + ..Default::default() + }, + tx, + ); + assert_snapshot!( + "list_selection_model_picker_width_80", + render_lines_with_width(&view, 80) + ); + } + + #[test] + fn snapshot_narrow_width_preserves_third_option() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let desc = "x".repeat(10); + let items: Vec = (1..=3) + .map(|idx| SelectionItem { + name: format!("Item {idx}"), + description: Some(desc.clone()), + dismiss_on_select: true, + ..Default::default() + }) + .collect(); + let view = ListSelectionView::new( + SelectionViewParams { + title: Some("Debug".to_string()), + items, + ..Default::default() + }, + tx, + ); + assert_snapshot!( + "list_selection_narrow_width_preserves_rows", + render_lines_with_width(&view, 24) + ); + } } diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_model_picker_width_80.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_model_picker_width_80.snap new file mode 100644 index 0000000000..be81978c89 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_model_picker_width_80.snap @@ -0,0 +1,13 @@ +--- +source: tui/src/bottom_pane/list_selection_view.rs +expression: "render_lines_with_width(&view, 80)" +--- + + Select Model and Effort + +› 1. gpt-5.1-codex (current) Optimized for Codex. Balance of reasoning + quality and coding ability. + 2. gpt-5.1-codex-mini Optimized for Codex. Cheaper, faster, but less + capable. + 3. gpt-4.1-codex Legacy model. Use when you need compatibility + with older automations. diff --git a/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_narrow_width_preserves_rows.snap b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_narrow_width_preserves_rows.snap new file mode 100644 index 0000000000..3ce6a3c45f --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/snapshots/codex_tui__bottom_pane__list_selection_view__tests__list_selection_narrow_width_preserves_rows.snap @@ -0,0 +1,16 @@ +--- +source: tui/src/bottom_pane/list_selection_view.rs +expression: "render_lines_with_width(&view, 24)" +--- + + Debug + +› 1. Item 1 + xxxxxxxxx + x + 2. Item 2 + xxxxxxxxx + x + 3. Item 3 + xxxxxxxxx + x From d28e9122146af52f3ea3266cea117155a63d6b81 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 13 Nov 2025 08:28:09 -0800 Subject: [PATCH 04/20] Overhaul shell detection and centralize command generation for unified exec (#6577) This fixes command display for unified exec. All `cd`s and `ls`es are now parsed. image Deletes a ton of tests that were doing nothing from shell.rs. --------- Co-authored-by: Pavel Krymets --- codex-rs/core/src/bash.rs | 24 +- .../src/command_safety/is_safe_command.rs | 10 +- codex-rs/core/src/command_safety/mod.rs | 1 - codex-rs/core/src/environment_context.rs | 2 - codex-rs/core/src/shell.rs | 553 +++++++----------- codex-rs/core/src/tools/events.rs | 8 +- codex-rs/core/src/tools/handlers/shell.rs | 23 +- .../core/src/tools/handlers/unified_exec.rs | 22 +- codex-rs/core/src/unified_exec/mod.rs | 12 +- .../core/src/unified_exec/session_manager.rs | 26 +- codex-rs/core/tests/suite/unified_exec.rs | 15 +- 11 files changed, 284 insertions(+), 412 deletions(-) diff --git a/codex-rs/core/src/bash.rs b/codex-rs/core/src/bash.rs index edeebaba37..0ffb8e785e 100644 --- a/codex-rs/core/src/bash.rs +++ b/codex-rs/core/src/bash.rs @@ -1,8 +1,13 @@ +use std::path::PathBuf; + use tree_sitter::Node; use tree_sitter::Parser; use tree_sitter::Tree; use tree_sitter_bash::LANGUAGE as BASH; +use crate::shell::ShellType; +use crate::shell::detect_shell_type; + /// Parse the provided bash source using tree-sitter-bash, returning a Tree on /// success or None if parsing failed. pub fn try_parse_shell(shell_lc_arg: &str) -> Option { @@ -88,23 +93,16 @@ pub fn try_parse_word_only_commands_sequence(tree: &Tree, src: &str) -> Option bool { - if shell == "bash" || shell == "zsh" { - return true; - } - - let shell_name = std::path::Path::new(shell) - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or(shell); - matches!(shell_name, "bash" | "zsh") -} - pub fn extract_bash_command(command: &[String]) -> Option<(&str, &str)> { let [shell, flag, script] = command else { return None; }; - if !matches!(flag.as_str(), "-lc" | "-c") || !is_well_known_sh_shell(shell) { + if !matches!(flag.as_str(), "-lc" | "-c") + || !matches!( + detect_shell_type(&PathBuf::from(shell)), + Some(ShellType::Zsh) | Some(ShellType::Bash) + ) + { return None; } Some((shell, script)) diff --git a/codex-rs/core/src/command_safety/is_safe_command.rs b/codex-rs/core/src/command_safety/is_safe_command.rs index ba3eb6ba7d..ab084c191b 100644 --- a/codex-rs/core/src/command_safety/is_safe_command.rs +++ b/codex-rs/core/src/command_safety/is_safe_command.rs @@ -1,4 +1,5 @@ use crate::bash::parse_shell_lc_plain_commands; +use crate::command_safety::windows_safe_commands::is_safe_command_windows; pub fn is_known_safe_command(command: &[String]) -> bool { let command: Vec = command @@ -11,12 +12,9 @@ pub fn is_known_safe_command(command: &[String]) -> bool { } }) .collect(); - #[cfg(target_os = "windows")] - { - use super::windows_safe_commands::is_safe_command_windows; - if is_safe_command_windows(&command) { - return true; - } + + if is_safe_command_windows(&command) { + return true; } if is_safe_to_call_with_exec(&command) { diff --git a/codex-rs/core/src/command_safety/mod.rs b/codex-rs/core/src/command_safety/mod.rs index 8279d67952..caf5c9f6ea 100644 --- a/codex-rs/core/src/command_safety/mod.rs +++ b/codex-rs/core/src/command_safety/mod.rs @@ -1,4 +1,3 @@ pub mod is_dangerous_command; pub mod is_safe_command; -#[cfg(target_os = "windows")] pub mod windows_safe_commands; diff --git a/codex-rs/core/src/environment_context.rs b/codex-rs/core/src/environment_context.rs index e7b2e19ffb..6db2bb8f52 100644 --- a/codex-rs/core/src/environment_context.rs +++ b/codex-rs/core/src/environment_context.rs @@ -329,7 +329,6 @@ mod tests { Some(workspace_write_policy(vec!["/repo"], false)), Some(Shell::Bash(BashShell { shell_path: "/bin/bash".into(), - bashrc_path: "/home/user/.bashrc".into(), })), ); let context2 = EnvironmentContext::new( @@ -338,7 +337,6 @@ mod tests { Some(workspace_write_policy(vec!["/repo"], false)), Some(Shell::Zsh(ZshShell { shell_path: "/bin/zsh".into(), - zshrc_path: "/home/user/.zshrc".into(), })), ); diff --git a/codex-rs/core/src/shell.rs b/codex-rs/core/src/shell.rs index 90f6c6b97a..60c1b41239 100644 --- a/codex-rs/core/src/shell.rs +++ b/codex-rs/core/src/shell.rs @@ -2,22 +2,26 @@ use serde::Deserialize; use serde::Serialize; use std::path::PathBuf; +#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] +pub enum ShellType { + Zsh, + Bash, + PowerShell, +} + #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct ZshShell { - pub(crate) shell_path: String, - pub(crate) zshrc_path: String, + pub(crate) shell_path: PathBuf, } #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct BashShell { - pub(crate) shell_path: String, - pub(crate) bashrc_path: String, + pub(crate) shell_path: PathBuf, } #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct PowerShellConfig { - pub(crate) exe: String, // Executable name or path, e.g. "pwsh" or "powershell.exe". - pub(crate) bash_exe_fallback: Option, // In case the model generates a bash command. + pub(crate) shell_path: PathBuf, // Executable name or path, e.g. "pwsh" or "powershell.exe". } #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] @@ -36,7 +40,10 @@ impl Shell { .file_name() .map(|s| s.to_string_lossy().to_string()) } - Shell::PowerShell(ps) => Some(ps.exe.clone()), + Shell::PowerShell(ps) => ps + .shell_path + .file_stem() + .map(|s| s.to_string_lossy().to_string()), Shell::Unknown => None, } } @@ -47,10 +54,17 @@ impl Shell { match self { Shell::Zsh(ZshShell { shell_path, .. }) | Shell::Bash(BashShell { shell_path, .. }) => { let arg = if use_login_shell { "-lc" } else { "-c" }; - vec![shell_path.clone(), arg.to_string(), command.to_string()] + vec![ + shell_path.to_string_lossy().to_string(), + arg.to_string(), + command.to_string(), + ] } Shell::PowerShell(ps) => { - let mut args = vec![ps.exe.clone(), "-NoLogo".to_string()]; + let mut args = vec![ + ps.shell_path.to_string_lossy().to_string(), + "-NoLogo".to_string(), + ]; if !use_login_shell { args.push("-NoProfile".to_string()); } @@ -65,7 +79,7 @@ impl Shell { } #[cfg(unix)] -fn detect_default_user_shell() -> Shell { +fn get_user_shell_path() -> Option { use libc::getpwuid; use libc::getuid; use std::ffi::CStr; @@ -78,75 +92,164 @@ fn detect_default_user_shell() -> Shell { let shell_path = CStr::from_ptr((*pw).pw_shell) .to_string_lossy() .into_owned(); - let home_path = CStr::from_ptr((*pw).pw_dir).to_string_lossy().into_owned(); + Some(PathBuf::from(shell_path)) + } else { + None + } + } +} - if shell_path.ends_with("/zsh") { - return Shell::Zsh(ZshShell { - shell_path, - zshrc_path: format!("{home_path}/.zshrc"), - }); - } +#[cfg(not(unix))] +fn get_user_shell_path() -> Option { + None +} - if shell_path.ends_with("/bash") { - return Shell::Bash(BashShell { - shell_path, - bashrc_path: format!("{home_path}/.bashrc"), - }); +fn file_exists(path: &PathBuf) -> Option { + if std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) { + Some(PathBuf::from(path)) + } else { + None + } +} + +fn get_shell_path( + shell_type: ShellType, + binary_name: &str, + fallback_paths: Vec<&str>, +) -> Option { + // Check if the shell we are trying to load is user's default shell + // if just use it + + let default_shell_path = get_user_shell_path(); + if let Some(default_shell_path) = default_shell_path + && detect_shell_type(&default_shell_path) == Some(shell_type) + { + return Some(default_shell_path); + } + + if let Ok(path) = which::which(binary_name) { + return Some(path); + } + + for path in fallback_paths { + //check exists + if let Some(path) = file_exists(&PathBuf::from(path)) { + return Some(path); + } + } + + None +} + +fn get_zsh_shell() -> Option { + let shell_path = get_shell_path(ShellType::Zsh, "zsh", vec!["/bin/zsh"]); + + shell_path.map(|shell_path| ZshShell { shell_path }) +} + +fn get_bash_shell() -> Option { + let shell_path = get_shell_path(ShellType::Bash, "bash", vec!["/bin/bash"]); + + shell_path.map(|shell_path| BashShell { shell_path }) +} + +fn get_powershell_shell() -> Option { + let shell_path = get_shell_path(ShellType::PowerShell, "pwsh", vec!["/usr/local/bin/pwsh"]) + .or_else(|| get_shell_path(ShellType::PowerShell, "powershell", vec![])); + + shell_path.map(|shell_path| PowerShellConfig { shell_path }) +} + +pub fn get_shell_by_model_provided_path(shell_path: &PathBuf) -> Shell { + detect_shell_type(shell_path) + .and_then(get_shell) + .unwrap_or(Shell::Unknown) +} + +pub fn get_shell(shell_type: ShellType) -> Option { + match shell_type { + ShellType::Zsh => get_zsh_shell().map(Shell::Zsh), + ShellType::Bash => get_bash_shell().map(Shell::Bash), + ShellType::PowerShell => get_powershell_shell().map(Shell::PowerShell), + } +} + +pub fn detect_shell_type(shell_path: &PathBuf) -> Option { + match shell_path.as_os_str().to_str() { + Some("zsh") => Some(ShellType::Zsh), + Some("bash") => Some(ShellType::Bash), + Some("pwsh") => Some(ShellType::PowerShell), + Some("powershell") => Some(ShellType::PowerShell), + _ => { + let shell_name = shell_path.file_stem(); + + if let Some(shell_name) = shell_name + && shell_name != shell_path + { + detect_shell_type(&PathBuf::from(shell_name)) + } else { + None } } } - Shell::Unknown } -#[cfg(unix)] pub async fn default_user_shell() -> Shell { - detect_default_user_shell() -} - -#[cfg(target_os = "windows")] -pub async fn default_user_shell() -> Shell { - use tokio::process::Command; - - // Prefer PowerShell 7+ (`pwsh`) if available, otherwise fall back to Windows PowerShell. - let has_pwsh = Command::new("pwsh") - .arg("-NoLogo") - .arg("-NoProfile") - .arg("-Command") - .arg("$PSVersionTable.PSVersion.Major") - .output() - .await - .map(|o| o.status.success()) - .unwrap_or(false); - let bash_exe = if Command::new("bash.exe") - .arg("--version") - .stdin(std::process::Stdio::null()) - .output() - .await - .ok() - .map(|o| o.status.success()) - .unwrap_or(false) - { - which::which("bash.exe").ok() + if cfg!(windows) { + get_shell(ShellType::PowerShell).unwrap_or(Shell::Unknown) } else { - None - }; - - if has_pwsh { - Shell::PowerShell(PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: bash_exe, - }) - } else { - Shell::PowerShell(PowerShellConfig { - exe: "powershell.exe".to_string(), - bash_exe_fallback: bash_exe, - }) + get_user_shell_path() + .and_then(|shell| detect_shell_type(&shell)) + .and_then(get_shell) + .unwrap_or(Shell::Unknown) } } -#[cfg(all(not(target_os = "windows"), not(unix)))] -pub async fn default_user_shell() -> Shell { - Shell::Unknown +#[cfg(test)] +mod detect_shell_type_tests { + use super::*; + + #[test] + fn test_detect_shell_type() { + assert_eq!( + detect_shell_type(&PathBuf::from("zsh")), + Some(ShellType::Zsh) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("bash")), + Some(ShellType::Bash) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("pwsh")), + Some(ShellType::PowerShell) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("powershell")), + Some(ShellType::PowerShell) + ); + assert_eq!(detect_shell_type(&PathBuf::from("fish")), None); + assert_eq!(detect_shell_type(&PathBuf::from("other")), None); + assert_eq!( + detect_shell_type(&PathBuf::from("/bin/zsh")), + Some(ShellType::Zsh) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("/bin/bash")), + Some(ShellType::Bash) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("powershell.exe")), + Some(ShellType::PowerShell) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("pwsh.exe")), + Some(ShellType::PowerShell) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("/usr/local/bin/pwsh")), + Some(ShellType::PowerShell) + ); + } } #[cfg(test)] @@ -156,6 +259,30 @@ mod tests { use std::path::PathBuf; use std::process::Command; + #[test] + #[cfg(target_os = "macos")] + fn detects_zsh() { + let zsh_shell = get_shell(ShellType::Zsh).unwrap(); + + let ZshShell { shell_path } = match zsh_shell { + Shell::Zsh(zsh_shell) => zsh_shell, + _ => panic!("expected zsh shell"), + }; + + assert_eq!(shell_path, PathBuf::from("/bin/zsh")); + } + + #[test] + fn detects_bash() { + let bash_shell = get_shell(ShellType::Bash).unwrap(); + let BashShell { shell_path } = match bash_shell { + Shell::Bash(bash_shell) => bash_shell, + _ => panic!("expected bash shell"), + }; + + assert_eq!(shell_path, PathBuf::from("/bin/bash")); + } + #[tokio::test] async fn test_current_shell_detects_zsh() { let shell = Command::new("sh") @@ -164,292 +291,42 @@ mod tests { .output() .unwrap(); - let home = std::env::var("HOME").unwrap(); let shell_path = String::from_utf8_lossy(&shell.stdout).trim().to_string(); if shell_path.ends_with("/zsh") { assert_eq!( default_user_shell().await, Shell::Zsh(ZshShell { - shell_path: shell_path.to_string(), - zshrc_path: format!("{home}/.zshrc",), + shell_path: PathBuf::from(shell_path), }) ); } } - - #[tokio::test] - async fn test_run_with_profile_bash_escaping_and_execution() { - let shell_path = "/bin/bash"; - - let cases = vec![ - ( - vec!["myecho"], - vec![shell_path, "-lc", "source BASHRC_PATH && (myecho)"], - Some("It works!\n"), - ), - ( - vec!["bash", "-lc", "echo 'single' \"double\""], - vec![ - shell_path, - "-lc", - "source BASHRC_PATH && (echo 'single' \"double\")", - ], - Some("single double\n"), - ), - ]; - - for (input, expected_cmd, expected_output) in cases { - use std::collections::HashMap; - - use crate::exec::ExecParams; - use crate::exec::SandboxType; - use crate::exec::process_exec_tool_call; - use crate::protocol::SandboxPolicy; - - let temp_home = tempfile::tempdir().unwrap(); - let bashrc_path = temp_home.path().join(".bashrc"); - std::fs::write( - &bashrc_path, - r#" - set -x - function myecho { - echo 'It works!' - } - "#, - ) - .unwrap(); - let command = expected_cmd - .iter() - .map(|s| s.replace("BASHRC_PATH", bashrc_path.to_str().unwrap())) - .collect::>(); - - let output = process_exec_tool_call( - ExecParams { - command: command.clone(), - cwd: PathBuf::from(temp_home.path()), - timeout_ms: None, - env: HashMap::from([( - "HOME".to_string(), - temp_home.path().to_str().unwrap().to_string(), - )]), - with_escalated_permissions: None, - justification: None, - arg0: None, - }, - SandboxType::None, - &SandboxPolicy::DangerFullAccess, - temp_home.path(), - &None, - None, - ) - .await - .unwrap(); - - assert_eq!(output.exit_code, 0, "input: {input:?} output: {output:?}"); - if let Some(expected) = expected_output { - assert_eq!( - output.stdout.text, expected, - "input: {input:?} output: {output:?}" - ); - } - } - } } #[cfg(test)] -#[cfg(target_os = "macos")] -mod macos_tests { - use std::path::PathBuf; - - #[tokio::test] - async fn test_run_with_profile_escaping_and_execution() { - let shell_path = "/bin/zsh"; - - let cases = vec![ - ( - vec!["myecho"], - vec![shell_path, "-lc", "source ZSHRC_PATH && (myecho)"], - Some("It works!\n"), - ), - ( - vec!["myecho"], - vec![shell_path, "-lc", "source ZSHRC_PATH && (myecho)"], - Some("It works!\n"), - ), - ( - vec!["bash", "-c", "echo 'single' \"double\""], - vec![ - shell_path, - "-lc", - "source ZSHRC_PATH && (bash -c \"echo 'single' \\\"double\\\"\")", - ], - Some("single double\n"), - ), - ( - vec!["bash", "-lc", "echo 'single' \"double\""], - vec![ - shell_path, - "-lc", - "source ZSHRC_PATH && (echo 'single' \"double\")", - ], - Some("single double\n"), - ), - ]; - for (input, expected_cmd, expected_output) in cases { - use std::collections::HashMap; - - use crate::exec::ExecParams; - use crate::exec::SandboxType; - use crate::exec::process_exec_tool_call; - use crate::protocol::SandboxPolicy; - - let temp_home = tempfile::tempdir().unwrap(); - let zshrc_path = temp_home.path().join(".zshrc"); - std::fs::write( - &zshrc_path, - r#" - set -x - function myecho { - echo 'It works!' - } - "#, - ) - .unwrap(); - let command = expected_cmd - .iter() - .map(|s| s.replace("ZSHRC_PATH", zshrc_path.to_str().unwrap())) - .collect::>(); - - let output = process_exec_tool_call( - ExecParams { - command: command.clone(), - cwd: PathBuf::from(temp_home.path()), - timeout_ms: None, - env: HashMap::from([( - "HOME".to_string(), - temp_home.path().to_str().unwrap().to_string(), - )]), - with_escalated_permissions: None, - justification: None, - arg0: None, - }, - SandboxType::None, - &SandboxPolicy::DangerFullAccess, - temp_home.path(), - &None, - None, - ) - .await - .unwrap(); - - assert_eq!(output.exit_code, 0, "input: {input:?} output: {output:?}"); - if let Some(expected) = expected_output { - assert_eq!( - output.stdout.text, expected, - "input: {input:?} output: {output:?}" - ); - } - } - } -} - -#[cfg(test)] -#[cfg(target_os = "windows")] -mod tests_windows { +#[cfg(windows)] +mod tests { use super::*; + #[tokio::test] + async fn detects_powershell_as_default() { + let powershell_shell = default_user_shell().await; + let PowerShellConfig { shell_path } = match powershell_shell { + Shell::PowerShell(powershell_shell) => powershell_shell, + _ => panic!("expected powershell shell"), + }; + + assert!(shell_path.ends_with("pwsh.exe") || shell_path.ends_with("powershell.exe")); + } + #[test] - fn test_format_default_shell_invocation_powershell() { - use std::path::PathBuf; + fn finds_poweshell() { + let powershell_shell = get_shell(ShellType::PowerShell).unwrap(); + let PowerShellConfig { shell_path } = match powershell_shell { + Shell::PowerShell(powershell_shell) => powershell_shell, + _ => panic!("expected powershell shell"), + }; - let cases = vec![ - ( - PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: None, - }, - vec!["bash", "-lc", "echo hello"], - vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], - ), - ( - PowerShellConfig { - exe: "powershell.exe".to_string(), - bash_exe_fallback: None, - }, - vec!["bash", "-lc", "echo hello"], - vec!["powershell.exe", "-NoProfile", "-Command", "echo hello"], - ), - ( - PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: Some(PathBuf::from("bash.exe")), - }, - vec!["bash", "-lc", "echo hello"], - vec!["bash.exe", "-lc", "echo hello"], - ), - ( - PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: Some(PathBuf::from("bash.exe")), - }, - vec![ - "bash", - "-lc", - "apply_patch <<'EOF'\n*** Begin Patch\n*** Update File: destination_file.txt\n-original content\n+modified content\n*** End Patch\nEOF", - ], - vec![ - "bash.exe", - "-lc", - "apply_patch <<'EOF'\n*** Begin Patch\n*** Update File: destination_file.txt\n-original content\n+modified content\n*** End Patch\nEOF", - ], - ), - ( - PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: Some(PathBuf::from("bash.exe")), - }, - vec!["echo", "hello"], - vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], - ), - ( - PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: Some(PathBuf::from("bash.exe")), - }, - vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], - vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], - ), - ( - PowerShellConfig { - exe: "powershell.exe".to_string(), - bash_exe_fallback: Some(PathBuf::from("bash.exe")), - }, - vec![ - "codex-mcp-server.exe", - "--codex-run-as-apply-patch", - "*** Begin Patch\n*** Update File: C:\\Users\\person\\destination_file.txt\n-original content\n+modified content\n*** End Patch", - ], - vec![ - "codex-mcp-server.exe", - "--codex-run-as-apply-patch", - "*** Begin Patch\n*** Update File: C:\\Users\\person\\destination_file.txt\n-original content\n+modified content\n*** End Patch", - ], - ), - ]; - - for (config, input, expected_cmd) in cases { - let command = expected_cmd - .iter() - .map(|s| (*s).to_string()) - .collect::>(); - - // These tests assert the final command for each scenario now that the helper - // has been removed. The inputs remain to document the original coverage. - let expected = expected_cmd - .iter() - .map(|s| (*s).to_string()) - .collect::>(); - assert_eq!(command, expected, "input: {input:?} config: {config:?}"); - } + assert!(shell_path.ends_with("pwsh.exe") || shell_path.ends_with("powershell.exe")); } } diff --git a/codex-rs/core/src/tools/events.rs b/codex-rs/core/src/tools/events.rs index 9019dac5ed..5f93d51d8c 100644 --- a/codex-rs/core/src/tools/events.rs +++ b/codex-rs/core/src/tools/events.rs @@ -87,7 +87,7 @@ pub(crate) enum ToolEmitter { auto_approved: bool, }, UnifiedExec { - command: String, + command: Vec, cwd: PathBuf, // True for `exec_command` and false for `write_stdin`. #[allow(dead_code)] @@ -111,9 +111,9 @@ impl ToolEmitter { } } - pub fn unified_exec(command: String, cwd: PathBuf, is_startup_command: bool) -> Self { + pub fn unified_exec(command: &[String], cwd: PathBuf, is_startup_command: bool) -> Self { Self::UnifiedExec { - command, + command: command.to_vec(), cwd, is_startup_command, } @@ -218,7 +218,7 @@ impl ToolEmitter { emit_patch_end(ctx, String::new(), (*message).to_string(), false).await; } (Self::UnifiedExec { command, cwd, .. }, ToolEventStage::Begin) => { - emit_exec_command_begin(ctx, &[command.to_string()], cwd.as_path(), false).await; + emit_exec_command_begin(ctx, command, cwd.as_path(), false).await; } (Self::UnifiedExec { .. }, ToolEventStage::Success(output)) => { emit_exec_end( diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index 3a5115f6ee..39f271b2da 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -324,8 +324,11 @@ impl ShellHandler { #[cfg(test)] mod tests { + use std::path::PathBuf; + use crate::is_safe_command::is_known_safe_command; use crate::shell::BashShell; + use crate::shell::PowerShellConfig; use crate::shell::Shell; use crate::shell::ZshShell; @@ -335,27 +338,19 @@ mod tests { #[test] fn commands_generated_by_shell_command_handler_can_be_matched_by_is_known_safe_command() { let bash_shell = Shell::Bash(BashShell { - shell_path: "/bin/bash".to_string(), - bashrc_path: "/home/user/.bashrc".to_string(), + shell_path: PathBuf::from("/bin/bash"), }); assert_safe(&bash_shell, "ls -la"); let zsh_shell = Shell::Zsh(ZshShell { - shell_path: "/bin/zsh".to_string(), - zshrc_path: "/home/user/.zshrc".to_string(), + shell_path: PathBuf::from("/bin/zsh"), }); assert_safe(&zsh_shell, "ls -la"); - #[cfg(target_os = "windows")] - { - use crate::shell::PowerShellConfig; - - let powershell = Shell::PowerShell(PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: None, - }); - assert_safe(&powershell, "ls -Name"); - } + let powershell = Shell::PowerShell(PowerShellConfig { + shell_path: PathBuf::from("pwsh.exe"), + }); + assert_safe(&powershell, "ls -Name"); } fn assert_safe(shell: &Shell, command: &str) { diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index fb94f23d0d..6e0596d6eb 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -5,6 +5,7 @@ use crate::is_safe_command::is_known_safe_command; use crate::protocol::EventMsg; use crate::protocol::ExecCommandOutputDeltaEvent; use crate::protocol::ExecOutputStream; +use crate::shell::get_shell_by_model_provided_path; use crate::tools::context::ToolInvocation; use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; @@ -84,7 +85,8 @@ impl ToolHandler for UnifiedExecHandler { let Ok(params) = serde_json::from_str::(arguments) else { return true; }; - !is_known_safe_command(&["bash".to_string(), "-lc".to_string(), params.cmd]) + let command = get_command(¶ms); + !is_known_safe_command(&command) } async fn handle(&self, invocation: ToolInvocation) -> Result { @@ -117,15 +119,15 @@ impl ToolHandler for UnifiedExecHandler { "failed to parse exec_command arguments: {err:?}" )) })?; + + let command = get_command(&args); let ExecCommandArgs { - cmd, workdir, - shell, - login, yield_time_ms, max_output_tokens, with_escalated_permissions, justification, + .. } = args; if with_escalated_permissions.unwrap_or(false) @@ -152,15 +154,14 @@ impl ToolHandler for UnifiedExecHandler { &context.call_id, None, ); - let emitter = ToolEmitter::unified_exec(cmd.clone(), cwd.clone(), true); + + let emitter = ToolEmitter::unified_exec(&command, cwd.clone(), true); emitter.emit(event_ctx, ToolEventStage::Begin).await; manager .exec_command( ExecCommandRequest { - command: &cmd, - shell: &shell, - login, + command, yield_time_ms, max_output_tokens, workdir, @@ -221,6 +222,11 @@ impl ToolHandler for UnifiedExecHandler { } } +fn get_command(args: &ExecCommandArgs) -> Vec { + let shell = get_shell_by_model_provided_path(&PathBuf::from(args.shell.clone())); + shell.derive_exec_args(&args.cmd, args.login) +} + fn format_response(response: &UnifiedExecResponse) -> String { let mut sections = Vec::new(); diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index b996ce79e3..3f7f7978ec 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -64,10 +64,8 @@ impl UnifiedExecContext { } #[derive(Debug)] -pub(crate) struct ExecCommandRequest<'a> { - pub command: &'a str, - pub shell: &'a str, - pub login: bool, +pub(crate) struct ExecCommandRequest { + pub command: Vec, pub yield_time_ms: Option, pub max_output_tokens: Option, pub workdir: Option, @@ -105,7 +103,7 @@ struct SessionEntry { session_ref: Arc, turn_ref: Arc, call_id: String, - command: String, + command: Vec, cwd: PathBuf, started_at: tokio::time::Instant, } @@ -197,9 +195,7 @@ mod tests { .unified_exec_manager .exec_command( ExecCommandRequest { - command: cmd, - shell: "/bin/bash", - login: true, + command: vec!["bash".to_string(), "-lc".to_string(), cmd.to_string()], yield_time_ms, max_output_tokens: None, workdir: None, diff --git a/codex-rs/core/src/unified_exec/session_manager.rs b/codex-rs/core/src/unified_exec/session_manager.rs index c9763fbc49..e3b17d6e9d 100644 --- a/codex-rs/core/src/unified_exec/session_manager.rs +++ b/codex-rs/core/src/unified_exec/session_manager.rs @@ -36,23 +36,17 @@ use super::truncate_output_to_tokens; impl UnifiedExecSessionManager { pub(crate) async fn exec_command( &self, - request: ExecCommandRequest<'_>, + request: ExecCommandRequest, context: &UnifiedExecContext, ) -> Result { let cwd = request .workdir .clone() .unwrap_or_else(|| context.turn.cwd.clone()); - let shell_flag = if request.login { "-lc" } else { "-c" }; - let command = vec![ - request.shell.to_string(), - shell_flag.to_string(), - request.command.to_string(), - ]; let session = self .open_session_with_sandbox( - command, + &request.command, cwd.clone(), request.with_escalated_permissions, request.justification, @@ -79,7 +73,7 @@ impl UnifiedExecSessionManager { None } else { Some( - self.store_session(session, context, request.command, cwd.clone(), start) + self.store_session(session, context, &request.command, cwd.clone(), start) .await, ) }; @@ -99,7 +93,7 @@ impl UnifiedExecSessionManager { let exit = response.exit_code.unwrap_or(-1); Self::emit_exec_end_from_context( context, - request.command.to_string(), + &request.command, cwd, response.output.clone(), exit, @@ -224,7 +218,7 @@ impl UnifiedExecSessionManager { &self, session: UnifiedExecSession, context: &UnifiedExecContext, - command: &str, + command: &[String], cwd: PathBuf, started_at: Instant, ) -> i32 { @@ -236,7 +230,7 @@ impl UnifiedExecSessionManager { session_ref: Arc::clone(&context.session), turn_ref: Arc::clone(&context.turn), call_id: context.call_id.clone(), - command: command.to_string(), + command: command.to_vec(), cwd, started_at, }; @@ -264,7 +258,7 @@ impl UnifiedExecSessionManager { &entry.call_id, None, ); - let emitter = ToolEmitter::unified_exec(entry.command, entry.cwd, true); + let emitter = ToolEmitter::unified_exec(&entry.command, entry.cwd, true); emitter .emit(event_ctx, ToolEventStage::Success(output)) .await; @@ -272,7 +266,7 @@ impl UnifiedExecSessionManager { async fn emit_exec_end_from_context( context: &UnifiedExecContext, - command: String, + command: &[String], cwd: PathBuf, aggregated_output: String, exit_code: i32, @@ -321,7 +315,7 @@ impl UnifiedExecSessionManager { pub(super) async fn open_session_with_sandbox( &self, - command: Vec, + command: &[String], cwd: PathBuf, with_escalated_permissions: Option, justification: Option, @@ -330,7 +324,7 @@ impl UnifiedExecSessionManager { let mut orchestrator = ToolOrchestrator::new(); let mut runtime = UnifiedExecRuntime::new(self); let req = UnifiedExecToolRequest::new( - command, + command.to_vec(), cwd, create_env(&context.turn.shell_environment_policy), with_escalated_permissions, diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index 1225b51ccd..07b17f78ad 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -214,7 +214,11 @@ async fn unified_exec_emits_exec_command_begin_event() -> Result<()> { assert_eq!( begin_event.command, - vec!["/bin/echo hello unified exec".to_string()] + vec![ + "/bin/bash".to_string(), + "-lc".to_string(), + "/bin/echo hello unified exec".to_string() + ] ); assert_eq!(begin_event.cwd, cwd.path()); @@ -654,7 +658,14 @@ async fn unified_exec_skips_begin_event_for_empty_input() -> Result<()> { "expected only the initial command to emit begin event" ); assert_eq!(begin_events[0].call_id, open_call_id); - assert_eq!(begin_events[0].command[0], "/bin/sh -c echo ready"); + assert_eq!( + begin_events[0].command, + vec![ + "/bin/bash".to_string(), + "-lc".to_string(), + "/bin/sh -c echo ready".to_string() + ] + ); Ok(()) } From e6995174c10cd889f6ba88e246cf2e0e2493bfee Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 13 Nov 2025 08:43:00 -0800 Subject: [PATCH 05/20] Revert "Overhaul shell detection and centralize command generation for unified exec" (#6606) Reverts openai/codex#6577 --- codex-rs/core/src/bash.rs | 24 +- .../src/command_safety/is_safe_command.rs | 10 +- codex-rs/core/src/command_safety/mod.rs | 1 + codex-rs/core/src/environment_context.rs | 2 + codex-rs/core/src/shell.rs | 551 +++++++++++------- codex-rs/core/src/tools/events.rs | 8 +- codex-rs/core/src/tools/handlers/shell.rs | 23 +- .../core/src/tools/handlers/unified_exec.rs | 22 +- codex-rs/core/src/unified_exec/mod.rs | 12 +- .../core/src/unified_exec/session_manager.rs | 26 +- codex-rs/core/tests/suite/unified_exec.rs | 15 +- 11 files changed, 411 insertions(+), 283 deletions(-) diff --git a/codex-rs/core/src/bash.rs b/codex-rs/core/src/bash.rs index 0ffb8e785e..edeebaba37 100644 --- a/codex-rs/core/src/bash.rs +++ b/codex-rs/core/src/bash.rs @@ -1,13 +1,8 @@ -use std::path::PathBuf; - use tree_sitter::Node; use tree_sitter::Parser; use tree_sitter::Tree; use tree_sitter_bash::LANGUAGE as BASH; -use crate::shell::ShellType; -use crate::shell::detect_shell_type; - /// Parse the provided bash source using tree-sitter-bash, returning a Tree on /// success or None if parsing failed. pub fn try_parse_shell(shell_lc_arg: &str) -> Option { @@ -93,16 +88,23 @@ pub fn try_parse_word_only_commands_sequence(tree: &Tree, src: &str) -> Option bool { + if shell == "bash" || shell == "zsh" { + return true; + } + + let shell_name = std::path::Path::new(shell) + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or(shell); + matches!(shell_name, "bash" | "zsh") +} + pub fn extract_bash_command(command: &[String]) -> Option<(&str, &str)> { let [shell, flag, script] = command else { return None; }; - if !matches!(flag.as_str(), "-lc" | "-c") - || !matches!( - detect_shell_type(&PathBuf::from(shell)), - Some(ShellType::Zsh) | Some(ShellType::Bash) - ) - { + if !matches!(flag.as_str(), "-lc" | "-c") || !is_well_known_sh_shell(shell) { return None; } Some((shell, script)) diff --git a/codex-rs/core/src/command_safety/is_safe_command.rs b/codex-rs/core/src/command_safety/is_safe_command.rs index ab084c191b..ba3eb6ba7d 100644 --- a/codex-rs/core/src/command_safety/is_safe_command.rs +++ b/codex-rs/core/src/command_safety/is_safe_command.rs @@ -1,5 +1,4 @@ use crate::bash::parse_shell_lc_plain_commands; -use crate::command_safety::windows_safe_commands::is_safe_command_windows; pub fn is_known_safe_command(command: &[String]) -> bool { let command: Vec = command @@ -12,9 +11,12 @@ pub fn is_known_safe_command(command: &[String]) -> bool { } }) .collect(); - - if is_safe_command_windows(&command) { - return true; + #[cfg(target_os = "windows")] + { + use super::windows_safe_commands::is_safe_command_windows; + if is_safe_command_windows(&command) { + return true; + } } if is_safe_to_call_with_exec(&command) { diff --git a/codex-rs/core/src/command_safety/mod.rs b/codex-rs/core/src/command_safety/mod.rs index caf5c9f6ea..8279d67952 100644 --- a/codex-rs/core/src/command_safety/mod.rs +++ b/codex-rs/core/src/command_safety/mod.rs @@ -1,3 +1,4 @@ pub mod is_dangerous_command; pub mod is_safe_command; +#[cfg(target_os = "windows")] pub mod windows_safe_commands; diff --git a/codex-rs/core/src/environment_context.rs b/codex-rs/core/src/environment_context.rs index 6db2bb8f52..e7b2e19ffb 100644 --- a/codex-rs/core/src/environment_context.rs +++ b/codex-rs/core/src/environment_context.rs @@ -329,6 +329,7 @@ mod tests { Some(workspace_write_policy(vec!["/repo"], false)), Some(Shell::Bash(BashShell { shell_path: "/bin/bash".into(), + bashrc_path: "/home/user/.bashrc".into(), })), ); let context2 = EnvironmentContext::new( @@ -337,6 +338,7 @@ mod tests { Some(workspace_write_policy(vec!["/repo"], false)), Some(Shell::Zsh(ZshShell { shell_path: "/bin/zsh".into(), + zshrc_path: "/home/user/.zshrc".into(), })), ); diff --git a/codex-rs/core/src/shell.rs b/codex-rs/core/src/shell.rs index 60c1b41239..90f6c6b97a 100644 --- a/codex-rs/core/src/shell.rs +++ b/codex-rs/core/src/shell.rs @@ -2,26 +2,22 @@ use serde::Deserialize; use serde::Serialize; use std::path::PathBuf; -#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] -pub enum ShellType { - Zsh, - Bash, - PowerShell, -} - #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct ZshShell { - pub(crate) shell_path: PathBuf, + pub(crate) shell_path: String, + pub(crate) zshrc_path: String, } #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct BashShell { - pub(crate) shell_path: PathBuf, + pub(crate) shell_path: String, + pub(crate) bashrc_path: String, } #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct PowerShellConfig { - pub(crate) shell_path: PathBuf, // Executable name or path, e.g. "pwsh" or "powershell.exe". + pub(crate) exe: String, // Executable name or path, e.g. "pwsh" or "powershell.exe". + pub(crate) bash_exe_fallback: Option, // In case the model generates a bash command. } #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] @@ -40,10 +36,7 @@ impl Shell { .file_name() .map(|s| s.to_string_lossy().to_string()) } - Shell::PowerShell(ps) => ps - .shell_path - .file_stem() - .map(|s| s.to_string_lossy().to_string()), + Shell::PowerShell(ps) => Some(ps.exe.clone()), Shell::Unknown => None, } } @@ -54,17 +47,10 @@ impl Shell { match self { Shell::Zsh(ZshShell { shell_path, .. }) | Shell::Bash(BashShell { shell_path, .. }) => { let arg = if use_login_shell { "-lc" } else { "-c" }; - vec![ - shell_path.to_string_lossy().to_string(), - arg.to_string(), - command.to_string(), - ] + vec![shell_path.clone(), arg.to_string(), command.to_string()] } Shell::PowerShell(ps) => { - let mut args = vec![ - ps.shell_path.to_string_lossy().to_string(), - "-NoLogo".to_string(), - ]; + let mut args = vec![ps.exe.clone(), "-NoLogo".to_string()]; if !use_login_shell { args.push("-NoProfile".to_string()); } @@ -79,7 +65,7 @@ impl Shell { } #[cfg(unix)] -fn get_user_shell_path() -> Option { +fn detect_default_user_shell() -> Shell { use libc::getpwuid; use libc::getuid; use std::ffi::CStr; @@ -92,164 +78,75 @@ fn get_user_shell_path() -> Option { let shell_path = CStr::from_ptr((*pw).pw_shell) .to_string_lossy() .into_owned(); - Some(PathBuf::from(shell_path)) - } else { - None - } - } -} + let home_path = CStr::from_ptr((*pw).pw_dir).to_string_lossy().into_owned(); -#[cfg(not(unix))] -fn get_user_shell_path() -> Option { - None -} + if shell_path.ends_with("/zsh") { + return Shell::Zsh(ZshShell { + shell_path, + zshrc_path: format!("{home_path}/.zshrc"), + }); + } -fn file_exists(path: &PathBuf) -> Option { - if std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) { - Some(PathBuf::from(path)) - } else { - None - } -} - -fn get_shell_path( - shell_type: ShellType, - binary_name: &str, - fallback_paths: Vec<&str>, -) -> Option { - // Check if the shell we are trying to load is user's default shell - // if just use it - - let default_shell_path = get_user_shell_path(); - if let Some(default_shell_path) = default_shell_path - && detect_shell_type(&default_shell_path) == Some(shell_type) - { - return Some(default_shell_path); - } - - if let Ok(path) = which::which(binary_name) { - return Some(path); - } - - for path in fallback_paths { - //check exists - if let Some(path) = file_exists(&PathBuf::from(path)) { - return Some(path); - } - } - - None -} - -fn get_zsh_shell() -> Option { - let shell_path = get_shell_path(ShellType::Zsh, "zsh", vec!["/bin/zsh"]); - - shell_path.map(|shell_path| ZshShell { shell_path }) -} - -fn get_bash_shell() -> Option { - let shell_path = get_shell_path(ShellType::Bash, "bash", vec!["/bin/bash"]); - - shell_path.map(|shell_path| BashShell { shell_path }) -} - -fn get_powershell_shell() -> Option { - let shell_path = get_shell_path(ShellType::PowerShell, "pwsh", vec!["/usr/local/bin/pwsh"]) - .or_else(|| get_shell_path(ShellType::PowerShell, "powershell", vec![])); - - shell_path.map(|shell_path| PowerShellConfig { shell_path }) -} - -pub fn get_shell_by_model_provided_path(shell_path: &PathBuf) -> Shell { - detect_shell_type(shell_path) - .and_then(get_shell) - .unwrap_or(Shell::Unknown) -} - -pub fn get_shell(shell_type: ShellType) -> Option { - match shell_type { - ShellType::Zsh => get_zsh_shell().map(Shell::Zsh), - ShellType::Bash => get_bash_shell().map(Shell::Bash), - ShellType::PowerShell => get_powershell_shell().map(Shell::PowerShell), - } -} - -pub fn detect_shell_type(shell_path: &PathBuf) -> Option { - match shell_path.as_os_str().to_str() { - Some("zsh") => Some(ShellType::Zsh), - Some("bash") => Some(ShellType::Bash), - Some("pwsh") => Some(ShellType::PowerShell), - Some("powershell") => Some(ShellType::PowerShell), - _ => { - let shell_name = shell_path.file_stem(); - - if let Some(shell_name) = shell_name - && shell_name != shell_path - { - detect_shell_type(&PathBuf::from(shell_name)) - } else { - None + if shell_path.ends_with("/bash") { + return Shell::Bash(BashShell { + shell_path, + bashrc_path: format!("{home_path}/.bashrc"), + }); } } } + Shell::Unknown } +#[cfg(unix)] pub async fn default_user_shell() -> Shell { - if cfg!(windows) { - get_shell(ShellType::PowerShell).unwrap_or(Shell::Unknown) + detect_default_user_shell() +} + +#[cfg(target_os = "windows")] +pub async fn default_user_shell() -> Shell { + use tokio::process::Command; + + // Prefer PowerShell 7+ (`pwsh`) if available, otherwise fall back to Windows PowerShell. + let has_pwsh = Command::new("pwsh") + .arg("-NoLogo") + .arg("-NoProfile") + .arg("-Command") + .arg("$PSVersionTable.PSVersion.Major") + .output() + .await + .map(|o| o.status.success()) + .unwrap_or(false); + let bash_exe = if Command::new("bash.exe") + .arg("--version") + .stdin(std::process::Stdio::null()) + .output() + .await + .ok() + .map(|o| o.status.success()) + .unwrap_or(false) + { + which::which("bash.exe").ok() } else { - get_user_shell_path() - .and_then(|shell| detect_shell_type(&shell)) - .and_then(get_shell) - .unwrap_or(Shell::Unknown) + None + }; + + if has_pwsh { + Shell::PowerShell(PowerShellConfig { + exe: "pwsh.exe".to_string(), + bash_exe_fallback: bash_exe, + }) + } else { + Shell::PowerShell(PowerShellConfig { + exe: "powershell.exe".to_string(), + bash_exe_fallback: bash_exe, + }) } } -#[cfg(test)] -mod detect_shell_type_tests { - use super::*; - - #[test] - fn test_detect_shell_type() { - assert_eq!( - detect_shell_type(&PathBuf::from("zsh")), - Some(ShellType::Zsh) - ); - assert_eq!( - detect_shell_type(&PathBuf::from("bash")), - Some(ShellType::Bash) - ); - assert_eq!( - detect_shell_type(&PathBuf::from("pwsh")), - Some(ShellType::PowerShell) - ); - assert_eq!( - detect_shell_type(&PathBuf::from("powershell")), - Some(ShellType::PowerShell) - ); - assert_eq!(detect_shell_type(&PathBuf::from("fish")), None); - assert_eq!(detect_shell_type(&PathBuf::from("other")), None); - assert_eq!( - detect_shell_type(&PathBuf::from("/bin/zsh")), - Some(ShellType::Zsh) - ); - assert_eq!( - detect_shell_type(&PathBuf::from("/bin/bash")), - Some(ShellType::Bash) - ); - assert_eq!( - detect_shell_type(&PathBuf::from("powershell.exe")), - Some(ShellType::PowerShell) - ); - assert_eq!( - detect_shell_type(&PathBuf::from("pwsh.exe")), - Some(ShellType::PowerShell) - ); - assert_eq!( - detect_shell_type(&PathBuf::from("/usr/local/bin/pwsh")), - Some(ShellType::PowerShell) - ); - } +#[cfg(all(not(target_os = "windows"), not(unix)))] +pub async fn default_user_shell() -> Shell { + Shell::Unknown } #[cfg(test)] @@ -259,30 +156,6 @@ mod tests { use std::path::PathBuf; use std::process::Command; - #[test] - #[cfg(target_os = "macos")] - fn detects_zsh() { - let zsh_shell = get_shell(ShellType::Zsh).unwrap(); - - let ZshShell { shell_path } = match zsh_shell { - Shell::Zsh(zsh_shell) => zsh_shell, - _ => panic!("expected zsh shell"), - }; - - assert_eq!(shell_path, PathBuf::from("/bin/zsh")); - } - - #[test] - fn detects_bash() { - let bash_shell = get_shell(ShellType::Bash).unwrap(); - let BashShell { shell_path } = match bash_shell { - Shell::Bash(bash_shell) => bash_shell, - _ => panic!("expected bash shell"), - }; - - assert_eq!(shell_path, PathBuf::from("/bin/bash")); - } - #[tokio::test] async fn test_current_shell_detects_zsh() { let shell = Command::new("sh") @@ -291,42 +164,292 @@ mod tests { .output() .unwrap(); + let home = std::env::var("HOME").unwrap(); let shell_path = String::from_utf8_lossy(&shell.stdout).trim().to_string(); if shell_path.ends_with("/zsh") { assert_eq!( default_user_shell().await, Shell::Zsh(ZshShell { - shell_path: PathBuf::from(shell_path), + shell_path: shell_path.to_string(), + zshrc_path: format!("{home}/.zshrc",), }) ); } } + + #[tokio::test] + async fn test_run_with_profile_bash_escaping_and_execution() { + let shell_path = "/bin/bash"; + + let cases = vec![ + ( + vec!["myecho"], + vec![shell_path, "-lc", "source BASHRC_PATH && (myecho)"], + Some("It works!\n"), + ), + ( + vec!["bash", "-lc", "echo 'single' \"double\""], + vec![ + shell_path, + "-lc", + "source BASHRC_PATH && (echo 'single' \"double\")", + ], + Some("single double\n"), + ), + ]; + + for (input, expected_cmd, expected_output) in cases { + use std::collections::HashMap; + + use crate::exec::ExecParams; + use crate::exec::SandboxType; + use crate::exec::process_exec_tool_call; + use crate::protocol::SandboxPolicy; + + let temp_home = tempfile::tempdir().unwrap(); + let bashrc_path = temp_home.path().join(".bashrc"); + std::fs::write( + &bashrc_path, + r#" + set -x + function myecho { + echo 'It works!' + } + "#, + ) + .unwrap(); + let command = expected_cmd + .iter() + .map(|s| s.replace("BASHRC_PATH", bashrc_path.to_str().unwrap())) + .collect::>(); + + let output = process_exec_tool_call( + ExecParams { + command: command.clone(), + cwd: PathBuf::from(temp_home.path()), + timeout_ms: None, + env: HashMap::from([( + "HOME".to_string(), + temp_home.path().to_str().unwrap().to_string(), + )]), + with_escalated_permissions: None, + justification: None, + arg0: None, + }, + SandboxType::None, + &SandboxPolicy::DangerFullAccess, + temp_home.path(), + &None, + None, + ) + .await + .unwrap(); + + assert_eq!(output.exit_code, 0, "input: {input:?} output: {output:?}"); + if let Some(expected) = expected_output { + assert_eq!( + output.stdout.text, expected, + "input: {input:?} output: {output:?}" + ); + } + } + } } #[cfg(test)] -#[cfg(windows)] -mod tests { - use super::*; +#[cfg(target_os = "macos")] +mod macos_tests { + use std::path::PathBuf; #[tokio::test] - async fn detects_powershell_as_default() { - let powershell_shell = default_user_shell().await; - let PowerShellConfig { shell_path } = match powershell_shell { - Shell::PowerShell(powershell_shell) => powershell_shell, - _ => panic!("expected powershell shell"), - }; + async fn test_run_with_profile_escaping_and_execution() { + let shell_path = "/bin/zsh"; - assert!(shell_path.ends_with("pwsh.exe") || shell_path.ends_with("powershell.exe")); - } + let cases = vec![ + ( + vec!["myecho"], + vec![shell_path, "-lc", "source ZSHRC_PATH && (myecho)"], + Some("It works!\n"), + ), + ( + vec!["myecho"], + vec![shell_path, "-lc", "source ZSHRC_PATH && (myecho)"], + Some("It works!\n"), + ), + ( + vec!["bash", "-c", "echo 'single' \"double\""], + vec![ + shell_path, + "-lc", + "source ZSHRC_PATH && (bash -c \"echo 'single' \\\"double\\\"\")", + ], + Some("single double\n"), + ), + ( + vec!["bash", "-lc", "echo 'single' \"double\""], + vec![ + shell_path, + "-lc", + "source ZSHRC_PATH && (echo 'single' \"double\")", + ], + Some("single double\n"), + ), + ]; + for (input, expected_cmd, expected_output) in cases { + use std::collections::HashMap; - #[test] - fn finds_poweshell() { - let powershell_shell = get_shell(ShellType::PowerShell).unwrap(); - let PowerShellConfig { shell_path } = match powershell_shell { - Shell::PowerShell(powershell_shell) => powershell_shell, - _ => panic!("expected powershell shell"), - }; + use crate::exec::ExecParams; + use crate::exec::SandboxType; + use crate::exec::process_exec_tool_call; + use crate::protocol::SandboxPolicy; - assert!(shell_path.ends_with("pwsh.exe") || shell_path.ends_with("powershell.exe")); + let temp_home = tempfile::tempdir().unwrap(); + let zshrc_path = temp_home.path().join(".zshrc"); + std::fs::write( + &zshrc_path, + r#" + set -x + function myecho { + echo 'It works!' + } + "#, + ) + .unwrap(); + let command = expected_cmd + .iter() + .map(|s| s.replace("ZSHRC_PATH", zshrc_path.to_str().unwrap())) + .collect::>(); + + let output = process_exec_tool_call( + ExecParams { + command: command.clone(), + cwd: PathBuf::from(temp_home.path()), + timeout_ms: None, + env: HashMap::from([( + "HOME".to_string(), + temp_home.path().to_str().unwrap().to_string(), + )]), + with_escalated_permissions: None, + justification: None, + arg0: None, + }, + SandboxType::None, + &SandboxPolicy::DangerFullAccess, + temp_home.path(), + &None, + None, + ) + .await + .unwrap(); + + assert_eq!(output.exit_code, 0, "input: {input:?} output: {output:?}"); + if let Some(expected) = expected_output { + assert_eq!( + output.stdout.text, expected, + "input: {input:?} output: {output:?}" + ); + } + } + } +} + +#[cfg(test)] +#[cfg(target_os = "windows")] +mod tests_windows { + use super::*; + + #[test] + fn test_format_default_shell_invocation_powershell() { + use std::path::PathBuf; + + let cases = vec![ + ( + PowerShellConfig { + exe: "pwsh.exe".to_string(), + bash_exe_fallback: None, + }, + vec!["bash", "-lc", "echo hello"], + vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], + ), + ( + PowerShellConfig { + exe: "powershell.exe".to_string(), + bash_exe_fallback: None, + }, + vec!["bash", "-lc", "echo hello"], + vec!["powershell.exe", "-NoProfile", "-Command", "echo hello"], + ), + ( + PowerShellConfig { + exe: "pwsh.exe".to_string(), + bash_exe_fallback: Some(PathBuf::from("bash.exe")), + }, + vec!["bash", "-lc", "echo hello"], + vec!["bash.exe", "-lc", "echo hello"], + ), + ( + PowerShellConfig { + exe: "pwsh.exe".to_string(), + bash_exe_fallback: Some(PathBuf::from("bash.exe")), + }, + vec![ + "bash", + "-lc", + "apply_patch <<'EOF'\n*** Begin Patch\n*** Update File: destination_file.txt\n-original content\n+modified content\n*** End Patch\nEOF", + ], + vec![ + "bash.exe", + "-lc", + "apply_patch <<'EOF'\n*** Begin Patch\n*** Update File: destination_file.txt\n-original content\n+modified content\n*** End Patch\nEOF", + ], + ), + ( + PowerShellConfig { + exe: "pwsh.exe".to_string(), + bash_exe_fallback: Some(PathBuf::from("bash.exe")), + }, + vec!["echo", "hello"], + vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], + ), + ( + PowerShellConfig { + exe: "pwsh.exe".to_string(), + bash_exe_fallback: Some(PathBuf::from("bash.exe")), + }, + vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], + vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], + ), + ( + PowerShellConfig { + exe: "powershell.exe".to_string(), + bash_exe_fallback: Some(PathBuf::from("bash.exe")), + }, + vec![ + "codex-mcp-server.exe", + "--codex-run-as-apply-patch", + "*** Begin Patch\n*** Update File: C:\\Users\\person\\destination_file.txt\n-original content\n+modified content\n*** End Patch", + ], + vec![ + "codex-mcp-server.exe", + "--codex-run-as-apply-patch", + "*** Begin Patch\n*** Update File: C:\\Users\\person\\destination_file.txt\n-original content\n+modified content\n*** End Patch", + ], + ), + ]; + + for (config, input, expected_cmd) in cases { + let command = expected_cmd + .iter() + .map(|s| (*s).to_string()) + .collect::>(); + + // These tests assert the final command for each scenario now that the helper + // has been removed. The inputs remain to document the original coverage. + let expected = expected_cmd + .iter() + .map(|s| (*s).to_string()) + .collect::>(); + assert_eq!(command, expected, "input: {input:?} config: {config:?}"); + } } } diff --git a/codex-rs/core/src/tools/events.rs b/codex-rs/core/src/tools/events.rs index 5f93d51d8c..9019dac5ed 100644 --- a/codex-rs/core/src/tools/events.rs +++ b/codex-rs/core/src/tools/events.rs @@ -87,7 +87,7 @@ pub(crate) enum ToolEmitter { auto_approved: bool, }, UnifiedExec { - command: Vec, + command: String, cwd: PathBuf, // True for `exec_command` and false for `write_stdin`. #[allow(dead_code)] @@ -111,9 +111,9 @@ impl ToolEmitter { } } - pub fn unified_exec(command: &[String], cwd: PathBuf, is_startup_command: bool) -> Self { + pub fn unified_exec(command: String, cwd: PathBuf, is_startup_command: bool) -> Self { Self::UnifiedExec { - command: command.to_vec(), + command, cwd, is_startup_command, } @@ -218,7 +218,7 @@ impl ToolEmitter { emit_patch_end(ctx, String::new(), (*message).to_string(), false).await; } (Self::UnifiedExec { command, cwd, .. }, ToolEventStage::Begin) => { - emit_exec_command_begin(ctx, command, cwd.as_path(), false).await; + emit_exec_command_begin(ctx, &[command.to_string()], cwd.as_path(), false).await; } (Self::UnifiedExec { .. }, ToolEventStage::Success(output)) => { emit_exec_end( diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index 39f271b2da..3a5115f6ee 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -324,11 +324,8 @@ impl ShellHandler { #[cfg(test)] mod tests { - use std::path::PathBuf; - use crate::is_safe_command::is_known_safe_command; use crate::shell::BashShell; - use crate::shell::PowerShellConfig; use crate::shell::Shell; use crate::shell::ZshShell; @@ -338,19 +335,27 @@ mod tests { #[test] fn commands_generated_by_shell_command_handler_can_be_matched_by_is_known_safe_command() { let bash_shell = Shell::Bash(BashShell { - shell_path: PathBuf::from("/bin/bash"), + shell_path: "/bin/bash".to_string(), + bashrc_path: "/home/user/.bashrc".to_string(), }); assert_safe(&bash_shell, "ls -la"); let zsh_shell = Shell::Zsh(ZshShell { - shell_path: PathBuf::from("/bin/zsh"), + shell_path: "/bin/zsh".to_string(), + zshrc_path: "/home/user/.zshrc".to_string(), }); assert_safe(&zsh_shell, "ls -la"); - let powershell = Shell::PowerShell(PowerShellConfig { - shell_path: PathBuf::from("pwsh.exe"), - }); - assert_safe(&powershell, "ls -Name"); + #[cfg(target_os = "windows")] + { + use crate::shell::PowerShellConfig; + + let powershell = Shell::PowerShell(PowerShellConfig { + exe: "pwsh.exe".to_string(), + bash_exe_fallback: None, + }); + assert_safe(&powershell, "ls -Name"); + } } fn assert_safe(shell: &Shell, command: &str) { diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index 6e0596d6eb..fb94f23d0d 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -5,7 +5,6 @@ use crate::is_safe_command::is_known_safe_command; use crate::protocol::EventMsg; use crate::protocol::ExecCommandOutputDeltaEvent; use crate::protocol::ExecOutputStream; -use crate::shell::get_shell_by_model_provided_path; use crate::tools::context::ToolInvocation; use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; @@ -85,8 +84,7 @@ impl ToolHandler for UnifiedExecHandler { let Ok(params) = serde_json::from_str::(arguments) else { return true; }; - let command = get_command(¶ms); - !is_known_safe_command(&command) + !is_known_safe_command(&["bash".to_string(), "-lc".to_string(), params.cmd]) } async fn handle(&self, invocation: ToolInvocation) -> Result { @@ -119,15 +117,15 @@ impl ToolHandler for UnifiedExecHandler { "failed to parse exec_command arguments: {err:?}" )) })?; - - let command = get_command(&args); let ExecCommandArgs { + cmd, workdir, + shell, + login, yield_time_ms, max_output_tokens, with_escalated_permissions, justification, - .. } = args; if with_escalated_permissions.unwrap_or(false) @@ -154,14 +152,15 @@ impl ToolHandler for UnifiedExecHandler { &context.call_id, None, ); - - let emitter = ToolEmitter::unified_exec(&command, cwd.clone(), true); + let emitter = ToolEmitter::unified_exec(cmd.clone(), cwd.clone(), true); emitter.emit(event_ctx, ToolEventStage::Begin).await; manager .exec_command( ExecCommandRequest { - command, + command: &cmd, + shell: &shell, + login, yield_time_ms, max_output_tokens, workdir, @@ -222,11 +221,6 @@ impl ToolHandler for UnifiedExecHandler { } } -fn get_command(args: &ExecCommandArgs) -> Vec { - let shell = get_shell_by_model_provided_path(&PathBuf::from(args.shell.clone())); - shell.derive_exec_args(&args.cmd, args.login) -} - fn format_response(response: &UnifiedExecResponse) -> String { let mut sections = Vec::new(); diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index 3f7f7978ec..b996ce79e3 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -64,8 +64,10 @@ impl UnifiedExecContext { } #[derive(Debug)] -pub(crate) struct ExecCommandRequest { - pub command: Vec, +pub(crate) struct ExecCommandRequest<'a> { + pub command: &'a str, + pub shell: &'a str, + pub login: bool, pub yield_time_ms: Option, pub max_output_tokens: Option, pub workdir: Option, @@ -103,7 +105,7 @@ struct SessionEntry { session_ref: Arc, turn_ref: Arc, call_id: String, - command: Vec, + command: String, cwd: PathBuf, started_at: tokio::time::Instant, } @@ -195,7 +197,9 @@ mod tests { .unified_exec_manager .exec_command( ExecCommandRequest { - command: vec!["bash".to_string(), "-lc".to_string(), cmd.to_string()], + command: cmd, + shell: "/bin/bash", + login: true, yield_time_ms, max_output_tokens: None, workdir: None, diff --git a/codex-rs/core/src/unified_exec/session_manager.rs b/codex-rs/core/src/unified_exec/session_manager.rs index e3b17d6e9d..c9763fbc49 100644 --- a/codex-rs/core/src/unified_exec/session_manager.rs +++ b/codex-rs/core/src/unified_exec/session_manager.rs @@ -36,17 +36,23 @@ use super::truncate_output_to_tokens; impl UnifiedExecSessionManager { pub(crate) async fn exec_command( &self, - request: ExecCommandRequest, + request: ExecCommandRequest<'_>, context: &UnifiedExecContext, ) -> Result { let cwd = request .workdir .clone() .unwrap_or_else(|| context.turn.cwd.clone()); + let shell_flag = if request.login { "-lc" } else { "-c" }; + let command = vec![ + request.shell.to_string(), + shell_flag.to_string(), + request.command.to_string(), + ]; let session = self .open_session_with_sandbox( - &request.command, + command, cwd.clone(), request.with_escalated_permissions, request.justification, @@ -73,7 +79,7 @@ impl UnifiedExecSessionManager { None } else { Some( - self.store_session(session, context, &request.command, cwd.clone(), start) + self.store_session(session, context, request.command, cwd.clone(), start) .await, ) }; @@ -93,7 +99,7 @@ impl UnifiedExecSessionManager { let exit = response.exit_code.unwrap_or(-1); Self::emit_exec_end_from_context( context, - &request.command, + request.command.to_string(), cwd, response.output.clone(), exit, @@ -218,7 +224,7 @@ impl UnifiedExecSessionManager { &self, session: UnifiedExecSession, context: &UnifiedExecContext, - command: &[String], + command: &str, cwd: PathBuf, started_at: Instant, ) -> i32 { @@ -230,7 +236,7 @@ impl UnifiedExecSessionManager { session_ref: Arc::clone(&context.session), turn_ref: Arc::clone(&context.turn), call_id: context.call_id.clone(), - command: command.to_vec(), + command: command.to_string(), cwd, started_at, }; @@ -258,7 +264,7 @@ impl UnifiedExecSessionManager { &entry.call_id, None, ); - let emitter = ToolEmitter::unified_exec(&entry.command, entry.cwd, true); + let emitter = ToolEmitter::unified_exec(entry.command, entry.cwd, true); emitter .emit(event_ctx, ToolEventStage::Success(output)) .await; @@ -266,7 +272,7 @@ impl UnifiedExecSessionManager { async fn emit_exec_end_from_context( context: &UnifiedExecContext, - command: &[String], + command: String, cwd: PathBuf, aggregated_output: String, exit_code: i32, @@ -315,7 +321,7 @@ impl UnifiedExecSessionManager { pub(super) async fn open_session_with_sandbox( &self, - command: &[String], + command: Vec, cwd: PathBuf, with_escalated_permissions: Option, justification: Option, @@ -324,7 +330,7 @@ impl UnifiedExecSessionManager { let mut orchestrator = ToolOrchestrator::new(); let mut runtime = UnifiedExecRuntime::new(self); let req = UnifiedExecToolRequest::new( - command.to_vec(), + command, cwd, create_env(&context.turn.shell_environment_policy), with_escalated_permissions, diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index 07b17f78ad..1225b51ccd 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -214,11 +214,7 @@ async fn unified_exec_emits_exec_command_begin_event() -> Result<()> { assert_eq!( begin_event.command, - vec![ - "/bin/bash".to_string(), - "-lc".to_string(), - "/bin/echo hello unified exec".to_string() - ] + vec!["/bin/echo hello unified exec".to_string()] ); assert_eq!(begin_event.cwd, cwd.path()); @@ -658,14 +654,7 @@ async fn unified_exec_skips_begin_event_for_empty_input() -> Result<()> { "expected only the initial command to emit begin event" ); assert_eq!(begin_events[0].call_id, open_call_id); - assert_eq!( - begin_events[0].command, - vec![ - "/bin/bash".to_string(), - "-lc".to_string(), - "/bin/sh -c echo ready".to_string() - ] - ); + assert_eq!(begin_events[0].command[0], "/bin/sh -c echo ready"); Ok(()) } From 041d6ad902ca6ed59691d289d0c876a47b0d8aac Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 13 Nov 2025 09:19:38 -0800 Subject: [PATCH 06/20] Migrate prompt caching tests to test_codex (#6605) To hopefully fix the flakiness --- codex-rs/core/tests/common/test_codex.rs | 11 +- codex-rs/core/tests/suite/prompt_caching.rs | 484 ++++++-------------- 2 files changed, 145 insertions(+), 350 deletions(-) diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 30c78d5be6..e56446c5ca 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -71,6 +71,7 @@ impl TestCodexBuilder { resume_from: Option, ) -> anyhow::Result { let (config, cwd) = self.prepare_config(server, &home).await?; + let conversation_manager = ConversationManager::with_auth(CodexAuth::from_api_key("dummy")); let new_conversation = match resume_from { @@ -79,15 +80,20 @@ impl TestCodexBuilder { CodexAuth::from_api_key("dummy"), ); conversation_manager - .resume_conversation_from_rollout(config, path, auth_manager) + .resume_conversation_from_rollout(config.clone(), path, auth_manager) + .await? + } + None => { + conversation_manager + .new_conversation(config.clone()) .await? } - None => conversation_manager.new_conversation(config).await?, }; Ok(TestCodex { home, cwd, + config, codex: new_conversation.conversation, session_configured: new_conversation.session_configured, }) @@ -131,6 +137,7 @@ pub struct TestCodex { pub cwd: Arc, pub codex: Arc, pub session_configured: SessionConfiguredEvent, + pub config: Config, } impl TestCodex { diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs index 4b1d4a2cec..813226873c 100644 --- a/codex-rs/core/tests/suite/prompt_caching.rs +++ b/codex-rs/core/tests/suite/prompt_caching.rs @@ -1,9 +1,5 @@ #![allow(clippy::unwrap_used)] -use codex_core::CodexAuth; -use codex_core::ConversationManager; -use codex_core::ModelProviderInfo; -use codex_core::built_in_model_providers; use codex_core::config::OPENAI_DEFAULT_MODEL; use codex_core::features::Feature; use codex_core::model_family::find_family_for_model; @@ -16,17 +12,16 @@ use codex_core::protocol_config_types::ReasoningSummary; use codex_core::shell::Shell; use codex_core::shell::default_user_shell; use codex_protocol::user_input::UserInput; -use core_test_support::load_default_config_for_test; use core_test_support::load_sse_fixture_with_id; +use core_test_support::responses::mount_sse_once_match; +use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; +use core_test_support::test_codex::TestCodex; +use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; use std::collections::HashMap; use tempfile::TempDir; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::method; -use wiremock::matchers::path; +use wiremock::matchers::any; fn text_user_input(text: String) -> serde_json::Value { serde_json::json!({ @@ -70,48 +65,24 @@ fn assert_tool_names(body: &serde_json::Value, expected_names: &[&str]) { } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn codex_mini_latest_tools() { - skip_if_no_network!(); +async fn codex_mini_latest_tools() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); use pretty_assertions::assert_eq; - let server = MockServer::start().await; + let server = start_mock_server().await; + let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; + let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; - let sse = sse_completed("resp"); - let template = ResponseTemplate::new(200) - .insert_header("content-type", "text/event-stream") - .set_body_raw(sse, "text/event-stream"); - - // Expect two POSTs to /v1/responses - Mock::given(method("POST")) - .and(path("/v1/responses")) - .respond_with(template) - .expect(2) - .mount(&server) - .await; - - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; - - let cwd = TempDir::new().unwrap(); - let codex_home = TempDir::new().unwrap(); - let mut config = load_default_config_for_test(&codex_home); - config.cwd = cwd.path().to_path_buf(); - config.model_provider = model_provider; - config.user_instructions = Some("be consistent and helpful".to_string()); - config.features.disable(Feature::ApplyPatchFreeform); - - let conversation_manager = - ConversationManager::with_auth(CodexAuth::from_api_key("Test API Key")); - config.model = "codex-mini-latest".to_string(); - config.model_family = find_family_for_model("codex-mini-latest").unwrap(); - - let codex = conversation_manager - .new_conversation(config) - .await - .expect("create new conversation") - .conversation; + let TestCodex { codex, .. } = test_codex() + .with_config(|config| { + config.user_instructions = Some("be consistent and helpful".to_string()); + config.features.disable(Feature::ApplyPatchFreeform); + config.model = "codex-mini-latest".to_string(); + config.model_family = find_family_for_model("codex-mini-latest") + .expect("model family for codex-mini-latest"); + }) + .build(&server) + .await?; codex .submit(Op::UserInput { @@ -119,8 +90,7 @@ async fn codex_mini_latest_tools() { text: "hello 1".into(), }], }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; codex @@ -129,72 +99,45 @@ async fn codex_mini_latest_tools() { text: "hello 2".into(), }], }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 2, "expected two POST requests"); - let expected_instructions = [ include_str!("../../prompt.md"), include_str!("../../../apply-patch/apply_patch_tool_instructions.md"), ] .join("\n"); - let body0 = requests[0].body_json::().unwrap(); + let body0 = req1.single_request().body_json(); assert_eq!( body0["instructions"], serde_json::json!(expected_instructions), ); - let body1 = requests[1].body_json::().unwrap(); + let body1 = req2.single_request().body_json(); assert_eq!( body1["instructions"], serde_json::json!(expected_instructions), ); + + Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] -async fn prompt_tools_are_consistent_across_requests() { - skip_if_no_network!(); +async fn prompt_tools_are_consistent_across_requests() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); use pretty_assertions::assert_eq; - let server = MockServer::start().await; + let server = start_mock_server().await; + let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; + let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; - let sse = sse_completed("resp"); - let template = ResponseTemplate::new(200) - .insert_header("content-type", "text/event-stream") - .set_body_raw(sse, "text/event-stream"); - - // Expect two POSTs to /v1/responses - Mock::given(method("POST")) - .and(path("/v1/responses")) - .respond_with(template) - .expect(2) - .mount(&server) - .await; - - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; - - let cwd = TempDir::new().unwrap(); - let codex_home = TempDir::new().unwrap(); - - let mut config = load_default_config_for_test(&codex_home); - config.cwd = cwd.path().to_path_buf(); - config.model_provider = model_provider; - config.user_instructions = Some("be consistent and helpful".to_string()); - - let conversation_manager = - ConversationManager::with_auth(CodexAuth::from_api_key("Test API Key")); + let TestCodex { codex, config, .. } = test_codex() + .with_config(|config| { + config.user_instructions = Some("be consistent and helpful".to_string()); + }) + .build(&server) + .await?; let base_instructions = config.model_family.base_instructions.clone(); - let codex = conversation_manager - .new_conversation(config) - .await - .expect("create new conversation") - .conversation; codex .submit(Op::UserInput { @@ -202,8 +145,7 @@ async fn prompt_tools_are_consistent_across_requests() { text: "hello 1".into(), }], }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; codex @@ -212,13 +154,9 @@ async fn prompt_tools_are_consistent_across_requests() { text: "hello 2".into(), }], }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 2, "expected two POST requests"); - // our internal implementation is responsible for keeping tools in sync // with the OpenAI schema, so we just verify the tool presence here let tools_by_model: HashMap<&'static str, Vec<&'static str>> = HashMap::from([ @@ -274,7 +212,7 @@ async fn prompt_tools_are_consistent_across_requests() { .get(OPENAI_DEFAULT_MODEL) .unwrap_or_else(|| panic!("expected tools to be defined for model {OPENAI_DEFAULT_MODEL}")) .as_slice(); - let body0 = requests[0].body_json::().unwrap(); + let body0 = req1.single_request().body_json(); let expected_instructions = if expected_tools_names.contains(&"apply_patch") { base_instructions @@ -292,54 +230,32 @@ async fn prompt_tools_are_consistent_across_requests() { ); assert_tool_names(&body0, expected_tools_names); - let body1 = requests[1].body_json::().unwrap(); + let body1 = req2.single_request().body_json(); assert_eq!( body1["instructions"], serde_json::json!(expected_instructions), ); assert_tool_names(&body1, expected_tools_names); + + Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -#[ignore = "flaky on ubuntu-24.04-arm - aarch64-unknown-linux-gpu"] -async fn prefixes_context_and_instructions_once_and_consistently_across_requests() { - skip_if_no_network!(); +async fn prefixes_context_and_instructions_once_and_consistently_across_requests() +-> anyhow::Result<()> { + skip_if_no_network!(Ok(())); use pretty_assertions::assert_eq; - let server = MockServer::start().await; + let server = start_mock_server().await; + let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; + let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; - let sse = sse_completed("resp"); - let template = ResponseTemplate::new(200) - .insert_header("content-type", "text/event-stream") - .set_body_raw(sse, "text/event-stream"); - - // Expect two POSTs to /v1/responses - Mock::given(method("POST")) - .and(path("/v1/responses")) - .respond_with(template) - .expect(2) - .mount(&server) - .await; - - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; - - let cwd = TempDir::new().unwrap(); - let codex_home = TempDir::new().unwrap(); - let mut config = load_default_config_for_test(&codex_home); - config.cwd = cwd.path().to_path_buf(); - config.model_provider = model_provider; - config.user_instructions = Some("be consistent and helpful".to_string()); - - let conversation_manager = - ConversationManager::with_auth(CodexAuth::from_api_key("Test API Key")); - let codex = conversation_manager - .new_conversation(config) - .await - .expect("create new conversation") - .conversation; + let TestCodex { codex, config, .. } = test_codex() + .with_config(|config| { + config.user_instructions = Some("be consistent and helpful".to_string()); + }) + .build(&server) + .await?; codex .submit(Op::UserInput { @@ -347,8 +263,7 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests text: "hello 1".into(), }], }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; codex @@ -357,31 +272,14 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests text: "hello 2".into(), }], }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 2, "expected two POST requests"); - let shell = default_user_shell().await; - - let expected_env_text = format!( - r#" - {} - on-request - read-only - restricted -{}"#, - cwd.path().to_string_lossy(), - match shell.name() { - Some(name) => format!(" {name}\n"), - None => String::new(), - } - ); + let cwd_str = config.cwd.to_string_lossy(); + let expected_env_text = default_env_context_str(&cwd_str, &shell); let expected_ui_text = format!( - "# AGENTS.md instructions for {}\n\n\nbe consistent and helpful\n", - cwd.path().to_string_lossy() + "# AGENTS.md instructions for {cwd_str}\n\n\nbe consistent and helpful\n" ); let expected_env_msg = serde_json::json!({ @@ -400,7 +298,7 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests "role": "user", "content": [ { "type": "input_text", "text": "hello 1" } ] }); - let body1 = requests[0].body_json::().unwrap(); + let body1 = req1.single_request().body_json(); assert_eq!( body1["input"], serde_json::json!([expected_ui_msg, expected_env_msg, expected_user_message_1]) @@ -411,7 +309,7 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests "role": "user", "content": [ { "type": "input_text", "text": "hello 2" } ] }); - let body2 = requests[1].body_json::().unwrap(); + let body2 = req2.single_request().body_json(); let expected_body2 = serde_json::json!( [ body1["input"].as_array().unwrap().as_slice(), @@ -420,47 +318,25 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests .concat() ); assert_eq!(body2["input"], expected_body2); + + Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() { - skip_if_no_network!(); +async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); use pretty_assertions::assert_eq; - let server = MockServer::start().await; + let server = start_mock_server().await; + let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; + let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; - let sse = sse_completed("resp"); - let template = ResponseTemplate::new(200) - .insert_header("content-type", "text/event-stream") - .set_body_raw(sse, "text/event-stream"); - - // Expect two POSTs to /v1/responses - Mock::given(method("POST")) - .and(path("/v1/responses")) - .respond_with(template) - .expect(2) - .mount(&server) - .await; - - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; - - let cwd = TempDir::new().unwrap(); - let codex_home = TempDir::new().unwrap(); - let mut config = load_default_config_for_test(&codex_home); - config.cwd = cwd.path().to_path_buf(); - config.model_provider = model_provider; - config.user_instructions = Some("be consistent and helpful".to_string()); - - let conversation_manager = - ConversationManager::with_auth(CodexAuth::from_api_key("Test API Key")); - let codex = conversation_manager - .new_conversation(config) - .await - .expect("create new conversation") - .conversation; + let TestCodex { codex, .. } = test_codex() + .with_config(|config| { + config.user_instructions = Some("be consistent and helpful".to_string()); + }) + .build(&server) + .await?; // First turn codex @@ -469,8 +345,7 @@ async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() { text: "hello 1".into(), }], }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; let writable = TempDir::new().unwrap(); @@ -488,8 +363,7 @@ async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() { effort: Some(Some(ReasoningEffort::High)), summary: Some(ReasoningSummary::Detailed), }) - .await - .unwrap(); + .await?; // Second turn after overrides codex @@ -498,16 +372,11 @@ async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() { text: "hello 2".into(), }], }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - // Verify we issued exactly two requests, and the cached prefix stayed identical. - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 2, "expected two POST requests"); - - let body1 = requests[0].body_json::().unwrap(); - let body2 = requests[1].body_json::().unwrap(); + let body1 = req1.single_request().body_json(); + let body2 = req2.single_request().body_json(); // prompt_cache_key should remain constant across overrides assert_eq!( body1["prompt_cache_key"], body2["prompt_cache_key"], @@ -548,47 +417,25 @@ async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() { .concat() ); assert_eq!(body2["input"], expected_body2); + + Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn per_turn_overrides_keep_cached_prefix_and_key_constant() { - skip_if_no_network!(); +async fn per_turn_overrides_keep_cached_prefix_and_key_constant() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); use pretty_assertions::assert_eq; - let server = MockServer::start().await; + let server = start_mock_server().await; + let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; + let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; - let sse = sse_completed("resp"); - let template = ResponseTemplate::new(200) - .insert_header("content-type", "text/event-stream") - .set_body_raw(sse, "text/event-stream"); - - // Expect two POSTs to /v1/responses - Mock::given(method("POST")) - .and(path("/v1/responses")) - .respond_with(template) - .expect(2) - .mount(&server) - .await; - - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; - - let cwd = TempDir::new().unwrap(); - let codex_home = TempDir::new().unwrap(); - let mut config = load_default_config_for_test(&codex_home); - config.cwd = cwd.path().to_path_buf(); - config.model_provider = model_provider; - config.user_instructions = Some("be consistent and helpful".to_string()); - - let conversation_manager = - ConversationManager::with_auth(CodexAuth::from_api_key("Test API Key")); - let codex = conversation_manager - .new_conversation(config) - .await - .expect("create new conversation") - .conversation; + let TestCodex { codex, .. } = test_codex() + .with_config(|config| { + config.user_instructions = Some("be consistent and helpful".to_string()); + }) + .build(&server) + .await?; // First turn codex @@ -597,8 +444,7 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() { text: "hello 1".into(), }], }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; // Second turn using per-turn overrides via UserTurn @@ -622,16 +468,11 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() { summary: ReasoningSummary::Detailed, final_output_json_schema: None, }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - // Verify we issued exactly two requests, and the cached prefix stayed identical. - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 2, "expected two POST requests"); - - let body1 = requests[0].body_json::().unwrap(); - let body2 = requests[1].body_json::().unwrap(); + let body1 = req1.single_request().body_json(); + let body2 = req2.single_request().body_json(); // prompt_cache_key should remain constant across per-turn overrides assert_eq!( @@ -672,38 +513,25 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() { .concat() ); assert_eq!(body2["input"], expected_body2); + + Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn send_user_turn_with_no_changes_does_not_send_environment_context() { - skip_if_no_network!(); +async fn send_user_turn_with_no_changes_does_not_send_environment_context() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); use pretty_assertions::assert_eq; - let server = MockServer::start().await; + let server = start_mock_server().await; + let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; + let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; - let sse = sse_completed("resp"); - let template = ResponseTemplate::new(200) - .insert_header("content-type", "text/event-stream") - .set_body_raw(sse, "text/event-stream"); - - Mock::given(method("POST")) - .and(path("/v1/responses")) - .respond_with(template) - .expect(2) - .mount(&server) - .await; - - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; - - let cwd = TempDir::new().unwrap(); - let codex_home = TempDir::new().unwrap(); - let mut config = load_default_config_for_test(&codex_home); - config.cwd = cwd.path().to_path_buf(); - config.model_provider = model_provider; - config.user_instructions = Some("be consistent and helpful".to_string()); + let TestCodex { codex, config, .. } = test_codex() + .with_config(|config| { + config.user_instructions = Some("be consistent and helpful".to_string()); + }) + .build(&server) + .await?; let default_cwd = config.cwd.clone(); let default_approval_policy = config.approval_policy; @@ -712,14 +540,6 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() { let default_effort = config.model_reasoning_effort; let default_summary = config.model_reasoning_summary; - let conversation_manager = - ConversationManager::with_auth(CodexAuth::from_api_key("Test API Key")); - let codex = conversation_manager - .new_conversation(config) - .await - .expect("create new conversation") - .conversation; - codex .submit(Op::UserTurn { items: vec![UserInput::Text { @@ -733,8 +553,7 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() { summary: default_summary, final_output_json_schema: None, }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; codex @@ -750,27 +569,20 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() { summary: default_summary, final_output_json_schema: None, }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 2, "expected two POST requests"); - - let body1 = requests[0].body_json::().unwrap(); - let body2 = requests[1].body_json::().unwrap(); + let body1 = req1.single_request().body_json(); + let body2 = req2.single_request().body_json(); let shell = default_user_shell().await; + let default_cwd_lossy = default_cwd.to_string_lossy(); let expected_ui_text = format!( - "# AGENTS.md instructions for {}\n\n\nbe consistent and helpful\n", - default_cwd.to_string_lossy() + "# AGENTS.md instructions for {default_cwd_lossy}\n\n\nbe consistent and helpful\n" ); let expected_ui_msg = text_user_input(expected_ui_text); - let expected_env_msg_1 = text_user_input(default_env_context_str( - &cwd.path().to_string_lossy(), - &shell, - )); + let expected_env_msg_1 = text_user_input(default_env_context_str(&default_cwd_lossy, &shell)); let expected_user_message_1 = text_user_input("hello 1".to_string()); let expected_input_1 = serde_json::Value::Array(vec![ @@ -788,38 +600,25 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() { expected_user_message_2, ]); assert_eq!(body2["input"], expected_input_2); + + Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn send_user_turn_with_changes_sends_environment_context() { - skip_if_no_network!(); +async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); use pretty_assertions::assert_eq; - let server = MockServer::start().await; + let server = start_mock_server().await; - let sse = sse_completed("resp"); - let template = ResponseTemplate::new(200) - .insert_header("content-type", "text/event-stream") - .set_body_raw(sse, "text/event-stream"); - - Mock::given(method("POST")) - .and(path("/v1/responses")) - .respond_with(template) - .expect(2) - .mount(&server) - .await; - - let model_provider = ModelProviderInfo { - base_url: Some(format!("{}/v1", server.uri())), - ..built_in_model_providers()["openai"].clone() - }; - - let cwd = TempDir::new().unwrap(); - let codex_home = TempDir::new().unwrap(); - let mut config = load_default_config_for_test(&codex_home); - config.cwd = cwd.path().to_path_buf(); - config.model_provider = model_provider; - config.user_instructions = Some("be consistent and helpful".to_string()); + let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; + let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; + let TestCodex { codex, config, .. } = test_codex() + .with_config(|config| { + config.user_instructions = Some("be consistent and helpful".to_string()); + }) + .build(&server) + .await?; let default_cwd = config.cwd.clone(); let default_approval_policy = config.approval_policy; @@ -828,14 +627,6 @@ async fn send_user_turn_with_changes_sends_environment_context() { let default_effort = config.model_reasoning_effort; let default_summary = config.model_reasoning_summary; - let conversation_manager = - ConversationManager::with_auth(CodexAuth::from_api_key("Test API Key")); - let codex = conversation_manager - .new_conversation(config.clone()) - .await - .expect("create new conversation") - .conversation; - codex .submit(Op::UserTurn { items: vec![UserInput::Text { @@ -849,8 +640,7 @@ async fn send_user_turn_with_changes_sends_environment_context() { summary: default_summary, final_output_json_schema: None, }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; codex @@ -866,15 +656,11 @@ async fn send_user_turn_with_changes_sends_environment_context() { summary: ReasoningSummary::Detailed, final_output_json_schema: None, }) - .await - .unwrap(); + .await?; wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - let requests = server.received_requests().await.unwrap(); - assert_eq!(requests.len(), 2, "expected two POST requests"); - - let body1 = requests[0].body_json::().unwrap(); - let body2 = requests[1].body_json::().unwrap(); + let body1 = req1.single_request().body_json(); + let body2 = req2.single_request().body_json(); let shell = default_user_shell().await; let expected_ui_text = format!( @@ -913,4 +699,6 @@ async fn send_user_turn_with_changes_sends_environment_context() { expected_user_message_2, ]); assert_eq!(body2["input"], expected_input_2); + + Ok(()) } From 6cda3de3a452d51eb858808f5a865f54968d363e Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 13 Nov 2025 10:01:51 -0800 Subject: [PATCH 07/20] Close stale PRs workflow (#6594) Closes stale PRs from OpenAI employees. --- .../workflows/close-stale-contributor-prs.yml | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 .github/workflows/close-stale-contributor-prs.yml diff --git a/.github/workflows/close-stale-contributor-prs.yml b/.github/workflows/close-stale-contributor-prs.yml new file mode 100644 index 0000000000..6a5b8b6f72 --- /dev/null +++ b/.github/workflows/close-stale-contributor-prs.yml @@ -0,0 +1,103 @@ +name: Close stale contributor PRs + +on: + workflow_dispatch: + schedule: + - cron: "0 9 * * *" + +permissions: + contents: read + issues: write + pull-requests: write + +jobs: + close-stale-contributor-prs: + runs-on: ubuntu-latest + steps: + - name: Close inactive PRs from contributors + uses: actions/github-script@v7 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const DAYS_INACTIVE = 14; + const cutoff = new Date(Date.now() - DAYS_INACTIVE * 24 * 60 * 60 * 1000); + const { owner, repo } = context.repo; + const dryRun = true; + const stalePrs = []; + + core.info(`Dry run mode: ${dryRun}`); + + const prs = await github.paginate(github.rest.pulls.list, { + owner, + repo, + state: "open", + per_page: 100, + sort: "updated", + direction: "asc", + }); + + for (const pr of prs) { + const lastUpdated = new Date(pr.updated_at); + if (lastUpdated > cutoff) { + continue; + } + + if (!pr.user || pr.user.type !== "User") { + continue; + } + + let permission; + try { + const permissionResponse = await github.rest.repos.getCollaboratorPermissionLevel({ + owner, + repo, + username: pr.user.login, + }); + permission = permissionResponse.data.permission; + } catch (error) { + if (error.status === 404) { + core.info(`Author ${pr.user.login} is not a collaborator; skipping #${pr.number}`); + continue; + } + throw error; + } + + const hasContributorAccess = ["admin", "maintain", "write"].includes(permission); + if (!hasContributorAccess) { + core.info(`Author ${pr.user.login} has ${permission} access; skipping #${pr.number}`); + continue; + } + + stalePrs.push(pr); + } + + if (!stalePrs.length) { + core.info("No stale contributor pull requests found."); + return; + } + + for (const pr of stalePrs) { + const issue_number = pr.number; + const closeComment = `Closing this pull request because it has had no updates for more than ${DAYS_INACTIVE} days. If you plan to continue working on it, feel free to reopen or open a new PR.`; + + if (dryRun) { + core.info(`[dry-run] Would close contributor PR #${issue_number} from ${pr.user.login}`); + continue; + } + + await github.rest.issues.createComment({ + owner, + repo, + issue_number, + body: closeComment, + }); + + await github.rest.pulls.update({ + owner, + repo, + pull_number: issue_number, + state: "closed", + }); + + core.info(`Closed contributor PR #${issue_number} from ${pr.user.login}`); + } From 0792a7953d4e5a897dbce9419bf7f3f1ac02a519 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 13 Nov 2025 10:24:41 -0800 Subject: [PATCH 08/20] Update default yield time (#6610) 10s for exec and 250ms for write_stdin --- .../core/src/tools/handlers/unified_exec.rs | 16 ++++-- codex-rs/core/src/unified_exec/mod.rs | 55 ++++++++----------- .../core/src/unified_exec/session_manager.rs | 4 +- 3 files changed, 36 insertions(+), 39 deletions(-) diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index fb94f23d0d..97229970a3 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -32,8 +32,8 @@ struct ExecCommandArgs { shell: String, #[serde(default = "default_login")] login: bool, - #[serde(default)] - yield_time_ms: Option, + #[serde(default = "default_exec_yield_time_ms")] + yield_time_ms: u64, #[serde(default)] max_output_tokens: Option, #[serde(default)] @@ -47,12 +47,20 @@ struct WriteStdinArgs { session_id: i32, #[serde(default)] chars: String, - #[serde(default)] - yield_time_ms: Option, + #[serde(default = "default_write_stdin_yield_time_ms")] + yield_time_ms: u64, #[serde(default)] max_output_tokens: Option, } +fn default_exec_yield_time_ms() -> u64 { + 10000 +} + +fn default_write_stdin_yield_time_ms() -> u64 { + 250 +} + fn default_shell() -> String { "/bin/bash".to_string() } diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index b996ce79e3..1ee65e971e 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -41,7 +41,6 @@ mod session_manager; pub(crate) use errors::UnifiedExecError; pub(crate) use session::UnifiedExecSession; -pub(crate) const DEFAULT_YIELD_TIME_MS: u64 = 10_000; pub(crate) const MIN_YIELD_TIME_MS: u64 = 250; pub(crate) const MAX_YIELD_TIME_MS: u64 = 30_000; pub(crate) const DEFAULT_MAX_OUTPUT_TOKENS: usize = 10_000; @@ -68,7 +67,7 @@ pub(crate) struct ExecCommandRequest<'a> { pub command: &'a str, pub shell: &'a str, pub login: bool, - pub yield_time_ms: Option, + pub yield_time_ms: u64, pub max_output_tokens: Option, pub workdir: Option, pub with_escalated_permissions: Option, @@ -79,7 +78,7 @@ pub(crate) struct ExecCommandRequest<'a> { pub(crate) struct WriteStdinRequest<'a> { pub session_id: i32, pub input: &'a str, - pub yield_time_ms: Option, + pub yield_time_ms: u64, pub max_output_tokens: Option, } @@ -110,11 +109,8 @@ struct SessionEntry { started_at: tokio::time::Instant, } -pub(crate) fn clamp_yield_time(yield_time_ms: Option) -> u64 { - match yield_time_ms { - Some(value) => value.clamp(MIN_YIELD_TIME_MS, MAX_YIELD_TIME_MS), - None => DEFAULT_YIELD_TIME_MS, - } +pub(crate) fn clamp_yield_time(yield_time_ms: u64) -> u64 { + yield_time_ms.clamp(MIN_YIELD_TIME_MS, MAX_YIELD_TIME_MS) } pub(crate) fn resolve_max_tokens(max_tokens: Option) -> usize { @@ -187,7 +183,7 @@ mod tests { session: &Arc, turn: &Arc, cmd: &str, - yield_time_ms: Option, + yield_time_ms: u64, ) -> Result { let context = UnifiedExecContext::new(Arc::clone(session), Arc::clone(turn), "call".to_string()); @@ -215,7 +211,7 @@ mod tests { session: &Arc, session_id: i32, input: &str, - yield_time_ms: Option, + yield_time_ms: u64, ) -> Result { session .services @@ -253,14 +249,14 @@ mod tests { let (session, turn) = test_session_and_turn(); - let open_shell = exec_command(&session, &turn, "bash -i", Some(2_500)).await?; + let open_shell = exec_command(&session, &turn, "bash -i", 2_500).await?; let session_id = open_shell.session_id.expect("expected session_id"); write_stdin( &session, session_id, "export CODEX_INTERACTIVE_SHELL_VAR=codex\n", - Some(2_500), + 2_500, ) .await?; @@ -268,7 +264,7 @@ mod tests { &session, session_id, "echo $CODEX_INTERACTIVE_SHELL_VAR\n", - Some(2_500), + 2_500, ) .await?; assert!( @@ -285,24 +281,19 @@ mod tests { let (session, turn) = test_session_and_turn(); - let shell_a = exec_command(&session, &turn, "bash -i", Some(2_500)).await?; + let shell_a = exec_command(&session, &turn, "bash -i", 2_500).await?; let session_a = shell_a.session_id.expect("expected session id"); write_stdin( &session, session_a, "export CODEX_INTERACTIVE_SHELL_VAR=codex\n", - Some(2_500), + 2_500, ) .await?; - let out_2 = exec_command( - &session, - &turn, - "echo $CODEX_INTERACTIVE_SHELL_VAR", - Some(2_500), - ) - .await?; + let out_2 = + exec_command(&session, &turn, "echo $CODEX_INTERACTIVE_SHELL_VAR", 2_500).await?; assert!( out_2.session_id.is_none(), "short command should not retain a session" @@ -316,7 +307,7 @@ mod tests { &session, session_a, "echo $CODEX_INTERACTIVE_SHELL_VAR\n", - Some(2_500), + 2_500, ) .await?; assert!( @@ -333,14 +324,14 @@ mod tests { let (session, turn) = test_session_and_turn(); - let open_shell = exec_command(&session, &turn, "bash -i", Some(2_500)).await?; + let open_shell = exec_command(&session, &turn, "bash -i", 2_500).await?; let session_id = open_shell.session_id.expect("expected session id"); write_stdin( &session, session_id, "export CODEX_INTERACTIVE_SHELL_VAR=codex\n", - Some(2_500), + 2_500, ) .await?; @@ -348,7 +339,7 @@ mod tests { &session, session_id, "sleep 5 && echo $CODEX_INTERACTIVE_SHELL_VAR\n", - Some(10), + 10, ) .await?; assert!( @@ -358,7 +349,7 @@ mod tests { tokio::time::sleep(Duration::from_secs(7)).await; - let out_3 = write_stdin(&session, session_id, "", Some(100)).await?; + let out_3 = write_stdin(&session, session_id, "", 100).await?; assert!( out_3.output.contains("codex"), @@ -373,7 +364,7 @@ mod tests { async fn requests_with_large_timeout_are_capped() -> anyhow::Result<()> { let (session, turn) = test_session_and_turn(); - let result = exec_command(&session, &turn, "echo codex", Some(120_000)).await?; + let result = exec_command(&session, &turn, "echo codex", 120_000).await?; assert!(result.session_id.is_none()); assert!(result.output.contains("codex")); @@ -385,7 +376,7 @@ mod tests { #[ignore] // Ignored while we have a better way to test this. async fn completed_commands_do_not_persist_sessions() -> anyhow::Result<()> { let (session, turn) = test_session_and_turn(); - let result = exec_command(&session, &turn, "echo codex", Some(2_500)).await?; + let result = exec_command(&session, &turn, "echo codex", 2_500).await?; assert!( result.session_id.is_none(), @@ -412,14 +403,14 @@ mod tests { let (session, turn) = test_session_and_turn(); - let open_shell = exec_command(&session, &turn, "bash -i", Some(2_500)).await?; + let open_shell = exec_command(&session, &turn, "bash -i", 2_500).await?; let session_id = open_shell.session_id.expect("expected session id"); - write_stdin(&session, session_id, "exit\n", Some(2_500)).await?; + write_stdin(&session, session_id, "exit\n", 2_500).await?; tokio::time::sleep(Duration::from_millis(200)).await; - let err = write_stdin(&session, session_id, "", Some(100)) + let err = write_stdin(&session, session_id, "", 100) .await .expect_err("expected unknown session error"); diff --git a/codex-rs/core/src/unified_exec/session_manager.rs b/codex-rs/core/src/unified_exec/session_manager.rs index c9763fbc49..df2c3aaf1c 100644 --- a/codex-rs/core/src/unified_exec/session_manager.rs +++ b/codex-rs/core/src/unified_exec/session_manager.rs @@ -19,7 +19,6 @@ use crate::tools::runtimes::unified_exec::UnifiedExecRuntime; use crate::tools::sandboxing::ToolCtx; use super::ExecCommandRequest; -use super::MIN_YIELD_TIME_MS; use super::SessionEntry; use super::UnifiedExecContext; use super::UnifiedExecError; @@ -61,8 +60,7 @@ impl UnifiedExecSessionManager { .await?; let max_tokens = resolve_max_tokens(request.max_output_tokens); - let yield_time_ms = - clamp_yield_time(Some(request.yield_time_ms.unwrap_or(MIN_YIELD_TIME_MS))); + let yield_time_ms = clamp_yield_time(request.yield_time_ms); let start = Instant::now(); let (output_buffer, output_notify) = session.output_handles(); From c95bd345ea0d3d6cd401bd0270c3f8d80835c106 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 13 Nov 2025 11:50:54 -0800 Subject: [PATCH 09/20] Enable close-stale-contributor-prs.yml workflow (#6615) Tested on https://github.com/openai/codex/pull/3036 --- .github/workflows/close-stale-contributor-prs.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/close-stale-contributor-prs.yml b/.github/workflows/close-stale-contributor-prs.yml index 6a5b8b6f72..b3cb7fb44e 100644 --- a/.github/workflows/close-stale-contributor-prs.yml +++ b/.github/workflows/close-stale-contributor-prs.yml @@ -3,7 +3,7 @@ name: Close stale contributor PRs on: workflow_dispatch: schedule: - - cron: "0 9 * * *" + - cron: "0 6 * * *" permissions: contents: read @@ -22,7 +22,7 @@ jobs: const DAYS_INACTIVE = 14; const cutoff = new Date(Date.now() - DAYS_INACTIVE * 24 * 60 * 60 * 1000); const { owner, repo } = context.repo; - const dryRun = true; + const dryRun = false; const stalePrs = []; core.info(`Dry run mode: ${dryRun}`); @@ -39,10 +39,12 @@ jobs: for (const pr of prs) { const lastUpdated = new Date(pr.updated_at); if (lastUpdated > cutoff) { + core.info(`PR ${pr.number} is fresh`); continue; } if (!pr.user || pr.user.type !== "User") { + core.info(`PR ${pr.number} wasn't created by a user`); continue; } From 439bc5dbbe211db369fdb48f2e1f5d434ac9cb37 Mon Sep 17 00:00:00 2001 From: Dan Hernandez <33551757+danfhernandez@users.noreply.github.com> Date: Thu, 13 Nov 2025 16:35:42 -0500 Subject: [PATCH 10/20] Add AbortSignal support to TypeScript SDK (#6378) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Adds AbortSignal support to the TypeScript SDK for canceling thread execution using AbortController. ## Changes - Add `signal?: AbortSignal` property to `TurnOptions` type - Pass signal through Thread class methods to exec layer - Add signal parameter to `CodexExecArgs` - Leverage Node.js native `spawn()` signal support for automatic cancellation - Add comprehensive test coverage (6 tests covering all abort scenarios) ## Implementation The implementation uses Node.js's built-in AbortSignal support in `spawn()` (available since Node v15, SDK requires >=18), which automatically handles: - Checking if already aborted before starting - Killing the child process when abort is triggered - Emitting appropriate error events - All cleanup operations This is a one-line change to the core implementation (`signal: args.signal` passed to spawn), making it simple, reliable, and maintainable. ## Usage Example ```typescript import { Codex } from '@openai/codex-sdk'; const codex = new Codex({ apiKey: 'your-api-key' }); const thread = codex.startThread(); // Create AbortController const controller = new AbortController(); // Run with abort signal const resultPromise = thread.run("Your prompt here", { signal: controller.signal }); // Cancel anytime controller.abort('User requested cancellation'); ``` ## Testing All tests pass (23 total across SDK): - ✅ Aborts when signal is already aborted (both run and runStreamed) - ✅ Aborts during execution/iteration - ✅ Completes normally when not aborted - ✅ Backward compatible (signal is optional) Tests verified to fail correctly when signal support is removed (no false positives). --------- Co-authored-by: Claude Co-authored-by: pakrym-oai --- sdk/typescript/eslint.config.js | 7 ++ sdk/typescript/src/exec.ts | 8 +- sdk/typescript/src/thread.ts | 1 + sdk/typescript/src/turnOptions.ts | 2 + sdk/typescript/tests/abort.test.ts | 165 +++++++++++++++++++++++++ sdk/typescript/tests/responsesProxy.ts | 39 ++++-- sdk/typescript/tests/run.test.ts | 11 +- 7 files changed, 218 insertions(+), 15 deletions(-) create mode 100644 sdk/typescript/tests/abort.test.ts diff --git a/sdk/typescript/eslint.config.js b/sdk/typescript/eslint.config.js index 742f6fc8fd..324d06818b 100644 --- a/sdk/typescript/eslint.config.js +++ b/sdk/typescript/eslint.config.js @@ -10,5 +10,12 @@ export default defineConfig(eslint.configs.recommended, tseslint.configs.recomme rules: { "node-import/prefer-node-protocol": 2, + "@typescript-eslint/no-unused-vars": [ + "error", + { + argsIgnorePattern: "^_", + varsIgnorePattern: "^_", + }, + ], }, }); diff --git a/sdk/typescript/src/exec.ts b/sdk/typescript/src/exec.ts index 8086c92a44..be05e7c3ea 100644 --- a/sdk/typescript/src/exec.ts +++ b/sdk/typescript/src/exec.ts @@ -24,6 +24,8 @@ export type CodexExecArgs = { outputSchemaFile?: string; // --config model_reasoning_effort modelReasoningEffort?: ModelReasoningEffort; + // AbortSignal to cancel the execution + signal?: AbortSignal; // --config sandbox_workspace_write.network_access networkAccessEnabled?: boolean; // --config features.web_search_request @@ -69,7 +71,10 @@ export class CodexExec { } if (args.networkAccessEnabled !== undefined) { - commandArgs.push("--config", `sandbox_workspace_write.network_access=${args.networkAccessEnabled}`); + commandArgs.push( + "--config", + `sandbox_workspace_write.network_access=${args.networkAccessEnabled}`, + ); } if (args.webSearchEnabled !== undefined) { @@ -105,6 +110,7 @@ export class CodexExec { const child = spawn(this.executablePath, commandArgs, { env, + signal: args.signal, }); let spawnError: unknown | null = null; diff --git a/sdk/typescript/src/thread.ts b/sdk/typescript/src/thread.ts index fec63cf4d4..90c7a8face 100644 --- a/sdk/typescript/src/thread.ts +++ b/sdk/typescript/src/thread.ts @@ -86,6 +86,7 @@ export class Thread { skipGitRepoCheck: options?.skipGitRepoCheck, outputSchemaFile: schemaPath, modelReasoningEffort: options?.modelReasoningEffort, + signal: turnOptions.signal, networkAccessEnabled: options?.networkAccessEnabled, webSearchEnabled: options?.webSearchEnabled, approvalPolicy: options?.approvalPolicy, diff --git a/sdk/typescript/src/turnOptions.ts b/sdk/typescript/src/turnOptions.ts index ed602f2f92..1eda806694 100644 --- a/sdk/typescript/src/turnOptions.ts +++ b/sdk/typescript/src/turnOptions.ts @@ -1,4 +1,6 @@ export type TurnOptions = { /** JSON schema describing the expected agent output. */ outputSchema?: unknown; + /** AbortSignal to cancel the turn. */ + signal?: AbortSignal; }; diff --git a/sdk/typescript/tests/abort.test.ts b/sdk/typescript/tests/abort.test.ts new file mode 100644 index 0000000000..d79319d654 --- /dev/null +++ b/sdk/typescript/tests/abort.test.ts @@ -0,0 +1,165 @@ +import path from "node:path"; + +import { describe, expect, it } from "@jest/globals"; + +import { Codex } from "../src/codex"; + +import { + assistantMessage, + responseCompleted, + responseStarted, + shell_call as shellCall, + sse, + SseResponseBody, + startResponsesTestProxy, +} from "./responsesProxy"; + +const codexExecPath = path.join(process.cwd(), "..", "..", "codex-rs", "target", "debug", "codex"); + +function* infiniteShellCall(): Generator { + while (true) { + yield sse(responseStarted(), shellCall(), responseCompleted()); + } +} + +describe("AbortSignal support", () => { + it("aborts run() when signal is aborted", async () => { + const { url, close } = await startResponsesTestProxy({ + statusCode: 200, + responseBodies: infiniteShellCall(), + }); + + try { + const client = new Codex({ codexPathOverride: codexExecPath, baseUrl: url, apiKey: "test" }); + const thread = client.startThread(); + + // Create an abort controller and abort it immediately + const controller = new AbortController(); + controller.abort("Test abort"); + + // The operation should fail because the signal is already aborted + await expect(thread.run("Hello, world!", { signal: controller.signal })).rejects.toThrow(); + } finally { + await close(); + } + }); + + it("aborts runStreamed() when signal is aborted", async () => { + const { url, close } = await startResponsesTestProxy({ + statusCode: 200, + responseBodies: infiniteShellCall(), + }); + + try { + const client = new Codex({ codexPathOverride: codexExecPath, baseUrl: url, apiKey: "test" }); + const thread = client.startThread(); + + // Create an abort controller and abort it immediately + const controller = new AbortController(); + controller.abort("Test abort"); + + const { events } = await thread.runStreamed("Hello, world!", { signal: controller.signal }); + + // Attempting to iterate should fail + let iterationStarted = false; + try { + for await (const event of events) { + iterationStarted = true; + // Should not get here + expect(event).toBeUndefined(); + } + // If we get here, the test should fail + throw new Error( + "Expected iteration to throw due to aborted signal, but it completed successfully", + ); + } catch (error) { + // We expect an error to be thrown + expect(iterationStarted).toBe(false); // Should fail before any iteration + expect(error).toBeDefined(); + } + } finally { + await close(); + } + }); + + it("aborts run() when signal is aborted during execution", async () => { + const { url, close } = await startResponsesTestProxy({ + statusCode: 200, + responseBodies: infiniteShellCall(), + }); + + try { + const client = new Codex({ codexPathOverride: codexExecPath, baseUrl: url, apiKey: "test" }); + const thread = client.startThread(); + + const controller = new AbortController(); + + // Start the operation and abort it immediately after + const runPromise = thread.run("Hello, world!", { signal: controller.signal }); + + // Abort after a tiny delay to simulate aborting during execution + setTimeout(() => controller.abort("Aborted during execution"), 10); + + // The operation should fail + await expect(runPromise).rejects.toThrow(); + } finally { + await close(); + } + }); + + it("aborts runStreamed() when signal is aborted during iteration", async () => { + const { url, close } = await startResponsesTestProxy({ + statusCode: 200, + responseBodies: infiniteShellCall(), + }); + + try { + const client = new Codex({ codexPathOverride: codexExecPath, baseUrl: url, apiKey: "test" }); + const thread = client.startThread(); + + const controller = new AbortController(); + + const { events } = await thread.runStreamed("Hello, world!", { signal: controller.signal }); + + // Abort during iteration + let eventCount = 0; + await expect( + (async () => { + for await (const event of events) { + void event; // Consume the event + eventCount++; + // Abort after first event + if (eventCount === 5) { + controller.abort("Aborted during iteration"); + } + // Continue iterating - should eventually throw + } + })(), + ).rejects.toThrow(); + } finally { + await close(); + } + }); + + it("completes normally when signal is not aborted", async () => { + const { url, close } = await startResponsesTestProxy({ + statusCode: 200, + responseBodies: [sse(responseStarted(), assistantMessage("Hi!"), responseCompleted())], + }); + + try { + const client = new Codex({ codexPathOverride: codexExecPath, baseUrl: url, apiKey: "test" }); + const thread = client.startThread(); + + const controller = new AbortController(); + + // Don't abort - should complete successfully + const result = await thread.run("Hello, world!", { signal: controller.signal }); + + expect(result.finalResponse).toBe("Hi!"); + expect(result.items).toHaveLength(1); + } finally { + await close(); + } + }); +}); diff --git a/sdk/typescript/tests/responsesProxy.ts b/sdk/typescript/tests/responsesProxy.ts index 6b8ee9bcac..e9d3b29146 100644 --- a/sdk/typescript/tests/responsesProxy.ts +++ b/sdk/typescript/tests/responsesProxy.ts @@ -19,18 +19,18 @@ const DEFAULT_COMPLETED_USAGE: ResponseCompletedUsage = { total_tokens: 47, }; -type SseEvent = { +export type SseEvent = { type: string; [key: string]: unknown; }; -type SseResponseBody = { +export type SseResponseBody = { kind: "sse"; events: SseEvent[]; }; export type ResponsesProxyOptions = { - responseBodies: SseResponseBody[]; + responseBodies: Generator | SseResponseBody[]; statusCode?: number; }; @@ -64,11 +64,17 @@ function formatSseEvent(event: SseEvent): string { export async function startResponsesTestProxy( options: ResponsesProxyOptions, ): Promise { - const responseBodies = options.responseBodies; - if (responseBodies.length === 0) { - throw new Error("responseBodies is required"); + function* createGenerator(array: SseResponseBody[]): Generator { + for (const elem of array) { + yield elem; + } + throw new Error("not enough responses provided"); } + const responseBodies: Generator = Array.isArray(options.responseBodies) + ? createGenerator(options.responseBodies) + : options.responseBodies; + const requests: RecordedRequest[] = []; function readRequestBody(req: http.IncomingMessage): Promise { @@ -84,8 +90,6 @@ export async function startResponsesTestProxy( }); } - let responseIndex = 0; - const server = http.createServer((req, res) => { async function handle(): Promise { if (req.method === "POST" && req.url === "/responses") { @@ -97,8 +101,7 @@ export async function startResponsesTestProxy( res.statusCode = status; res.setHeader("content-type", "text/event-stream"); - const responseBody = responseBodies[Math.min(responseIndex, responseBodies.length - 1)]!; - responseIndex += 1; + const responseBody = responseBodies.next().value; for (const event of responseBody.events) { res.write(formatSseEvent(event)); } @@ -177,6 +180,22 @@ export function assistantMessage(text: string, itemId: string = DEFAULT_MESSAGE_ }; } +export function shell_call(): SseEvent { + const command = ["bash", "-lc", "echo 'Hello, world!'"]; + return { + type: "response.output_item.done", + item: { + type: "function_call", + call_id: `call_id${Math.random().toString(36).slice(2)}`, + name: "shell", + arguments: JSON.stringify({ + command, + timeout_ms: 100, + }), + }, + }; +} + export function responseFailed(errorMessage: string): SseEvent { return { type: "error", diff --git a/sdk/typescript/tests/run.test.ts b/sdk/typescript/tests/run.test.ts index f461e16667..1a85b5823e 100644 --- a/sdk/typescript/tests/run.test.ts +++ b/sdk/typescript/tests/run.test.ts @@ -14,6 +14,7 @@ import { sse, responseFailed, startResponsesTestProxy, + SseResponseBody, } from "./responsesProxy"; const codexExecPath = path.join(process.cwd(), "..", "..", "codex-rs", "target", "debug", "codex"); @@ -572,10 +573,12 @@ describe("Codex", () => { it("throws ThreadRunError on turn failures", async () => { const { url, close } = await startResponsesTestProxy({ statusCode: 200, - responseBodies: [ - sse(responseStarted("response_1")), - sse(responseFailed("rate limit exceeded")), - ], + responseBodies: (function* (): Generator { + yield sse(responseStarted("response_1")); + while (true) { + yield sse(responseFailed("rate limit exceeded")); + } + })(), }); try { From b4a53aef47824c13367b973694dcdcb9fd3b958c Mon Sep 17 00:00:00 2001 From: Dan Hernandez <33551757+danfhernandez@users.noreply.github.com> Date: Thu, 13 Nov 2025 16:47:10 -0500 Subject: [PATCH 11/20] feat: Add support for --add-dir to exec and TypeScript SDK (#6565) ## Summary Adds support for specifying additional directories in the TypeScript SDK through a new `additionalDirectories` option in `ThreadOptions`. ## Changes - Added `additionalDirectories` parameter to `ThreadOptions` interface - Updated `CodexExec` to accept and pass through additional directories via the `--config` flag for `sandbox_workspace_write.writable_roots` - Added comprehensive test coverage for the new functionality ## Test plan - Added test case that verifies `additionalDirectories` is correctly passed as repeated flags - Existing tests continue to pass --------- Co-authored-by: Claude --- codex-rs/exec/src/cli.rs | 4 ++ codex-rs/exec/src/lib.rs | 3 +- codex-rs/exec/tests/suite/add_dir.rs | 72 ++++++++++++++++++++++++++++ codex-rs/exec/tests/suite/mod.rs | 1 + sdk/typescript/src/exec.ts | 8 ++++ sdk/typescript/src/thread.ts | 1 + sdk/typescript/src/threadOptions.ts | 1 + sdk/typescript/tests/run.test.ts | 42 ++++++++++++++++ 8 files changed, 131 insertions(+), 1 deletion(-) create mode 100644 codex-rs/exec/tests/suite/add_dir.rs diff --git a/codex-rs/exec/src/cli.rs b/codex-rs/exec/src/cli.rs index 065f4826a0..0b5b0b4b6d 100644 --- a/codex-rs/exec/src/cli.rs +++ b/codex-rs/exec/src/cli.rs @@ -52,6 +52,10 @@ pub struct Cli { #[arg(long = "skip-git-repo-check", default_value_t = false)] pub skip_git_repo_check: bool, + /// Additional directories that should be writable alongside the primary workspace. + #[arg(long = "add-dir", value_name = "DIR", value_hint = clap::ValueHint::DirPath)] + pub add_dir: Vec, + /// Path to a JSON Schema file describing the model's final response shape. #[arg(long = "output-schema", value_name = "FILE")] pub output_schema: Option, diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 13d43f61e2..a9cf6b2c6d 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -62,6 +62,7 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any dangerously_bypass_approvals_and_sandbox, cwd, skip_git_repo_check, + add_dir, color, last_message_file, json: json_mode, @@ -180,7 +181,7 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any show_raw_agent_reasoning: oss.then_some(true), tools_web_search_request: None, experimental_sandbox_command_assessment: None, - additional_writable_roots: Vec::new(), + additional_writable_roots: add_dir, }; // Parse `-c` overrides. let cli_kv_overrides = match config_overrides.parse_overrides() { diff --git a/codex-rs/exec/tests/suite/add_dir.rs b/codex-rs/exec/tests/suite/add_dir.rs new file mode 100644 index 0000000000..2093c46aca --- /dev/null +++ b/codex-rs/exec/tests/suite/add_dir.rs @@ -0,0 +1,72 @@ +#![cfg(not(target_os = "windows"))] +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use core_test_support::responses; +use core_test_support::test_codex_exec::test_codex_exec; + +/// Verify that the --add-dir flag is accepted and the command runs successfully. +/// This test confirms the CLI argument is properly wired up. +#[tokio::test(flavor = "multi_thread", worker_threads = 1)] +async fn accepts_add_dir_flag() -> anyhow::Result<()> { + let test = test_codex_exec(); + + let server = responses::start_mock_server().await; + let body = responses::sse(vec![ + responses::ev_response_created("response_1"), + responses::ev_assistant_message("response_1", "Task completed"), + responses::ev_completed("response_1"), + ]); + responses::mount_sse_once(&server, body).await; + + // Create temporary directories to use with --add-dir + let temp_dir1 = tempfile::tempdir()?; + let temp_dir2 = tempfile::tempdir()?; + + test.cmd_with_server(&server) + .arg("--skip-git-repo-check") + .arg("--sandbox") + .arg("workspace-write") + .arg("--add-dir") + .arg(temp_dir1.path()) + .arg("--add-dir") + .arg(temp_dir2.path()) + .arg("test with additional directories") + .assert() + .code(0); + + Ok(()) +} + +/// Verify that multiple --add-dir flags can be specified. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn accepts_multiple_add_dir_flags() -> anyhow::Result<()> { + let test = test_codex_exec(); + + let server = responses::start_mock_server().await; + let body = responses::sse(vec![ + responses::ev_response_created("response_1"), + responses::ev_assistant_message("response_1", "Multiple directories accepted"), + responses::ev_completed("response_1"), + ]); + responses::mount_sse_once(&server, body).await; + + let temp_dir1 = tempfile::tempdir()?; + let temp_dir2 = tempfile::tempdir()?; + let temp_dir3 = tempfile::tempdir()?; + + test.cmd_with_server(&server) + .arg("--skip-git-repo-check") + .arg("--sandbox") + .arg("workspace-write") + .arg("--add-dir") + .arg(temp_dir1.path()) + .arg("--add-dir") + .arg(temp_dir2.path()) + .arg("--add-dir") + .arg(temp_dir3.path()) + .arg("test with three directories") + .assert() + .code(0); + + Ok(()) +} diff --git a/codex-rs/exec/tests/suite/mod.rs b/codex-rs/exec/tests/suite/mod.rs index 052c43bf38..77012ee3b7 100644 --- a/codex-rs/exec/tests/suite/mod.rs +++ b/codex-rs/exec/tests/suite/mod.rs @@ -1,4 +1,5 @@ // Aggregates all former standalone integration tests as modules. +mod add_dir; mod apply_patch; mod auth_env; mod originator; diff --git a/sdk/typescript/src/exec.ts b/sdk/typescript/src/exec.ts index be05e7c3ea..3c47c5572e 100644 --- a/sdk/typescript/src/exec.ts +++ b/sdk/typescript/src/exec.ts @@ -18,6 +18,8 @@ export type CodexExecArgs = { sandboxMode?: SandboxMode; // --cd workingDirectory?: string; + // --add-dir + additionalDirectories?: string[]; // --skip-git-repo-check skipGitRepoCheck?: boolean; // --output-schema @@ -58,6 +60,12 @@ export class CodexExec { commandArgs.push("--cd", args.workingDirectory); } + if (args.additionalDirectories?.length) { + for (const dir of args.additionalDirectories) { + commandArgs.push("--add-dir", dir); + } + } + if (args.skipGitRepoCheck) { commandArgs.push("--skip-git-repo-check"); } diff --git a/sdk/typescript/src/thread.ts b/sdk/typescript/src/thread.ts index 90c7a8face..6aed29c849 100644 --- a/sdk/typescript/src/thread.ts +++ b/sdk/typescript/src/thread.ts @@ -90,6 +90,7 @@ export class Thread { networkAccessEnabled: options?.networkAccessEnabled, webSearchEnabled: options?.webSearchEnabled, approvalPolicy: options?.approvalPolicy, + additionalDirectories: options?.additionalDirectories, }); try { for await (const item of generator) { diff --git a/sdk/typescript/src/threadOptions.ts b/sdk/typescript/src/threadOptions.ts index 77d91b89e5..d81ffc60c7 100644 --- a/sdk/typescript/src/threadOptions.ts +++ b/sdk/typescript/src/threadOptions.ts @@ -13,4 +13,5 @@ export type ThreadOptions = { networkAccessEnabled?: boolean; webSearchEnabled?: boolean; approvalPolicy?: ApprovalMode; + additionalDirectories?: string[]; }; diff --git a/sdk/typescript/tests/run.test.ts b/sdk/typescript/tests/run.test.ts index 1a85b5823e..586e396a36 100644 --- a/sdk/typescript/tests/run.test.ts +++ b/sdk/typescript/tests/run.test.ts @@ -348,6 +348,48 @@ describe("Codex", () => { } }); + it("passes additionalDirectories as repeated flags", async () => { + const { url, close } = await startResponsesTestProxy({ + statusCode: 200, + responseBodies: [ + sse( + responseStarted("response_1"), + assistantMessage("Additional directories applied", "item_1"), + responseCompleted("response_1"), + ), + ], + }); + + const { args: spawnArgs, restore } = codexExecSpy(); + + try { + const client = new Codex({ codexPathOverride: codexExecPath, baseUrl: url, apiKey: "test" }); + + const thread = client.startThread({ + additionalDirectories: ["../backend", "/tmp/shared"], + }); + await thread.run("test additional dirs"); + + const commandArgs = spawnArgs[0]; + expect(commandArgs).toBeDefined(); + if (!commandArgs) { + throw new Error("Command args missing"); + } + + // Find the --add-dir flags + const addDirArgs: string[] = []; + for (let i = 0; i < commandArgs.length; i += 1) { + if (commandArgs[i] === "--add-dir") { + addDirArgs.push(commandArgs[i + 1] ?? ""); + } + } + expect(addDirArgs).toEqual(["../backend", "/tmp/shared"]); + } finally { + restore(); + await close(); + } + }); + it("writes output schema to a temporary file and forwards it", async () => { const { url, close, requests } = await startResponsesTestProxy({ statusCode: 200, From 547be54ee87592c4d278cb2e9c03ba09913e8164 Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 13 Nov 2025 13:50:33 -0800 Subject: [PATCH 12/20] Only list failed tests (#6619) Makes output easier to parse --- .github/workflows/rust-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/rust-ci.yml b/.github/workflows/rust-ci.yml index 1a900bffd2..5d3103d7b2 100644 --- a/.github/workflows/rust-ci.yml +++ b/.github/workflows/rust-ci.yml @@ -406,10 +406,10 @@ jobs: - name: tests id: test - continue-on-error: true run: cargo nextest run --all-features --no-fail-fast --target ${{ matrix.target }} --cargo-profile ci-test env: RUST_BACKTRACE: 1 + NEXTEST_STATUS_LEVEL: leak - name: Save cargo home cache if: always() && !cancelled() && steps.cache_cargo_home_restore.outputs.cache-hit != 'true' From 2c1b693da453d9f8ebdb0e347140f464122a0c50 Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Thu, 13 Nov 2025 15:52:39 -0800 Subject: [PATCH 13/20] chore(core) Consolidate apply_patch tests (#6545) ## Summary Consolidates our apply_patch tests into one suite, and ensures each test case tests the various ways the harness supports apply_patch: 1. Freeform custom tool call 2. JSON function tool 3. Simple shell call 4. Heredoc shell call There are a few test cases that are specific to a particular variant, I've left those alone. ## Testing - [x] This adds a significant number of tests --- codex-rs/Cargo.lock | 34 + codex-rs/core/Cargo.toml | 1 + codex-rs/core/tests/common/responses.rs | 32 + codex-rs/core/tests/common/test_codex.rs | 22 + codex-rs/core/tests/suite/apply_patch_cli.rs | 276 +++-- .../core/tests/suite/apply_patch_freeform.rs | 1001 ----------------- codex-rs/core/tests/suite/mod.rs | 2 - 7 files changed, 289 insertions(+), 1079 deletions(-) delete mode 100644 codex-rs/core/tests/suite/apply_patch_freeform.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 35424d822a..d288c0f668 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1115,6 +1115,7 @@ dependencies = [ "similar", "strum_macros 0.27.2", "tempfile", + "test-case", "test-log", "thiserror 2.0.17", "time", @@ -6161,6 +6162,39 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" +[[package]] +name = "test-case" +version = "3.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb2550dd13afcd286853192af8601920d959b14c401fcece38071d53bf0768a8" +dependencies = [ + "test-case-macros", +] + +[[package]] +name = "test-case-core" +version = "3.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adcb7fd841cd518e279be3d5a3eb0636409487998a4aff22f3de87b81e88384f" +dependencies = [ + "cfg-if", + "proc-macro2", + "quote", + "syn 2.0.104", +] + +[[package]] +name = "test-case-macros" +version = "3.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c89e72a01ed4c579669add59014b9a524d609c0c88c6a585ce37485879f6ffb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.104", + "test-case-core", +] + [[package]] name = "test-log" version = "0.2.18" diff --git a/codex-rs/core/Cargo.toml b/codex-rs/core/Cargo.toml index 6839504be5..ab732c910c 100644 --- a/codex-rs/core/Cargo.toml +++ b/codex-rs/core/Cargo.toml @@ -60,6 +60,7 @@ shlex = { workspace = true } similar = { workspace = true } strum_macros = { workspace = true } tempfile = { workspace = true } +test-case = "3.3.1" test-log = { workspace = true } thiserror = { workspace = true } time = { workspace = true, features = [ diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index 8a62903600..703461f941 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -12,6 +12,8 @@ use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path_regex; +use crate::test_codex::ApplyPatchModelOutput; + #[derive(Debug, Clone)] pub struct ResponseMock { requests: Arc>>, @@ -367,6 +369,21 @@ pub fn ev_local_shell_call(call_id: &str, status: &str, command: Vec<&str>) -> V }) } +pub fn ev_apply_patch_call( + call_id: &str, + patch: &str, + output_type: ApplyPatchModelOutput, +) -> Value { + match output_type { + ApplyPatchModelOutput::Freeform => ev_apply_patch_custom_tool_call(call_id, patch), + ApplyPatchModelOutput::Function => ev_apply_patch_function_call(call_id, patch), + ApplyPatchModelOutput::Shell => ev_apply_patch_shell_call(call_id, patch), + ApplyPatchModelOutput::ShellViaHeredoc => { + ev_apply_patch_shell_call_via_heredoc(call_id, patch) + } + } +} + /// Convenience: SSE event for an `apply_patch` custom tool call with raw patch /// text. This mirrors the payload produced by the Responses API when the model /// invokes `apply_patch` directly (before we convert it to a function call). @@ -400,6 +417,21 @@ pub fn ev_apply_patch_function_call(call_id: &str, patch: &str) -> Value { }) } +pub fn ev_apply_patch_shell_call(call_id: &str, patch: &str) -> Value { + let args = serde_json::json!({ "command": ["apply_patch", patch] }); + let arguments = serde_json::to_string(&args).expect("serialize apply_patch arguments"); + + ev_function_call(call_id, "shell", &arguments) +} + +pub fn ev_apply_patch_shell_call_via_heredoc(call_id: &str, patch: &str) -> Value { + let script = format!("apply_patch <<'EOF'\n{patch}\nEOF\n"); + let args = serde_json::json!({ "command": ["bash", "-lc", script] }); + let arguments = serde_json::to_string(&args).expect("serialize apply_patch arguments"); + + ev_function_call(call_id, "shell", &arguments) +} + pub fn sse_failed(id: &str, code: &str, message: &str) -> String { sse(vec![serde_json::json!({ "type": "response.failed", diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index e56446c5ca..2741d8bed1 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -29,6 +29,15 @@ use crate::wait_for_event; type ConfigMutator = dyn FnOnce(&mut Config) + Send; +/// A collection of different ways the model can output an apply_patch call +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ApplyPatchModelOutput { + Freeform, + Function, + Shell, + ShellViaHeredoc, +} + pub struct TestCodexBuilder { config_mutators: Vec>, } @@ -265,6 +274,19 @@ impl TestCodexHarness { .expect("output string") .to_string() } + + pub async fn apply_patch_output( + &self, + call_id: &str, + output_type: ApplyPatchModelOutput, + ) -> String { + match output_type { + ApplyPatchModelOutput::Freeform => self.custom_tool_call_output(call_id).await, + ApplyPatchModelOutput::Function + | ApplyPatchModelOutput::Shell + | ApplyPatchModelOutput::ShellViaHeredoc => self.function_call_stdout(call_id).await, + } + } } fn custom_tool_call_output<'a>(bodies: &'a [Value], call_id: &str) -> &'a Value { diff --git a/codex-rs/core/tests/suite/apply_patch_cli.rs b/codex-rs/core/tests/suite/apply_patch_cli.rs index 6e9761ae4a..db20370370 100644 --- a/codex-rs/core/tests/suite/apply_patch_cli.rs +++ b/codex-rs/core/tests/suite/apply_patch_cli.rs @@ -1,6 +1,8 @@ #![allow(clippy::expect_used)] use anyhow::Result; +use core_test_support::responses::ev_apply_patch_call; +use core_test_support::test_codex::ApplyPatchModelOutput; use pretty_assertions::assert_eq; use std::fs; @@ -25,6 +27,7 @@ use core_test_support::skip_if_no_network; use core_test_support::test_codex::TestCodexHarness; use core_test_support::wait_for_event; use serde_json::json; +use test_case::test_case; async fn apply_patch_harness() -> Result { apply_patch_harness_with(|_| {}).await @@ -45,19 +48,25 @@ async fn mount_apply_patch( call_id: &str, patch: &str, assistant_msg: &str, + output_type: ApplyPatchModelOutput, ) { mount_sse_sequence( harness.server(), - apply_patch_responses(call_id, patch, assistant_msg), + apply_patch_responses(call_id, patch, assistant_msg, output_type), ) .await; } -fn apply_patch_responses(call_id: &str, patch: &str, assistant_msg: &str) -> Vec { +fn apply_patch_responses( + call_id: &str, + patch: &str, + assistant_msg: &str, + output_type: ApplyPatchModelOutput, +) -> Vec { vec![ sse(vec![ ev_response_created("resp-1"), - ev_apply_patch_function_call(call_id, patch), + ev_apply_patch_call(call_id, patch, output_type), ev_completed("resp-1"), ]), sse(vec![ @@ -68,7 +77,13 @@ fn apply_patch_responses(call_id: &str, patch: &str, assistant_msg: &str) -> Vec } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_multiple_operations_integration() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_multiple_operations_integration( + output_type: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness_with(|config| { @@ -86,11 +101,11 @@ async fn apply_patch_cli_multiple_operations_integration() -> Result<()> { let patch = "*** Begin Patch\n*** Add File: nested/new.txt\n+created\n*** Delete File: delete.txt\n*** Update File: modify.txt\n@@\n-line2\n+changed\n*** End Patch"; let call_id = "apply-multi-ops"; - mount_apply_patch(&harness, call_id, patch, "done").await; + mount_apply_patch(&harness, call_id, patch, "done", output_type).await; harness.submit("please apply multi-ops patch").await?; - let out = harness.function_call_stdout(call_id).await; + let out = harness.apply_patch_output(call_id, output_type).await; let expected = r"(?s)^Exit code: 0 Wall time: [0-9]+(?:\.[0-9]+)? seconds @@ -113,7 +128,11 @@ D delete.txt } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_multiple_chunks() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_multiple_chunks(model_output: ApplyPatchModelOutput) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -123,7 +142,7 @@ async fn apply_patch_cli_multiple_chunks() -> Result<()> { let patch = "*** Begin Patch\n*** Update File: multi.txt\n@@\n-line2\n+changed2\n@@\n-line4\n+changed4\n*** End Patch"; let call_id = "apply-multi-chunks"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("apply multi-chunk patch").await?; @@ -135,7 +154,13 @@ async fn apply_patch_cli_multiple_chunks() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_moves_file_to_new_directory() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_moves_file_to_new_directory( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -147,7 +172,7 @@ async fn apply_patch_cli_moves_file_to_new_directory() -> Result<()> { let patch = "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/dir/name.txt\n@@\n-old content\n+new content\n*** End Patch"; let call_id = "apply-move"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("apply move patch").await?; @@ -157,7 +182,13 @@ async fn apply_patch_cli_moves_file_to_new_directory() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_updates_file_appends_trailing_newline() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_updates_file_appends_trailing_newline( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -167,7 +198,7 @@ async fn apply_patch_cli_updates_file_appends_trailing_newline() -> Result<()> { let patch = "*** Begin Patch\n*** Update File: no_newline.txt\n@@\n-no newline at end\n+first line\n+second line\n*** End Patch"; let call_id = "apply-append-nl"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("apply newline patch").await?; @@ -178,7 +209,13 @@ async fn apply_patch_cli_updates_file_appends_trailing_newline() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_insert_only_hunk_modifies_file() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_insert_only_hunk_modifies_file( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -188,7 +225,7 @@ async fn apply_patch_cli_insert_only_hunk_modifies_file() -> Result<()> { let patch = "*** Begin Patch\n*** Update File: insert_only.txt\n@@\n alpha\n+beta\n omega\n*** End Patch"; let call_id = "apply-insert-only"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("insert lines via apply_patch").await?; @@ -197,7 +234,13 @@ async fn apply_patch_cli_insert_only_hunk_modifies_file() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_move_overwrites_existing_destination() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_move_overwrites_existing_destination( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -211,7 +254,7 @@ async fn apply_patch_cli_move_overwrites_existing_destination() -> Result<()> { let patch = "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/dir/name.txt\n@@\n-from\n+new\n*** End Patch"; let call_id = "apply-move-overwrite"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("apply move overwrite patch").await?; @@ -221,7 +264,13 @@ async fn apply_patch_cli_move_overwrites_existing_destination() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_move_without_content_change_has_no_turn_diff() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_move_without_content_change_has_no_turn_diff( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -236,7 +285,7 @@ async fn apply_patch_cli_move_without_content_change_has_no_turn_diff() -> Resul let patch = "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/name.txt\n@@\n same\n*** End Patch"; let call_id = "apply-move-no-change"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; let model = test.session_configured.model.clone(); codex @@ -272,7 +321,13 @@ async fn apply_patch_cli_move_without_content_change_has_no_turn_diff() -> Resul } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_add_overwrites_existing_file() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_add_overwrites_existing_file( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -282,7 +337,7 @@ async fn apply_patch_cli_add_overwrites_existing_file() -> Result<()> { let patch = "*** Begin Patch\n*** Add File: duplicate.txt\n+new content\n*** End Patch"; let call_id = "apply-add-overwrite"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("apply add overwrite patch").await?; @@ -291,18 +346,24 @@ async fn apply_patch_cli_add_overwrites_existing_file() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_rejects_invalid_hunk_header() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_rejects_invalid_hunk_header( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; let patch = "*** Begin Patch\n*** Frobnicate File: foo\n*** End Patch"; let call_id = "apply-invalid-header"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("apply invalid header patch").await?; - let out = harness.function_call_stdout(call_id).await; + let out = harness.apply_patch_output(call_id, model_output).await; assert!( out.contains("apply_patch verification failed"), @@ -316,7 +377,13 @@ async fn apply_patch_cli_rejects_invalid_hunk_header() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_reports_missing_context() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_reports_missing_context( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -327,11 +394,11 @@ async fn apply_patch_cli_reports_missing_context() -> Result<()> { let patch = "*** Begin Patch\n*** Update File: modify.txt\n@@\n-missing\n+changed\n*** End Patch"; let call_id = "apply-missing-context"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("apply missing context patch").await?; - let out = harness.function_call_stdout(call_id).await; + let out = harness.apply_patch_output(call_id, model_output).await; assert!( out.contains("apply_patch verification failed"), @@ -343,18 +410,24 @@ async fn apply_patch_cli_reports_missing_context() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_reports_missing_target_file() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_reports_missing_target_file( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; let patch = "*** Begin Patch\n*** Update File: missing.txt\n@@\n-nope\n+better\n*** End Patch"; let call_id = "apply-missing-file"; - mount_apply_patch(&harness, call_id, patch, "fail").await; + mount_apply_patch(&harness, call_id, patch, "fail", model_output).await; harness.submit("attempt to update a missing file").await?; - let out = harness.function_call_stdout(call_id).await; + let out = harness.apply_patch_output(call_id, model_output).await; assert!( out.contains("apply_patch verification failed"), "expected verification failure message" @@ -372,18 +445,24 @@ async fn apply_patch_cli_reports_missing_target_file() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_delete_missing_file_reports_error() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_delete_missing_file_reports_error( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; let patch = "*** Begin Patch\n*** Delete File: missing.txt\n*** End Patch"; let call_id = "apply-delete-missing"; - mount_apply_patch(&harness, call_id, patch, "fail").await; + mount_apply_patch(&harness, call_id, patch, "fail", model_output).await; harness.submit("attempt to delete missing file").await?; - let out = harness.function_call_stdout(call_id).await; + let out = harness.apply_patch_output(call_id, model_output).await; assert!( out.contains("apply_patch verification failed"), @@ -402,18 +481,22 @@ async fn apply_patch_cli_delete_missing_file_reports_error() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_rejects_empty_patch() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_rejects_empty_patch(model_output: ApplyPatchModelOutput) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; let patch = "*** Begin Patch\n*** End Patch"; let call_id = "apply-empty"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("apply empty patch").await?; - let out = harness.function_call_stdout(call_id).await; + let out = harness.apply_patch_output(call_id, model_output).await; assert!( out.contains("patch rejected: empty patch"), "expected rejection for empty patch: {out}" @@ -422,7 +505,13 @@ async fn apply_patch_cli_rejects_empty_patch() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_delete_directory_reports_verification_error() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_delete_directory_reports_verification_error( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -431,18 +520,24 @@ async fn apply_patch_cli_delete_directory_reports_verification_error() -> Result let patch = "*** Begin Patch\n*** Delete File: dir\n*** End Patch"; let call_id = "apply-delete-dir"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("delete a directory via apply_patch").await?; - let out = harness.function_call_stdout(call_id).await; + let out = harness.apply_patch_output(call_id, model_output).await; assert!(out.contains("apply_patch verification failed")); assert!(out.contains("Failed to read")); Ok(()) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_rejects_path_traversal_outside_workspace() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_rejects_path_traversal_outside_workspace( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -458,7 +553,7 @@ async fn apply_patch_cli_rejects_path_traversal_outside_workspace() -> Result<() let patch = "*** Begin Patch\n*** Add File: ../escape.txt\n+outside\n*** End Patch"; let call_id = "apply-path-traversal"; - mount_apply_patch(&harness, call_id, patch, "fail").await; + mount_apply_patch(&harness, call_id, patch, "fail", model_output).await; let sandbox_policy = SandboxPolicy::WorkspaceWrite { writable_roots: vec![], @@ -473,7 +568,7 @@ async fn apply_patch_cli_rejects_path_traversal_outside_workspace() -> Result<() ) .await?; - let out = harness.function_call_stdout(call_id).await; + let out = harness.apply_patch_output(call_id, model_output).await; assert!( out.contains( "patch rejected: writing outside of the project; rejected by user approval settings" @@ -488,7 +583,13 @@ async fn apply_patch_cli_rejects_path_traversal_outside_workspace() -> Result<() } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_rejects_move_path_traversal_outside_workspace() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_rejects_move_path_traversal_outside_workspace( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -507,7 +608,7 @@ async fn apply_patch_cli_rejects_move_path_traversal_outside_workspace() -> Resu let patch = "*** Begin Patch\n*** Update File: stay.txt\n*** Move to: ../escape-move.txt\n@@\n-from\n+to\n*** End Patch"; let call_id = "apply-move-traversal"; - mount_apply_patch(&harness, call_id, patch, "fail").await; + mount_apply_patch(&harness, call_id, patch, "fail", model_output).await; let sandbox_policy = SandboxPolicy::WorkspaceWrite { writable_roots: vec![], @@ -519,7 +620,7 @@ async fn apply_patch_cli_rejects_move_path_traversal_outside_workspace() -> Resu .submit_with_policy("attempt move traversal via apply_patch", sandbox_policy) .await?; - let out = harness.function_call_stdout(call_id).await; + let out = harness.apply_patch_output(call_id, model_output).await; assert!( out.contains( "patch rejected: writing outside of the project; rejected by user approval settings" @@ -535,7 +636,13 @@ async fn apply_patch_cli_rejects_move_path_traversal_outside_workspace() -> Resu } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_verification_failure_has_no_side_effects() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_verification_failure_has_no_side_effects( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness_with(|config| { @@ -547,7 +654,7 @@ async fn apply_patch_cli_verification_failure_has_no_side_effects() -> Result<() let call_id = "apply-partial-no-side-effects"; let patch = "*** Begin Patch\n*** Add File: created.txt\n+hello\n*** Update File: missing.txt\n@@\n-old\n+new\n*** End Patch"; - mount_apply_patch(&harness, call_id, patch, "failed").await; + mount_apply_patch(&harness, call_id, patch, "failed", model_output).await; harness.submit("attempt partial apply patch").await?; @@ -700,7 +807,14 @@ async fn apply_patch_function_accepts_lenient_heredoc_wrapped_patch() -> Result< format!("*** Begin Patch\n*** Add File: {file_name}\n+lenient\n*** End Patch\n"); let wrapped = format!("<<'EOF'\n{patch_inner}EOF\n"); let call_id = "apply-lenient"; - mount_apply_patch(&harness, call_id, &wrapped, "ok").await; + mount_apply_patch( + &harness, + call_id, + wrapped.as_str(), + "ok", + ApplyPatchModelOutput::Function, + ) + .await; harness.submit("apply lenient heredoc patch").await?; @@ -710,7 +824,11 @@ async fn apply_patch_function_accepts_lenient_heredoc_wrapped_patch() -> Result< } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_end_of_file_anchor() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_end_of_file_anchor(model_output: ApplyPatchModelOutput) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -720,7 +838,7 @@ async fn apply_patch_cli_end_of_file_anchor() -> Result<()> { let patch = "*** Begin Patch\n*** Update File: tail.txt\n@@\n-last\n+end\n*** End of File\n*** End Patch"; let call_id = "apply-eof"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("apply EOF-anchored patch").await?; assert_eq!(fs::read_to_string(&target)?, "alpha\nend\n"); @@ -728,7 +846,13 @@ async fn apply_patch_cli_end_of_file_anchor() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_missing_second_chunk_context_rejected() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_cli_missing_second_chunk_context_rejected( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -740,11 +864,11 @@ async fn apply_patch_cli_missing_second_chunk_context_rejected() -> Result<()> { let patch = "*** Begin Patch\n*** Update File: two_chunks.txt\n@@\n-b\n+B\n\n-d\n+D\n*** End Patch"; let call_id = "apply-missing-ctx-2nd"; - mount_apply_patch(&harness, call_id, patch, "fail").await; + mount_apply_patch(&harness, call_id, patch, "fail", model_output).await; harness.submit("apply missing context second chunk").await?; - let out = harness.function_call_stdout(call_id).await; + let out = harness.apply_patch_output(call_id, model_output).await; assert!(out.contains("apply_patch verification failed")); assert!( out.contains("Failed to find expected lines in"), @@ -756,7 +880,13 @@ async fn apply_patch_cli_missing_second_chunk_context_rejected() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_emits_turn_diff_event_with_unified_diff() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_emits_turn_diff_event_with_unified_diff( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -767,16 +897,7 @@ async fn apply_patch_emits_turn_diff_event_with_unified_diff() -> Result<()> { let call_id = "apply-diff-event"; let file = "udiff.txt"; let patch = format!("*** Begin Patch\n*** Add File: {file}\n+hello\n*** End Patch\n"); - let first = sse(vec![ - ev_response_created("resp-1"), - ev_apply_patch_function_call(call_id, &patch), - ev_completed("resp-1"), - ]); - let second = sse(vec![ - ev_assistant_message("msg-1", "ok"), - ev_completed("resp-2"), - ]); - mount_sse_sequence(harness.server(), vec![first, second]).await; + mount_apply_patch(&harness, call_id, patch.as_str(), "ok", model_output).await; let model = test.session_configured.model.clone(); codex @@ -814,7 +935,13 @@ async fn apply_patch_emits_turn_diff_event_with_unified_diff() -> Result<()> { } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_turn_diff_for_rename_with_content_change() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_turn_diff_for_rename_with_content_change( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -829,16 +956,7 @@ async fn apply_patch_turn_diff_for_rename_with_content_change() -> Result<()> { // Patch: update + move let call_id = "apply-rename-change"; let patch = "*** Begin Patch\n*** Update File: old.txt\n*** Move to: new.txt\n@@\n-old\n+new\n*** End Patch"; - let first = sse(vec![ - ev_response_created("resp-1"), - ev_apply_patch_function_call(call_id, patch), - ev_completed("resp-1"), - ]); - let second = sse(vec![ - ev_assistant_message("msg-1", "ok"), - ev_completed("resp-2"), - ]); - mount_sse_sequence(harness.server(), vec![first, second]).await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; let model = test.session_configured.model.clone(); codex @@ -1031,7 +1149,13 @@ async fn apply_patch_aggregates_diff_preserves_success_after_failure() -> Result } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_change_context_disambiguates_target() -> Result<()> { +#[test_case(ApplyPatchModelOutput::Freeform)] +#[test_case(ApplyPatchModelOutput::Function)] +#[test_case(ApplyPatchModelOutput::Shell)] +#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)] +async fn apply_patch_change_context_disambiguates_target( + model_output: ApplyPatchModelOutput, +) -> Result<()> { skip_if_no_network!(Ok(())); let harness = apply_patch_harness().await?; @@ -1042,7 +1166,7 @@ async fn apply_patch_change_context_disambiguates_target() -> Result<()> { let patch = "*** Begin Patch\n*** Update File: multi_ctx.txt\n@@ fn b\n-x=10\n+x=11\n*** End Patch"; let call_id = "apply-ctx"; - mount_apply_patch(&harness, call_id, patch, "ok").await; + mount_apply_patch(&harness, call_id, patch, "ok", model_output).await; harness.submit("apply with change_context").await?; diff --git a/codex-rs/core/tests/suite/apply_patch_freeform.rs b/codex-rs/core/tests/suite/apply_patch_freeform.rs deleted file mode 100644 index 72c405eb1b..0000000000 --- a/codex-rs/core/tests/suite/apply_patch_freeform.rs +++ /dev/null @@ -1,1001 +0,0 @@ -#![allow(clippy::expect_used)] - -use anyhow::Result; -use core_test_support::responses::ev_apply_patch_custom_tool_call; -use pretty_assertions::assert_eq; -use std::fs; - -use codex_core::config::Config; -use codex_core::features::Feature; -use codex_core::model_family::find_family_for_model; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::user_input::UserInput; -use core_test_support::assert_regex_match; -use core_test_support::responses::ev_assistant_message; -use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_response_created; -use core_test_support::responses::mount_sse_sequence; -use core_test_support::responses::sse; -use core_test_support::skip_if_no_network; -use core_test_support::test_codex::TestCodexHarness; -use core_test_support::wait_for_event; - -async fn apply_patch_harness() -> Result { - apply_patch_harness_with(|_| {}).await -} - -async fn apply_patch_harness_with( - configure: impl FnOnce(&mut Config) + Send + 'static, -) -> Result { - TestCodexHarness::with_config(|config| { - config.include_apply_patch_tool = true; - configure(config); - }) - .await -} - -async fn mount_apply_patch( - harness: &TestCodexHarness, - call_id: &str, - patch: &str, - assistant_msg: &str, -) { - mount_sse_sequence( - harness.server(), - freeform_apply_patch_responses(call_id, patch, assistant_msg), - ) - .await; -} - -fn freeform_apply_patch_responses(call_id: &str, patch: &str, assistant_msg: &str) -> Vec { - vec![ - sse(vec![ - ev_response_created("resp-1"), - ev_apply_patch_custom_tool_call(call_id, patch), - ev_completed("resp-1"), - ]), - sse(vec![ - ev_assistant_message("msg-1", assistant_msg), - ev_completed("resp-2"), - ]), - ] -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_multiple_operations_integration() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness_with(|config| { - config.model = "gpt-5".to_string(); - config.model_family = find_family_for_model("gpt-5").expect("gpt-5 is valid"); - }) - .await?; - - // Seed workspace state - let modify_path = harness.path("modify.txt"); - let delete_path = harness.path("delete.txt"); - fs::write(&modify_path, "line1\nline2\n")?; - fs::write(&delete_path, "obsolete\n")?; - - let patch = "*** Begin Patch\n*** Add File: nested/new.txt\n+created\n*** Delete File: delete.txt\n*** Update File: modify.txt\n@@\n-line2\n+changed\n*** End Patch"; - - let call_id = "apply-multi-ops"; - mount_apply_patch(&harness, call_id, patch, "done").await; - - harness.submit("please apply multi-ops patch").await?; - - let out = harness.custom_tool_call_output(call_id).await; - - let expected = r"(?s)^Exit code: 0 -Wall time: [0-9]+(?:\.[0-9]+)? seconds -Output: -Success. Updated the following files: -A nested/new.txt -M modify.txt -D delete.txt -?$"; - assert_regex_match(expected, &out); - - assert_eq!( - fs::read_to_string(harness.path("nested/new.txt"))?, - "created\n" - ); - assert_eq!(fs::read_to_string(&modify_path)?, "line1\nchanged\n"); - assert!(!delete_path.exists()); - - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_multiple_chunks() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let target = harness.path("multi.txt"); - fs::write(&target, "line1\nline2\nline3\nline4\n")?; - - let patch = "*** Begin Patch\n*** Update File: multi.txt\n@@\n-line2\n+changed2\n@@\n-line4\n+changed4\n*** End Patch"; - let call_id = "apply-multi-chunks"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("apply multi-chunk patch").await?; - - assert_eq!( - fs::read_to_string(&target)?, - "line1\nchanged2\nline3\nchanged4\n" - ); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_moves_file_to_new_directory() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let original = harness.path("old/name.txt"); - let new_path = harness.path("renamed/dir/name.txt"); - fs::create_dir_all(original.parent().expect("parent"))?; - fs::write(&original, "old content\n")?; - - let patch = "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/dir/name.txt\n@@\n-old content\n+new content\n*** End Patch"; - let call_id = "apply-move"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("apply move patch").await?; - - assert!(!original.exists()); - assert_eq!(fs::read_to_string(&new_path)?, "new content\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_updates_file_appends_trailing_newline() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let target = harness.path("no_newline.txt"); - fs::write(&target, "no newline at end")?; - - let patch = "*** Begin Patch\n*** Update File: no_newline.txt\n@@\n-no newline at end\n+first line\n+second line\n*** End Patch"; - let call_id = "apply-append-nl"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("apply newline patch").await?; - - let contents = fs::read_to_string(&target)?; - assert!(contents.ends_with('\n')); - assert_eq!(contents, "first line\nsecond line\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_insert_only_hunk_modifies_file() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let target = harness.path("insert_only.txt"); - fs::write(&target, "alpha\nomega\n")?; - - let patch = "*** Begin Patch\n*** Update File: insert_only.txt\n@@\n alpha\n+beta\n omega\n*** End Patch"; - let call_id = "apply-insert-only"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("insert lines via apply_patch").await?; - - assert_eq!(fs::read_to_string(&target)?, "alpha\nbeta\nomega\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_move_overwrites_existing_destination() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let original = harness.path("old/name.txt"); - let destination = harness.path("renamed/dir/name.txt"); - fs::create_dir_all(original.parent().expect("parent"))?; - fs::create_dir_all(destination.parent().expect("parent"))?; - fs::write(&original, "from\n")?; - fs::write(&destination, "existing\n")?; - - let patch = "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/dir/name.txt\n@@\n-from\n+new\n*** End Patch"; - let call_id = "apply-move-overwrite"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("apply move overwrite patch").await?; - - assert!(!original.exists()); - assert_eq!(fs::read_to_string(&destination)?, "new\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_move_without_content_change_has_no_turn_diff() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - let test = harness.test(); - let codex = test.codex.clone(); - let cwd = test.cwd.clone(); - - let original = harness.path("old/name.txt"); - let destination = harness.path("renamed/name.txt"); - fs::create_dir_all(original.parent().expect("parent should exist"))?; - fs::write(&original, "same\n")?; - - let patch = "*** Begin Patch\n*** Update File: old/name.txt\n*** Move to: renamed/name.txt\n@@\n same\n*** End Patch"; - let call_id = "apply-move-no-change"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - let model = test.session_configured.model.clone(); - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "rename without content change".into(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model, - effort: None, - summary: ReasoningSummary::Auto, - }) - .await?; - - let mut saw_turn_diff = false; - wait_for_event(&codex, |event| match event { - EventMsg::TurnDiff(_) => { - saw_turn_diff = true; - false - } - EventMsg::TaskComplete(_) => true, - _ => false, - }) - .await; - - assert!(!saw_turn_diff, "pure rename should not emit a turn diff"); - assert!(!original.exists()); - assert_eq!(fs::read_to_string(&destination)?, "same\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_add_overwrites_existing_file() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let path = harness.path("duplicate.txt"); - fs::write(&path, "old content\n")?; - - let patch = "*** Begin Patch\n*** Add File: duplicate.txt\n+new content\n*** End Patch"; - let call_id = "apply-add-overwrite"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("apply add overwrite patch").await?; - - assert_eq!(fs::read_to_string(&path)?, "new content\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_rejects_invalid_hunk_header() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let patch = "*** Begin Patch\n*** Frobnicate File: foo\n*** End Patch"; - let call_id = "apply-invalid-header"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("apply invalid header patch").await?; - - let out = harness.custom_tool_call_output(call_id).await; - - assert!( - out.contains("apply_patch verification failed"), - "expected verification failure message" - ); - assert!( - out.contains("is not a valid hunk header"), - "expected parse diagnostics in output: {out:?}" - ); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_reports_missing_context() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let target = harness.path("modify.txt"); - fs::write(&target, "line1\nline2\n")?; - - let patch = - "*** Begin Patch\n*** Update File: modify.txt\n@@\n-missing\n+changed\n*** End Patch"; - let call_id = "apply-missing-context"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("apply missing context patch").await?; - - let out = harness.custom_tool_call_output(call_id).await; - - assert!( - out.contains("apply_patch verification failed"), - "expected verification failure message" - ); - assert!(out.contains("Failed to find expected lines in")); - assert_eq!(fs::read_to_string(&target)?, "line1\nline2\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_reports_missing_target_file() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let patch = "*** Begin Patch\n*** Update File: missing.txt\n@@\n-nope\n+better\n*** End Patch"; - let call_id = "apply-missing-file"; - mount_apply_patch(&harness, call_id, patch, "fail").await; - - harness.submit("attempt to update a missing file").await?; - - let out = harness.custom_tool_call_output(call_id).await; - assert!( - out.contains("apply_patch verification failed"), - "expected verification failure message" - ); - assert!( - out.contains("Failed to read file to update"), - "expected missing file diagnostics: {out}" - ); - assert!( - out.contains("missing.txt"), - "expected missing file path in diagnostics: {out}" - ); - assert!(!harness.path("missing.txt").exists()); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_delete_missing_file_reports_error() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let patch = "*** Begin Patch\n*** Delete File: missing.txt\n*** End Patch"; - let call_id = "apply-delete-missing"; - mount_apply_patch(&harness, call_id, patch, "fail").await; - - harness.submit("attempt to delete missing file").await?; - - let out = harness.custom_tool_call_output(call_id).await; - - assert!( - out.contains("apply_patch verification failed"), - "expected verification failure message: {out}" - ); - assert!( - out.contains("Failed to read"), - "missing delete diagnostics should mention read failure: {out}" - ); - assert!( - out.contains("missing.txt"), - "missing delete diagnostics should surface target path: {out}" - ); - assert!(!harness.path("missing.txt").exists()); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_rejects_empty_patch() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let patch = "*** Begin Patch\n*** End Patch"; - let call_id = "apply-empty"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("apply empty patch").await?; - - let out = harness.custom_tool_call_output(call_id).await; - assert!( - out.contains("patch rejected: empty patch"), - "expected rejection for empty patch: {out}" - ); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_delete_directory_reports_verification_error() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - fs::create_dir(harness.path("dir"))?; - - let patch = "*** Begin Patch\n*** Delete File: dir\n*** End Patch"; - let call_id = "apply-delete-dir"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("delete a directory via apply_patch").await?; - - let out = harness.custom_tool_call_output(call_id).await; - assert!(out.contains("apply_patch verification failed")); - assert!(out.contains("Failed to read")); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_rejects_path_traversal_outside_workspace() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let escape_path = harness - .test() - .cwd - .path() - .parent() - .expect("cwd should have parent") - .join("escape.txt"); - let _ = fs::remove_file(&escape_path); - - let patch = "*** Begin Patch\n*** Add File: ../escape.txt\n+outside\n*** End Patch"; - let call_id = "apply-path-traversal"; - mount_apply_patch(&harness, call_id, patch, "fail").await; - - let sandbox_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], - network_access: false, - exclude_tmpdir_env_var: true, - exclude_slash_tmp: true, - }; - harness - .submit_with_policy( - "attempt to escape workspace via apply_patch", - sandbox_policy, - ) - .await?; - - let out = harness.custom_tool_call_output(call_id).await; - assert!( - out.contains( - "patch rejected: writing outside of the project; rejected by user approval settings" - ), - "expected rejection message for path traversal: {out}" - ); - assert!( - !escape_path.exists(), - "path traversal should be rejected; tool output: {out}" - ); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_rejects_move_path_traversal_outside_workspace() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let escape_path = harness - .test() - .cwd - .path() - .parent() - .expect("cwd should have parent") - .join("escape-move.txt"); - let _ = fs::remove_file(&escape_path); - - let source = harness.path("stay.txt"); - fs::write(&source, "from\n")?; - - let patch = "*** Begin Patch\n*** Update File: stay.txt\n*** Move to: ../escape-move.txt\n@@\n-from\n+to\n*** End Patch"; - let call_id = "apply-move-traversal"; - mount_apply_patch(&harness, call_id, patch, "fail").await; - - let sandbox_policy = SandboxPolicy::WorkspaceWrite { - writable_roots: vec![], - network_access: false, - exclude_tmpdir_env_var: true, - exclude_slash_tmp: true, - }; - harness - .submit_with_policy("attempt move traversal via apply_patch", sandbox_policy) - .await?; - - let out = harness.custom_tool_call_output(call_id).await; - assert!( - out.contains( - "patch rejected: writing outside of the project; rejected by user approval settings" - ), - "expected rejection message for path traversal: {out}" - ); - assert!( - !escape_path.exists(), - "move path traversal should be rejected; tool output: {out}" - ); - assert_eq!(fs::read_to_string(&source)?, "from\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_verification_failure_has_no_side_effects() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness_with(|config| { - config.features.enable(Feature::ApplyPatchFreeform); - }) - .await?; - - // Compose a patch that would create a file, then fail verification on an update. - let call_id = "apply-partial-no-side-effects"; - let patch = "*** Begin Patch\n*** Add File: created.txt\n+hello\n*** Update File: missing.txt\n@@\n-old\n+new\n*** End Patch"; - - mount_apply_patch(&harness, call_id, patch, "failed").await; - - harness.submit("attempt partial apply patch").await?; - - let created = harness.path("created.txt"); - assert!( - !created.exists(), - "verification failure should prevent any filesystem changes" - ); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_shell_failure_propagates_error_and_skips_diff() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness_with(|config| { - config.model = "gpt-5".to_string(); - config.model_family = find_family_for_model("gpt-5").expect("gpt-5 is valid"); - }) - .await?; - let test = harness.test(); - let codex = test.codex.clone(); - let cwd = test.cwd.clone(); - - let target = cwd.path().join("invalid.txt"); - fs::write(&target, "ok\n")?; - - let patch = - "*** Begin Patch\n*** Update File: invalid.txt\n@@\n-nope\n+changed\n*** End Patch\n"; - let call_id = "shell-apply-failure"; - let bodies = vec![ - sse(vec![ - ev_response_created("resp-1"), - ev_apply_patch_custom_tool_call(call_id, patch), - ev_completed("resp-1"), - ]), - sse(vec![ - ev_assistant_message("msg-1", "fail"), - ev_completed("resp-2"), - ]), - ]; - mount_sse_sequence(harness.server(), bodies).await; - - let model = test.session_configured.model.clone(); - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "apply patch via shell".into(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model, - effort: None, - summary: ReasoningSummary::Auto, - }) - .await?; - - let mut saw_turn_diff = false; - wait_for_event(&codex, |event| match event { - EventMsg::TurnDiff(_) => { - saw_turn_diff = true; - false - } - EventMsg::TaskComplete(_) => true, - _ => false, - }) - .await; - - assert!( - !saw_turn_diff, - "turn diff should not be emitted when shell apply_patch fails verification" - ); - - let out = harness.custom_tool_call_output(call_id).await; - assert!( - out.contains("apply_patch verification failed"), - "expected verification failure message" - ); - assert!( - out.contains("Failed to find expected lines in"), - "expected failure diagnostics: {out}" - ); - assert!( - out.contains("invalid.txt"), - "expected file path in output: {out}" - ); - assert_eq!(fs::read_to_string(&target)?, "ok\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_function_accepts_lenient_heredoc_wrapped_patch() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let file_name = "lenient.txt"; - let patch_inner = - format!("*** Begin Patch\n*** Add File: {file_name}\n+lenient\n*** End Patch\n"); - let wrapped = format!("<<'EOF'\n{patch_inner}EOF\n"); - let call_id = "apply-lenient"; - mount_apply_patch(&harness, call_id, &wrapped, "ok").await; - - harness.submit("apply lenient heredoc patch").await?; - - let new_file = harness.path(file_name); - assert_eq!(fs::read_to_string(new_file)?, "lenient\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_end_of_file_anchor() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let target = harness.path("tail.txt"); - fs::write(&target, "alpha\nlast\n")?; - - let patch = "*** Begin Patch\n*** Update File: tail.txt\n@@\n-last\n+end\n*** End of File\n*** End Patch"; - let call_id = "apply-eof"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("apply EOF-anchored patch").await?; - assert_eq!(fs::read_to_string(&target)?, "alpha\nend\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_cli_missing_second_chunk_context_rejected() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let target = harness.path("two_chunks.txt"); - fs::write(&target, "a\nb\nc\nd\n")?; - - // First chunk has @@, second chunk intentionally omits @@ to trigger parse error. - let patch = - "*** Begin Patch\n*** Update File: two_chunks.txt\n@@\n-b\n+B\n\n-d\n+D\n*** End Patch"; - let call_id = "apply-missing-ctx-2nd"; - mount_apply_patch(&harness, call_id, patch, "fail").await; - - harness.submit("apply missing context second chunk").await?; - - let out = harness.custom_tool_call_output(call_id).await; - assert!(out.contains("apply_patch verification failed")); - assert!( - out.contains("Failed to find expected lines in"), - "expected hunk context diagnostics: {out}" - ); - // Original file unchanged on failure - assert_eq!(fs::read_to_string(&target)?, "a\nb\nc\nd\n"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_emits_turn_diff_event_with_unified_diff() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - let test = harness.test(); - let codex = test.codex.clone(); - let cwd = test.cwd.clone(); - - let call_id = "apply-diff-event"; - let file = "udiff.txt"; - let patch = format!("*** Begin Patch\n*** Add File: {file}\n+hello\n*** End Patch\n"); - let first = sse(vec![ - ev_response_created("resp-1"), - ev_apply_patch_custom_tool_call(call_id, &patch), - ev_completed("resp-1"), - ]); - let second = sse(vec![ - ev_assistant_message("msg-1", "ok"), - ev_completed("resp-2"), - ]); - mount_sse_sequence(harness.server(), vec![first, second]).await; - - let model = test.session_configured.model.clone(); - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "emit diff".into(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model, - effort: None, - summary: ReasoningSummary::Auto, - }) - .await?; - - let mut saw_turn_diff = None; - wait_for_event(&codex, |event| match event { - EventMsg::TurnDiff(ev) => { - saw_turn_diff = Some(ev.unified_diff.clone()); - false - } - EventMsg::TaskComplete(_) => true, - _ => false, - }) - .await; - - let diff = saw_turn_diff.expect("expected TurnDiff event"); - // Basic markers of a unified diff with file addition - assert!(diff.contains("diff --git"), "diff header missing: {diff:?}"); - assert!(diff.contains("--- /dev/null") || diff.contains("--- a/")); - assert!(diff.contains("+++ b/")); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_turn_diff_for_rename_with_content_change() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - let test = harness.test(); - let codex = test.codex.clone(); - let cwd = test.cwd.clone(); - - // Seed original file - let old = cwd.path().join("old.txt"); - fs::write(&old, "old\n")?; - - // Patch: update + move - let call_id = "apply-rename-change"; - let patch = "*** Begin Patch\n*** Update File: old.txt\n*** Move to: new.txt\n@@\n-old\n+new\n*** End Patch"; - let first = sse(vec![ - ev_response_created("resp-1"), - ev_apply_patch_custom_tool_call(call_id, patch), - ev_completed("resp-1"), - ]); - let second = sse(vec![ - ev_assistant_message("msg-1", "ok"), - ev_completed("resp-2"), - ]); - mount_sse_sequence(harness.server(), vec![first, second]).await; - - let model = test.session_configured.model.clone(); - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "rename with change".into(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model, - effort: None, - summary: ReasoningSummary::Auto, - }) - .await?; - - let mut last_diff: Option = None; - wait_for_event(&codex, |event| match event { - EventMsg::TurnDiff(ev) => { - last_diff = Some(ev.unified_diff.clone()); - false - } - EventMsg::TaskComplete(_) => true, - _ => false, - }) - .await; - - let diff = last_diff.expect("expected TurnDiff event after rename"); - // Basic checks: shows old -> new, and the content delta - assert!(diff.contains("old.txt"), "diff missing old path: {diff:?}"); - assert!(diff.contains("new.txt"), "diff missing new path: {diff:?}"); - assert!(diff.contains("--- a/"), "missing old header"); - assert!(diff.contains("+++ b/"), "missing new header"); - assert!(diff.contains("-old\n"), "missing removal line"); - assert!(diff.contains("+new\n"), "missing addition line"); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_aggregates_diff_across_multiple_tool_calls() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - let test = harness.test(); - let codex = test.codex.clone(); - let cwd = test.cwd.clone(); - - let call1 = "agg-1"; - let call2 = "agg-2"; - let patch1 = "*** Begin Patch\n*** Add File: agg/a.txt\n+v1\n*** End Patch"; - let patch2 = "*** Begin Patch\n*** Update File: agg/a.txt\n@@\n-v1\n+v2\n*** Add File: agg/b.txt\n+B\n*** End Patch"; - - let s1 = sse(vec![ - ev_response_created("resp-1"), - ev_apply_patch_custom_tool_call(call1, patch1), - ev_completed("resp-1"), - ]); - let s2 = sse(vec![ - ev_response_created("resp-2"), - ev_apply_patch_custom_tool_call(call2, patch2), - ev_completed("resp-2"), - ]); - let s3 = sse(vec![ - ev_assistant_message("msg-1", "ok"), - ev_completed("resp-3"), - ]); - mount_sse_sequence(harness.server(), vec![s1, s2, s3]).await; - - let model = test.session_configured.model.clone(); - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "aggregate diffs".into(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model, - effort: None, - summary: ReasoningSummary::Auto, - }) - .await?; - - let mut last_diff: Option = None; - wait_for_event(&codex, |event| match event { - EventMsg::TurnDiff(ev) => { - last_diff = Some(ev.unified_diff.clone()); - false - } - EventMsg::TaskComplete(_) => true, - _ => false, - }) - .await; - - let diff = last_diff.expect("expected TurnDiff after two patches"); - assert!(diff.contains("agg/a.txt"), "diff missing a.txt"); - assert!(diff.contains("agg/b.txt"), "diff missing b.txt"); - // Final content reflects v2 for a.txt - assert!(diff.contains("+v2\n") || diff.contains("v2\n")); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_aggregates_diff_preserves_success_after_failure() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - let test = harness.test(); - let codex = test.codex.clone(); - let cwd = test.cwd.clone(); - - let call_success = "agg-success"; - let call_failure = "agg-failure"; - let patch_success = "*** Begin Patch\n*** Add File: partial/success.txt\n+ok\n*** End Patch"; - let patch_failure = - "*** Begin Patch\n*** Update File: partial/success.txt\n@@\n-missing\n+new\n*** End Patch"; - - let responses = vec![ - sse(vec![ - ev_response_created("resp-1"), - ev_apply_patch_custom_tool_call(call_success, patch_success), - ev_completed("resp-1"), - ]), - sse(vec![ - ev_response_created("resp-2"), - ev_apply_patch_custom_tool_call(call_failure, patch_failure), - ev_completed("resp-2"), - ]), - sse(vec![ - ev_assistant_message("msg-1", "failed"), - ev_completed("resp-3"), - ]), - ]; - mount_sse_sequence(harness.server(), responses).await; - - let model = test.session_configured.model.clone(); - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "apply patch twice with failure".into(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model, - effort: None, - summary: ReasoningSummary::Auto, - }) - .await?; - - let mut last_diff: Option = None; - wait_for_event(&codex, |event| match event { - EventMsg::TurnDiff(ev) => { - last_diff = Some(ev.unified_diff.clone()); - false - } - EventMsg::TaskComplete(_) => true, - _ => false, - }) - .await; - - let diff = last_diff.expect("expected TurnDiff after failed patch"); - assert!( - diff.contains("partial/success.txt"), - "diff should still include the successful addition: {diff}" - ); - assert!( - diff.contains("+ok"), - "diff should include contents from successful patch: {diff}" - ); - - let failure_out = harness.custom_tool_call_output(call_failure).await; - assert!( - failure_out.contains("apply_patch verification failed"), - "expected verification failure output: {failure_out}" - ); - assert!( - failure_out.contains("Failed to find expected lines in"), - "expected missing context diagnostics: {failure_out}" - ); - - assert_eq!( - fs::read_to_string(cwd.path().join("partial/success.txt"))?, - "ok\n" - ); - Ok(()) -} - -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn apply_patch_change_context_disambiguates_target() -> Result<()> { - skip_if_no_network!(Ok(())); - - let harness = apply_patch_harness().await?; - - let target = harness.path("multi_ctx.txt"); - fs::write(&target, "fn a\nx=10\ny=2\nfn b\nx=10\ny=20\n")?; - - let patch = - "*** Begin Patch\n*** Update File: multi_ctx.txt\n@@ fn b\n-x=10\n+x=11\n*** End Patch"; - let call_id = "apply-ctx"; - mount_apply_patch(&harness, call_id, patch, "ok").await; - - harness.submit("apply with change_context").await?; - - let contents = fs::read_to_string(&target)?; - assert_eq!(contents, "fn a\nx=10\ny=2\nfn b\nx=11\ny=20\n"); - Ok(()) -} diff --git a/codex-rs/core/tests/suite/mod.rs b/codex-rs/core/tests/suite/mod.rs index a19bfa2505..2224939afd 100644 --- a/codex-rs/core/tests/suite/mod.rs +++ b/codex-rs/core/tests/suite/mod.rs @@ -18,8 +18,6 @@ mod abort_tasks; #[cfg(not(target_os = "windows"))] mod apply_patch_cli; #[cfg(not(target_os = "windows"))] -mod apply_patch_freeform; -#[cfg(not(target_os = "windows"))] mod approvals; mod auth_refresh; mod cli_stream; From b8ec97c0ef37e4acc6b6243d893989183a478467 Mon Sep 17 00:00:00 2001 From: Celia Chen Date: Thu, 13 Nov 2025 16:25:01 -0800 Subject: [PATCH 14/20] [App-server] add new v2 events:`item/reasoning/delta`, `item/agentMessage/delta` & `item/reasoning/summaryPartAdded` (#6559) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit core event to app server event mapping: 1. `codex/event/reasoning_content_delta` -> `item/reasoning/summaryTextDelta`. 2. `codex/event/reasoning_raw_content_delta` -> `item/reasoning/textDelta` 3. `codex/event/agent_message_content_delta` → `item/agentMessage/delta`. 4. `codex/event/agent_reasoning_section_break` -> `item/reasoning/summaryPartAdded`. Also added a change in core to pass down content index, summary index and item id from events. Tested with the `git checkout owen/app_server_test_client && cargo run -p codex-app-server-test-client -- send-message-v2 "hello"` and verified that new events are emitted correctly. --- .../src/protocol/common.rs | 3 ++ .../app-server-protocol/src/protocol/v2.rs | 50 ++++++++++++++----- .../app-server/src/codex_message_processor.rs | 46 +++++++++++++++++ codex-rs/core/src/chat_completions.rs | 20 ++++++-- codex-rs/core/src/client.rs | 26 +++++++--- codex-rs/core/src/client_common.rs | 14 ++++-- codex-rs/core/src/codex.rs | 31 +++++++++--- codex-rs/core/tests/chat_completions_sse.rs | 40 +++++++++++++-- codex-rs/core/tests/common/responses.rs | 2 + codex-rs/protocol/src/protocol.rs | 14 +++++- 10 files changed, 203 insertions(+), 43 deletions(-) diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index f754ece562..d36e81be02 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -508,6 +508,9 @@ server_notification_definitions! { McpToolCallProgress => "item/mcpToolCall/progress" (v2::McpToolCallProgressNotification), AccountUpdated => "account/updated" (v2::AccountUpdatedNotification), AccountRateLimitsUpdated => "account/rateLimits/updated" (v2::AccountRateLimitsUpdatedNotification), + ReasoningSummaryTextDelta => "item/reasoning/summaryTextDelta" (v2::ReasoningSummaryTextDeltaNotification), + ReasoningSummaryPartAdded => "item/reasoning/summaryPartAdded" (v2::ReasoningSummaryPartAddedNotification), + ReasoningTextDelta => "item/reasoning/textDelta" (v2::ReasoningTextDeltaNotification), #[serde(rename = "account/login/completed")] #[ts(rename = "account/login/completed")] diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 10196884aa..4642798c68 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -516,7 +516,10 @@ pub enum ThreadItem { }, Reasoning { id: String, - text: String, + #[serde(default)] + summary: Vec, + #[serde(default)] + content: Vec, }, CommandExecution { id: String, @@ -575,17 +578,11 @@ impl From for ThreadItem { .collect::(); ThreadItem::AgentMessage { id: agent.id, text } } - CoreTurnItem::Reasoning(reasoning) => { - let text = if !reasoning.summary_text.is_empty() { - reasoning.summary_text.join("\n") - } else { - reasoning.raw_content.join("\n") - }; - ThreadItem::Reasoning { - id: reasoning.id, - text, - } - } + CoreTurnItem::Reasoning(reasoning) => ThreadItem::Reasoning { + id: reasoning.id, + summary: reasoning.summary_text, + content: reasoning.raw_content, + }, CoreTurnItem::WebSearch(search) => ThreadItem::WebSearch { id: search.id, query: search.query, @@ -719,6 +716,32 @@ pub struct AgentMessageDeltaNotification { pub delta: String, } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ReasoningSummaryTextDeltaNotification { + pub item_id: String, + pub delta: String, + pub summary_index: i64, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ReasoningSummaryPartAddedNotification { + pub item_id: String, + pub summary_index: i64, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ReasoningTextDeltaNotification { + pub item_id: String, + pub delta: String, + pub content_index: i64, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -867,7 +890,8 @@ mod tests { ThreadItem::from(reasoning_item), ThreadItem::Reasoning { id: "reasoning-1".to_string(), - text: "line one\nline two".to_string(), + summary: vec!["line one".to_string(), "line two".to_string()], + content: vec![], } ); diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 23fbe59a90..b012458da9 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -12,6 +12,7 @@ use codex_app_server_protocol::AccountRateLimitsUpdatedNotification; use codex_app_server_protocol::AccountUpdatedNotification; use codex_app_server_protocol::AddConversationListenerParams; use codex_app_server_protocol::AddConversationSubscriptionResponse; +use codex_app_server_protocol::AgentMessageDeltaNotification; use codex_app_server_protocol::ApplyPatchApprovalParams; use codex_app_server_protocol::ApplyPatchApprovalResponse; use codex_app_server_protocol::ArchiveConversationParams; @@ -62,6 +63,9 @@ use codex_app_server_protocol::ModelListParams; use codex_app_server_protocol::ModelListResponse; use codex_app_server_protocol::NewConversationParams; use codex_app_server_protocol::NewConversationResponse; +use codex_app_server_protocol::ReasoningSummaryPartAddedNotification; +use codex_app_server_protocol::ReasoningSummaryTextDeltaNotification; +use codex_app_server_protocol::ReasoningTextDeltaNotification; use codex_app_server_protocol::RemoveConversationListenerParams; use codex_app_server_protocol::RemoveConversationSubscriptionResponse; use codex_app_server_protocol::RequestId; @@ -2681,6 +2685,48 @@ async fn apply_bespoke_event_handling( on_patch_approval_response(event_id, rx, conversation).await; }); } + EventMsg::AgentMessageContentDelta(event) => { + let notification = AgentMessageDeltaNotification { + item_id: event.item_id, + delta: event.delta, + }; + outgoing + .send_server_notification(ServerNotification::AgentMessageDelta(notification)) + .await; + } + EventMsg::ReasoningContentDelta(event) => { + let notification = ReasoningSummaryTextDeltaNotification { + item_id: event.item_id, + delta: event.delta, + summary_index: event.summary_index, + }; + outgoing + .send_server_notification(ServerNotification::ReasoningSummaryTextDelta( + notification, + )) + .await; + } + EventMsg::ReasoningRawContentDelta(event) => { + let notification = ReasoningTextDeltaNotification { + item_id: event.item_id, + delta: event.delta, + content_index: event.content_index, + }; + outgoing + .send_server_notification(ServerNotification::ReasoningTextDelta(notification)) + .await; + } + EventMsg::AgentReasoningSectionBreak(event) => { + let notification = ReasoningSummaryPartAddedNotification { + item_id: event.item_id, + summary_index: event.summary_index, + }; + outgoing + .send_server_notification(ServerNotification::ReasoningSummaryPartAdded( + notification, + )) + .await; + } EventMsg::ExecApprovalRequest(ExecApprovalRequestEvent { call_id, command, diff --git a/codex-rs/core/src/chat_completions.rs b/codex-rs/core/src/chat_completions.rs index d8d3a63d13..5b9578e759 100644 --- a/codex-rs/core/src/chat_completions.rs +++ b/codex-rs/core/src/chat_completions.rs @@ -477,10 +477,14 @@ async fn append_reasoning_text( .. }) = reasoning_item { + let content_index = content.len() as i64; content.push(ReasoningItemContent::ReasoningText { text: text.clone() }); let _ = tx_event - .send(Ok(ResponseEvent::ReasoningContentDelta(text.clone()))) + .send(Ok(ResponseEvent::ReasoningContentDelta { + delta: text.clone(), + content_index, + })) .await; } } @@ -898,20 +902,26 @@ where continue; } } - Poll::Ready(Some(Ok(ResponseEvent::ReasoningContentDelta(delta)))) => { + Poll::Ready(Some(Ok(ResponseEvent::ReasoningContentDelta { + delta, + content_index, + }))) => { // Always accumulate reasoning deltas so we can emit a final Reasoning item at Completed. this.cumulative_reasoning.push_str(&delta); if matches!(this.mode, AggregateMode::Streaming) { // In streaming mode, also forward the delta immediately. - return Poll::Ready(Some(Ok(ResponseEvent::ReasoningContentDelta(delta)))); + return Poll::Ready(Some(Ok(ResponseEvent::ReasoningContentDelta { + delta, + content_index, + }))); } else { continue; } } - Poll::Ready(Some(Ok(ResponseEvent::ReasoningSummaryDelta(_)))) => { + Poll::Ready(Some(Ok(ResponseEvent::ReasoningSummaryDelta { .. }))) => { continue; } - Poll::Ready(Some(Ok(ResponseEvent::ReasoningSummaryPartAdded))) => { + Poll::Ready(Some(Ok(ResponseEvent::ReasoningSummaryPartAdded { .. }))) => { continue; } Poll::Ready(Some(Ok(ResponseEvent::OutputItemAdded(item)))) => { diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index d1ade21825..98775e3d3a 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -560,6 +560,8 @@ struct SseEvent { response: Option, item: Option, delta: Option, + summary_index: Option, + content_index: Option, } #[derive(Debug, Deserialize)] @@ -819,16 +821,22 @@ async fn process_sse( } } "response.reasoning_summary_text.delta" => { - if let Some(delta) = event.delta { - let event = ResponseEvent::ReasoningSummaryDelta(delta); + if let (Some(delta), Some(summary_index)) = (event.delta, event.summary_index) { + let event = ResponseEvent::ReasoningSummaryDelta { + delta, + summary_index, + }; if tx_event.send(Ok(event)).await.is_err() { return; } } } "response.reasoning_text.delta" => { - if let Some(delta) = event.delta { - let event = ResponseEvent::ReasoningContentDelta(delta); + if let (Some(delta), Some(content_index)) = (event.delta, event.content_index) { + let event = ResponseEvent::ReasoningContentDelta { + delta, + content_index, + }; if tx_event.send(Ok(event)).await.is_err() { return; } @@ -905,10 +913,12 @@ async fn process_sse( } } "response.reasoning_summary_part.added" => { - // Boundary between reasoning summary sections (e.g., titles). - let event = ResponseEvent::ReasoningSummaryPartAdded; - if tx_event.send(Ok(event)).await.is_err() { - return; + if let Some(summary_index) = event.summary_index { + // Boundary between reasoning summary sections (e.g., titles). + let event = ResponseEvent::ReasoningSummaryPartAdded { summary_index }; + if tx_event.send(Ok(event)).await.is_err() { + return; + } } } "response.reasoning_summary_text.done" => {} diff --git a/codex-rs/core/src/client_common.rs b/codex-rs/core/src/client_common.rs index 7d33751e26..a628e0d320 100644 --- a/codex-rs/core/src/client_common.rs +++ b/codex-rs/core/src/client_common.rs @@ -203,9 +203,17 @@ pub enum ResponseEvent { token_usage: Option, }, OutputTextDelta(String), - ReasoningSummaryDelta(String), - ReasoningContentDelta(String), - ReasoningSummaryPartAdded, + ReasoningSummaryDelta { + delta: String, + summary_index: i64, + }, + ReasoningContentDelta { + delta: String, + content_index: i64, + }, + ReasoningSummaryPartAdded { + summary_index: i64, + }, RateLimits(RateLimitSnapshot), } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 273f7a4975..4422b3884e 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -2232,13 +2232,17 @@ async fn try_run_turn( error_or_panic("ReasoningSummaryDelta without active item".to_string()); } } - ResponseEvent::ReasoningSummaryDelta(delta) => { + ResponseEvent::ReasoningSummaryDelta { + delta, + summary_index, + } => { if let Some(active) = active_item.as_ref() { let event = ReasoningContentDeltaEvent { thread_id: sess.conversation_id.to_string(), turn_id: turn_context.sub_id.clone(), item_id: active.id(), - delta: delta.clone(), + delta, + summary_index, }; sess.send_event(&turn_context, EventMsg::ReasoningContentDelta(event)) .await; @@ -2246,18 +2250,29 @@ async fn try_run_turn( error_or_panic("ReasoningSummaryDelta without active item".to_string()); } } - ResponseEvent::ReasoningSummaryPartAdded => { - let event = - EventMsg::AgentReasoningSectionBreak(AgentReasoningSectionBreakEvent {}); - sess.send_event(&turn_context, event).await; + ResponseEvent::ReasoningSummaryPartAdded { summary_index } => { + if let Some(active) = active_item.as_ref() { + let event = + EventMsg::AgentReasoningSectionBreak(AgentReasoningSectionBreakEvent { + item_id: active.id(), + summary_index, + }); + sess.send_event(&turn_context, event).await; + } else { + error_or_panic("ReasoningSummaryPartAdded without active item".to_string()); + } } - ResponseEvent::ReasoningContentDelta(delta) => { + ResponseEvent::ReasoningContentDelta { + delta, + content_index, + } => { if let Some(active) = active_item.as_ref() { let event = ReasoningRawContentDeltaEvent { thread_id: sess.conversation_id.to_string(), turn_id: turn_context.sub_id.clone(), item_id: active.id(), - delta: delta.clone(), + delta, + content_index, }; sess.send_event(&turn_context, EventMsg::ReasoningRawContentDelta(event)) .await; diff --git a/codex-rs/core/tests/chat_completions_sse.rs b/codex-rs/core/tests/chat_completions_sse.rs index 46378b0823..b499b76e8f 100644 --- a/codex-rs/core/tests/chat_completions_sse.rs +++ b/codex-rs/core/tests/chat_completions_sse.rs @@ -215,7 +215,13 @@ async fn streams_reasoning_from_string_delta() { } match &events[1] { - ResponseEvent::ReasoningContentDelta(text) => assert_eq!(text, "think1"), + ResponseEvent::ReasoningContentDelta { + delta, + content_index, + } => { + assert_eq!(delta, "think1"); + assert_eq!(content_index, &0); + } other => panic!("expected reasoning delta, got {other:?}"), } @@ -267,12 +273,24 @@ async fn streams_reasoning_from_object_delta() { } match &events[1] { - ResponseEvent::ReasoningContentDelta(text) => assert_eq!(text, "partA"), + ResponseEvent::ReasoningContentDelta { + delta, + content_index, + } => { + assert_eq!(delta, "partA"); + assert_eq!(content_index, &0); + } other => panic!("expected reasoning delta, got {other:?}"), } match &events[2] { - ResponseEvent::ReasoningContentDelta(text) => assert_eq!(text, "partB"), + ResponseEvent::ReasoningContentDelta { + delta, + content_index, + } => { + assert_eq!(delta, "partB"); + assert_eq!(content_index, &1); + } other => panic!("expected reasoning delta, got {other:?}"), } @@ -319,7 +337,13 @@ async fn streams_reasoning_from_final_message() { } match &events[1] { - ResponseEvent::ReasoningContentDelta(text) => assert_eq!(text, "final-cot"), + ResponseEvent::ReasoningContentDelta { + delta, + content_index, + } => { + assert_eq!(delta, "final-cot"); + assert_eq!(content_index, &0); + } other => panic!("expected reasoning delta, got {other:?}"), } @@ -354,7 +378,13 @@ async fn streams_reasoning_before_tool_call() { } match &events[1] { - ResponseEvent::ReasoningContentDelta(text) => assert_eq!(text, "pre-tool"), + ResponseEvent::ReasoningContentDelta { + delta, + content_index, + } => { + assert_eq!(delta, "pre-tool"); + assert_eq!(content_index, &0); + } other => panic!("expected reasoning delta, got {other:?}"), } diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index 703461f941..b78f921bc0 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -296,6 +296,7 @@ pub fn ev_reasoning_summary_text_delta(delta: &str) -> Value { serde_json::json!({ "type": "response.reasoning_summary_text.delta", "delta": delta, + "summary_index": 0, }) } @@ -303,6 +304,7 @@ pub fn ev_reasoning_text_delta(delta: &str) -> Value { serde_json::json!({ "type": "response.reasoning_text.delta", "delta": delta, + "content_index": 0, }) } diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 2d0b0f013a..2b9b43d79c 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -617,6 +617,9 @@ pub struct ReasoningContentDeltaEvent { pub turn_id: String, pub item_id: String, pub delta: String, + // load with default value so it's backward compatible with the old format. + #[serde(default)] + pub summary_index: i64, } impl HasLegacyEvent for ReasoningContentDeltaEvent { @@ -633,6 +636,9 @@ pub struct ReasoningRawContentDeltaEvent { pub turn_id: String, pub item_id: String, pub delta: String, + // load with default value so it's backward compatible with the old format. + #[serde(default)] + pub content_index: i64, } impl HasLegacyEvent for ReasoningRawContentDeltaEvent { @@ -923,7 +929,13 @@ pub struct AgentReasoningRawContentDeltaEvent { } #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] -pub struct AgentReasoningSectionBreakEvent {} +pub struct AgentReasoningSectionBreakEvent { + // load with default value so it's backward compatible with the old format. + #[serde(default)] + pub item_id: String, + #[serde(default)] + pub summary_index: i64, +} #[derive(Debug, Clone, Deserialize, Serialize, JsonSchema, TS)] pub struct AgentReasoningDeltaEvent { From db2aa57d73b265acc4f14b67c2cad0ab620dd49e Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Thu, 13 Nov 2025 16:25:17 -0800 Subject: [PATCH 15/20] [app-server] small fixes for JSON schema export and one-of types (#6614) A partner is consuming our generated JSON schema bundle for app-server and identified a few issues: - not all polymorphic / one-of types have a type descriminator - `"$ref": "#/definitions/v2/SandboxPolicy"` is missing - "Option<>" is an invalid schema name, and also unnecessary This PR: - adds the type descriminator to the various types that are missing it except for `SessionSource` and `SubAgentSource` because they are serialized to disk (adding this would break backwards compat for resume), and they should not be necessary to consume for an integration with app-server. - removes the special handling in `export.rs` of various types like SandboxPolicy, which turned out to be unnecessary and incorrect - filters out `Option<>` which was auto-generated for request params that don't need a body For context, we currently pull in wayyy more types than we need through the `EventMsg` god object which we are **not** planning to expose in API v2 (this is how I suspect `SessionSource` and `SubAgentSource` are being pulled in). But until we have all the necessary v2 notifications in place that will allow us to remove `EventMsg`, we will keep exporting it for now. --- codex-rs/app-server-protocol/src/export.rs | 27 +++------- .../app-server-protocol/src/protocol/v2.rs | 4 +- .../app-server/tests/suite/v2/thread_list.rs | 49 +++---------------- codex-rs/protocol/src/items.rs | 4 ++ codex-rs/protocol/src/protocol.rs | 6 ++- codex-rs/tui/src/chatwidget/tests.rs | 31 ++++++++++++ 6 files changed, 56 insertions(+), 65 deletions(-) diff --git a/codex-rs/app-server-protocol/src/export.rs b/codex-rs/app-server-protocol/src/export.rs index a1408d61d5..11296e8e54 100644 --- a/codex-rs/app-server-protocol/src/export.rs +++ b/codex-rs/app-server-protocol/src/export.rs @@ -13,10 +13,7 @@ use crate::export_server_responses; use anyhow::Context; use anyhow::Result; use anyhow::anyhow; -use codex_protocol::parse_command::ParsedCommand; use codex_protocol::protocol::EventMsg; -use codex_protocol::protocol::FileChange; -use codex_protocol::protocol::SandboxPolicy; use schemars::JsonSchema; use schemars::schema_for; use serde::Serialize; @@ -120,10 +117,6 @@ pub fn generate_json(out_dir: &Path) -> Result<()> { |d| write_json_schema_with_return::(d, "ClientNotification"), |d| write_json_schema_with_return::(d, "ServerNotification"), |d| write_json_schema_with_return::(d, "EventMsg"), - |d| write_json_schema_with_return::(d, "FileChange"), - |d| write_json_schema_with_return::(d, "InputItem"), - |d| write_json_schema_with_return::(d, "ParsedCommand"), - |d| write_json_schema_with_return::(d, "SandboxPolicy"), ]; let mut schemas: Vec = Vec::new(); @@ -152,13 +145,10 @@ fn build_schema_bundle(schemas: Vec) -> Result { "ClientNotification", "ClientRequest", "EventMsg", - "FileChange", - "InputItem", - "ParsedCommand", - "SandboxPolicy", "ServerNotification", "ServerRequest", ]; + const IGNORED_DEFINITIONS: &[&str] = &["Option<()>"]; let namespaced_types = collect_namespaced_types(&schemas); let mut definitions = Map::new(); @@ -171,6 +161,10 @@ fn build_schema_bundle(schemas: Vec) -> Result { in_v1_dir, } = schema; + if IGNORED_DEFINITIONS.contains(&logical_name.as_str()) { + continue; + } + if let Some(ref ns) = namespace { rewrite_refs_to_namespace(&mut value, ns); } @@ -181,6 +175,9 @@ fn build_schema_bundle(schemas: Vec) -> Result { && let Value::Object(defs_obj) = defs { for (def_name, mut def_schema) in defs_obj { + if IGNORED_DEFINITIONS.contains(&def_name.as_str()) { + continue; + } if SPECIAL_DEFINITIONS.contains(&def_name.as_str()) { continue; } @@ -386,14 +383,6 @@ fn variant_definition_name(base: &str, variant: &Value) -> Option { }); } - if let Some(mode_literal) = literal_from_property(props, "mode") { - let pascal = to_pascal_case(mode_literal); - return Some(match base { - "SandboxPolicy" => format!("{pascal}SandboxPolicy"), - _ => format!("{pascal}{base}"), - }); - } - if props.len() == 1 && let Some(key) = props.keys().next() { diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 4642798c68..cc74a8de72 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -57,8 +57,8 @@ v2_enum_from_core!( ); #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] -#[serde(tag = "mode", rename_all = "camelCase")] -#[ts(tag = "mode")] +#[serde(tag = "type", rename_all = "camelCase")] +#[ts(tag = "type")] #[ts(export_to = "v2/")] pub enum SandboxPolicy { DangerFullAccess, diff --git a/codex-rs/app-server/tests/suite/v2/thread_list.rs b/codex-rs/app-server/tests/suite/v2/thread_list.rs index 09ef0ebfd2..464fb4eee8 100644 --- a/codex-rs/app-server/tests/suite/v2/thread_list.rs +++ b/codex-rs/app-server/tests/suite/v2/thread_list.rs @@ -6,10 +6,8 @@ use codex_app_server_protocol::JSONRPCResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ThreadListParams; use codex_app_server_protocol::ThreadListResponse; -use serde_json::json; use tempfile::TempDir; use tokio::time::timeout; -use uuid::Uuid; const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); @@ -150,46 +148,13 @@ async fn thread_list_respects_provider_filter() -> Result<()> { "X", Some("mock_provider"), )?; // mock_provider - // one with a different provider - let uuid = Uuid::new_v4(); - let dir = codex_home - .path() - .join("sessions") - .join("2025") - .join("01") - .join("02"); - std::fs::create_dir_all(&dir)?; - let file_path = dir.join(format!("rollout-2025-01-02T11-00-00-{uuid}.jsonl")); - let lines = [ - json!({ - "timestamp": "2025-01-02T11:00:00Z", - "type": "session_meta", - "payload": { - "id": uuid, - "timestamp": "2025-01-02T11:00:00Z", - "cwd": "/", - "originator": "codex", - "cli_version": "0.0.0", - "instructions": null, - "source": "vscode", - "model_provider": "other_provider" - } - }) - .to_string(), - json!({ - "timestamp": "2025-01-02T11:00:00Z", - "type":"response_item", - "payload": {"type":"message","role":"user","content":[{"type":"input_text","text":"X"}]} - }) - .to_string(), - json!({ - "timestamp": "2025-01-02T11:00:00Z", - "type":"event_msg", - "payload": {"type":"user_message","message":"X","kind":"plain"} - }) - .to_string(), - ]; - std::fs::write(file_path, lines.join("\n") + "\n")?; + let _b = create_fake_rollout( + codex_home.path(), + "2025-01-02T11-00-00", + "2025-01-02T11:00:00Z", + "X", + Some("other_provider"), + )?; let mut mcp = McpProcess::new(codex_home.path()).await?; timeout(DEFAULT_READ_TIMEOUT, mcp.initialize()).await??; diff --git a/codex-rs/protocol/src/items.rs b/codex-rs/protocol/src/items.rs index 27a9b94743..36ee0be07c 100644 --- a/codex-rs/protocol/src/items.rs +++ b/codex-rs/protocol/src/items.rs @@ -11,6 +11,8 @@ use serde::Serialize; use ts_rs::TS; #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] +#[serde(tag = "type")] +#[ts(tag = "type")] pub enum TurnItem { UserMessage(UserMessageItem), AgentMessage(AgentMessageItem), @@ -25,6 +27,8 @@ pub struct UserMessageItem { } #[derive(Debug, Clone, Deserialize, Serialize, TS, JsonSchema)] +#[serde(tag = "type")] +#[ts(tag = "type")] pub enum AgentMessageContent { Text { text: String }, } diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 2b9b43d79c..95e64089cb 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -241,7 +241,7 @@ pub enum AskForApproval { /// Determines execution restrictions for model shell commands. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Display, JsonSchema, TS)] #[strum(serialize_all = "kebab-case")] -#[serde(tag = "mode", rename_all = "kebab-case")] +#[serde(tag = "type", rename_all = "kebab-case")] pub enum SandboxPolicy { /// No restrictions whatsoever. Use with caution. #[serde(rename = "danger-full-access")] @@ -432,6 +432,7 @@ pub struct Event { /// NOTE: Make sure none of these values have optional types, as it will mess up the extension code-gen. #[derive(Debug, Clone, Deserialize, Serialize, Display, JsonSchema, TS)] #[serde(tag = "type", rename_all = "snake_case")] +#[ts(tag = "type")] #[strum(serialize_all = "snake_case")] pub enum EventMsg { /// Error while executing a submission @@ -1443,7 +1444,8 @@ pub enum ReviewDecision { } #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, JsonSchema, TS)] -#[serde(rename_all = "snake_case")] +#[serde(tag = "type", rename_all = "snake_case")] +#[ts(tag = "type")] pub enum FileChange { Add { content: String, diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 217e0fb307..f50ba9e9ae 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -100,6 +100,37 @@ fn upgrade_event_payload_for_tests(mut payload: serde_json::Value) -> serde_json serde_json::Value::String(aggregated), ); } + } else if ty == "patch_apply_begin" + && let Some(changes) = m.get_mut("changes").and_then(|v| v.as_object_mut()) + { + for change in changes.values_mut() { + if change.get("type").is_some() { + continue; + } + if let Some(change_obj) = change.as_object_mut() + && change_obj.len() == 1 + && let Some((legacy_kind, legacy_value)) = change_obj + .iter() + .next() + .map(|(k, v)| (k.clone(), v.clone())) + { + change_obj.clear(); + change_obj.insert( + "type".to_string(), + serde_json::Value::String(legacy_kind.clone()), + ); + match legacy_value { + serde_json::Value::Object(payload) => { + for (k, v) in payload { + change_obj.insert(k, v); + } + } + other => { + change_obj.insert("content".to_string(), other); + } + } + } + } } } payload From 7b027e7536e921264a37ab855b6a23496bcdfbfa Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 13 Nov 2025 16:45:17 -0800 Subject: [PATCH 16/20] Revert "Revert "Overhaul shell detection and centralize command generation for unified exec"" (#6607) Reverts openai/codex#6606 --- codex-rs/core/src/bash.rs | 24 +- .../src/command_safety/is_safe_command.rs | 10 +- codex-rs/core/src/command_safety/mod.rs | 1 - codex-rs/core/src/environment_context.rs | 2 - codex-rs/core/src/shell.rs | 569 +++++++----------- codex-rs/core/src/tools/events.rs | 8 +- codex-rs/core/src/tools/handlers/shell.rs | 23 +- .../core/src/tools/handlers/unified_exec.rs | 22 +- codex-rs/core/src/unified_exec/mod.rs | 12 +- .../core/src/unified_exec/session_manager.rs | 26 +- codex-rs/core/tests/suite/unified_exec.rs | 15 +- 11 files changed, 300 insertions(+), 412 deletions(-) diff --git a/codex-rs/core/src/bash.rs b/codex-rs/core/src/bash.rs index edeebaba37..0ffb8e785e 100644 --- a/codex-rs/core/src/bash.rs +++ b/codex-rs/core/src/bash.rs @@ -1,8 +1,13 @@ +use std::path::PathBuf; + use tree_sitter::Node; use tree_sitter::Parser; use tree_sitter::Tree; use tree_sitter_bash::LANGUAGE as BASH; +use crate::shell::ShellType; +use crate::shell::detect_shell_type; + /// Parse the provided bash source using tree-sitter-bash, returning a Tree on /// success or None if parsing failed. pub fn try_parse_shell(shell_lc_arg: &str) -> Option { @@ -88,23 +93,16 @@ pub fn try_parse_word_only_commands_sequence(tree: &Tree, src: &str) -> Option bool { - if shell == "bash" || shell == "zsh" { - return true; - } - - let shell_name = std::path::Path::new(shell) - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or(shell); - matches!(shell_name, "bash" | "zsh") -} - pub fn extract_bash_command(command: &[String]) -> Option<(&str, &str)> { let [shell, flag, script] = command else { return None; }; - if !matches!(flag.as_str(), "-lc" | "-c") || !is_well_known_sh_shell(shell) { + if !matches!(flag.as_str(), "-lc" | "-c") + || !matches!( + detect_shell_type(&PathBuf::from(shell)), + Some(ShellType::Zsh) | Some(ShellType::Bash) + ) + { return None; } Some((shell, script)) diff --git a/codex-rs/core/src/command_safety/is_safe_command.rs b/codex-rs/core/src/command_safety/is_safe_command.rs index ba3eb6ba7d..ab084c191b 100644 --- a/codex-rs/core/src/command_safety/is_safe_command.rs +++ b/codex-rs/core/src/command_safety/is_safe_command.rs @@ -1,4 +1,5 @@ use crate::bash::parse_shell_lc_plain_commands; +use crate::command_safety::windows_safe_commands::is_safe_command_windows; pub fn is_known_safe_command(command: &[String]) -> bool { let command: Vec = command @@ -11,12 +12,9 @@ pub fn is_known_safe_command(command: &[String]) -> bool { } }) .collect(); - #[cfg(target_os = "windows")] - { - use super::windows_safe_commands::is_safe_command_windows; - if is_safe_command_windows(&command) { - return true; - } + + if is_safe_command_windows(&command) { + return true; } if is_safe_to_call_with_exec(&command) { diff --git a/codex-rs/core/src/command_safety/mod.rs b/codex-rs/core/src/command_safety/mod.rs index 8279d67952..caf5c9f6ea 100644 --- a/codex-rs/core/src/command_safety/mod.rs +++ b/codex-rs/core/src/command_safety/mod.rs @@ -1,4 +1,3 @@ pub mod is_dangerous_command; pub mod is_safe_command; -#[cfg(target_os = "windows")] pub mod windows_safe_commands; diff --git a/codex-rs/core/src/environment_context.rs b/codex-rs/core/src/environment_context.rs index e7b2e19ffb..6db2bb8f52 100644 --- a/codex-rs/core/src/environment_context.rs +++ b/codex-rs/core/src/environment_context.rs @@ -329,7 +329,6 @@ mod tests { Some(workspace_write_policy(vec!["/repo"], false)), Some(Shell::Bash(BashShell { shell_path: "/bin/bash".into(), - bashrc_path: "/home/user/.bashrc".into(), })), ); let context2 = EnvironmentContext::new( @@ -338,7 +337,6 @@ mod tests { Some(workspace_write_policy(vec!["/repo"], false)), Some(Shell::Zsh(ZshShell { shell_path: "/bin/zsh".into(), - zshrc_path: "/home/user/.zshrc".into(), })), ); diff --git a/codex-rs/core/src/shell.rs b/codex-rs/core/src/shell.rs index 90f6c6b97a..ed52491dad 100644 --- a/codex-rs/core/src/shell.rs +++ b/codex-rs/core/src/shell.rs @@ -2,22 +2,26 @@ use serde::Deserialize; use serde::Serialize; use std::path::PathBuf; +#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] +pub enum ShellType { + Zsh, + Bash, + PowerShell, +} + #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct ZshShell { - pub(crate) shell_path: String, - pub(crate) zshrc_path: String, + pub(crate) shell_path: PathBuf, } #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct BashShell { - pub(crate) shell_path: String, - pub(crate) bashrc_path: String, + pub(crate) shell_path: PathBuf, } #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] pub struct PowerShellConfig { - pub(crate) exe: String, // Executable name or path, e.g. "pwsh" or "powershell.exe". - pub(crate) bash_exe_fallback: Option, // In case the model generates a bash command. + pub(crate) shell_path: PathBuf, // Executable name or path, e.g. "pwsh" or "powershell.exe". } #[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] @@ -36,7 +40,10 @@ impl Shell { .file_name() .map(|s| s.to_string_lossy().to_string()) } - Shell::PowerShell(ps) => Some(ps.exe.clone()), + Shell::PowerShell(ps) => ps + .shell_path + .file_stem() + .map(|s| s.to_string_lossy().to_string()), Shell::Unknown => None, } } @@ -47,10 +54,17 @@ impl Shell { match self { Shell::Zsh(ZshShell { shell_path, .. }) | Shell::Bash(BashShell { shell_path, .. }) => { let arg = if use_login_shell { "-lc" } else { "-c" }; - vec![shell_path.clone(), arg.to_string(), command.to_string()] + vec![ + shell_path.to_string_lossy().to_string(), + arg.to_string(), + command.to_string(), + ] } Shell::PowerShell(ps) => { - let mut args = vec![ps.exe.clone(), "-NoLogo".to_string()]; + let mut args = vec![ + ps.shell_path.to_string_lossy().to_string(), + "-NoLogo".to_string(), + ]; if !use_login_shell { args.push("-NoProfile".to_string()); } @@ -65,7 +79,7 @@ impl Shell { } #[cfg(unix)] -fn detect_default_user_shell() -> Shell { +fn get_user_shell_path() -> Option { use libc::getpwuid; use libc::getuid; use std::ffi::CStr; @@ -78,75 +92,174 @@ fn detect_default_user_shell() -> Shell { let shell_path = CStr::from_ptr((*pw).pw_shell) .to_string_lossy() .into_owned(); - let home_path = CStr::from_ptr((*pw).pw_dir).to_string_lossy().into_owned(); + Some(PathBuf::from(shell_path)) + } else { + None + } + } +} - if shell_path.ends_with("/zsh") { - return Shell::Zsh(ZshShell { - shell_path, - zshrc_path: format!("{home_path}/.zshrc"), - }); - } +#[cfg(not(unix))] +fn get_user_shell_path() -> Option { + None +} - if shell_path.ends_with("/bash") { - return Shell::Bash(BashShell { - shell_path, - bashrc_path: format!("{home_path}/.bashrc"), - }); +fn file_exists(path: &PathBuf) -> Option { + if std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) { + Some(PathBuf::from(path)) + } else { + None + } +} + +fn get_shell_path( + shell_type: ShellType, + provided_path: Option<&PathBuf>, + binary_name: &str, + fallback_paths: Vec<&str>, +) -> Option { + // If exact provided path exists, use it + if provided_path.and_then(file_exists).is_some() { + return provided_path.cloned(); + } + + // Check if the shell we are trying to load is user's default shell + // if just use it + let default_shell_path = get_user_shell_path(); + if let Some(default_shell_path) = default_shell_path + && detect_shell_type(&default_shell_path) == Some(shell_type) + { + return Some(default_shell_path); + } + + if let Ok(path) = which::which(binary_name) { + return Some(path); + } + + for path in fallback_paths { + //check exists + if let Some(path) = file_exists(&PathBuf::from(path)) { + return Some(path); + } + } + + None +} + +fn get_zsh_shell(path: Option<&PathBuf>) -> Option { + let shell_path = get_shell_path(ShellType::Zsh, path, "zsh", vec!["/bin/zsh"]); + + shell_path.map(|shell_path| ZshShell { shell_path }) +} + +fn get_bash_shell(path: Option<&PathBuf>) -> Option { + let shell_path = get_shell_path(ShellType::Bash, path, "bash", vec!["/bin/bash"]); + + shell_path.map(|shell_path| BashShell { shell_path }) +} + +fn get_powershell_shell(path: Option<&PathBuf>) -> Option { + let shell_path = get_shell_path( + ShellType::PowerShell, + path, + "pwsh", + vec!["/usr/local/bin/pwsh"], + ) + .or_else(|| get_shell_path(ShellType::PowerShell, path, "powershell", vec![])); + + shell_path.map(|shell_path| PowerShellConfig { shell_path }) +} + +pub fn get_shell_by_model_provided_path(shell_path: &PathBuf) -> Shell { + detect_shell_type(shell_path) + .and_then(|shell_type| get_shell(shell_type, Some(shell_path))) + .unwrap_or(Shell::Unknown) +} + +pub fn get_shell(shell_type: ShellType, path: Option<&PathBuf>) -> Option { + match shell_type { + ShellType::Zsh => get_zsh_shell(path).map(Shell::Zsh), + ShellType::Bash => get_bash_shell(path).map(Shell::Bash), + ShellType::PowerShell => get_powershell_shell(path).map(Shell::PowerShell), + } +} + +pub fn detect_shell_type(shell_path: &PathBuf) -> Option { + match shell_path.as_os_str().to_str() { + Some("zsh") => Some(ShellType::Zsh), + Some("bash") => Some(ShellType::Bash), + Some("pwsh") => Some(ShellType::PowerShell), + Some("powershell") => Some(ShellType::PowerShell), + _ => { + let shell_name = shell_path.file_stem(); + + if let Some(shell_name) = shell_name + && shell_name != shell_path + { + detect_shell_type(&PathBuf::from(shell_name)) + } else { + None } } } - Shell::Unknown } -#[cfg(unix)] pub async fn default_user_shell() -> Shell { - detect_default_user_shell() -} - -#[cfg(target_os = "windows")] -pub async fn default_user_shell() -> Shell { - use tokio::process::Command; - - // Prefer PowerShell 7+ (`pwsh`) if available, otherwise fall back to Windows PowerShell. - let has_pwsh = Command::new("pwsh") - .arg("-NoLogo") - .arg("-NoProfile") - .arg("-Command") - .arg("$PSVersionTable.PSVersion.Major") - .output() - .await - .map(|o| o.status.success()) - .unwrap_or(false); - let bash_exe = if Command::new("bash.exe") - .arg("--version") - .stdin(std::process::Stdio::null()) - .output() - .await - .ok() - .map(|o| o.status.success()) - .unwrap_or(false) - { - which::which("bash.exe").ok() + if cfg!(windows) { + get_shell(ShellType::PowerShell, None).unwrap_or(Shell::Unknown) } else { - None - }; - - if has_pwsh { - Shell::PowerShell(PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: bash_exe, - }) - } else { - Shell::PowerShell(PowerShellConfig { - exe: "powershell.exe".to_string(), - bash_exe_fallback: bash_exe, - }) + get_user_shell_path() + .and_then(|shell| detect_shell_type(&shell)) + .and_then(|shell_type| get_shell(shell_type, None)) + .unwrap_or(Shell::Unknown) } } -#[cfg(all(not(target_os = "windows"), not(unix)))] -pub async fn default_user_shell() -> Shell { - Shell::Unknown +#[cfg(test)] +mod detect_shell_type_tests { + use super::*; + + #[test] + fn test_detect_shell_type() { + assert_eq!( + detect_shell_type(&PathBuf::from("zsh")), + Some(ShellType::Zsh) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("bash")), + Some(ShellType::Bash) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("pwsh")), + Some(ShellType::PowerShell) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("powershell")), + Some(ShellType::PowerShell) + ); + assert_eq!(detect_shell_type(&PathBuf::from("fish")), None); + assert_eq!(detect_shell_type(&PathBuf::from("other")), None); + assert_eq!( + detect_shell_type(&PathBuf::from("/bin/zsh")), + Some(ShellType::Zsh) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("/bin/bash")), + Some(ShellType::Bash) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("powershell.exe")), + Some(ShellType::PowerShell) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("pwsh.exe")), + Some(ShellType::PowerShell) + ); + assert_eq!( + detect_shell_type(&PathBuf::from("/usr/local/bin/pwsh")), + Some(ShellType::PowerShell) + ); + } } #[cfg(test)] @@ -156,6 +269,34 @@ mod tests { use std::path::PathBuf; use std::process::Command; + #[test] + #[cfg(target_os = "macos")] + fn detects_zsh() { + let zsh_shell = get_shell(ShellType::Zsh, None).unwrap(); + + let ZshShell { shell_path } = match zsh_shell { + Shell::Zsh(zsh_shell) => zsh_shell, + _ => panic!("expected zsh shell"), + }; + + assert_eq!(shell_path, PathBuf::from("/bin/zsh")); + } + + #[test] + fn detects_bash() { + let bash_shell = get_shell(ShellType::Bash, None).unwrap(); + let BashShell { shell_path } = match bash_shell { + Shell::Bash(bash_shell) => bash_shell, + _ => panic!("expected bash shell"), + }; + + assert!( + shell_path == PathBuf::from("/bin/bash") + || shell_path == PathBuf::from("/usr/bin/bash"), + "shell path: {shell_path:?}", + ); + } + #[tokio::test] async fn test_current_shell_detects_zsh() { let shell = Command::new("sh") @@ -164,292 +305,44 @@ mod tests { .output() .unwrap(); - let home = std::env::var("HOME").unwrap(); let shell_path = String::from_utf8_lossy(&shell.stdout).trim().to_string(); if shell_path.ends_with("/zsh") { assert_eq!( default_user_shell().await, Shell::Zsh(ZshShell { - shell_path: shell_path.to_string(), - zshrc_path: format!("{home}/.zshrc",), + shell_path: PathBuf::from(shell_path), }) ); } } #[tokio::test] - async fn test_run_with_profile_bash_escaping_and_execution() { - let shell_path = "/bin/bash"; - - let cases = vec![ - ( - vec!["myecho"], - vec![shell_path, "-lc", "source BASHRC_PATH && (myecho)"], - Some("It works!\n"), - ), - ( - vec!["bash", "-lc", "echo 'single' \"double\""], - vec![ - shell_path, - "-lc", - "source BASHRC_PATH && (echo 'single' \"double\")", - ], - Some("single double\n"), - ), - ]; - - for (input, expected_cmd, expected_output) in cases { - use std::collections::HashMap; - - use crate::exec::ExecParams; - use crate::exec::SandboxType; - use crate::exec::process_exec_tool_call; - use crate::protocol::SandboxPolicy; - - let temp_home = tempfile::tempdir().unwrap(); - let bashrc_path = temp_home.path().join(".bashrc"); - std::fs::write( - &bashrc_path, - r#" - set -x - function myecho { - echo 'It works!' - } - "#, - ) - .unwrap(); - let command = expected_cmd - .iter() - .map(|s| s.replace("BASHRC_PATH", bashrc_path.to_str().unwrap())) - .collect::>(); - - let output = process_exec_tool_call( - ExecParams { - command: command.clone(), - cwd: PathBuf::from(temp_home.path()), - timeout_ms: None, - env: HashMap::from([( - "HOME".to_string(), - temp_home.path().to_str().unwrap().to_string(), - )]), - with_escalated_permissions: None, - justification: None, - arg0: None, - }, - SandboxType::None, - &SandboxPolicy::DangerFullAccess, - temp_home.path(), - &None, - None, - ) - .await - .unwrap(); - - assert_eq!(output.exit_code, 0, "input: {input:?} output: {output:?}"); - if let Some(expected) = expected_output { - assert_eq!( - output.stdout.text, expected, - "input: {input:?} output: {output:?}" - ); - } + async fn detects_powershell_as_default() { + if !cfg!(windows) { + return; } + + let powershell_shell = default_user_shell().await; + let PowerShellConfig { shell_path } = match powershell_shell { + Shell::PowerShell(powershell_shell) => powershell_shell, + _ => panic!("expected powershell shell"), + }; + + assert!(shell_path.ends_with("pwsh.exe") || shell_path.ends_with("powershell.exe")); } -} - -#[cfg(test)] -#[cfg(target_os = "macos")] -mod macos_tests { - use std::path::PathBuf; - - #[tokio::test] - async fn test_run_with_profile_escaping_and_execution() { - let shell_path = "/bin/zsh"; - - let cases = vec![ - ( - vec!["myecho"], - vec![shell_path, "-lc", "source ZSHRC_PATH && (myecho)"], - Some("It works!\n"), - ), - ( - vec!["myecho"], - vec![shell_path, "-lc", "source ZSHRC_PATH && (myecho)"], - Some("It works!\n"), - ), - ( - vec!["bash", "-c", "echo 'single' \"double\""], - vec![ - shell_path, - "-lc", - "source ZSHRC_PATH && (bash -c \"echo 'single' \\\"double\\\"\")", - ], - Some("single double\n"), - ), - ( - vec!["bash", "-lc", "echo 'single' \"double\""], - vec![ - shell_path, - "-lc", - "source ZSHRC_PATH && (echo 'single' \"double\")", - ], - Some("single double\n"), - ), - ]; - for (input, expected_cmd, expected_output) in cases { - use std::collections::HashMap; - - use crate::exec::ExecParams; - use crate::exec::SandboxType; - use crate::exec::process_exec_tool_call; - use crate::protocol::SandboxPolicy; - - let temp_home = tempfile::tempdir().unwrap(); - let zshrc_path = temp_home.path().join(".zshrc"); - std::fs::write( - &zshrc_path, - r#" - set -x - function myecho { - echo 'It works!' - } - "#, - ) - .unwrap(); - let command = expected_cmd - .iter() - .map(|s| s.replace("ZSHRC_PATH", zshrc_path.to_str().unwrap())) - .collect::>(); - - let output = process_exec_tool_call( - ExecParams { - command: command.clone(), - cwd: PathBuf::from(temp_home.path()), - timeout_ms: None, - env: HashMap::from([( - "HOME".to_string(), - temp_home.path().to_str().unwrap().to_string(), - )]), - with_escalated_permissions: None, - justification: None, - arg0: None, - }, - SandboxType::None, - &SandboxPolicy::DangerFullAccess, - temp_home.path(), - &None, - None, - ) - .await - .unwrap(); - - assert_eq!(output.exit_code, 0, "input: {input:?} output: {output:?}"); - if let Some(expected) = expected_output { - assert_eq!( - output.stdout.text, expected, - "input: {input:?} output: {output:?}" - ); - } - } - } -} - -#[cfg(test)] -#[cfg(target_os = "windows")] -mod tests_windows { - use super::*; #[test] - fn test_format_default_shell_invocation_powershell() { - use std::path::PathBuf; - - let cases = vec![ - ( - PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: None, - }, - vec!["bash", "-lc", "echo hello"], - vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], - ), - ( - PowerShellConfig { - exe: "powershell.exe".to_string(), - bash_exe_fallback: None, - }, - vec!["bash", "-lc", "echo hello"], - vec!["powershell.exe", "-NoProfile", "-Command", "echo hello"], - ), - ( - PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: Some(PathBuf::from("bash.exe")), - }, - vec!["bash", "-lc", "echo hello"], - vec!["bash.exe", "-lc", "echo hello"], - ), - ( - PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: Some(PathBuf::from("bash.exe")), - }, - vec![ - "bash", - "-lc", - "apply_patch <<'EOF'\n*** Begin Patch\n*** Update File: destination_file.txt\n-original content\n+modified content\n*** End Patch\nEOF", - ], - vec![ - "bash.exe", - "-lc", - "apply_patch <<'EOF'\n*** Begin Patch\n*** Update File: destination_file.txt\n-original content\n+modified content\n*** End Patch\nEOF", - ], - ), - ( - PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: Some(PathBuf::from("bash.exe")), - }, - vec!["echo", "hello"], - vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], - ), - ( - PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: Some(PathBuf::from("bash.exe")), - }, - vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], - vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"], - ), - ( - PowerShellConfig { - exe: "powershell.exe".to_string(), - bash_exe_fallback: Some(PathBuf::from("bash.exe")), - }, - vec![ - "codex-mcp-server.exe", - "--codex-run-as-apply-patch", - "*** Begin Patch\n*** Update File: C:\\Users\\person\\destination_file.txt\n-original content\n+modified content\n*** End Patch", - ], - vec![ - "codex-mcp-server.exe", - "--codex-run-as-apply-patch", - "*** Begin Patch\n*** Update File: C:\\Users\\person\\destination_file.txt\n-original content\n+modified content\n*** End Patch", - ], - ), - ]; - - for (config, input, expected_cmd) in cases { - let command = expected_cmd - .iter() - .map(|s| (*s).to_string()) - .collect::>(); - - // These tests assert the final command for each scenario now that the helper - // has been removed. The inputs remain to document the original coverage. - let expected = expected_cmd - .iter() - .map(|s| (*s).to_string()) - .collect::>(); - assert_eq!(command, expected, "input: {input:?} config: {config:?}"); + fn finds_poweshell() { + if !cfg!(windows) { + return; } + + let powershell_shell = get_shell(ShellType::PowerShell, None).unwrap(); + let PowerShellConfig { shell_path } = match powershell_shell { + Shell::PowerShell(powershell_shell) => powershell_shell, + _ => panic!("expected powershell shell"), + }; + + assert!(shell_path.ends_with("pwsh.exe") || shell_path.ends_with("powershell.exe")); } } diff --git a/codex-rs/core/src/tools/events.rs b/codex-rs/core/src/tools/events.rs index 9019dac5ed..5f93d51d8c 100644 --- a/codex-rs/core/src/tools/events.rs +++ b/codex-rs/core/src/tools/events.rs @@ -87,7 +87,7 @@ pub(crate) enum ToolEmitter { auto_approved: bool, }, UnifiedExec { - command: String, + command: Vec, cwd: PathBuf, // True for `exec_command` and false for `write_stdin`. #[allow(dead_code)] @@ -111,9 +111,9 @@ impl ToolEmitter { } } - pub fn unified_exec(command: String, cwd: PathBuf, is_startup_command: bool) -> Self { + pub fn unified_exec(command: &[String], cwd: PathBuf, is_startup_command: bool) -> Self { Self::UnifiedExec { - command, + command: command.to_vec(), cwd, is_startup_command, } @@ -218,7 +218,7 @@ impl ToolEmitter { emit_patch_end(ctx, String::new(), (*message).to_string(), false).await; } (Self::UnifiedExec { command, cwd, .. }, ToolEventStage::Begin) => { - emit_exec_command_begin(ctx, &[command.to_string()], cwd.as_path(), false).await; + emit_exec_command_begin(ctx, command, cwd.as_path(), false).await; } (Self::UnifiedExec { .. }, ToolEventStage::Success(output)) => { emit_exec_end( diff --git a/codex-rs/core/src/tools/handlers/shell.rs b/codex-rs/core/src/tools/handlers/shell.rs index 3a5115f6ee..39f271b2da 100644 --- a/codex-rs/core/src/tools/handlers/shell.rs +++ b/codex-rs/core/src/tools/handlers/shell.rs @@ -324,8 +324,11 @@ impl ShellHandler { #[cfg(test)] mod tests { + use std::path::PathBuf; + use crate::is_safe_command::is_known_safe_command; use crate::shell::BashShell; + use crate::shell::PowerShellConfig; use crate::shell::Shell; use crate::shell::ZshShell; @@ -335,27 +338,19 @@ mod tests { #[test] fn commands_generated_by_shell_command_handler_can_be_matched_by_is_known_safe_command() { let bash_shell = Shell::Bash(BashShell { - shell_path: "/bin/bash".to_string(), - bashrc_path: "/home/user/.bashrc".to_string(), + shell_path: PathBuf::from("/bin/bash"), }); assert_safe(&bash_shell, "ls -la"); let zsh_shell = Shell::Zsh(ZshShell { - shell_path: "/bin/zsh".to_string(), - zshrc_path: "/home/user/.zshrc".to_string(), + shell_path: PathBuf::from("/bin/zsh"), }); assert_safe(&zsh_shell, "ls -la"); - #[cfg(target_os = "windows")] - { - use crate::shell::PowerShellConfig; - - let powershell = Shell::PowerShell(PowerShellConfig { - exe: "pwsh.exe".to_string(), - bash_exe_fallback: None, - }); - assert_safe(&powershell, "ls -Name"); - } + let powershell = Shell::PowerShell(PowerShellConfig { + shell_path: PathBuf::from("pwsh.exe"), + }); + assert_safe(&powershell, "ls -Name"); } fn assert_safe(shell: &Shell, command: &str) { diff --git a/codex-rs/core/src/tools/handlers/unified_exec.rs b/codex-rs/core/src/tools/handlers/unified_exec.rs index 97229970a3..d5b4ecd716 100644 --- a/codex-rs/core/src/tools/handlers/unified_exec.rs +++ b/codex-rs/core/src/tools/handlers/unified_exec.rs @@ -5,6 +5,7 @@ use crate::is_safe_command::is_known_safe_command; use crate::protocol::EventMsg; use crate::protocol::ExecCommandOutputDeltaEvent; use crate::protocol::ExecOutputStream; +use crate::shell::get_shell_by_model_provided_path; use crate::tools::context::ToolInvocation; use crate::tools::context::ToolOutput; use crate::tools::context::ToolPayload; @@ -92,7 +93,8 @@ impl ToolHandler for UnifiedExecHandler { let Ok(params) = serde_json::from_str::(arguments) else { return true; }; - !is_known_safe_command(&["bash".to_string(), "-lc".to_string(), params.cmd]) + let command = get_command(¶ms); + !is_known_safe_command(&command) } async fn handle(&self, invocation: ToolInvocation) -> Result { @@ -125,15 +127,15 @@ impl ToolHandler for UnifiedExecHandler { "failed to parse exec_command arguments: {err:?}" )) })?; + + let command = get_command(&args); let ExecCommandArgs { - cmd, workdir, - shell, - login, yield_time_ms, max_output_tokens, with_escalated_permissions, justification, + .. } = args; if with_escalated_permissions.unwrap_or(false) @@ -160,15 +162,14 @@ impl ToolHandler for UnifiedExecHandler { &context.call_id, None, ); - let emitter = ToolEmitter::unified_exec(cmd.clone(), cwd.clone(), true); + + let emitter = ToolEmitter::unified_exec(&command, cwd.clone(), true); emitter.emit(event_ctx, ToolEventStage::Begin).await; manager .exec_command( ExecCommandRequest { - command: &cmd, - shell: &shell, - login, + command, yield_time_ms, max_output_tokens, workdir, @@ -229,6 +230,11 @@ impl ToolHandler for UnifiedExecHandler { } } +fn get_command(args: &ExecCommandArgs) -> Vec { + let shell = get_shell_by_model_provided_path(&PathBuf::from(args.shell.clone())); + shell.derive_exec_args(&args.cmd, args.login) +} + fn format_response(response: &UnifiedExecResponse) -> String { let mut sections = Vec::new(); diff --git a/codex-rs/core/src/unified_exec/mod.rs b/codex-rs/core/src/unified_exec/mod.rs index 1ee65e971e..951032c075 100644 --- a/codex-rs/core/src/unified_exec/mod.rs +++ b/codex-rs/core/src/unified_exec/mod.rs @@ -63,10 +63,8 @@ impl UnifiedExecContext { } #[derive(Debug)] -pub(crate) struct ExecCommandRequest<'a> { - pub command: &'a str, - pub shell: &'a str, - pub login: bool, +pub(crate) struct ExecCommandRequest { + pub command: Vec, pub yield_time_ms: u64, pub max_output_tokens: Option, pub workdir: Option, @@ -104,7 +102,7 @@ struct SessionEntry { session_ref: Arc, turn_ref: Arc, call_id: String, - command: String, + command: Vec, cwd: PathBuf, started_at: tokio::time::Instant, } @@ -193,9 +191,7 @@ mod tests { .unified_exec_manager .exec_command( ExecCommandRequest { - command: cmd, - shell: "/bin/bash", - login: true, + command: vec!["bash".to_string(), "-lc".to_string(), cmd.to_string()], yield_time_ms, max_output_tokens: None, workdir: None, diff --git a/codex-rs/core/src/unified_exec/session_manager.rs b/codex-rs/core/src/unified_exec/session_manager.rs index df2c3aaf1c..55e9102b7e 100644 --- a/codex-rs/core/src/unified_exec/session_manager.rs +++ b/codex-rs/core/src/unified_exec/session_manager.rs @@ -35,23 +35,17 @@ use super::truncate_output_to_tokens; impl UnifiedExecSessionManager { pub(crate) async fn exec_command( &self, - request: ExecCommandRequest<'_>, + request: ExecCommandRequest, context: &UnifiedExecContext, ) -> Result { let cwd = request .workdir .clone() .unwrap_or_else(|| context.turn.cwd.clone()); - let shell_flag = if request.login { "-lc" } else { "-c" }; - let command = vec![ - request.shell.to_string(), - shell_flag.to_string(), - request.command.to_string(), - ]; let session = self .open_session_with_sandbox( - command, + &request.command, cwd.clone(), request.with_escalated_permissions, request.justification, @@ -77,7 +71,7 @@ impl UnifiedExecSessionManager { None } else { Some( - self.store_session(session, context, request.command, cwd.clone(), start) + self.store_session(session, context, &request.command, cwd.clone(), start) .await, ) }; @@ -97,7 +91,7 @@ impl UnifiedExecSessionManager { let exit = response.exit_code.unwrap_or(-1); Self::emit_exec_end_from_context( context, - request.command.to_string(), + &request.command, cwd, response.output.clone(), exit, @@ -222,7 +216,7 @@ impl UnifiedExecSessionManager { &self, session: UnifiedExecSession, context: &UnifiedExecContext, - command: &str, + command: &[String], cwd: PathBuf, started_at: Instant, ) -> i32 { @@ -234,7 +228,7 @@ impl UnifiedExecSessionManager { session_ref: Arc::clone(&context.session), turn_ref: Arc::clone(&context.turn), call_id: context.call_id.clone(), - command: command.to_string(), + command: command.to_vec(), cwd, started_at, }; @@ -262,7 +256,7 @@ impl UnifiedExecSessionManager { &entry.call_id, None, ); - let emitter = ToolEmitter::unified_exec(entry.command, entry.cwd, true); + let emitter = ToolEmitter::unified_exec(&entry.command, entry.cwd, true); emitter .emit(event_ctx, ToolEventStage::Success(output)) .await; @@ -270,7 +264,7 @@ impl UnifiedExecSessionManager { async fn emit_exec_end_from_context( context: &UnifiedExecContext, - command: String, + command: &[String], cwd: PathBuf, aggregated_output: String, exit_code: i32, @@ -319,7 +313,7 @@ impl UnifiedExecSessionManager { pub(super) async fn open_session_with_sandbox( &self, - command: Vec, + command: &[String], cwd: PathBuf, with_escalated_permissions: Option, justification: Option, @@ -328,7 +322,7 @@ impl UnifiedExecSessionManager { let mut orchestrator = ToolOrchestrator::new(); let mut runtime = UnifiedExecRuntime::new(self); let req = UnifiedExecToolRequest::new( - command, + command.to_vec(), cwd, create_env(&context.turn.shell_environment_policy), with_escalated_permissions, diff --git a/codex-rs/core/tests/suite/unified_exec.rs b/codex-rs/core/tests/suite/unified_exec.rs index 1225b51ccd..07b17f78ad 100644 --- a/codex-rs/core/tests/suite/unified_exec.rs +++ b/codex-rs/core/tests/suite/unified_exec.rs @@ -214,7 +214,11 @@ async fn unified_exec_emits_exec_command_begin_event() -> Result<()> { assert_eq!( begin_event.command, - vec!["/bin/echo hello unified exec".to_string()] + vec![ + "/bin/bash".to_string(), + "-lc".to_string(), + "/bin/echo hello unified exec".to_string() + ] ); assert_eq!(begin_event.cwd, cwd.path()); @@ -654,7 +658,14 @@ async fn unified_exec_skips_begin_event_for_empty_input() -> Result<()> { "expected only the initial command to emit begin event" ); assert_eq!(begin_events[0].call_id, open_call_id); - assert_eq!(begin_events[0].command[0], "/bin/sh -c echo ready"); + assert_eq!( + begin_events[0].command, + vec![ + "/bin/bash".to_string(), + "-lc".to_string(), + "/bin/sh -c echo ready".to_string() + ] + ); Ok(()) } From 9890ceb939948d77b0f004d91163fb7c3cb34bd8 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 13 Nov 2025 16:59:31 -0800 Subject: [PATCH 17/20] Avoid double truncation (#6631) 1. Avoid double truncation by giving 10% above the tool default constant 2. Add tests that fails when const = 1 --- codex-rs/core/src/context_manager/history.rs | 19 +++- .../core/src/context_manager/history_tests.rs | 40 ++++++-- codex-rs/core/src/context_manager/mod.rs | 2 + codex-rs/core/src/context_manager/truncate.rs | 54 ++++++---- codex-rs/core/src/tools/mod.rs | 4 +- codex-rs/core/tests/suite/truncation.rs | 98 +++++++++++++++++-- codex-rs/core/tests/suite/user_shell_cmd.rs | 82 ++++++++++++++++ 7 files changed, 264 insertions(+), 35 deletions(-) diff --git a/codex-rs/core/src/context_manager/history.rs b/codex-rs/core/src/context_manager/history.rs index 07ff54ad1c..8f8200caad 100644 --- a/codex-rs/core/src/context_manager/history.rs +++ b/codex-rs/core/src/context_manager/history.rs @@ -1,5 +1,6 @@ use crate::codex::TurnContext; use crate::context_manager::normalize; +use crate::context_manager::truncate; use crate::context_manager::truncate::format_output_for_model_body; use crate::context_manager::truncate::globally_truncate_function_output_items; use codex_protocol::models::FunctionCallOutputPayload; @@ -9,6 +10,12 @@ use codex_protocol::protocol::TokenUsageInfo; use codex_utils_tokenizer::Tokenizer; use std::ops::Deref; +const CONTEXT_WINDOW_HARD_LIMIT_FACTOR: f64 = 1.1; +const CONTEXT_WINDOW_HARD_LIMIT_BYTES: usize = + (truncate::MODEL_FORMAT_MAX_BYTES as f64 * CONTEXT_WINDOW_HARD_LIMIT_FACTOR) as usize; +const CONTEXT_WINDOW_HARD_LIMIT_LINES: usize = + (truncate::MODEL_FORMAT_MAX_LINES as f64 * CONTEXT_WINDOW_HARD_LIMIT_FACTOR) as usize; + /// Transcript of conversation history #[derive(Debug, Clone, Default)] pub(crate) struct ContextManager { @@ -146,7 +153,11 @@ impl ContextManager { fn process_item(item: &ResponseItem) -> ResponseItem { match item { ResponseItem::FunctionCallOutput { call_id, output } => { - let truncated = format_output_for_model_body(output.content.as_str()); + let truncated = format_output_for_model_body( + output.content.as_str(), + CONTEXT_WINDOW_HARD_LIMIT_BYTES, + CONTEXT_WINDOW_HARD_LIMIT_LINES, + ); let truncated_items = output .content_items .as_ref() @@ -161,7 +172,11 @@ impl ContextManager { } } ResponseItem::CustomToolCallOutput { call_id, output } => { - let truncated = format_output_for_model_body(output); + let truncated = format_output_for_model_body( + output, + CONTEXT_WINDOW_HARD_LIMIT_BYTES, + CONTEXT_WINDOW_HARD_LIMIT_LINES, + ); ResponseItem::CustomToolCallOutput { call_id: call_id.clone(), output: truncated, diff --git a/codex-rs/core/src/context_manager/history_tests.rs b/codex-rs/core/src/context_manager/history_tests.rs index ae3e0368fa..a1aeacd322 100644 --- a/codex-rs/core/src/context_manager/history_tests.rs +++ b/codex-rs/core/src/context_manager/history_tests.rs @@ -1,4 +1,5 @@ use super::*; +use crate::context_manager::MODEL_FORMAT_MAX_LINES; use crate::context_manager::truncate; use codex_git::GhostCommit; use codex_protocol::models::ContentItem; @@ -308,8 +309,10 @@ fn assert_truncated_message_matches(message: &str, line: &str, total_lines: usiz } fn truncated_message_pattern(line: &str, total_lines: usize) -> String { - let head_take = truncate::MODEL_FORMAT_HEAD_LINES.min(total_lines); - let tail_take = truncate::MODEL_FORMAT_TAIL_LINES.min(total_lines.saturating_sub(head_take)); + let head_lines = MODEL_FORMAT_MAX_LINES / 2; + let tail_lines = MODEL_FORMAT_MAX_LINES - head_lines; + let head_take = head_lines.min(total_lines); + let tail_take = tail_lines.min(total_lines.saturating_sub(head_take)); let omitted = total_lines.saturating_sub(head_take + tail_take); let escaped_line = regex_lite::escape(line); if omitted == 0 { @@ -328,7 +331,11 @@ fn format_exec_output_truncates_large_error() { let line = "very long execution error line that should trigger truncation\n"; let large_error = line.repeat(2_500); // way beyond both byte and line limits - let truncated = truncate::format_output_for_model_body(&large_error); + let truncated = truncate::format_output_for_model_body( + &large_error, + truncate::MODEL_FORMAT_MAX_BYTES, + truncate::MODEL_FORMAT_MAX_LINES, + ); let total_lines = large_error.lines().count(); assert_truncated_message_matches(&truncated, line, total_lines); @@ -338,7 +345,11 @@ fn format_exec_output_truncates_large_error() { #[test] fn format_exec_output_marks_byte_truncation_without_omitted_lines() { let long_line = "a".repeat(truncate::MODEL_FORMAT_MAX_BYTES + 50); - let truncated = truncate::format_output_for_model_body(&long_line); + let truncated = truncate::format_output_for_model_body( + &long_line, + truncate::MODEL_FORMAT_MAX_BYTES, + truncate::MODEL_FORMAT_MAX_LINES, + ); assert_ne!(truncated, long_line); let marker_line = format!( @@ -359,7 +370,14 @@ fn format_exec_output_marks_byte_truncation_without_omitted_lines() { fn format_exec_output_returns_original_when_within_limits() { let content = "example output\n".repeat(10); - assert_eq!(truncate::format_output_for_model_body(&content), content); + assert_eq!( + truncate::format_output_for_model_body( + &content, + truncate::MODEL_FORMAT_MAX_BYTES, + truncate::MODEL_FORMAT_MAX_LINES + ), + content + ); } #[test] @@ -369,7 +387,11 @@ fn format_exec_output_reports_omitted_lines_and_keeps_head_and_tail() { .map(|idx| format!("line-{idx}\n")) .collect(); - let truncated = truncate::format_output_for_model_body(&content); + let truncated = truncate::format_output_for_model_body( + &content, + truncate::MODEL_FORMAT_MAX_BYTES, + truncate::MODEL_FORMAT_MAX_LINES, + ); let omitted = total_lines - truncate::MODEL_FORMAT_MAX_LINES; let expected_marker = format!("[... omitted {omitted} of {total_lines} lines ...]"); @@ -397,7 +419,11 @@ fn format_exec_output_prefers_line_marker_when_both_limits_exceeded() { .map(|idx| format!("line-{idx}-{long_line}\n")) .collect(); - let truncated = truncate::format_output_for_model_body(&content); + let truncated = truncate::format_output_for_model_body( + &content, + truncate::MODEL_FORMAT_MAX_BYTES, + truncate::MODEL_FORMAT_MAX_LINES, + ); assert!( truncated.contains("[... omitted 42 of 298 lines ...]"), diff --git a/codex-rs/core/src/context_manager/mod.rs b/codex-rs/core/src/context_manager/mod.rs index 8531e443fa..d945cb95b0 100644 --- a/codex-rs/core/src/context_manager/mod.rs +++ b/codex-rs/core/src/context_manager/mod.rs @@ -3,4 +3,6 @@ mod normalize; mod truncate; pub(crate) use history::ContextManager; +pub(crate) use truncate::MODEL_FORMAT_MAX_BYTES; +pub(crate) use truncate::MODEL_FORMAT_MAX_LINES; pub(crate) use truncate::format_output_for_model_body; diff --git a/codex-rs/core/src/context_manager/truncate.rs b/codex-rs/core/src/context_manager/truncate.rs index 65e6dc99a5..88027ad15d 100644 --- a/codex-rs/core/src/context_manager/truncate.rs +++ b/codex-rs/core/src/context_manager/truncate.rs @@ -2,12 +2,11 @@ use codex_protocol::models::FunctionCallOutputContentItem; use codex_utils_string::take_bytes_at_char_boundary; use codex_utils_string::take_last_bytes_at_char_boundary; +use crate::util::error_or_panic; + // Model-formatting limits: clients get full streams; only content sent to the model is truncated. -pub(crate) const MODEL_FORMAT_MAX_BYTES: usize = 10 * 1024; // 10 KiB -pub(crate) const MODEL_FORMAT_MAX_LINES: usize = 256; // lines -pub(crate) const MODEL_FORMAT_HEAD_LINES: usize = MODEL_FORMAT_MAX_LINES / 2; -pub(crate) const MODEL_FORMAT_TAIL_LINES: usize = MODEL_FORMAT_MAX_LINES - MODEL_FORMAT_HEAD_LINES; // 128 -pub(crate) const MODEL_FORMAT_HEAD_BYTES: usize = MODEL_FORMAT_MAX_BYTES / 2; +pub const MODEL_FORMAT_MAX_BYTES: usize = 10 * 1024; // 10 KiB +pub const MODEL_FORMAT_MAX_LINES: usize = 256; // lines pub(crate) fn globally_truncate_function_output_items( items: &[FunctionCallOutputContentItem], @@ -56,21 +55,34 @@ pub(crate) fn globally_truncate_function_output_items( out } -pub(crate) fn format_output_for_model_body(content: &str) -> String { +pub(crate) fn format_output_for_model_body( + content: &str, + limit_bytes: usize, + limit_lines: usize, +) -> String { // Head+tail truncation for the model: show the beginning and end with an elision. // Clients still receive full streams; only this formatted summary is capped. let total_lines = content.lines().count(); - if content.len() <= MODEL_FORMAT_MAX_BYTES && total_lines <= MODEL_FORMAT_MAX_LINES { + if content.len() <= limit_bytes && total_lines <= limit_lines { return content.to_string(); } - let output = truncate_formatted_exec_output(content, total_lines); + let output = truncate_formatted_exec_output(content, total_lines, limit_bytes, limit_lines); format!("Total output lines: {total_lines}\n\n{output}") } -fn truncate_formatted_exec_output(content: &str, total_lines: usize) -> String { +fn truncate_formatted_exec_output( + content: &str, + total_lines: usize, + limit_bytes: usize, + limit_lines: usize, +) -> String { + debug_panic_on_double_truncation(content); + let head_lines: usize = limit_lines / 2; + let tail_lines: usize = limit_lines - head_lines; // 128 + let head_bytes: usize = limit_bytes / 2; let segments: Vec<&str> = content.split_inclusive('\n').collect(); - let head_take = MODEL_FORMAT_HEAD_LINES.min(segments.len()); - let tail_take = MODEL_FORMAT_TAIL_LINES.min(segments.len().saturating_sub(head_take)); + let head_take = head_lines.min(segments.len()); + let tail_take = tail_lines.min(segments.len().saturating_sub(head_take)); let omitted = segments.len().saturating_sub(head_take + tail_take); let head_slice_end: usize = segments @@ -91,7 +103,7 @@ fn truncate_formatted_exec_output(content: &str, total_lines: usize) -> String { }; let head_slice = &content[..head_slice_end]; let tail_slice = &content[tail_slice_start..]; - let truncated_by_bytes = content.len() > MODEL_FORMAT_MAX_BYTES; + let truncated_by_bytes = content.len() > limit_bytes; // this is a bit wrong. We are counting metadata lines and not just shell output lines. let marker = if omitted > 0 { Some(format!( @@ -99,24 +111,24 @@ fn truncate_formatted_exec_output(content: &str, total_lines: usize) -> String { )) } else if truncated_by_bytes { Some(format!( - "\n[... output truncated to fit {MODEL_FORMAT_MAX_BYTES} bytes ...]\n\n" + "\n[... output truncated to fit {limit_bytes} bytes ...]\n\n" )) } else { None }; let marker_len = marker.as_ref().map_or(0, String::len); - let base_head_budget = MODEL_FORMAT_HEAD_BYTES.min(MODEL_FORMAT_MAX_BYTES); - let head_budget = base_head_budget.min(MODEL_FORMAT_MAX_BYTES.saturating_sub(marker_len)); + let base_head_budget = head_bytes.min(limit_bytes); + let head_budget = base_head_budget.min(limit_bytes.saturating_sub(marker_len)); let head_part = take_bytes_at_char_boundary(head_slice, head_budget); - let mut result = String::with_capacity(MODEL_FORMAT_MAX_BYTES.min(content.len())); + let mut result = String::with_capacity(limit_bytes.min(content.len())); result.push_str(head_part); if let Some(marker_text) = marker.as_ref() { result.push_str(marker_text); } - let remaining = MODEL_FORMAT_MAX_BYTES.saturating_sub(result.len()); + let remaining = limit_bytes.saturating_sub(result.len()); if remaining == 0 { return result; } @@ -126,3 +138,11 @@ fn truncate_formatted_exec_output(content: &str, total_lines: usize) -> String { result } + +fn debug_panic_on_double_truncation(content: &str) { + if content.contains("Total output lines:") && content.contains("omitted") { + error_or_panic(format!( + "FunctionCallOutput content was already truncated before ContextManager::record_items; this would cause double truncation {content}" + )); + } +} diff --git a/codex-rs/core/src/tools/mod.rs b/codex-rs/core/src/tools/mod.rs index 92509c857c..c94a7c28d9 100644 --- a/codex-rs/core/src/tools/mod.rs +++ b/codex-rs/core/src/tools/mod.rs @@ -9,6 +9,8 @@ pub mod runtimes; pub mod sandboxing; pub mod spec; +use crate::context_manager::MODEL_FORMAT_MAX_BYTES; +use crate::context_manager::MODEL_FORMAT_MAX_LINES; use crate::context_manager::format_output_for_model_body; use crate::exec::ExecToolCallOutput; pub use router::ToolRouter; @@ -75,5 +77,5 @@ pub fn format_exec_output_str(exec_output: &ExecToolCallOutput) -> String { }; // Truncate for model consumption before serialization. - format_output_for_model_body(&body) + format_output_for_model_body(&body, MODEL_FORMAT_MAX_BYTES, MODEL_FORMAT_MAX_LINES) } diff --git a/codex-rs/core/tests/suite/truncation.rs b/codex-rs/core/tests/suite/truncation.rs index aab95fa028..101bdc6199 100644 --- a/codex-rs/core/tests/suite/truncation.rs +++ b/codex-rs/core/tests/suite/truncation.rs @@ -19,6 +19,7 @@ use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_function_call; use core_test_support::responses::ev_response_created; +use core_test_support::responses::mount_sse_once; use core_test_support::responses::mount_sse_once_match; use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::sse; @@ -86,7 +87,7 @@ async fn truncate_function_error_trims_respond_to_model() -> Result<()> { serde_json::from_str::(&output).is_err(), "expected error output to be plain text", ); - let truncated_pattern = r#"(?s)^Total output lines: 1\s+.*\[\.\.\. output truncated to fit 10240 bytes \.\.\.\]\s*$"#; + let truncated_pattern = r#"(?s)^Total output lines: 1\s+.*\[\.\.\. output truncated to fit 11264 bytes \.\.\.\]\s*$"#; assert_regex_match(truncated_pattern, &output); assert!( !output.contains("omitted"), @@ -113,15 +114,25 @@ async fn tool_call_output_exceeds_limit_truncated_for_model() -> Result<()> { let fixture = builder.build(&server).await?; let call_id = "shell-too-large"; - let args = serde_json::json!({ - "command": ["/bin/sh", "-c", "seq 1 400"], - "timeout_ms": 5_000, - }); + let args = if cfg!(windows) { + serde_json::json!({ + "command": [ + "powershell", + "-Command", + "for ($i=1; $i -le 400; $i++) { Write-Output $i }" + ], + "timeout_ms": 5_000, + }) + } else { + serde_json::json!({ + "command": ["/bin/sh", "-c", "seq 1 400"], + "timeout_ms": 5_000, + }) + }; // First response: model tells us to run the tool; second: complete the turn. - mount_sse_once_match( + mount_sse_once( &server, - any(), sse(vec![ responses::ev_response_created("resp-1"), responses::ev_function_call(call_id, "shell", &serde_json::to_string(&args)?), @@ -149,6 +160,7 @@ async fn tool_call_output_exceeds_limit_truncated_for_model() -> Result<()> { .single_request() .function_call_output_text(call_id) .context("function_call_output present for shell call")?; + let output = output.replace("\r\n", "\n"); // Expect plain text (not JSON) with truncation markers and line elision. assert!( @@ -180,6 +192,75 @@ $"#; Ok(()) } +// Ensures shell tool outputs that exceed the line limit are truncated only once. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn tool_call_output_truncated_only_once() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + + let mut builder = test_codex().with_config(|config| { + config.model = "gpt-5-codex".to_string(); + config.model_family = + find_family_for_model("gpt-5-codex").expect("gpt-5-codex is a model family"); + }); + let fixture = builder.build(&server).await?; + let call_id = "shell-single-truncation"; + let args = if cfg!(windows) { + serde_json::json!({ + "command": [ + "powershell", + "-Command", + "for ($i=1; $i -le 2000; $i++) { Write-Output $i }" + ], + "timeout_ms": 5_000, + }) + } else { + serde_json::json!({ + "command": ["/bin/sh", "-c", "seq 1 2000"], + "timeout_ms": 5_000, + }) + }; + + mount_sse_once_match( + &server, + any(), + sse(vec![ + responses::ev_response_created("resp-1"), + responses::ev_function_call(call_id, "shell", &serde_json::to_string(&args)?), + responses::ev_completed("resp-1"), + ]), + ) + .await; + let mock2 = mount_sse_once_match( + &server, + any(), + sse(vec![ + responses::ev_assistant_message("msg-1", "done"), + responses::ev_completed("resp-2"), + ]), + ) + .await; + + fixture + .submit_turn_with_policy("trigger big shell output", SandboxPolicy::DangerFullAccess) + .await?; + + let output = mock2 + .single_request() + .function_call_output_text(call_id) + .context("function_call_output present for shell call")?; + + let total_line_headers = output.matches("Total output lines:").count(); + + assert_eq!( + total_line_headers, 1, + "shell output should carry only one truncation header: {output}" + ); + + Ok(()) +} + // Verifies that an MCP tool call result exceeding the model formatting limits // is truncated before being sent back to the model. #[tokio::test(flavor = "multi_thread", worker_threads = 1)] @@ -269,7 +350,8 @@ async fn mcp_tool_call_output_exceeds_limit_truncated_for_model() -> Result<()> output.starts_with("Total output lines: 1\n\n{"), "expected total line header and JSON head, got: {output}" ); - let byte_marker = Regex::new(r"\[\.\.\. output truncated to fit 10240 bytes \.\.\.\]") + + let byte_marker = Regex::new(r"\[\.\.\. output truncated to fit 11264 bytes \.\.\.\]") .expect("compile regex"); assert!( byte_marker.is_match(&output), diff --git a/codex-rs/core/tests/suite/user_shell_cmd.rs b/codex-rs/core/tests/suite/user_shell_cmd.rs index fa09f0056d..8910161f1e 100644 --- a/codex-rs/core/tests/suite/user_shell_cmd.rs +++ b/codex-rs/core/tests/suite/user_shell_cmd.rs @@ -1,18 +1,31 @@ +use anyhow::Context; use codex_core::ConversationManager; use codex_core::NewConversation; +use codex_core::model_family::find_family_for_model; use codex_core::protocol::EventMsg; use codex_core::protocol::ExecCommandEndEvent; use codex_core::protocol::ExecOutputStream; use codex_core::protocol::Op; +use codex_core::protocol::SandboxPolicy; use codex_core::protocol::TurnAbortReason; use core_test_support::assert_regex_match; use core_test_support::load_default_config_for_test; use core_test_support::responses; +use core_test_support::responses::ev_assistant_message; +use core_test_support::responses::ev_completed; +use core_test_support::responses::ev_function_call; +use core_test_support::responses::ev_response_created; +use core_test_support::responses::mount_sse_once_match; +use core_test_support::responses::sse; +use core_test_support::responses::start_mock_server; +use core_test_support::skip_if_no_network; +use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; use core_test_support::wait_for_event_match; use regex_lite::escape; use std::path::PathBuf; use tempfile::TempDir; +use wiremock::matchers::any; #[tokio::test] async fn user_shell_cmd_ls_and_cat_in_temp_dir() { @@ -249,3 +262,72 @@ async fn user_shell_command_output_is_truncated_in_history() -> anyhow::Result<( Ok(()) } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn user_shell_command_is_truncated_only_once() -> anyhow::Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + + let mut builder = test_codex().with_config(|config| { + config.model = "gpt-5-codex".to_string(); + config.model_family = + find_family_for_model("gpt-5-codex").expect("gpt-5-codex is a model family"); + }); + let fixture = builder.build(&server).await?; + + let call_id = "user-shell-double-truncation"; + let args = if cfg!(windows) { + serde_json::json!({ + "command": [ + "powershell", + "-Command", + "for ($i=1; $i -le 2000; $i++) { Write-Output $i }" + ], + "timeout_ms": 5_000, + }) + } else { + serde_json::json!({ + "command": ["/bin/sh", "-c", "seq 1 2000"], + "timeout_ms": 5_000, + }) + }; + + mount_sse_once_match( + &server, + any(), + sse(vec![ + ev_response_created("resp-1"), + ev_function_call(call_id, "shell", &serde_json::to_string(&args)?), + ev_completed("resp-1"), + ]), + ) + .await; + let mock2 = mount_sse_once_match( + &server, + any(), + sse(vec![ + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]), + ) + .await; + + fixture + .submit_turn_with_policy("trigger big shell output", SandboxPolicy::DangerFullAccess) + .await?; + + let output = mock2 + .single_request() + .function_call_output_text(call_id) + .context("function_call_output present for shell call")?; + + let truncation_headers = output.matches("Total output lines:").count(); + + assert_eq!( + truncation_headers, 1, + "shell output should carry only one truncation header: {output}" + ); + + Ok(()) +} From f3c6b1334b44206264c77f0696c3585eba6598fe Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 13 Nov 2025 17:11:43 -0800 Subject: [PATCH 18/20] Use shared network gating helper in chat completion tests (#6461) ## Summary - replace the bespoke network check in the chat completion payload and SSE tests with the existing `skip_if_no_network!` helper so they follow the same gating convention as the rest of the suite ## Testing - `just fmt` ------ [Codex Task](https://chatgpt.com/codex/tasks/task_i_69112d4cb9f08321ba773e8ccf39778e) --- .../core/tests/chat_completions_payload.rs | 62 +++---------------- codex-rs/core/tests/chat_completions_sse.rs | 62 +++---------------- 2 files changed, 18 insertions(+), 106 deletions(-) diff --git a/codex-rs/core/tests/chat_completions_payload.rs b/codex-rs/core/tests/chat_completions_payload.rs index cadf6be294..accac55e01 100644 --- a/codex-rs/core/tests/chat_completions_payload.rs +++ b/codex-rs/core/tests/chat_completions_payload.rs @@ -10,11 +10,11 @@ use codex_core::ModelProviderInfo; use codex_core::Prompt; use codex_core::ResponseItem; use codex_core::WireApi; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use codex_otel::otel_event_manager::OtelEventManager; use codex_protocol::ConversationId; use codex_protocol::models::ReasoningItemContent; use core_test_support::load_default_config_for_test; +use core_test_support::skip_if_no_network; use futures::StreamExt; use serde_json::Value; use tempfile::TempDir; @@ -24,10 +24,6 @@ use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; -fn network_disabled() -> bool { - std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() -} - async fn run_request(input: Vec) -> Value { let server = MockServer::start().await; @@ -191,12 +187,7 @@ fn first_assistant(messages: &[Value]) -> &Value { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn omits_reasoning_when_none_present() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let body = run_request(vec![user_message("u1"), assistant_message("a1")]).await; let messages = messages_from(&body); @@ -208,12 +199,7 @@ async fn omits_reasoning_when_none_present() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn attaches_reasoning_to_previous_assistant() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let body = run_request(vec![ user_message("u1"), @@ -230,12 +216,7 @@ async fn attaches_reasoning_to_previous_assistant() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn attaches_reasoning_to_function_call_anchor() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let body = run_request(vec![ user_message("u1"), @@ -257,12 +238,7 @@ async fn attaches_reasoning_to_function_call_anchor() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn attaches_reasoning_to_local_shell_call() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let body = run_request(vec![ user_message("u1"), @@ -282,12 +258,7 @@ async fn attaches_reasoning_to_local_shell_call() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn drops_reasoning_when_last_role_is_user() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let body = run_request(vec![ assistant_message("aPrev"), @@ -301,12 +272,7 @@ async fn drops_reasoning_when_last_role_is_user() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn ignores_reasoning_before_last_user() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let body = run_request(vec![ user_message("u1"), @@ -321,12 +287,7 @@ async fn ignores_reasoning_before_last_user() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn skips_empty_reasoning_segments() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let body = run_request(vec![ user_message("u1"), @@ -342,12 +303,7 @@ async fn skips_empty_reasoning_segments() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn suppresses_duplicate_assistant_messages() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let body = run_request(vec![assistant_message("dup"), assistant_message("dup")]).await; let messages = messages_from(&body); diff --git a/codex-rs/core/tests/chat_completions_sse.rs b/codex-rs/core/tests/chat_completions_sse.rs index b499b76e8f..7b87163605 100644 --- a/codex-rs/core/tests/chat_completions_sse.rs +++ b/codex-rs/core/tests/chat_completions_sse.rs @@ -10,11 +10,11 @@ use codex_core::Prompt; use codex_core::ResponseEvent; use codex_core::ResponseItem; use codex_core::WireApi; -use codex_core::spawn::CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR; use codex_otel::otel_event_manager::OtelEventManager; use codex_protocol::ConversationId; use codex_protocol::models::ReasoningItemContent; use core_test_support::load_default_config_for_test; +use core_test_support::skip_if_no_network; use futures::StreamExt; use tempfile::TempDir; use wiremock::Mock; @@ -23,10 +23,6 @@ use wiremock::ResponseTemplate; use wiremock::matchers::method; use wiremock::matchers::path; -fn network_disabled() -> bool { - std::env::var(CODEX_SANDBOX_NETWORK_DISABLED_ENV_VAR).is_ok() -} - async fn run_stream(sse_body: &str) -> Vec { run_stream_with_bytes(sse_body.as_bytes()).await } @@ -157,12 +153,7 @@ fn assert_reasoning(item: &ResponseItem, expected: &str) { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn streams_text_without_reasoning() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let sse = concat!( "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\n", @@ -193,12 +184,7 @@ async fn streams_text_without_reasoning() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn streams_reasoning_from_string_delta() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let sse = concat!( "data: {\"choices\":[{\"delta\":{\"reasoning\":\"think1\"}}]}\n\n", @@ -250,12 +236,7 @@ async fn streams_reasoning_from_string_delta() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn streams_reasoning_from_object_delta() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let sse = concat!( "data: {\"choices\":[{\"delta\":{\"reasoning\":{\"text\":\"partA\"}}}]}\n\n", @@ -319,12 +300,7 @@ async fn streams_reasoning_from_object_delta() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn streams_reasoning_from_final_message() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let sse = "data: {\"choices\":[{\"message\":{\"reasoning\":\"final-cot\"},\"finish_reason\":\"stop\"}]}\n\n"; @@ -357,12 +333,7 @@ async fn streams_reasoning_from_final_message() { #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn streams_reasoning_before_tool_call() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let sse = concat!( "data: {\"choices\":[{\"delta\":{\"reasoning\":\"pre-tool\"}}]}\n\n", @@ -413,12 +384,7 @@ async fn streams_reasoning_before_tool_call() { #[tokio::test] #[traced_test] async fn chat_sse_emits_failed_on_parse_error() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let sse_body = concat!("data: not-json\n\n", "data: [DONE]\n\n"); @@ -450,12 +416,7 @@ async fn chat_sse_emits_failed_on_parse_error() { #[tokio::test] #[traced_test] async fn chat_sse_done_chunk_emits_event() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let sse_body = "data: [DONE]\n\n"; @@ -473,12 +434,7 @@ async fn chat_sse_done_chunk_emits_event() { #[tokio::test] #[traced_test] async fn chat_sse_emits_error_on_invalid_utf8() { - if network_disabled() { - println!( - "Skipping test because it cannot execute when network is disabled in a Codex sandbox." - ); - return; - } + skip_if_no_network!(); let _ = run_stream_with_bytes(b"data: \x80\x80\n\n").await; From 2a6e9b20dfd8ff0fd9e2d09d3fc377e4790e9c56 Mon Sep 17 00:00:00 2001 From: Ahmed Ibrahim Date: Thu, 13 Nov 2025 17:12:10 -0800 Subject: [PATCH 19/20] Promote shared helpers for suite tests (#6460) ## Summary - add `TestCodex::submit_turn_with_policies` and extend the response helpers with reusable tool-call utilities - update the grep_files, read_file, list_dir, shell_serialization, and tools suites to rely on the shared helpers instead of local copies - make the list_dir helper return `anyhow::Result` so clippy no longer warns about `expect` ## Testing - `just fix -p codex-core` - `cargo test -p codex-core --test all suite::grep_files::grep_files_tool_collects_matches` - `cargo test -p codex-core suite::grep_files::grep_files_tool_collects_matches -- --ignored` (filter requests ignored tests so nothing runs, but the build stays clean) ------ [Codex Task](https://chatgpt.com/codex/tasks/task_i_69112d53abac83219813cab4d7cb6446) --- codex-rs/core/tests/common/responses.rs | 73 ++++ codex-rs/core/tests/common/test_codex.rs | 20 +- codex-rs/core/tests/suite/grep_files.rs | 129 +----- codex-rs/core/tests/suite/list_dir.rs | 385 +++--------------- codex-rs/core/tests/suite/read_file.rs | 81 +--- .../core/tests/suite/shell_serialization.rs | 269 ++++-------- codex-rs/core/tests/suite/tool_harness.rs | 72 ++-- codex-rs/core/tests/suite/tools.rs | 74 +--- codex-rs/core/tests/suite/view_image.rs | 43 +- 9 files changed, 305 insertions(+), 841 deletions(-) diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index b78f921bc0..7a60cbe83c 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use std::sync::Mutex; +use anyhow::Result; use serde_json::Value; use wiremock::BodyPrintLimit; use wiremock::Match; @@ -9,6 +10,7 @@ use wiremock::MockBuilder; use wiremock::MockServer; use wiremock::Respond; use wiremock::ResponseTemplate; +use wiremock::matchers::any; use wiremock::matchers::method; use wiremock::matchers::path_regex; @@ -38,6 +40,10 @@ impl ResponseMock { self.requests.lock().unwrap().clone() } + pub fn last_request(&self) -> Option { + self.requests.lock().unwrap().last().cloned() + } + /// Returns true if any captured request contains a `function_call` with the /// provided `call_id`. pub fn saw_function_call(&self, call_id: &str) -> bool { @@ -130,6 +136,42 @@ impl ResponsesRequest { .map(str::to_string) } + pub fn function_call_output_content_and_success( + &self, + call_id: &str, + ) -> Option<(Option, Option)> { + self.call_output_content_and_success(call_id, "function_call_output") + } + + pub fn custom_tool_call_output_content_and_success( + &self, + call_id: &str, + ) -> Option<(Option, Option)> { + self.call_output_content_and_success(call_id, "custom_tool_call_output") + } + + fn call_output_content_and_success( + &self, + call_id: &str, + call_type: &str, + ) -> Option<(Option, Option)> { + let output = self + .call_output(call_id, call_type) + .get("output") + .cloned() + .unwrap_or(Value::Null); + match output { + Value::String(text) => Some((Some(text), None)), + Value::Object(obj) => Some(( + obj.get("content") + .and_then(Value::as_str) + .map(str::to_string), + obj.get("success").and_then(Value::as_bool), + )), + _ => Some((None, None)), + } + } + pub fn header(&self, name: &str) -> Option { self.0 .headers @@ -487,6 +529,37 @@ pub async fn start_mock_server() -> MockServer { .await } +#[derive(Clone)] +pub struct FunctionCallResponseMocks { + pub function_call: ResponseMock, + pub completion: ResponseMock, +} + +pub async fn mount_function_call_agent_response( + server: &MockServer, + call_id: &str, + arguments: &str, + tool_name: &str, +) -> FunctionCallResponseMocks { + let first_response = sse(vec![ + ev_response_created("resp-1"), + ev_function_call(call_id, tool_name, arguments), + ev_completed("resp-1"), + ]); + let function_call = mount_sse_once_match(server, any(), first_response).await; + + let second_response = sse(vec![ + ev_assistant_message("msg-1", "done"), + ev_completed("resp-2"), + ]); + let completion = mount_sse_once_match(server, any(), second_response).await; + + FunctionCallResponseMocks { + function_call, + completion, + } +} + /// Mounts a sequence of SSE response bodies and serves them in order for each /// POST to `/v1/responses`. Panics if more requests are received than bodies /// provided. Also asserts the exact number of expected calls. diff --git a/codex-rs/core/tests/common/test_codex.rs b/codex-rs/core/tests/common/test_codex.rs index 2741d8bed1..e88c410ece 100644 --- a/codex-rs/core/tests/common/test_codex.rs +++ b/codex-rs/core/tests/common/test_codex.rs @@ -159,14 +159,28 @@ impl TestCodex { } pub async fn submit_turn(&self, prompt: &str) -> Result<()> { - self.submit_turn_with_policy(prompt, SandboxPolicy::DangerFullAccess) - .await + self.submit_turn_with_policies( + prompt, + AskForApproval::Never, + SandboxPolicy::DangerFullAccess, + ) + .await } pub async fn submit_turn_with_policy( &self, prompt: &str, sandbox_policy: SandboxPolicy, + ) -> Result<()> { + self.submit_turn_with_policies(prompt, AskForApproval::Never, sandbox_policy) + .await + } + + pub async fn submit_turn_with_policies( + &self, + prompt: &str, + approval_policy: AskForApproval, + sandbox_policy: SandboxPolicy, ) -> Result<()> { let session_model = self.session_configured.model.clone(); self.codex @@ -176,7 +190,7 @@ impl TestCodex { }], final_output_json_schema: None, cwd: self.cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, + approval_policy, sandbox_policy, model: session_model, effort: None, diff --git a/codex-rs/core/tests/suite/grep_files.rs b/codex-rs/core/tests/suite/grep_files.rs index f8097558d9..8b9f2a3b34 100644 --- a/codex-rs/core/tests/suite/grep_files.rs +++ b/codex-rs/core/tests/suite/grep_files.rs @@ -2,28 +2,14 @@ use anyhow::Result; use codex_core::model_family::find_family_for_model; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::user_input::UserInput; -use core_test_support::responses; -use core_test_support::responses::ev_assistant_message; -use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_function_call; -use core_test_support::responses::ev_response_created; -use core_test_support::responses::sse; +use core_test_support::responses::mount_function_call_agent_response; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; -use core_test_support::wait_for_event; -use serde_json::Value; use std::collections::HashSet; use std::path::Path; use std::process::Command as StdCommand; -use wiremock::matchers::any; const MODEL_WITH_TOOL: &str = "test-gpt-5-codex"; @@ -69,18 +55,22 @@ async fn grep_files_tool_collects_matches() -> Result<()> { }) .to_string(); - mount_tool_sequence(&server, call_id, &arguments, "grep_files").await; - submit_turn(&test, "please find uses of needle").await?; + let mocks = + mount_function_call_agent_response(&server, call_id, &arguments, "grep_files").await; + test.submit_turn("please find uses of needle").await?; - let bodies = recorded_bodies(&server).await?; - let tool_output = find_tool_output(&bodies, call_id).expect("tool output present"); - let payload = tool_output.get("output").expect("output field present"); - let (content_opt, success_opt) = extract_content_and_success(payload); + let req = mocks.completion.single_request(); + let (content_opt, success_opt) = req + .function_call_output_content_and_success(call_id) + .expect("tool output present"); let content = content_opt.expect("content present"); let success = success_opt.unwrap_or(true); - assert!(success, "expected success for matches, got {payload:?}"); + assert!( + success, + "expected success for matches, got content={content}" + ); - let entries = collect_file_names(content); + let entries = collect_file_names(&content); assert_eq!(entries.len(), 2, "content: {content}"); assert!( entries.contains("alpha.rs"), @@ -118,16 +108,17 @@ async fn grep_files_tool_reports_empty_results() -> Result<()> { }) .to_string(); - mount_tool_sequence(&server, call_id, &arguments, "grep_files").await; - submit_turn(&test, "search again").await?; + let mocks = + mount_function_call_agent_response(&server, call_id, &arguments, "grep_files").await; + test.submit_turn("search again").await?; - let bodies = recorded_bodies(&server).await?; - let tool_output = find_tool_output(&bodies, call_id).expect("tool output present"); - let payload = tool_output.get("output").expect("output field present"); - let (content_opt, success_opt) = extract_content_and_success(payload); + let req = mocks.completion.single_request(); + let (content_opt, success_opt) = req + .function_call_output_content_and_success(call_id) + .expect("tool output present"); let content = content_opt.expect("content present"); if let Some(success) = success_opt { - assert!(!success, "expected success=false payload: {payload:?}"); + assert!(!success, "expected success=false content={content}"); } assert_eq!(content, "No matches found."); @@ -144,73 +135,6 @@ async fn build_test_codex(server: &wiremock::MockServer) -> Result { builder.build(server).await } -async fn submit_turn(test: &TestCodex, prompt: &str) -> Result<()> { - let session_model = test.session_configured.model.clone(); - - test.codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: prompt.into(), - }], - final_output_json_schema: None, - cwd: test.cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: ReasoningSummary::Auto, - }) - .await?; - - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TaskComplete(_)) - }) - .await; - Ok(()) -} - -async fn mount_tool_sequence( - server: &wiremock::MockServer, - call_id: &str, - arguments: &str, - tool_name: &str, -) { - let first_response = sse(vec![ - ev_response_created("resp-1"), - ev_function_call(call_id, tool_name, arguments), - ev_completed("resp-1"), - ]); - responses::mount_sse_once_match(server, any(), first_response).await; - - let second_response = sse(vec![ - ev_assistant_message("msg-1", "done"), - ev_completed("resp-2"), - ]); - responses::mount_sse_once_match(server, any(), second_response).await; -} - -#[allow(clippy::expect_used)] -async fn recorded_bodies(server: &wiremock::MockServer) -> Result> { - let requests = server.received_requests().await.expect("requests recorded"); - Ok(requests - .iter() - .map(|req| req.body_json::().expect("request json")) - .collect()) -} - -fn find_tool_output<'a>(requests: &'a [Value], call_id: &str) -> Option<&'a Value> { - requests.iter().find_map(|body| { - body.get("input") - .and_then(Value::as_array) - .and_then(|items| { - items.iter().find(|item| { - item.get("type").and_then(Value::as_str) == Some("function_call_output") - && item.get("call_id").and_then(Value::as_str) == Some(call_id) - }) - }) - }) -} - fn collect_file_names(content: &str) -> HashSet { content .lines() @@ -224,14 +148,3 @@ fn collect_file_names(content: &str) -> HashSet { }) .collect() } - -fn extract_content_and_success(value: &Value) -> (Option<&str>, Option) { - match value { - Value::String(text) => (Some(text.as_str()), None), - Value::Object(obj) => ( - obj.get("content").and_then(Value::as_str), - obj.get("success").and_then(Value::as_bool), - ), - _ => (None, None), - } -} diff --git a/codex-rs/core/tests/suite/list_dir.rs b/codex-rs/core/tests/suite/list_dir.rs index 2a04d3075d..802080d846 100644 --- a/codex-rs/core/tests/suite/list_dir.rs +++ b/codex-rs/core/tests/suite/list_dir.rs @@ -1,25 +1,11 @@ #![cfg(not(target_os = "windows"))] -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::user_input::UserInput; -use core_test_support::responses; -use core_test_support::responses::ev_assistant_message; -use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_function_call; -use core_test_support::responses::ev_response_created; -use core_test_support::responses::sse; +use core_test_support::responses::mount_function_call_agent_response; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; -use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; -use core_test_support::wait_for_event; use pretty_assertions::assert_eq; -use serde_json::Value; -use wiremock::matchers::any; +use serde_json::json; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[ignore = "disabled until we enable list_dir tool"] @@ -27,99 +13,30 @@ async fn list_dir_tool_returns_entries() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; + let test = test_codex().build(&server).await?; - let TestCodex { - codex, - cwd, - session_configured, - .. - } = test_codex().build(&server).await?; - - let dir_path = cwd.path().join("sample_dir"); + let dir_path = test.cwd.path().join("sample_dir"); std::fs::create_dir(&dir_path)?; std::fs::write(dir_path.join("alpha.txt"), "first file")?; std::fs::create_dir(dir_path.join("nested"))?; let dir_path = dir_path.to_string_lossy().to_string(); let call_id = "list-dir-call"; - let arguments = serde_json::json!({ + let arguments = json!({ "dir_path": dir_path, "offset": 1, "limit": 2, }) .to_string(); - let first_response = sse(vec![ - ev_response_created("resp-1"), - ev_function_call(call_id, "list_dir", &arguments), - ev_completed("resp-1"), - ]); - responses::mount_sse_once_match(&server, any(), first_response).await; - - let second_response = sse(vec![ - ev_assistant_message("msg-1", "done"), - ev_completed("resp-2"), - ]); - responses::mount_sse_once_match(&server, any(), second_response).await; - - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "list directory contents".into(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: ReasoningSummary::Auto, - }) - .await?; - - wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - - let requests = server.received_requests().await.expect("recorded requests"); - let request_bodies = requests - .iter() - .map(|req| req.body_json::().unwrap()) - .collect::>(); - assert!( - !request_bodies.is_empty(), - "expected at least one request body" - ); - - let tool_output_item = request_bodies - .iter() - .find_map(|body| { - body.get("input") - .and_then(Value::as_array) - .and_then(|items| { - items.iter().find(|item| { - item.get("type").and_then(Value::as_str) == Some("function_call_output") - }) - }) - }) - .unwrap_or_else(|| { - panic!("function_call_output item not found in requests: {request_bodies:#?}") - }); - - assert_eq!( - tool_output_item.get("call_id").and_then(Value::as_str), - Some(call_id) - ); - - let output_text = tool_output_item - .get("output") - .and_then(|value| match value { - Value::String(text) => Some(text.as_str()), - Value::Object(obj) => obj.get("content").and_then(Value::as_str), - _ => None, - }) - .expect("output text present"); - assert_eq!(output_text, "E1: [file] alpha.txt\nE2: [dir] nested"); + let mocks = mount_function_call_agent_response(&server, call_id, &arguments, "list_dir").await; + test.submit_turn("list directory contents").await?; + let req = mocks.completion.single_request(); + let (content_opt, _) = req + .function_call_output_content_and_success(call_id) + .expect("function_call_output present"); + let output = content_opt.expect("output content present in tool output"); + assert_eq!(output, "E1: [file] alpha.txt\nE2: [dir] nested"); Ok(()) } @@ -130,15 +47,9 @@ async fn list_dir_tool_depth_one_omits_children() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; + let test = test_codex().build(&server).await?; - let TestCodex { - codex, - cwd, - session_configured, - .. - } = test_codex().build(&server).await?; - - let dir_path = cwd.path().join("depth_one"); + let dir_path = test.cwd.path().join("depth_one"); std::fs::create_dir(&dir_path)?; std::fs::write(dir_path.join("alpha.txt"), "alpha")?; std::fs::create_dir(dir_path.join("nested"))?; @@ -146,7 +57,7 @@ async fn list_dir_tool_depth_one_omits_children() -> anyhow::Result<()> { let dir_path = dir_path.to_string_lossy().to_string(); let call_id = "list-dir-depth1"; - let arguments = serde_json::json!({ + let arguments = json!({ "dir_path": dir_path, "offset": 1, "limit": 10, @@ -154,77 +65,15 @@ async fn list_dir_tool_depth_one_omits_children() -> anyhow::Result<()> { }) .to_string(); - let first_response = sse(vec![ - ev_response_created("resp-1"), - ev_function_call(call_id, "list_dir", &arguments), - ev_completed("resp-1"), - ]); - responses::mount_sse_once_match(&server, any(), first_response).await; - - let second_response = sse(vec![ - ev_assistant_message("msg-1", "done"), - ev_completed("resp-2"), - ]); - responses::mount_sse_once_match(&server, any(), second_response).await; - - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "list directory contents depth one".into(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: ReasoningSummary::Auto, - }) + let mocks = mount_function_call_agent_response(&server, call_id, &arguments, "list_dir").await; + test.submit_turn("list directory contents depth one") .await?; - - wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - - let requests = server.received_requests().await.expect("recorded requests"); - let request_bodies = requests - .iter() - .map(|req| req.body_json::().unwrap()) - .collect::>(); - assert!( - !request_bodies.is_empty(), - "expected at least one request body" - ); - - let tool_output_item = request_bodies - .iter() - .find_map(|body| { - body.get("input") - .and_then(Value::as_array) - .and_then(|items| { - items.iter().find(|item| { - item.get("type").and_then(Value::as_str) == Some("function_call_output") - }) - }) - }) - .unwrap_or_else(|| { - panic!("function_call_output item not found in requests: {request_bodies:#?}") - }); - - assert_eq!( - tool_output_item.get("call_id").and_then(Value::as_str), - Some(call_id) - ); - - let output_text = tool_output_item - .get("output") - .and_then(|value| match value { - Value::String(text) => Some(text.as_str()), - Value::Object(obj) => obj.get("content").and_then(Value::as_str), - _ => None, - }) - .expect("output text present"); - assert_eq!(output_text, "E1: [file] alpha.txt\nE2: [dir] nested"); + let req = mocks.completion.single_request(); + let (content_opt, _) = req + .function_call_output_content_and_success(call_id) + .expect("function_call_output present"); + let output = content_opt.expect("output content present in tool output"); + assert_eq!(output, "E1: [file] alpha.txt\nE2: [dir] nested"); Ok(()) } @@ -235,15 +84,9 @@ async fn list_dir_tool_depth_two_includes_children_only() -> anyhow::Result<()> skip_if_no_network!(Ok(())); let server = start_mock_server().await; + let test = test_codex().build(&server).await?; - let TestCodex { - codex, - cwd, - session_configured, - .. - } = test_codex().build(&server).await?; - - let dir_path = cwd.path().join("depth_two"); + let dir_path = test.cwd.path().join("depth_two"); std::fs::create_dir(&dir_path)?; std::fs::write(dir_path.join("alpha.txt"), "alpha")?; let nested = dir_path.join("nested"); @@ -255,7 +98,7 @@ async fn list_dir_tool_depth_two_includes_children_only() -> anyhow::Result<()> let dir_path_string = dir_path.to_string_lossy().to_string(); let call_id = "list-dir-depth2"; - let arguments = serde_json::json!({ + let arguments = json!({ "dir_path": dir_path_string, "offset": 1, "limit": 10, @@ -263,81 +106,16 @@ async fn list_dir_tool_depth_two_includes_children_only() -> anyhow::Result<()> }) .to_string(); - let first_response = sse(vec![ - serde_json::json!({ - "type": "response.created", - "response": {"id": "resp-1"} - }), - ev_function_call(call_id, "list_dir", &arguments), - ev_completed("resp-1"), - ]); - responses::mount_sse_once_match(&server, any(), first_response).await; - - let second_response = sse(vec![ - ev_assistant_message("msg-1", "done"), - ev_completed("resp-2"), - ]); - responses::mount_sse_once_match(&server, any(), second_response).await; - - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "list directory contents depth two".into(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: ReasoningSummary::Auto, - }) + let mocks = mount_function_call_agent_response(&server, call_id, &arguments, "list_dir").await; + test.submit_turn("list directory contents depth two") .await?; - - wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - - let requests = server.received_requests().await.expect("recorded requests"); - let request_bodies = requests - .iter() - .map(|req| req.body_json::().unwrap()) - .collect::>(); - assert!( - !request_bodies.is_empty(), - "expected at least one request body" - ); - - let tool_output_item = request_bodies - .iter() - .find_map(|body| { - body.get("input") - .and_then(Value::as_array) - .and_then(|items| { - items.iter().find(|item| { - item.get("type").and_then(Value::as_str) == Some("function_call_output") - }) - }) - }) - .unwrap_or_else(|| { - panic!("function_call_output item not found in requests: {request_bodies:#?}") - }); - + let req = mocks.completion.single_request(); + let (content_opt, _) = req + .function_call_output_content_and_success(call_id) + .expect("function_call_output present"); + let output = content_opt.expect("output content present in tool output"); assert_eq!( - tool_output_item.get("call_id").and_then(Value::as_str), - Some(call_id) - ); - - let output_text = tool_output_item - .get("output") - .and_then(|value| match value { - Value::String(text) => Some(text.as_str()), - Value::Object(obj) => obj.get("content").and_then(Value::as_str), - _ => None, - }) - .expect("output text present"); - assert_eq!( - output_text, + output, "E1: [file] alpha.txt\nE2: [dir] nested\nE3: [file] nested/beta.txt\nE4: [dir] nested/grand" ); @@ -350,15 +128,9 @@ async fn list_dir_tool_depth_three_includes_grandchildren() -> anyhow::Result<() skip_if_no_network!(Ok(())); let server = start_mock_server().await; + let test = test_codex().build(&server).await?; - let TestCodex { - codex, - cwd, - session_configured, - .. - } = test_codex().build(&server).await?; - - let dir_path = cwd.path().join("depth_three"); + let dir_path = test.cwd.path().join("depth_three"); std::fs::create_dir(&dir_path)?; std::fs::write(dir_path.join("alpha.txt"), "alpha")?; let nested = dir_path.join("nested"); @@ -370,7 +142,7 @@ async fn list_dir_tool_depth_three_includes_grandchildren() -> anyhow::Result<() let dir_path_string = dir_path.to_string_lossy().to_string(); let call_id = "list-dir-depth3"; - let arguments = serde_json::json!({ + let arguments = json!({ "dir_path": dir_path_string, "offset": 1, "limit": 10, @@ -378,81 +150,16 @@ async fn list_dir_tool_depth_three_includes_grandchildren() -> anyhow::Result<() }) .to_string(); - let first_response = sse(vec![ - serde_json::json!({ - "type": "response.created", - "response": {"id": "resp-1"} - }), - ev_function_call(call_id, "list_dir", &arguments), - ev_completed("resp-1"), - ]); - responses::mount_sse_once_match(&server, any(), first_response).await; - - let second_response = sse(vec![ - ev_assistant_message("msg-1", "done"), - ev_completed("resp-2"), - ]); - responses::mount_sse_once_match(&server, any(), second_response).await; - - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "list directory contents depth three".into(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: ReasoningSummary::Auto, - }) + let mocks = mount_function_call_agent_response(&server, call_id, &arguments, "list_dir").await; + test.submit_turn("list directory contents depth three") .await?; - - wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - - let requests = server.received_requests().await.expect("recorded requests"); - let request_bodies = requests - .iter() - .map(|req| req.body_json::().unwrap()) - .collect::>(); - assert!( - !request_bodies.is_empty(), - "expected at least one request body" - ); - - let tool_output_item = request_bodies - .iter() - .find_map(|body| { - body.get("input") - .and_then(Value::as_array) - .and_then(|items| { - items.iter().find(|item| { - item.get("type").and_then(Value::as_str) == Some("function_call_output") - }) - }) - }) - .unwrap_or_else(|| { - panic!("function_call_output item not found in requests: {request_bodies:#?}") - }); - + let req = mocks.completion.single_request(); + let (content_opt, _) = req + .function_call_output_content_and_success(call_id) + .expect("function_call_output present"); + let output = content_opt.expect("output content present in tool output"); assert_eq!( - tool_output_item.get("call_id").and_then(Value::as_str), - Some(call_id) - ); - - let output_text = tool_output_item - .get("output") - .and_then(|value| match value { - Value::String(text) => Some(text.as_str()), - Value::Object(obj) => obj.get("content").and_then(Value::as_str), - _ => None, - }) - .expect("output text present"); - assert_eq!( - output_text, + output, "E1: [file] alpha.txt\nE2: [dir] nested\nE3: [file] nested/beta.txt\nE4: [dir] nested/grand\nE5: [file] nested/grand/gamma.txt" ); diff --git a/codex-rs/core/tests/suite/read_file.rs b/codex-rs/core/tests/suite/read_file.rs index a74bd8b2a9..57be21f9f7 100644 --- a/codex-rs/core/tests/suite/read_file.rs +++ b/codex-rs/core/tests/suite/read_file.rs @@ -1,25 +1,11 @@ #![cfg(not(target_os = "windows"))] -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; -use codex_core::protocol::SandboxPolicy; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::user_input::UserInput; -use core_test_support::responses; -use core_test_support::responses::ev_assistant_message; -use core_test_support::responses::ev_completed; -use core_test_support::responses::ev_function_call; -use core_test_support::responses::ev_response_created; -use core_test_support::responses::sse; +use core_test_support::responses::mount_function_call_agent_response; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; -use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; -use core_test_support::wait_for_event; use pretty_assertions::assert_eq; -use serde_json::Value; -use wiremock::matchers::any; +use serde_json::json; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] #[ignore = "disabled until we enable read_file tool"] @@ -27,72 +13,29 @@ async fn read_file_tool_returns_requested_lines() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = start_mock_server().await; + let test = test_codex().build(&server).await?; - let TestCodex { - codex, - cwd, - session_configured, - .. - } = test_codex().build(&server).await?; - - let file_path = cwd.path().join("sample.txt"); + let file_path = test.cwd.path().join("sample.txt"); std::fs::write(&file_path, "first\nsecond\nthird\nfourth\n")?; let file_path = file_path.to_string_lossy().to_string(); let call_id = "read-file-call"; - let arguments = serde_json::json!({ + let arguments = json!({ "file_path": file_path, "offset": 2, "limit": 2, }) .to_string(); - let first_response = sse(vec![ - ev_response_created("resp-1"), - ev_function_call(call_id, "read_file", &arguments), - ev_completed("resp-1"), - ]); - responses::mount_sse_once_match(&server, any(), first_response).await; + let mocks = mount_function_call_agent_response(&server, call_id, &arguments, "read_file").await; - let second_response = sse(vec![ - ev_assistant_message("msg-1", "done"), - ev_completed("resp-2"), - ]); - let second_mock = responses::mount_sse_once_match(&server, any(), second_response).await; + test.submit_turn("please inspect sample.txt").await?; - let session_model = session_configured.model.clone(); - - codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: "please inspect sample.txt".into(), - }], - final_output_json_schema: None, - cwd: cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy: SandboxPolicy::DangerFullAccess, - model: session_model, - effort: None, - summary: ReasoningSummary::Auto, - }) - .await?; - - wait_for_event(&codex, |ev| matches!(ev, EventMsg::TaskComplete(_))).await; - - let req = second_mock.single_request(); - let tool_output_item = req.function_call_output(call_id); - assert_eq!( - tool_output_item.get("call_id").and_then(Value::as_str), - Some(call_id) - ); - let output_text = tool_output_item - .get("output") - .and_then(|value| match value { - Value::String(text) => Some(text.as_str()), - Value::Object(obj) => obj.get("content").and_then(Value::as_str), - _ => None, - }) - .expect("output text present"); + let req = mocks.completion.single_request(); + let (output_text_opt, _) = req + .function_call_output_content_and_success(call_id) + .expect("output present"); + let output_text = output_text_opt.expect("output text present"); assert_eq!(output_text, "L2: second\nL3: third"); Ok(()) diff --git a/codex-rs/core/tests/suite/shell_serialization.rs b/codex-rs/core/tests/suite/shell_serialization.rs index d748fe6b4c..237b2db377 100644 --- a/codex-rs/core/tests/suite/shell_serialization.rs +++ b/codex-rs/core/tests/suite/shell_serialization.rs @@ -3,12 +3,7 @@ use anyhow::Result; use codex_core::features::Feature; use codex_core::model_family::find_family_for_model; -use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; use codex_core::protocol::SandboxPolicy; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::user_input::UserInput; use core_test_support::assert_regex_match; use core_test_support::responses::ev_apply_patch_function_call; use core_test_support::responses::ev_assistant_message; @@ -21,9 +16,7 @@ use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; -use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; -use core_test_support::wait_for_event; use pretty_assertions::assert_eq; use regex_lite::Regex; use serde_json::Value; @@ -42,69 +35,6 @@ const FIXTURE_JSON: &str = r#"{ } "#; -async fn submit_turn(test: &TestCodex, prompt: &str, sandbox_policy: SandboxPolicy) -> Result<()> { - let session_model = test.session_configured.model.clone(); - - test.codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: prompt.into(), - }], - final_output_json_schema: None, - cwd: test.cwd.path().to_path_buf(), - approval_policy: AskForApproval::Never, - sandbox_policy, - model: session_model, - effort: None, - summary: ReasoningSummary::Auto, - }) - .await?; - - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TaskComplete(_)) - }) - .await; - - Ok(()) -} - -fn request_bodies(requests: &[wiremock::Request]) -> Result> { - requests - .iter() - .map(|req| Ok(serde_json::from_slice::(&req.body)?)) - .collect() -} - -fn find_function_call_output<'a>(bodies: &'a [Value], call_id: &str) -> Option<&'a Value> { - for body in bodies { - if let Some(items) = body.get("input").and_then(Value::as_array) { - for item in items { - if item.get("type").and_then(Value::as_str) == Some("function_call_output") - && item.get("call_id").and_then(Value::as_str) == Some(call_id) - { - return Some(item); - } - } - } - } - None -} - -fn find_custom_tool_call_output<'a>(bodies: &'a [Value], call_id: &str) -> Option<&'a Value> { - for body in bodies { - if let Some(items) = body.get("input").and_then(Value::as_array) { - for item in items { - if item.get("type").and_then(Value::as_str) == Some("custom_tool_call_output") - && item.get("call_id").and_then(Value::as_str) == Some(call_id) - { - return Some(item); - } - } - } - } - None -} - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn shell_output_stays_json_without_freeform_apply_patch() -> Result<()> { skip_if_no_network!(Ok(())); @@ -133,21 +63,16 @@ async fn shell_output_stays_json_without_freeform_apply_patch() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "run the json shell command", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = find_function_call_output(&bodies, call_id).expect("shell output present"); + let req = mock.last_request().expect("shell output request recorded"); + let output_item = req.function_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -202,22 +127,18 @@ async fn shell_output_is_structured_with_freeform_apply_patch() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "run the structured shell command", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = - find_function_call_output(&bodies, call_id).expect("structured output present"); + let req = mock + .last_request() + .expect("structured shell output request recorded"); + let output_item = req.function_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -269,21 +190,16 @@ async fn shell_output_preserves_fixture_json_without_serialization() -> Result<( ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "read the fixture JSON with sed", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = find_function_call_output(&bodies, call_id).expect("shell output present"); + let req = mock.last_request().expect("shell output request recorded"); + let output_item = req.function_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -345,22 +261,18 @@ async fn shell_output_structures_fixture_with_serialization() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "read the fixture JSON with structured output", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = - find_function_call_output(&bodies, call_id).expect("structured output present"); + let req = mock + .last_request() + .expect("structured output request recorded"); + let output_item = req.function_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -420,22 +332,18 @@ async fn shell_output_for_freeform_tool_records_duration() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "run the structured shell command", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = - find_function_call_output(&bodies, call_id).expect("structured output present"); + let req = mock + .last_request() + .expect("structured output request recorded"); + let output_item = req.function_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -490,22 +398,18 @@ async fn shell_output_reserializes_truncated_content() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "run the truncation shell command", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = - find_function_call_output(&bodies, call_id).expect("truncated output present"); + let req = mock + .last_request() + .expect("truncated output request recorded"); + let output_item = req.function_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -570,22 +474,18 @@ async fn apply_patch_custom_tool_output_is_structured() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "apply the patch via custom tool", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = - find_custom_tool_call_output(&bodies, call_id).expect("apply_patch output present"); + let req = mock + .last_request() + .expect("apply_patch output request recorded"); + let output_item = req.custom_tool_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -630,22 +530,18 @@ async fn apply_patch_custom_tool_call_creates_file() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "apply the patch via custom tool to create a file", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = - find_custom_tool_call_output(&bodies, call_id).expect("apply_patch output present"); + let req = mock + .last_request() + .expect("apply_patch output request recorded"); + let output_item = req.custom_tool_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -699,22 +595,18 @@ async fn apply_patch_custom_tool_call_updates_existing_file() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "apply the patch via custom tool to update a file", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = - find_custom_tool_call_output(&bodies, call_id).expect("apply_patch output present"); + let req = mock + .last_request() + .expect("apply_patch output request recorded"); + let output_item = req.custom_tool_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -762,22 +654,18 @@ async fn apply_patch_custom_tool_call_reports_failure_output() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "attempt a failing apply_patch via custom tool", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = - find_custom_tool_call_output(&bodies, call_id).expect("apply_patch output present"); + let req = mock + .last_request() + .expect("apply_patch output request recorded"); + let output_item = req.custom_tool_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -817,22 +705,18 @@ async fn apply_patch_function_call_output_is_structured() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "apply the patch via function-call apply_patch", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = - find_function_call_output(&bodies, call_id).expect("apply_patch function output present"); + let req = mock + .last_request() + .expect("apply_patch function output request recorded"); + let output_item = req.function_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -880,21 +764,16 @@ async fn shell_output_is_structured_for_nonzero_exit() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "run the failing shell command", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = find_function_call_output(&bodies, call_id).expect("shell output present"); + let req = mock.last_request().expect("shell output request recorded"); + let output_item = req.function_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) @@ -934,22 +813,18 @@ async fn local_shell_call_output_is_structured() -> Result<()> { ev_completed("resp-2"), ]), ]; - mount_sse_sequence(&server, responses).await; + let mock = mount_sse_sequence(&server, responses).await; - submit_turn( - &test, + test.submit_turn_with_policy( "run the local shell command", SandboxPolicy::DangerFullAccess, ) .await?; - let requests = server - .received_requests() - .await - .expect("recorded requests present"); - let bodies = request_bodies(&requests)?; - let output_item = - find_function_call_output(&bodies, call_id).expect("local shell output present"); + let req = mock + .last_request() + .expect("local shell output request recorded"); + let output_item = req.function_call_output(call_id); let output = output_item .get("output") .and_then(Value::as_str) diff --git a/codex-rs/core/tests/suite/tool_harness.rs b/codex-rs/core/tests/suite/tool_harness.rs index e9f9552c50..3288822ff3 100644 --- a/codex-rs/core/tests/suite/tool_harness.rs +++ b/codex-rs/core/tests/suite/tool_harness.rs @@ -14,6 +14,7 @@ use codex_protocol::plan_tool::StepStatus; use codex_protocol::user_input::UserInput; use core_test_support::assert_regex_match; use core_test_support::responses; +use core_test_support::responses::ResponsesRequest; use core_test_support::responses::ev_apply_patch_function_call; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; @@ -30,12 +31,22 @@ use serde_json::Value; use serde_json::json; use wiremock::matchers::any; -fn extract_output_text(item: &Value) -> Option<&str> { - item.get("output").and_then(|value| match value { - Value::String(text) => Some(text.as_str()), - Value::Object(obj) => obj.get("content").and_then(Value::as_str), - _ => None, - }) +fn call_output(req: &ResponsesRequest, call_id: &str) -> (String, Option) { + let raw = req.function_call_output(call_id); + assert_eq!( + raw.get("call_id").and_then(Value::as_str), + Some(call_id), + "mismatched call_id in function_call_output" + ); + let (content_opt, success) = match req.function_call_output_content_and_success(call_id) { + Some(values) => values, + None => panic!("function_call_output present"), + }; + let content = match content_opt { + Some(c) => c, + None => panic!("function_call_output content present"), + }; + (content, success) } #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -90,9 +101,8 @@ async fn shell_tool_executes_command_and_streams_output() -> anyhow::Result<()> wait_for_event(&codex, |event| matches!(event, EventMsg::TaskComplete(_))).await; let req = second_mock.single_request(); - let output_item = req.function_call_output(call_id); - let output_text = extract_output_text(&output_item).expect("output text present"); - let exec_output: Value = serde_json::from_str(output_text)?; + let (output_text, _) = call_output(&req, call_id); + let exec_output: Value = serde_json::from_str(&output_text)?; assert_eq!(exec_output["metadata"]["exit_code"], 0); let stdout = exec_output["output"].as_str().expect("stdout field"); assert_regex_match(r"(?s)^tool harness\n?$", stdout); @@ -174,12 +184,7 @@ async fn update_plan_tool_emits_plan_update_event() -> anyhow::Result<()> { assert!(saw_plan_update, "expected PlanUpdate event"); let req = second_mock.single_request(); - let output_item = req.function_call_output(call_id); - assert_eq!( - output_item.get("call_id").and_then(Value::as_str), - Some(call_id) - ); - let output_text = extract_output_text(&output_item).expect("output text present"); + let (output_text, _success_flag) = call_output(&req, call_id); assert_eq!(output_text, "Plan updated"); Ok(()) @@ -252,22 +257,12 @@ async fn update_plan_tool_rejects_malformed_payload() -> anyhow::Result<()> { ); let req = second_mock.single_request(); - let output_item = req.function_call_output(call_id); - assert_eq!( - output_item.get("call_id").and_then(Value::as_str), - Some(call_id) - ); - let output_text = extract_output_text(&output_item).expect("output text present"); + let (output_text, success_flag) = call_output(&req, call_id); assert!( output_text.contains("failed to parse function arguments"), "expected parse error message in output text, got {output_text:?}" ); - if let Some(success_flag) = output_item - .get("output") - .and_then(|value| value.as_object()) - .and_then(|obj| obj.get("success")) - .and_then(serde_json::Value::as_bool) - { + if let Some(success_flag) = success_flag { assert!( !success_flag, "expected tool output to mark success=false for malformed payload" @@ -357,12 +352,7 @@ async fn apply_patch_tool_executes_and_emits_patch_events() -> anyhow::Result<() assert!(patch_end_success); let req = second_mock.single_request(); - let output_item = req.function_call_output(call_id); - assert_eq!( - output_item.get("call_id").and_then(Value::as_str), - Some(call_id) - ); - let output_text = extract_output_text(&output_item).expect("output text present"); + let (output_text, _success_flag) = call_output(&req, call_id); let expected_pattern = format!( r"(?s)^Exit code: 0 @@ -372,7 +362,7 @@ Success. Updated the following files: A {file_name} ?$" ); - assert_regex_match(&expected_pattern, output_text); + assert_regex_match(&expected_pattern, &output_text); let updated_contents = fs::read_to_string(file_path)?; assert_eq!( @@ -437,12 +427,7 @@ async fn apply_patch_reports_parse_diagnostics() -> anyhow::Result<()> { wait_for_event(&codex, |event| matches!(event, EventMsg::TaskComplete(_))).await; let req = second_mock.single_request(); - let output_item = req.function_call_output(call_id); - assert_eq!( - output_item.get("call_id").and_then(Value::as_str), - Some(call_id) - ); - let output_text = extract_output_text(&output_item).expect("output text present"); + let (output_text, success_flag) = call_output(&req, call_id); assert!( output_text.contains("apply_patch verification failed"), @@ -453,12 +438,7 @@ async fn apply_patch_reports_parse_diagnostics() -> anyhow::Result<()> { "expected parse diagnostics in output text, got {output_text:?}" ); - if let Some(success_flag) = output_item - .get("output") - .and_then(|value| value.as_object()) - .and_then(|obj| obj.get("success")) - .and_then(serde_json::Value::as_bool) - { + if let Some(success_flag) = success_flag { assert!( !success_flag, "expected tool output to mark success=false for parse failures" diff --git a/codex-rs/core/tests/suite/tools.rs b/codex-rs/core/tests/suite/tools.rs index 2e92e65961..ca844db4c8 100644 --- a/codex-rs/core/tests/suite/tools.rs +++ b/codex-rs/core/tests/suite/tools.rs @@ -10,11 +10,7 @@ use anyhow::Result; use codex_core::features::Feature; use codex_core::model_family::find_family_for_model; use codex_core::protocol::AskForApproval; -use codex_core::protocol::EventMsg; -use codex_core::protocol::Op; use codex_core::protocol::SandboxPolicy; -use codex_protocol::config_types::ReasoningSummary; -use codex_protocol::user_input::UserInput; use core_test_support::assert_regex_match; use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; @@ -26,44 +22,11 @@ use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; -use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; -use core_test_support::wait_for_event; use regex_lite::Regex; use serde_json::Value; use serde_json::json; -async fn submit_turn( - test: &TestCodex, - prompt: &str, - approval_policy: AskForApproval, - sandbox_policy: SandboxPolicy, -) -> Result<()> { - let session_model = test.session_configured.model.clone(); - - test.codex - .submit(Op::UserTurn { - items: vec![UserInput::Text { - text: prompt.into(), - }], - final_output_json_schema: None, - cwd: test.cwd.path().to_path_buf(), - approval_policy, - sandbox_policy, - model: session_model, - effort: None, - summary: ReasoningSummary::Auto, - }) - .await?; - - wait_for_event(&test.codex, |event| { - matches!(event, EventMsg::TaskComplete(_)) - }) - .await; - - Ok(()) -} - fn tool_names(body: &Value) -> Vec { body.get("tools") .and_then(Value::as_array) @@ -110,8 +73,7 @@ async fn custom_tool_unknown_returns_custom_output_error() -> Result<()> { ) .await; - submit_turn( - &test, + test.submit_turn_with_policies( "invoke custom tool", AskForApproval::Never, SandboxPolicy::DangerFullAccess, @@ -189,8 +151,7 @@ async fn shell_escalated_permissions_rejected_then_ok() -> Result<()> { ) .await; - submit_turn( - &test, + test.submit_turn_with_policies( "run the shell command", AskForApproval::Never, SandboxPolicy::DangerFullAccess, @@ -202,24 +163,22 @@ async fn shell_escalated_permissions_rejected_then_ok() -> Result<()> { "approval policy is {policy:?}; reject command — you should not ask for escalated permissions if the approval policy is {policy:?}" ); - let blocked_item = second_mock + let blocked_output = second_mock .single_request() - .function_call_output(call_id_blocked); + .function_call_output_content_and_success(call_id_blocked) + .and_then(|(content, _)| content) + .expect("blocked output string"); assert_eq!( - blocked_item.get("output").and_then(Value::as_str), - Some(expected_message.as_str()), + blocked_output, expected_message, "unexpected rejection message" ); - let success_item = third_mock + let success_output = third_mock .single_request() - .function_call_output(call_id_success); - let output_json: Value = serde_json::from_str( - success_item - .get("output") - .and_then(Value::as_str) - .expect("success output string"), - )?; + .function_call_output_content_and_success(call_id_success) + .and_then(|(content, _)| content) + .expect("success output string"); + let output_json: Value = serde_json::from_str(&success_output)?; assert_eq!( output_json["metadata"]["exit_code"].as_i64(), Some(0), @@ -348,8 +307,7 @@ async fn collect_tools(use_unified_exec: bool) -> Result> { }); let test = builder.build(&server).await?; - submit_turn( - &test, + test.submit_turn_with_policies( "list tools", AskForApproval::Never, SandboxPolicy::DangerFullAccess, @@ -423,8 +381,7 @@ async fn shell_timeout_includes_timeout_prefix_and_metadata() -> Result<()> { ) .await; - submit_turn( - &test, + test.submit_turn_with_policies( "run a long command", AskForApproval::Never, SandboxPolicy::DangerFullAccess, @@ -600,8 +557,7 @@ async fn shell_spawn_failure_truncates_exec_error() -> Result<()> { ) .await; - submit_turn( - &test, + test.submit_turn_with_policies( "spawn a missing binary", AskForApproval::Never, SandboxPolicy::DangerFullAccess, diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index ae9af966f6..00931ebceb 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -45,14 +45,6 @@ fn find_image_message(body: &Value) -> Option<&Value> { }) } -fn extract_output_text(item: &Value) -> Option<&str> { - item.get("output").and_then(|value| match value { - Value::String(text) => Some(text.as_str()), - Value::Object(obj) => obj.get("content").and_then(Value::as_str), - _ => None, - }) -} - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn user_turn_with_local_image_attaches_image() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); @@ -207,10 +199,12 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> { assert_eq!(tool_event.call_id, call_id); assert_eq!(tool_event.path, abs_path); - let body = mock.single_request().body_json(); - let output_item = mock.single_request().function_call_output(call_id); - - let output_text = extract_output_text(&output_item).expect("output text present"); + let req = mock.single_request(); + let body = req.body_json(); + let output_text = req + .function_call_output_content_and_success(call_id) + .and_then(|(content, _)| content) + .expect("output text present"); assert_eq!(output_text, "attached local image path"); let image_message = @@ -299,9 +293,12 @@ async fn view_image_tool_errors_when_path_is_directory() -> anyhow::Result<()> { wait_for_event(&codex, |event| matches!(event, EventMsg::TaskComplete(_))).await; - let body_with_tool_output = mock.single_request().body_json(); - let output_item = mock.single_request().function_call_output(call_id); - let output_text = extract_output_text(&output_item).expect("output text present"); + let req = mock.single_request(); + let body_with_tool_output = req.body_json(); + let output_text = req + .function_call_output_content_and_success(call_id) + .and_then(|(content, _)| content) + .expect("output text present"); let expected_message = format!("image path `{}` is not a file", abs_path.display()); assert_eq!(output_text, expected_message); @@ -398,8 +395,11 @@ async fn view_image_tool_placeholder_for_non_image_files() -> anyhow::Result<()> "placeholder should mention path: {placeholder}" ); - let output_item = mock.single_request().function_call_output(call_id); - let output_text = extract_output_text(&output_item).expect("output text present"); + let output_text = mock + .single_request() + .function_call_output_content_and_success(call_id) + .and_then(|(content, _)| content) + .expect("output text present"); assert_eq!(output_text, "attached local image path"); Ok(()) @@ -456,9 +456,12 @@ async fn view_image_tool_errors_when_file_missing() -> anyhow::Result<()> { wait_for_event(&codex, |event| matches!(event, EventMsg::TaskComplete(_))).await; - let body_with_tool_output = mock.single_request().body_json(); - let output_item = mock.single_request().function_call_output(call_id); - let output_text = extract_output_text(&output_item).expect("output text present"); + let req = mock.single_request(); + let body_with_tool_output = req.body_json(); + let output_text = req + .function_call_output_content_and_success(call_id) + .and_then(|(content, _)| content) + .expect("output text present"); let expected_prefix = format!("unable to locate image at `{}`:", abs_path.display()); assert!( output_text.starts_with(&expected_prefix), From 6c384eb9c610f9a83037d9cad120fb792e782c7c Mon Sep 17 00:00:00 2001 From: pakrym-oai Date: Thu, 13 Nov 2025 18:04:05 -0800 Subject: [PATCH 20/20] tests: replace mount_sse_once_match with mount_sse_once for SSE mocking (#6640) --- AGENTS.md | 1 + codex-rs/core/tests/common/responses.rs | 5 +-- codex-rs/core/tests/suite/cli_stream.rs | 7 +--- codex-rs/core/tests/suite/client.rs | 40 +++++-------------- codex-rs/core/tests/suite/items.rs | 17 ++++---- codex-rs/core/tests/suite/model_tools.rs | 2 +- codex-rs/core/tests/suite/prompt_caching.rs | 31 +++++++------- codex-rs/core/tests/suite/resume.rs | 7 ++-- codex-rs/core/tests/suite/rmcp_client.rs | 33 +++++---------- codex-rs/core/tests/suite/tool_harness.rs | 21 +++++----- codex-rs/core/tests/suite/tools.rs | 3 +- codex-rs/core/tests/suite/truncation.rs | 23 ++++------- .../core/tests/suite/user_notification.rs | 3 +- codex-rs/core/tests/suite/user_shell_cmd.rs | 9 ++--- codex-rs/core/tests/suite/view_image.rs | 19 +++++---- codex-rs/exec/tests/suite/output_schema.rs | 3 +- .../exec/tests/suite/server_error_exit.rs | 3 +- 17 files changed, 85 insertions(+), 142 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7960ebba9b..aaebd0dfd3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -85,6 +85,7 @@ If you don’t have the tool: - `ResponsesRequest` exposes helpers (`body_json`, `input`, `function_call_output`, `custom_tool_call_output`, `call_output`, `header`, `path`, `query_param`) so assertions can target structured payloads instead of manual JSON digging. - Build SSE payloads with the provided `ev_*` constructors and the `sse(...)`. - Prefer `wait_for_event` over `wait_for_event_with_timeout`. +- Prefer `mount_sse_once` over `mount_sse_once_match` or `mount_sse_sequence` - Typical pattern: diff --git a/codex-rs/core/tests/common/responses.rs b/codex-rs/core/tests/common/responses.rs index 7a60cbe83c..2c88dd8ff5 100644 --- a/codex-rs/core/tests/common/responses.rs +++ b/codex-rs/core/tests/common/responses.rs @@ -10,7 +10,6 @@ use wiremock::MockBuilder; use wiremock::MockServer; use wiremock::Respond; use wiremock::ResponseTemplate; -use wiremock::matchers::any; use wiremock::matchers::method; use wiremock::matchers::path_regex; @@ -546,13 +545,13 @@ pub async fn mount_function_call_agent_response( ev_function_call(call_id, tool_name, arguments), ev_completed("resp-1"), ]); - let function_call = mount_sse_once_match(server, any(), first_response).await; + let function_call = mount_sse_once(server, first_response).await; let second_response = sse(vec![ ev_assistant_message("msg-1", "done"), ev_completed("resp-2"), ]); - let completion = mount_sse_once_match(server, any(), second_response).await; + let completion = mount_sse_once(server, second_response).await; FunctionCallResponseMocks { function_call, diff --git a/codex-rs/core/tests/suite/cli_stream.rs b/codex-rs/core/tests/suite/cli_stream.rs index 64d6247f3d..b484eca22a 100644 --- a/codex-rs/core/tests/suite/cli_stream.rs +++ b/codex-rs/core/tests/suite/cli_stream.rs @@ -110,12 +110,7 @@ async fn exec_cli_applies_experimental_instructions_file() { "data: {\"type\":\"response.created\",\"response\":{}}\n\n", "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"r1\"}}\n\n" ); - let resp_mock = core_test_support::responses::mount_sse_once_match( - &server, - path("/v1/responses"), - sse.to_string(), - ) - .await; + let resp_mock = core_test_support::responses::mount_sse_once(&server, sse.to_string()).await; // Create a temporary instructions file with a unique marker we can assert // appears in the outbound request payload. diff --git a/codex-rs/core/tests/suite/client.rs b/codex-rs/core/tests/suite/client.rs index 8c740e6333..79c158e084 100644 --- a/codex-rs/core/tests/suite/client.rs +++ b/codex-rs/core/tests/suite/client.rs @@ -238,9 +238,7 @@ async fn resume_includes_initial_messages_and_sends_prior_items() { // Mock server that will receive the resumed request let server = MockServer::start().await; - let resp_mock = - responses::mount_sse_once_match(&server, path("/v1/responses"), sse_completed("resp1")) - .await; + let resp_mock = responses::mount_sse_once(&server, sse_completed("resp1")).await; // Configure Codex to resume from our file let model_provider = ModelProviderInfo { @@ -381,9 +379,7 @@ async fn includes_base_instructions_override_in_request() { skip_if_no_network!(); // Mock server let server = MockServer::start().await; - let resp_mock = - responses::mount_sse_once_match(&server, path("/v1/responses"), sse_completed("resp1")) - .await; + let resp_mock = responses::mount_sse_once(&server, sse_completed("resp1")).await; let model_provider = ModelProviderInfo { base_url: Some(format!("{}/v1", server.uri())), @@ -571,9 +567,7 @@ async fn includes_user_instructions_message_in_request() { skip_if_no_network!(); let server = MockServer::start().await; - let resp_mock = - responses::mount_sse_once_match(&server, path("/v1/responses"), sse_completed("resp1")) - .await; + let resp_mock = responses::mount_sse_once(&server, sse_completed("resp1")).await; let model_provider = ModelProviderInfo { base_url: Some(format!("{}/v1", server.uri())), @@ -631,9 +625,7 @@ async fn includes_configured_effort_in_request() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = MockServer::start().await; - let resp_mock = - responses::mount_sse_once_match(&server, path("/v1/responses"), sse_completed("resp1")) - .await; + let resp_mock = responses::mount_sse_once(&server, sse_completed("resp1")).await; let TestCodex { codex, .. } = test_codex() .with_model("gpt-5.1-codex") .with_config(|config| { @@ -672,9 +664,7 @@ async fn includes_no_effort_in_request() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = MockServer::start().await; - let resp_mock = - responses::mount_sse_once_match(&server, path("/v1/responses"), sse_completed("resp1")) - .await; + let resp_mock = responses::mount_sse_once(&server, sse_completed("resp1")).await; let TestCodex { codex, .. } = test_codex() .with_model("gpt-5.1-codex") .build(&server) @@ -711,9 +701,7 @@ async fn includes_default_reasoning_effort_in_request_when_defined_by_model_fami skip_if_no_network!(Ok(())); let server = MockServer::start().await; - let resp_mock = - responses::mount_sse_once_match(&server, path("/v1/responses"), sse_completed("resp1")) - .await; + let resp_mock = responses::mount_sse_once(&server, sse_completed("resp1")).await; let TestCodex { codex, .. } = test_codex().with_model("gpt-5.1").build(&server).await?; codex @@ -746,9 +734,7 @@ async fn includes_default_verbosity_in_request() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = MockServer::start().await; - let resp_mock = - responses::mount_sse_once_match(&server, path("/v1/responses"), sse_completed("resp1")) - .await; + let resp_mock = responses::mount_sse_once(&server, sse_completed("resp1")).await; let TestCodex { codex, .. } = test_codex().with_model("gpt-5.1").build(&server).await?; codex @@ -781,9 +767,7 @@ async fn configured_verbosity_not_sent_for_models_without_support() -> anyhow::R skip_if_no_network!(Ok(())); let server = MockServer::start().await; - let resp_mock = - responses::mount_sse_once_match(&server, path("/v1/responses"), sse_completed("resp1")) - .await; + let resp_mock = responses::mount_sse_once(&server, sse_completed("resp1")).await; let TestCodex { codex, .. } = test_codex() .with_model("gpt-5-codex") .with_config(|config| { @@ -821,9 +805,7 @@ async fn configured_verbosity_is_sent() -> anyhow::Result<()> { skip_if_no_network!(Ok(())); let server = MockServer::start().await; - let resp_mock = - responses::mount_sse_once_match(&server, path("/v1/responses"), sse_completed("resp1")) - .await; + let resp_mock = responses::mount_sse_once(&server, sse_completed("resp1")).await; let TestCodex { codex, .. } = test_codex() .with_model("gpt-5") .with_config(|config| { @@ -862,9 +844,7 @@ async fn includes_developer_instructions_message_in_request() { skip_if_no_network!(); let server = MockServer::start().await; - let resp_mock = - responses::mount_sse_once_match(&server, path("/v1/responses"), sse_completed("resp1")) - .await; + let resp_mock = responses::mount_sse_once(&server, sse_completed("resp1")).await; let model_provider = ModelProviderInfo { base_url: Some(format!("{}/v1", server.uri())), diff --git a/codex-rs/core/tests/suite/items.rs b/codex-rs/core/tests/suite/items.rs index 7a96522090..4ec23e9de6 100644 --- a/codex-rs/core/tests/suite/items.rs +++ b/codex-rs/core/tests/suite/items.rs @@ -18,7 +18,7 @@ use core_test_support::responses::ev_reasoning_text_delta; use core_test_support::responses::ev_response_created; use core_test_support::responses::ev_web_search_call_added; use core_test_support::responses::ev_web_search_call_done; -use core_test_support::responses::mount_sse_once_match; +use core_test_support::responses::mount_sse_once; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; @@ -26,7 +26,6 @@ use core_test_support::test_codex::TestCodex; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event_match; use pretty_assertions::assert_eq; -use wiremock::matchers::any; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn user_message_item_is_emitted() -> anyhow::Result<()> { @@ -37,7 +36,7 @@ async fn user_message_item_is_emitted() -> anyhow::Result<()> { let TestCodex { codex, .. } = test_codex().build(&server).await?; let first_response = sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]); - mount_sse_once_match(&server, any(), first_response).await; + mount_sse_once(&server, first_response).await; codex .submit(Op::UserInput { @@ -93,7 +92,7 @@ async fn assistant_message_item_is_emitted() -> anyhow::Result<()> { ev_assistant_message("msg-1", "all done"), ev_completed("resp-1"), ]); - mount_sse_once_match(&server, any(), first_response).await; + mount_sse_once(&server, first_response).await; codex .submit(Op::UserInput { @@ -149,7 +148,7 @@ async fn reasoning_item_is_emitted() -> anyhow::Result<()> { reasoning_item, ev_completed("resp-1"), ]); - mount_sse_once_match(&server, any(), first_response).await; + mount_sse_once(&server, first_response).await; codex .submit(Op::UserInput { @@ -207,7 +206,7 @@ async fn web_search_item_is_emitted() -> anyhow::Result<()> { web_search_done, ev_completed("resp-1"), ]); - mount_sse_once_match(&server, any(), first_response).await; + mount_sse_once(&server, first_response).await; codex .submit(Op::UserInput { @@ -259,7 +258,7 @@ async fn agent_message_content_delta_has_item_metadata() -> anyhow::Result<()> { ev_assistant_message("msg-1", "streamed response"), ev_completed("resp-1"), ]); - mount_sse_once_match(&server, any(), stream).await; + mount_sse_once(&server, stream).await; codex .submit(Op::UserInput { @@ -324,7 +323,7 @@ async fn reasoning_content_delta_has_item_metadata() -> anyhow::Result<()> { ev_reasoning_item("reasoning-1", &["step one"], &[]), ev_completed("resp-1"), ]); - mount_sse_once_match(&server, any(), stream).await; + mount_sse_once(&server, stream).await; codex .submit(Op::UserInput { @@ -381,7 +380,7 @@ async fn reasoning_raw_content_delta_respects_flag() -> anyhow::Result<()> { ev_reasoning_item("reasoning-raw", &["complete"], &["raw detail"]), ev_completed("resp-1"), ]); - mount_sse_once_match(&server, any(), stream).await; + mount_sse_once(&server, stream).await; codex .submit(Op::UserInput { diff --git a/codex-rs/core/tests/suite/model_tools.rs b/codex-rs/core/tests/suite/model_tools.rs index b98d64328e..42bc655f57 100644 --- a/codex-rs/core/tests/suite/model_tools.rs +++ b/codex-rs/core/tests/suite/model_tools.rs @@ -42,7 +42,7 @@ async fn collect_tool_identifiers_for_model(model: &str) -> Vec { let server = MockServer::start().await; let sse = sse_completed(model); - let resp_mock = responses::mount_sse_once_match(&server, wiremock::matchers::any(), sse).await; + let resp_mock = responses::mount_sse_once(&server, sse).await; let model_provider = ModelProviderInfo { base_url: Some(format!("{}/v1", server.uri())), diff --git a/codex-rs/core/tests/suite/prompt_caching.rs b/codex-rs/core/tests/suite/prompt_caching.rs index 813226873c..0d0f52b47a 100644 --- a/codex-rs/core/tests/suite/prompt_caching.rs +++ b/codex-rs/core/tests/suite/prompt_caching.rs @@ -13,7 +13,7 @@ use codex_core::shell::Shell; use codex_core::shell::default_user_shell; use codex_protocol::user_input::UserInput; use core_test_support::load_sse_fixture_with_id; -use core_test_support::responses::mount_sse_once_match; +use core_test_support::responses::mount_sse_once; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; use core_test_support::test_codex::TestCodex; @@ -21,7 +21,6 @@ use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; use std::collections::HashMap; use tempfile::TempDir; -use wiremock::matchers::any; fn text_user_input(text: String) -> serde_json::Value { serde_json::json!({ @@ -70,8 +69,8 @@ async fn codex_mini_latest_tools() -> anyhow::Result<()> { use pretty_assertions::assert_eq; let server = start_mock_server().await; - let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; - let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; + let req1 = mount_sse_once(&server, sse_completed("resp-1")).await; + let req2 = mount_sse_once(&server, sse_completed("resp-2")).await; let TestCodex { codex, .. } = test_codex() .with_config(|config| { @@ -128,8 +127,8 @@ async fn prompt_tools_are_consistent_across_requests() -> anyhow::Result<()> { use pretty_assertions::assert_eq; let server = start_mock_server().await; - let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; - let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; + let req1 = mount_sse_once(&server, sse_completed("resp-1")).await; + let req2 = mount_sse_once(&server, sse_completed("resp-2")).await; let TestCodex { codex, config, .. } = test_codex() .with_config(|config| { @@ -247,8 +246,8 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests use pretty_assertions::assert_eq; let server = start_mock_server().await; - let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; - let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; + let req1 = mount_sse_once(&server, sse_completed("resp-1")).await; + let req2 = mount_sse_once(&server, sse_completed("resp-2")).await; let TestCodex { codex, config, .. } = test_codex() .with_config(|config| { @@ -328,8 +327,8 @@ async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() -> an use pretty_assertions::assert_eq; let server = start_mock_server().await; - let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; - let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; + let req1 = mount_sse_once(&server, sse_completed("resp-1")).await; + let req2 = mount_sse_once(&server, sse_completed("resp-2")).await; let TestCodex { codex, .. } = test_codex() .with_config(|config| { @@ -427,8 +426,8 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() -> anyhow::Res use pretty_assertions::assert_eq; let server = start_mock_server().await; - let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; - let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; + let req1 = mount_sse_once(&server, sse_completed("resp-1")).await; + let req2 = mount_sse_once(&server, sse_completed("resp-2")).await; let TestCodex { codex, .. } = test_codex() .with_config(|config| { @@ -523,8 +522,8 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() -> a use pretty_assertions::assert_eq; let server = start_mock_server().await; - let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; - let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; + let req1 = mount_sse_once(&server, sse_completed("resp-1")).await; + let req2 = mount_sse_once(&server, sse_completed("resp-2")).await; let TestCodex { codex, config, .. } = test_codex() .with_config(|config| { @@ -611,8 +610,8 @@ async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Resu let server = start_mock_server().await; - let req1 = mount_sse_once_match(&server, any(), sse_completed("resp-1")).await; - let req2 = mount_sse_once_match(&server, any(), sse_completed("resp-2")).await; + let req1 = mount_sse_once(&server, sse_completed("resp-1")).await; + let req2 = mount_sse_once(&server, sse_completed("resp-2")).await; let TestCodex { codex, config, .. } = test_codex() .with_config(|config| { config.user_instructions = Some("be consistent and helpful".to_string()); diff --git a/codex-rs/core/tests/suite/resume.rs b/codex-rs/core/tests/suite/resume.rs index 3a902b6b6f..bda27533cd 100644 --- a/codex-rs/core/tests/suite/resume.rs +++ b/codex-rs/core/tests/suite/resume.rs @@ -6,14 +6,13 @@ use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_reasoning_item; use core_test_support::responses::ev_response_created; -use core_test_support::responses::mount_sse_once_match; +use core_test_support::responses::mount_sse_once; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; use std::sync::Arc; -use wiremock::matchers::any; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn resume_includes_initial_messages_from_rollout_events() -> Result<()> { @@ -31,7 +30,7 @@ async fn resume_includes_initial_messages_from_rollout_events() -> Result<()> { ev_assistant_message("msg-1", "Completed first turn"), ev_completed("resp-initial"), ]); - mount_sse_once_match(&server, any(), initial_sse).await; + mount_sse_once(&server, initial_sse).await; codex .submit(Op::UserInput { @@ -83,7 +82,7 @@ async fn resume_includes_initial_messages_from_reasoning_events() -> Result<()> ev_assistant_message("msg-1", "Completed reasoning turn"), ev_completed("resp-initial"), ]); - mount_sse_once_match(&server, any(), initial_sse).await; + mount_sse_once(&server, initial_sse).await; codex .submit(Op::UserInput { diff --git a/codex-rs/core/tests/suite/rmcp_client.rs b/codex-rs/core/tests/suite/rmcp_client.rs index 343b506d4c..cc653a9c56 100644 --- a/codex-rs/core/tests/suite/rmcp_client.rs +++ b/codex-rs/core/tests/suite/rmcp_client.rs @@ -21,7 +21,7 @@ use codex_core::protocol::SandboxPolicy; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::user_input::UserInput; use core_test_support::responses; -use core_test_support::responses::mount_sse_once_match; +use core_test_support::responses::mount_sse_once; use core_test_support::skip_if_no_network; use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; @@ -36,7 +36,6 @@ use tokio::process::Child; use tokio::process::Command; use tokio::time::Instant; use tokio::time::sleep; -use wiremock::matchers::any; static OPENAI_PNG: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAD0AAAA9CAYAAAAeYmHpAAAE6klEQVR4Aeyau44UVxCGx1fZsmRLlm3Zoe0XcGQ5cUiCCIgJeS9CHgAhMkISQnIuGQgJEkBcxLW+nqnZ6uqqc+nuWRC7q/P3qetf9e+MtOwyX25O4Nep6JPyop++0qev9HrfgZ+F6r2DuB/vHOrt/UIkqdDHYvujOW6fO7h/CNEI+a5jc+pBR8uy0jVFsziYu5HtfSUk+Io34q921hLNctFSX0gwww+S8wce8K1LfCU+cYW4888aov8NxqvQILUPPReLOrm6zyLxa4i+6VZuFbJo8d1MOHZm+7VUtB/aIvhPWc/3SWg49JcwFLlHxuXKjtyloo+YNhuW3VS+WPBuUEMvCFKjEDVgFBQHXrnazpqiSxNZCkQ1kYiozsbm9Oz7l4i2Il7vGccGNWAc3XosDrZe/9P3ZnMmzHNEQw4smf8RQ87XEAMsC7Az0Au+dgXerfH4+sHvEc0SYGic8WBBUGqFH2gN7yDrazy7m2pbRTeRmU3+MjZmr1h6LJgPbGy23SI6GlYT0brQ71IY8Us4PNQCm+zepSbaD2BY9xCaAsD9IIj/IzFmKMSdHHonwdZATbTnYREf6/VZGER98N9yCWIvXQwXDoDdhZJoT8jwLnJXDB9w4Sb3e6nK5ndzlkTLnP3JBu4LKkbrYrU69gCVceV0JvpyuW1xlsUVngzhwMetn/XamtTORF9IO5YnWNiyeF9zCAfqR3fUW+vZZKLtgP+ts8BmQRBREAdRDhH3o8QuRh/YucNFz2BEjxbRN6LGzphfKmvP6v6QhqIQyZ8XNJ0W0X83MR1PEcJBNO2KC2Z1TW/v244scp9FwRViZxIOBF0Lctk7ZVSavdLvRlV1hz/ysUi9sr8CIcB3nvWBwA93ykTz18eAYxQ6N/K2DkPA1lv3iXCwmDUT7YkjIby9siXueIJj9H+pzSqJ9oIuJWTUgSSt4WO7o/9GGg0viR4VinNRUDoIj34xoCd6pxD3aK3zfdbnx5v1J3ZNNEJsE0sBG7N27ReDrJc4sFxz7dI/ZAbOmmiKvHBitQXpAdR6+F7v+/ol/tOouUV01EeMZQF2BoQDn6dP4XNr+j9GZEtEK1/L8pFw7bd3a53tsTa7WD+054jOFmPg1XBKPQgnqFfmFcy32ZRvjmiIIQTYFvyDxQ8nH8WIwwGwlyDjDznnilYyFr6njrlZwsKkBpO59A7OwgdzPEWRm+G+oeb7IfyNuzjEEVLrOVxJsxvxwF8kmCM6I2QYmJunz4u4TrADpfl7mlbRTWQ7VmrBzh3+C9f6Grc3YoGN9dg/SXFthpRsT6vobfXRs2VBlgBHXVMLHjDNbIZv1sZ9+X3hB09cXdH1JKViyG0+W9bWZDa/r2f9zAFR71sTzGpMSWz2iI4YssWjWo3REy1MDGjdwe5e0dFSiAC1JakBvu4/CUS8Eh6dqHdU0Or0ioY3W5ClSqDXAy7/6SRfgw8vt4I+tbvvNtFT2kVDhY5+IGb1rCqYaXNF08vSALsXCPmt0kQNqJT1p5eI1mkIV/BxCY1z85lOzeFbPBQHURkkPTlwTYK9gTVE25l84IbFFN+YJDHjdpn0gq6mrHht0dkcjbM4UL9283O5p77GN+SPW/QwVB4IUYg7Or+Kp7naR6qktP98LNF2UxWo9yObPIT9KYg+hK4i56no4rfnM0qeyFf6AwAAAP//trwR3wAAAAZJREFUAwBZ0sR75itw5gAAAABJRU5ErkJggg=="; @@ -51,9 +50,8 @@ async fn stdio_server_round_trip() -> anyhow::Result<()> { let server_name = "rmcp"; let tool_name = format!("mcp__{server_name}__echo"); - mount_sse_once_match( + mount_sse_once( &server, - any(), responses::sse(vec![ responses::ev_response_created("resp-1"), responses::ev_function_call(call_id, &tool_name, "{\"message\":\"ping\"}"), @@ -61,9 +59,8 @@ async fn stdio_server_round_trip() -> anyhow::Result<()> { ]), ) .await; - mount_sse_once_match( + mount_sse_once( &server, - any(), responses::sse(vec![ responses::ev_assistant_message("msg-1", "rmcp echo tool completed successfully."), responses::ev_completed("resp-2"), @@ -190,9 +187,8 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> { let tool_name = format!("mcp__{server_name}__image"); // First stream: model decides to call the image tool. - mount_sse_once_match( + mount_sse_once( &server, - any(), responses::sse(vec![ responses::ev_response_created("resp-1"), responses::ev_function_call(call_id, &tool_name, "{}"), @@ -201,9 +197,8 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> { ) .await; // Second stream: after tool execution, assistant emits a message and completes. - let final_mock = mount_sse_once_match( + let final_mock = mount_sse_once( &server, - any(), responses::sse(vec![ responses::ev_assistant_message("msg-1", "rmcp image tool completed successfully."), responses::ev_completed("resp-2"), @@ -531,9 +526,8 @@ async fn stdio_server_propagates_whitelisted_env_vars() -> anyhow::Result<()> { let server_name = "rmcp_whitelist"; let tool_name = format!("mcp__{server_name}__echo"); - mount_sse_once_match( + mount_sse_once( &server, - any(), responses::sse(vec![ responses::ev_response_created("resp-1"), responses::ev_function_call(call_id, &tool_name, "{\"message\":\"ping\"}"), @@ -541,9 +535,8 @@ async fn stdio_server_propagates_whitelisted_env_vars() -> anyhow::Result<()> { ]), ) .await; - mount_sse_once_match( + mount_sse_once( &server, - any(), responses::sse(vec![ responses::ev_assistant_message("msg-1", "rmcp echo tool completed successfully."), responses::ev_completed("resp-2"), @@ -666,9 +659,8 @@ async fn streamable_http_tool_call_round_trip() -> anyhow::Result<()> { let server_name = "rmcp_http"; let tool_name = format!("mcp__{server_name}__echo"); - mount_sse_once_match( + mount_sse_once( &server, - any(), responses::sse(vec![ responses::ev_response_created("resp-1"), responses::ev_function_call(call_id, &tool_name, "{\"message\":\"ping\"}"), @@ -676,9 +668,8 @@ async fn streamable_http_tool_call_round_trip() -> anyhow::Result<()> { ]), ) .await; - mount_sse_once_match( + mount_sse_once( &server, - any(), responses::sse(vec![ responses::ev_assistant_message( "msg-1", @@ -834,9 +825,8 @@ async fn streamable_http_with_oauth_round_trip() -> anyhow::Result<()> { let server_name = "rmcp_http_oauth"; let tool_name = format!("mcp__{server_name}__echo"); - mount_sse_once_match( + mount_sse_once( &server, - any(), responses::sse(vec![ responses::ev_response_created("resp-1"), responses::ev_function_call(call_id, &tool_name, "{\"message\":\"ping\"}"), @@ -844,9 +834,8 @@ async fn streamable_http_with_oauth_round_trip() -> anyhow::Result<()> { ]), ) .await; - mount_sse_once_match( + mount_sse_once( &server, - any(), responses::sse(vec![ responses::ev_assistant_message( "msg-1", diff --git a/codex-rs/core/tests/suite/tool_harness.rs b/codex-rs/core/tests/suite/tool_harness.rs index 3288822ff3..02c7494cc0 100644 --- a/codex-rs/core/tests/suite/tool_harness.rs +++ b/codex-rs/core/tests/suite/tool_harness.rs @@ -29,7 +29,6 @@ use core_test_support::test_codex::test_codex; use core_test_support::wait_for_event; use serde_json::Value; use serde_json::json; -use wiremock::matchers::any; fn call_output(req: &ResponsesRequest, call_id: &str) -> (String, Option) { let raw = req.function_call_output(call_id); @@ -73,13 +72,13 @@ async fn shell_tool_executes_command_and_streams_output() -> anyhow::Result<()> ev_local_shell_call(call_id, "completed", command), ev_completed("resp-1"), ]); - responses::mount_sse_once_match(&server, any(), first_response).await; + responses::mount_sse_once(&server, first_response).await; let second_response = sse(vec![ ev_assistant_message("msg-1", "all done"), ev_completed("resp-2"), ]); - let second_mock = responses::mount_sse_once_match(&server, any(), second_response).await; + let second_mock = responses::mount_sse_once(&server, second_response).await; let session_model = session_configured.model.clone(); @@ -139,13 +138,13 @@ async fn update_plan_tool_emits_plan_update_event() -> anyhow::Result<()> { ev_function_call(call_id, "update_plan", &plan_args), ev_completed("resp-1"), ]); - responses::mount_sse_once_match(&server, any(), first_response).await; + responses::mount_sse_once(&server, first_response).await; let second_response = sse(vec![ ev_assistant_message("msg-1", "plan acknowledged"), ev_completed("resp-2"), ]); - let second_mock = responses::mount_sse_once_match(&server, any(), second_response).await; + let second_mock = responses::mount_sse_once(&server, second_response).await; let session_model = session_configured.model.clone(); @@ -215,13 +214,13 @@ async fn update_plan_tool_rejects_malformed_payload() -> anyhow::Result<()> { ev_function_call(call_id, "update_plan", &invalid_args), ev_completed("resp-1"), ]); - responses::mount_sse_once_match(&server, any(), first_response).await; + responses::mount_sse_once(&server, first_response).await; let second_response = sse(vec![ ev_assistant_message("msg-1", "malformed plan payload"), ev_completed("resp-2"), ]); - let second_mock = responses::mount_sse_once_match(&server, any(), second_response).await; + let second_mock = responses::mount_sse_once(&server, second_response).await; let session_model = session_configured.model.clone(); @@ -303,13 +302,13 @@ async fn apply_patch_tool_executes_and_emits_patch_events() -> anyhow::Result<() ev_apply_patch_function_call(call_id, &patch_content), ev_completed("resp-1"), ]); - responses::mount_sse_once_match(&server, any(), first_response).await; + responses::mount_sse_once(&server, first_response).await; let second_response = sse(vec![ ev_assistant_message("msg-1", "patch complete"), ev_completed("resp-2"), ]); - let second_mock = responses::mount_sse_once_match(&server, any(), second_response).await; + let second_mock = responses::mount_sse_once(&server, second_response).await; let session_model = session_configured.model.clone(); @@ -399,13 +398,13 @@ async fn apply_patch_reports_parse_diagnostics() -> anyhow::Result<()> { ev_apply_patch_function_call(call_id, patch_content), ev_completed("resp-1"), ]); - responses::mount_sse_once_match(&server, any(), first_response).await; + responses::mount_sse_once(&server, first_response).await; let second_response = sse(vec![ ev_assistant_message("msg-1", "failed"), ev_completed("resp-2"), ]); - let second_mock = responses::mount_sse_once_match(&server, any(), second_response).await; + let second_mock = responses::mount_sse_once(&server, second_response).await; let session_model = session_configured.model.clone(); diff --git a/codex-rs/core/tests/suite/tools.rs b/codex-rs/core/tests/suite/tools.rs index ca844db4c8..a6086dcbfb 100644 --- a/codex-rs/core/tests/suite/tools.rs +++ b/codex-rs/core/tests/suite/tools.rs @@ -472,8 +472,7 @@ time.sleep(60) let start = Instant::now(); let output_str = tokio::time::timeout(Duration::from_secs(10), async { - submit_turn( - &test, + test.submit_turn_with_policies( "run a command with a detached grandchild", AskForApproval::Never, SandboxPolicy::DangerFullAccess, diff --git a/codex-rs/core/tests/suite/truncation.rs b/codex-rs/core/tests/suite/truncation.rs index 101bdc6199..37ee4f3990 100644 --- a/codex-rs/core/tests/suite/truncation.rs +++ b/codex-rs/core/tests/suite/truncation.rs @@ -20,7 +20,6 @@ use core_test_support::responses::ev_completed; use core_test_support::responses::ev_function_call; use core_test_support::responses::ev_response_created; use core_test_support::responses::mount_sse_once; -use core_test_support::responses::mount_sse_once_match; use core_test_support::responses::mount_sse_sequence; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; @@ -33,7 +32,6 @@ use serde_json::Value; use serde_json::json; use std::collections::HashMap; use std::time::Duration; -use wiremock::matchers::any; // Verifies byte-truncation formatting for function error output (RespondToModel errors) #[tokio::test(flavor = "multi_thread", worker_threads = 2)] @@ -140,9 +138,8 @@ async fn tool_call_output_exceeds_limit_truncated_for_model() -> Result<()> { ]), ) .await; - let mock2 = mount_sse_once_match( + let mock2 = mount_sse_once( &server, - any(), sse(vec![ responses::ev_assistant_message("msg-1", "done"), responses::ev_completed("resp-2"), @@ -222,9 +219,8 @@ async fn tool_call_output_truncated_only_once() -> Result<()> { }) }; - mount_sse_once_match( + mount_sse_once( &server, - any(), sse(vec![ responses::ev_response_created("resp-1"), responses::ev_function_call(call_id, "shell", &serde_json::to_string(&args)?), @@ -232,9 +228,8 @@ async fn tool_call_output_truncated_only_once() -> Result<()> { ]), ) .await; - let mock2 = mount_sse_once_match( + let mock2 = mount_sse_once( &server, - any(), sse(vec![ responses::ev_assistant_message("msg-1", "done"), responses::ev_completed("resp-2"), @@ -277,9 +272,8 @@ async fn mcp_tool_call_output_exceeds_limit_truncated_for_model() -> Result<()> let large_msg = "long-message-with-newlines-".repeat(600); let args_json = serde_json::json!({ "message": large_msg }); - mount_sse_once_match( + mount_sse_once( &server, - any(), sse(vec![ responses::ev_response_created("resp-1"), responses::ev_function_call(call_id, &tool_name, &args_json.to_string()), @@ -287,9 +281,8 @@ async fn mcp_tool_call_output_exceeds_limit_truncated_for_model() -> Result<()> ]), ) .await; - let mock2 = mount_sse_once_match( + let mock2 = mount_sse_once( &server, - any(), sse(vec![ responses::ev_assistant_message("msg-1", "rmcp echo tool completed."), responses::ev_completed("resp-2"), @@ -373,9 +366,8 @@ async fn mcp_image_output_preserves_image_and_no_text_summary() -> Result<()> { let server_name = "rmcp"; let tool_name = format!("mcp__{server_name}__image"); - mount_sse_once_match( + mount_sse_once( &server, - any(), sse(vec![ ev_response_created("resp-1"), ev_function_call(call_id, &tool_name, "{}"), @@ -383,9 +375,8 @@ async fn mcp_image_output_preserves_image_and_no_text_summary() -> Result<()> { ]), ) .await; - let final_mock = mount_sse_once_match( + let final_mock = mount_sse_once( &server, - any(), sse(vec![ ev_assistant_message("msg-1", "done"), ev_completed("resp-2"), diff --git a/codex-rs/core/tests/suite/user_notification.rs b/codex-rs/core/tests/suite/user_notification.rs index 74b59736f4..0d1e941d28 100644 --- a/codex-rs/core/tests/suite/user_notification.rs +++ b/codex-rs/core/tests/suite/user_notification.rs @@ -15,7 +15,6 @@ use pretty_assertions::assert_eq; use serde_json::Value; use serde_json::json; use tempfile::TempDir; -use wiremock::matchers::any; use responses::ev_assistant_message; use responses::ev_completed; @@ -35,7 +34,7 @@ async fn summarize_context_three_requests_and_instructions() -> anyhow::Result<( let sse1 = sse(vec![ev_assistant_message("m1", "Done"), ev_completed("r1")]); - responses::mount_sse_once_match(&server, any(), sse1).await; + responses::mount_sse_once(&server, sse1).await; let notify_dir = TempDir::new()?; // write a script to the notify that touches a file next to it diff --git a/codex-rs/core/tests/suite/user_shell_cmd.rs b/codex-rs/core/tests/suite/user_shell_cmd.rs index 8910161f1e..396b6c7d95 100644 --- a/codex-rs/core/tests/suite/user_shell_cmd.rs +++ b/codex-rs/core/tests/suite/user_shell_cmd.rs @@ -15,7 +15,7 @@ use core_test_support::responses::ev_assistant_message; use core_test_support::responses::ev_completed; use core_test_support::responses::ev_function_call; use core_test_support::responses::ev_response_created; -use core_test_support::responses::mount_sse_once_match; +use core_test_support::responses::mount_sse_once; use core_test_support::responses::sse; use core_test_support::responses::start_mock_server; use core_test_support::skip_if_no_network; @@ -25,7 +25,6 @@ use core_test_support::wait_for_event_match; use regex_lite::escape; use std::path::PathBuf; use tempfile::TempDir; -use wiremock::matchers::any; #[tokio::test] async fn user_shell_cmd_ls_and_cat_in_temp_dir() { @@ -293,9 +292,8 @@ async fn user_shell_command_is_truncated_only_once() -> anyhow::Result<()> { }) }; - mount_sse_once_match( + mount_sse_once( &server, - any(), sse(vec![ ev_response_created("resp-1"), ev_function_call(call_id, "shell", &serde_json::to_string(&args)?), @@ -303,9 +301,8 @@ async fn user_shell_command_is_truncated_only_once() -> anyhow::Result<()> { ]), ) .await; - let mock2 = mount_sse_once_match( + let mock2 = mount_sse_once( &server, - any(), sse(vec![ ev_assistant_message("msg-1", "done"), ev_completed("resp-2"), diff --git a/codex-rs/core/tests/suite/view_image.rs b/codex-rs/core/tests/suite/view_image.rs index 00931ebceb..394c5c2f14 100644 --- a/codex-rs/core/tests/suite/view_image.rs +++ b/codex-rs/core/tests/suite/view_image.rs @@ -24,7 +24,6 @@ use image::ImageBuffer; use image::Rgba; use image::load_from_memory; use serde_json::Value; -use wiremock::matchers::any; fn find_image_message(body: &Value) -> Option<&Value> { body.get("input") @@ -71,7 +70,7 @@ async fn user_turn_with_local_image_attaches_image() -> anyhow::Result<()> { ev_assistant_message("msg-1", "done"), ev_completed("resp-1"), ]); - let mock = responses::mount_sse_once_match(&server, any(), response).await; + let mock = responses::mount_sse_once(&server, response).await; let session_model = session_configured.model.clone(); @@ -156,13 +155,13 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> { ev_function_call(call_id, "view_image", &arguments), ev_completed("resp-1"), ]); - responses::mount_sse_once_match(&server, any(), first_response).await; + responses::mount_sse_once(&server, first_response).await; let second_response = sse(vec![ ev_assistant_message("msg-1", "done"), ev_completed("resp-2"), ]); - let mock = responses::mount_sse_once_match(&server, any(), second_response).await; + let mock = responses::mount_sse_once(&server, second_response).await; let session_model = session_configured.model.clone(); @@ -266,13 +265,13 @@ async fn view_image_tool_errors_when_path_is_directory() -> anyhow::Result<()> { ev_function_call(call_id, "view_image", &arguments), ev_completed("resp-1"), ]); - responses::mount_sse_once_match(&server, any(), first_response).await; + responses::mount_sse_once(&server, first_response).await; let second_response = sse(vec![ ev_assistant_message("msg-1", "done"), ev_completed("resp-2"), ]); - let mock = responses::mount_sse_once_match(&server, any(), second_response).await; + let mock = responses::mount_sse_once(&server, second_response).await; let session_model = session_configured.model.clone(); @@ -338,13 +337,13 @@ async fn view_image_tool_placeholder_for_non_image_files() -> anyhow::Result<()> ev_function_call(call_id, "view_image", &arguments), ev_completed("resp-1"), ]); - responses::mount_sse_once_match(&server, any(), first_response).await; + responses::mount_sse_once(&server, first_response).await; let second_response = sse(vec![ ev_assistant_message("msg-1", "done"), ev_completed("resp-2"), ]); - let mock = responses::mount_sse_once_match(&server, any(), second_response).await; + let mock = responses::mount_sse_once(&server, second_response).await; let session_model = session_configured.model.clone(); @@ -429,13 +428,13 @@ async fn view_image_tool_errors_when_file_missing() -> anyhow::Result<()> { ev_function_call(call_id, "view_image", &arguments), ev_completed("resp-1"), ]); - responses::mount_sse_once_match(&server, any(), first_response).await; + responses::mount_sse_once(&server, first_response).await; let second_response = sse(vec![ ev_assistant_message("msg-1", "done"), ev_completed("resp-2"), ]); - let mock = responses::mount_sse_once_match(&server, any(), second_response).await; + let mock = responses::mount_sse_once(&server, second_response).await; let session_model = session_configured.model.clone(); diff --git a/codex-rs/exec/tests/suite/output_schema.rs b/codex-rs/exec/tests/suite/output_schema.rs index 913270eff4..485f5e3c79 100644 --- a/codex-rs/exec/tests/suite/output_schema.rs +++ b/codex-rs/exec/tests/suite/output_schema.rs @@ -4,7 +4,6 @@ use core_test_support::responses; use core_test_support::test_codex_exec::test_codex_exec; use serde_json::Value; -use wiremock::matchers::any; #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn exec_includes_output_schema_in_request() -> anyhow::Result<()> { @@ -28,7 +27,7 @@ async fn exec_includes_output_schema_in_request() -> anyhow::Result<()> { responses::ev_assistant_message("m1", "fixture hello"), responses::ev_completed("resp1"), ]); - let response_mock = responses::mount_sse_once_match(&server, any(), body).await; + let response_mock = responses::mount_sse_once(&server, body).await; test.cmd_with_server(&server) .arg("--skip-git-repo-check") diff --git a/codex-rs/exec/tests/suite/server_error_exit.rs b/codex-rs/exec/tests/suite/server_error_exit.rs index 051306cedd..909f48be3c 100644 --- a/codex-rs/exec/tests/suite/server_error_exit.rs +++ b/codex-rs/exec/tests/suite/server_error_exit.rs @@ -3,7 +3,6 @@ use core_test_support::responses; use core_test_support::test_codex_exec::test_codex_exec; -use wiremock::matchers::any; /// Verify that when the server reports an error, `codex-exec` exits with a /// non-zero status code so automation can detect failures. @@ -21,7 +20,7 @@ async fn exits_non_zero_when_server_reports_error() -> anyhow::Result<()> { "error": {"code": "rate_limit_exceeded", "message": "synthetic server error"} } })]); - responses::mount_sse_once_match(&server, any(), body).await; + responses::mount_sse_once(&server, body).await; test.cmd_with_server(&server) .arg("--skip-git-repo-check")