Merge main into post-tool output rewrite

This commit is contained in:
Abhinav Vedmala
2026-05-13 00:15:54 -07:00
1502 changed files with 132384 additions and 61683 deletions
@@ -1,8 +0,0 @@
event: response.created
data: {"type":"response.created","response":{"id":"resp1"}}
event: response.output_item.done
data: {"type":"response.output_item.done","item":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"fixture hello"}]}}
event: response.completed
data: {"type":"response.completed","response":{"id":"resp1","output":[]}}
+2 -2
View File
@@ -4,7 +4,7 @@ codex_rust_crate(
name = "common",
crate_name = "core_test_support",
crate_srcs = glob(["*.rs"]),
lib_data_extra = [
"//codex-rs/core:model_availability_nux_fixtures",
deps_extra = [
"@crates//:similar",
],
)
+4
View File
@@ -6,6 +6,7 @@ license.workspace = true
[lib]
path = "lib.rs"
doctest = false
[lints]
workspace = true
@@ -17,8 +18,10 @@ base64 = { workspace = true }
codex-arg0 = { workspace = true }
codex-config = { workspace = true }
codex-core = { workspace = true }
codex-extension-api = { workspace = true }
codex-exec-server = { workspace = true }
codex-features = { workspace = true }
codex-hooks = { workspace = true }
codex-login = { workspace = true }
codex-model-provider-info = { workspace = true }
codex-models-manager = { workspace = true }
@@ -32,6 +35,7 @@ opentelemetry = { workspace = true }
opentelemetry_sdk = { workspace = true }
regex-lite = { workspace = true }
serde_json = { workspace = true }
similar = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["net", "time"] }
tokio-tungstenite = { workspace = true }
@@ -1,5 +1,7 @@
use regex_lite::Regex;
use serde_json::Value;
use similar::ChangeTag;
use similar::TextDiff;
use std::sync::OnceLock;
use crate::responses::ResponsesRequest;
@@ -242,6 +244,102 @@ pub fn format_labeled_items_snapshot(
format!("Scenario: {scenario}\n\n{sections}")
}
/// Render changed JSON lines between two captured `/responses` request bodies.
///
/// Request-parity tests use this to compare the entire JSON payload while showing only fields that
/// changed, with the same redactions as the other context snapshots.
pub fn format_request_body_diff_snapshot(
scenario: &str,
before_title: &str,
before_request: &ResponsesRequest,
after_title: &str,
after_request: &ResponsesRequest,
options: &ContextSnapshotOptions,
) -> String {
let before = format_request_body_snapshot(before_request, options);
let after = format_request_body_snapshot(after_request, options);
let diff = format_changed_lines_diff(before_title, &before, after_title, &after);
format!("Scenario: {scenario}\n\n{diff}")
}
fn format_request_body_snapshot(
request: &ResponsesRequest,
options: &ContextSnapshotOptions,
) -> String {
let mut body = request.body_json();
canonicalize_json_snapshot_value(&mut body, options);
serde_json::to_string_pretty(&body).expect("request body should serialize")
}
fn canonicalize_json_snapshot_value(value: &mut Value, options: &ContextSnapshotOptions) {
match value {
Value::Array(values) => {
for value in values {
canonicalize_json_snapshot_value(value, options);
}
}
Value::Object(map) => {
// Keep request-body snapshots stable when serde_json preserves insertion order.
let mut entries = std::mem::take(map).into_iter().collect::<Vec<_>>();
entries.sort_by(|(left_key, _), (right_key, _)| left_key.cmp(right_key));
for (key, mut value) in entries {
canonicalize_json_snapshot_value(&mut value, options);
map.insert(key, value);
}
}
Value::String(text) => {
*text = format_snapshot_json_string(text, options);
}
Value::Null | Value::Bool(_) | Value::Number(_) => {}
}
}
fn format_snapshot_json_string(text: &str, options: &ContextSnapshotOptions) -> String {
let normalized = match options.render_mode {
ContextSnapshotRenderMode::RedactedText
| ContextSnapshotRenderMode::KindWithTextPrefix { .. } => normalize_snapshot_uuids(
&normalize_snapshot_line_endings(&canonicalize_snapshot_text(text)),
),
ContextSnapshotRenderMode::FullText => normalize_snapshot_line_endings(text),
ContextSnapshotRenderMode::KindOnly => unreachable!(),
};
match options.render_mode {
ContextSnapshotRenderMode::KindWithTextPrefix { max_chars }
if normalized.chars().count() > max_chars =>
{
let prefix = normalized.chars().take(max_chars).collect::<String>();
format!("{prefix}...")
}
ContextSnapshotRenderMode::RedactedText
| ContextSnapshotRenderMode::FullText
| ContextSnapshotRenderMode::KindWithTextPrefix { .. } => normalized,
ContextSnapshotRenderMode::KindOnly => unreachable!(),
}
}
fn format_changed_lines_diff(
before_title: &str,
before: &str,
after_title: &str,
after: &str,
) -> String {
let mut diff = format!("--- {before_title}\n+++ {after_title}\n");
for change in TextDiff::from_lines(before, after).iter_all_changes() {
match change.tag() {
ChangeTag::Equal => {}
ChangeTag::Delete => {
diff.push('-');
diff.push_str(change.value());
}
ChangeTag::Insert => {
diff.push('+');
diff.push_str(change.value());
}
}
}
diff
}
fn format_snapshot_text(text: &str, options: &ContextSnapshotOptions) -> String {
match options.render_mode {
ContextSnapshotRenderMode::RedactedText => {
@@ -342,6 +440,17 @@ fn normalize_dynamic_snapshot_paths(text: &str) -> String {
.into_owned()
}
fn normalize_snapshot_uuids(text: &str) -> String {
static UUID_RE: OnceLock<Regex> = OnceLock::new();
let uuid_re = UUID_RE.get_or_init(|| {
Regex::new(
r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b",
)
.expect("uuid regex should compile")
});
uuid_re.replace_all(text, "<UUID>").into_owned()
}
#[cfg(test)]
mod tests {
use super::ContextSnapshotOptions;
+70
View File
@@ -0,0 +1,70 @@
use codex_config::CONFIG_TOML_FILE;
use codex_config::ConfigLayerStack;
use codex_config::TomlValue;
use codex_core::config::Config;
use codex_features::Feature;
use codex_hooks::HookListEntry;
use codex_utils_absolute_path::AbsolutePathBuf;
pub fn trust_discovered_hooks(config: &mut Config) {
if let Err(err) = config.features.enable(Feature::CodexHooks) {
panic!("test config should allow feature update: {err}");
}
let listed = codex_hooks::list_hooks(codex_hooks::HooksConfig {
feature_enabled: true,
config_layer_stack: Some(config.config_layer_stack.clone()),
..codex_hooks::HooksConfig::default()
});
assert!(
!listed.hooks.is_empty(),
"trusted hook fixture should discover at least one hook"
);
trust_hooks(config, listed.hooks);
}
pub fn trust_hooks(config: &mut Config, hooks: Vec<HookListEntry>) {
config.config_layer_stack =
trusted_config_layer_stack(&config.config_layer_stack, &config.codex_home, hooks);
}
pub fn trusted_config_layer_stack(
config_layer_stack: &ConfigLayerStack,
codex_home: &AbsolutePathBuf,
hooks: Vec<HookListEntry>,
) -> ConfigLayerStack {
let mut user_config = config_layer_stack
.get_user_layer()
.map(|layer| layer.config.clone())
.unwrap_or_else(|| TomlValue::Table(Default::default()));
let Some(user_table) = user_config.as_table_mut() else {
panic!("user config should be a table");
};
let Some(hooks_table) = user_table
.entry("hooks")
.or_insert_with(|| TomlValue::Table(Default::default()))
.as_table_mut()
else {
panic!("hooks config should be a table");
};
let Some(state_table) = hooks_table
.entry("state")
.or_insert_with(|| TomlValue::Table(Default::default()))
.as_table_mut()
else {
panic!("hook state config should be a table");
};
for hook in hooks {
let mut hook_state = TomlValue::Table(Default::default());
let Some(hook_state_table) = hook_state.as_table_mut() else {
panic!("hook state should be a table");
};
hook_state_table.insert(
"trusted_hash".to_string(),
TomlValue::String(hook.current_hash),
);
state_table.insert(hook.key, hook_state);
}
config_layer_stack.with_user_config(&codex_home.join(CONFIG_TOML_FILE), user_config)
}
+3
View File
@@ -10,6 +10,7 @@ use tempfile::TempDir;
use codex_config::CloudRequirementsLoader;
use codex_config::ConfigRequirementsToml;
use codex_config::LoaderOverrides;
use codex_config::NetworkRequirementsToml;
use codex_core::CodexThread;
use codex_core::config::Config;
@@ -23,6 +24,7 @@ use std::path::PathBuf;
pub mod apps_test_server;
pub mod context_snapshot;
pub mod hooks;
pub mod process;
pub mod responses;
pub mod streaming_sse;
@@ -181,6 +183,7 @@ pub async fn load_default_config_for_test_with_cloud_requirements(
cloud_requirements: CloudRequirementsLoader,
) -> Config {
ConfigBuilder::default()
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
.codex_home(codex_home.path().to_path_buf())
.harness_overrides(default_test_overrides())
.cloud_requirements(cloud_requirements)
+1 -20
View File
@@ -890,7 +890,6 @@ pub fn ev_apply_patch_call(
) -> 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)
@@ -903,7 +902,7 @@ pub fn ev_apply_patch_call(
/// 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).
/// invokes `apply_patch` directly.
pub fn ev_apply_patch_custom_tool_call(call_id: &str, patch: &str) -> Value {
serde_json::json!({
"type": "response.output_item.done",
@@ -916,24 +915,6 @@ pub fn ev_apply_patch_custom_tool_call(call_id: &str, patch: &str) -> Value {
})
}
/// Convenience: SSE event for an `apply_patch` function call. The Responses API
/// wraps the patch content in a JSON string under the `input` key; we recreate
/// the same structure so downstream code exercises the full parsing path.
pub fn ev_apply_patch_function_call(call_id: &str, patch: &str) -> Value {
let arguments = serde_json::json!({ "input": patch });
let arguments = serde_json::to_string(&arguments).expect("serialize apply_patch arguments");
serde_json::json!({
"type": "response.output_item.done",
"item": {
"type": "function_call",
"name": "apply_patch",
"arguments": arguments,
"call_id": call_id
}
})
}
pub fn ev_shell_command_call(call_id: &str, command: &str) -> Value {
let args = serde_json::json!({ "command": command });
ev_shell_command_call_with_args(call_id, &args)
+34 -30
View File
@@ -16,12 +16,14 @@ use codex_config::CloudRequirementsLoader;
use codex_core::CodexThread;
use codex_core::ThreadManager;
use codex_core::config::Config;
use codex_core::resolve_installation_id;
use codex_core::shell::Shell;
use codex_core::shell::get_shell_by_model_provided_path;
use codex_core::thread_store_from_config;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::RemoveOptions;
use codex_extension_api::empty_extension_registry;
use codex_features::Feature;
use codex_login::CodexAuth;
use codex_model_provider_info::ModelProviderInfo;
@@ -71,6 +73,7 @@ const SUBMIT_TURN_COMPLETE_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug)]
pub struct TestEnv {
environment: codex_exec_server::Environment,
exec_server_url: Option<String>,
cwd: AbsolutePathBuf,
local_cwd_temp_dir: Option<Arc<TempDir>>,
remote_container_name: Option<String>,
@@ -84,6 +87,7 @@ impl TestEnv {
codex_exec_server::Environment::create_for_tests(/*exec_server_url*/ None)?;
Ok(Self {
environment,
exec_server_url: None,
cwd,
local_cwd_temp_dir: Some(local_cwd_temp_dir),
remote_container_name: None,
@@ -98,10 +102,6 @@ impl TestEnv {
&self.environment
}
pub fn exec_server_url(&self) -> Option<&str> {
self.environment.exec_server_url()
}
fn local_cwd_temp_dir(&self) -> Option<Arc<TempDir>> {
self.local_cwd_temp_dir.clone()
}
@@ -121,7 +121,7 @@ pub async fn test_env() -> Result<TestEnv> {
Some(remote_env) => {
let websocket_url = remote_exec_server_url()?;
let environment =
codex_exec_server::Environment::create_for_tests(Some(websocket_url))?;
codex_exec_server::Environment::create_for_tests(Some(websocket_url.clone()))?;
let cwd = remote_aware_cwd_path();
environment
.get_filesystem()
@@ -133,6 +133,7 @@ pub async fn test_env() -> Result<TestEnv> {
.await?;
Ok(TestEnv {
environment,
exec_server_url: Some(websocket_url),
cwd,
local_cwd_temp_dir: None,
remote_container_name: Some(remote_env.container_name),
@@ -188,7 +189,6 @@ fn docker_command_capture_stdout<const N: usize>(args: [&str; N]) -> Result<Stri
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ApplyPatchModelOutput {
Freeform,
Function,
Shell,
ShellViaHeredoc,
ShellCommandViaHeredoc,
@@ -383,10 +383,17 @@ impl TestCodexBuilder {
let exec_server_url = self
.exec_server_url
.clone()
.or_else(|| test_env.exec_server_url().map(str::to_owned));
.or_else(|| test_env.exec_server_url.clone());
#[cfg(target_os = "linux")]
let codex_linux_sandbox_exe = Some(
crate::find_codex_linux_sandbox_exe()
.context("should find binary for codex-linux-sandbox")?,
);
#[cfg(not(target_os = "linux"))]
let codex_linux_sandbox_exe = None;
let local_runtime_paths = codex_exec_server::ExecServerRuntimePaths::new(
std::env::current_exe()?,
/*codex_linux_sandbox_exe*/ None,
codex_linux_sandbox_exe,
)?;
let environment_manager = Arc::new(
codex_exec_server::EnvironmentManager::create_for_tests(
@@ -423,23 +430,21 @@ impl TestCodexBuilder {
environment_manager: Arc<codex_exec_server::EnvironmentManager>,
) -> anyhow::Result<TestCodex> {
let auth = self.auth.clone();
let thread_manager = if config.model_catalog.is_some() {
ThreadManager::new(
&config,
codex_core::test_support::auth_manager_from_auth(auth.clone()),
SessionSource::Exec,
Arc::clone(&environment_manager),
/*analytics_events_client*/ None,
thread_store_from_config(&config),
)
} else {
codex_core::test_support::thread_manager_with_models_provider_and_home(
auth.clone(),
config.model_provider.clone(),
config.codex_home.to_path_buf(),
Arc::clone(&environment_manager),
)
};
let state_db = codex_core::init_state_db(&config).await;
let thread_store = thread_store_from_config(&config, state_db.clone());
let installation_id = resolve_installation_id(&config.codex_home).await?;
let thread_manager = ThreadManager::new(
&config,
codex_core::test_support::auth_manager_from_auth(auth.clone()),
SessionSource::Exec,
Arc::clone(&environment_manager),
empty_extension_registry(),
/*analytics_events_client*/ None,
thread_store,
state_db.clone(),
installation_id,
/*attestation_provider*/ None,
);
let thread_manager = Arc::new(thread_manager);
let user_shell_override = self.user_shell_override.clone();
@@ -641,7 +646,7 @@ impl TestCodex {
prompt,
AskForApproval::Never,
PermissionProfile::Disabled,
Some(service_tier),
Some(service_tier.map(|service_tier| service_tier.request_value().to_string())),
/*environments*/ None,
)
.await
@@ -703,7 +708,7 @@ impl TestCodex {
prompt: &str,
approval_policy: AskForApproval,
permission_profile: PermissionProfile,
service_tier: Option<Option<ServiceTier>>,
service_tier: Option<Option<String>>,
environments: Option<Vec<TurnEnvironmentSelection>>,
) -> Result<()> {
self.submit_turn_with_context(
@@ -721,7 +726,7 @@ impl TestCodex {
prompt: &str,
approval_policy: AskForApproval,
permission_profile: PermissionProfile,
service_tier: Option<Option<ServiceTier>>,
service_tier: Option<Option<String>>,
environments: Option<Vec<TurnEnvironmentSelection>>,
) -> Result<()> {
let (sandbox_policy, permission_profile) =
@@ -954,8 +959,7 @@ impl TestCodexHarness {
ApplyPatchModelOutput::Freeform => {
Box::pin(self.custom_tool_call_output(call_id)).await
}
ApplyPatchModelOutput::Function
| ApplyPatchModelOutput::Shell
ApplyPatchModelOutput::Shell
| ApplyPatchModelOutput::ShellViaHeredoc
| ApplyPatchModelOutput::ShellCommandViaHeredoc => {
Box::pin(self.function_call_stdout(call_id)).await
+19 -13
View File
@@ -80,13 +80,13 @@ async fn responses_stream_includes_subagent_header_on_review() {
config.model = Some(model.clone());
let config = Arc::new(config);
let conversation_id = ThreadId::new();
let thread_id = ThreadId::new();
let auth_mode = TelemetryAuthMode::Chatgpt;
let session_source = SessionSource::SubAgent(SubAgentSource::Review);
let model_info =
codex_core::test_support::construct_model_info_offline(model.as_str(), &config);
let session_telemetry = SessionTelemetry::new(
conversation_id,
thread_id,
model.as_str(),
model_info.slug.as_str(),
/*account_id*/ None,
@@ -100,7 +100,8 @@ async fn responses_stream_includes_subagent_header_on_review() {
let client = ModelClient::new(
/*auth_manager*/ None,
conversation_id,
thread_id.into(),
thread_id,
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
provider.clone(),
session_source,
@@ -108,6 +109,7 @@ async fn responses_stream_includes_subagent_header_on_review() {
/*enable_request_compression*/ false,
/*include_timing_metrics*/ false,
/*beta_features_header*/ None,
/*attestation_provider*/ None,
);
let mut client_session = client.new_session();
@@ -141,7 +143,7 @@ async fn responses_stream_includes_subagent_header_on_review() {
}
let request = request_recorder.single_request();
let expected_window_id = format!("{conversation_id}:0");
let expected_window_id = format!("{thread_id}:0");
assert_eq!(
request.header("x-openai-subagent").as_deref(),
Some("review")
@@ -205,14 +207,14 @@ async fn responses_stream_includes_subagent_header_on_other() {
config.model = Some(model.clone());
let config = Arc::new(config);
let conversation_id = ThreadId::new();
let thread_id = ThreadId::new();
let auth_mode = TelemetryAuthMode::Chatgpt;
let session_source = SessionSource::SubAgent(SubAgentSource::Other("my-task".to_string()));
let model_info =
codex_core::test_support::construct_model_info_offline(model.as_str(), &config);
let session_telemetry = SessionTelemetry::new(
conversation_id,
thread_id,
model.as_str(),
model_info.slug.as_str(),
/*account_id*/ None,
@@ -226,7 +228,8 @@ async fn responses_stream_includes_subagent_header_on_other() {
let client = ModelClient::new(
/*auth_manager*/ None,
conversation_id,
thread_id.into(),
thread_id,
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
provider.clone(),
session_source,
@@ -234,6 +237,7 @@ async fn responses_stream_includes_subagent_header_on_other() {
/*enable_request_compression*/ false,
/*include_timing_metrics*/ false,
/*beta_features_header*/ None,
/*attestation_provider*/ None,
);
let mut client_session = client.new_session();
@@ -317,7 +321,7 @@ async fn responses_respects_model_info_overrides_from_config() {
let model = config.model.clone().expect("model configured");
let config = Arc::new(config);
let conversation_id = ThreadId::new();
let thread_id = ThreadId::new();
let auth_mode =
codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("Test API Key"))
.auth_mode()
@@ -327,7 +331,7 @@ async fn responses_respects_model_info_overrides_from_config() {
let model_info =
codex_core::test_support::construct_model_info_offline(model.as_str(), &config);
let session_telemetry = SessionTelemetry::new(
conversation_id,
thread_id,
model.as_str(),
model_info.slug.as_str(),
/*account_id*/ None,
@@ -341,7 +345,8 @@ async fn responses_respects_model_info_overrides_from_config() {
let client = ModelClient::new(
/*auth_manager*/ None,
conversation_id,
thread_id.into(),
thread_id,
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
provider.clone(),
session_source,
@@ -349,6 +354,7 @@ async fn responses_respects_model_info_overrides_from_config() {
/*enable_request_compression*/ false,
/*include_timing_metrics*/ false,
/*beta_features_header*/ None,
/*attestation_provider*/ None,
);
let mut client_session = client.new_session();
@@ -452,7 +458,7 @@ async fn responses_stream_includes_turn_metadata_header_for_git_workspace_e2e()
initial_parsed
.get("thread_source")
.and_then(serde_json::Value::as_str),
Some("user")
None
);
let git_config_global = cwd.join("empty-git-config");
@@ -565,13 +571,13 @@ async fn responses_stream_includes_turn_metadata_header_for_git_workspace_e2e()
first_parsed
.get("thread_source")
.and_then(serde_json::Value::as_str),
Some("user")
None
);
assert_eq!(
second_parsed
.get("thread_source")
.and_then(serde_json::Value::as_str),
Some("user")
None
);
assert_eq!(
first_turn_id, second_turn_id,
+1 -1
View File
@@ -313,7 +313,7 @@ async fn websocket_v2_first_turn_drops_fast_tier_after_startup_prewarm() -> Resu
.features
.enable(Feature::ResponsesWebsocketsV2)
.expect("test config should allow feature update");
config.service_tier = Some(ServiceTier::Fast);
config.service_tier = Some(ServiceTier::Fast.request_value().to_string());
});
let test = builder.build_with_websocket_server(&server).await?;
+469 -107
View File
@@ -12,8 +12,14 @@ use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering;
use std::time::Duration;
use codex_exec_server::CreateDirectoryOptions;
use codex_features::Feature;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSpecialPath;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
@@ -22,8 +28,8 @@ use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::user_input::UserInput;
#[cfg(target_os = "linux")]
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
use codex_utils_absolute_path::AbsolutePathBuf;
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;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call;
@@ -62,6 +68,21 @@ async fn apply_patch_harness_with(
}
async fn submit_without_wait(harness: &TestCodexHarness, prompt: &str) -> Result<()> {
submit_without_wait_with_turn_permissions(
harness,
prompt,
SandboxPolicy::DangerFullAccess,
/*permission_profile*/ None,
)
.await
}
async fn submit_without_wait_with_turn_permissions(
harness: &TestCodexHarness,
prompt: &str,
sandbox_policy: SandboxPolicy,
permission_profile: Option<PermissionProfile>,
) -> Result<()> {
let test = harness.test();
let session_model = test.session_configured.model.clone();
test.codex
@@ -75,8 +96,8 @@ async fn submit_without_wait(harness: &TestCodexHarness, prompt: &str) -> Result
cwd: harness.cwd().to_path_buf(),
approval_policy: AskForApproval::Never,
approvals_reviewer: None,
sandbox_policy: SandboxPolicy::DangerFullAccess,
permission_profile: None,
sandbox_policy,
permission_profile,
model: session_model,
effort: None,
summary: None,
@@ -97,6 +118,67 @@ fn restrictive_workspace_write_profile() -> PermissionProfile {
)
}
fn workspace_write_with_read_only_root(read_only_root: AbsolutePathBuf) -> PermissionProfile {
let file_system_sandbox_policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: read_only_root,
},
access: FileSystemAccessMode::Read,
},
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
},
access: FileSystemAccessMode::Write,
},
]);
PermissionProfile::from_runtime_permissions(
&file_system_sandbox_policy,
NetworkSandboxPolicy::Restricted,
)
}
#[cfg(unix)]
fn workspace_write_with_unreadable_path(unreadable_path: AbsolutePathBuf) -> PermissionProfile {
let file_system_sandbox_policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: unreadable_path,
},
access: FileSystemAccessMode::None,
},
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
},
access: FileSystemAccessMode::Write,
},
]);
PermissionProfile::from_runtime_permissions(
&file_system_sandbox_policy,
NetworkSandboxPolicy::Restricted,
)
}
#[cfg(unix)]
fn create_file_symlink(source: &std::path::Path, link: &std::path::Path) -> std::io::Result<()> {
std::os::unix::fs::symlink(source, link)
}
#[cfg(windows)]
fn create_file_symlink(source: &std::path::Path, link: &std::path::Path) -> std::io::Result<()> {
std::os::windows::fs::symlink_file(source, link)
}
#[cfg(not(any(unix, windows)))]
fn create_file_symlink(_source: &std::path::Path, _link: &std::path::Path) -> std::io::Result<()> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"file symlinks are unsupported on this platform",
))
}
pub async fn mount_apply_patch(
harness: &TestCodexHarness,
call_id: &str,
@@ -156,14 +238,14 @@ async fn apply_patch_cli_uses_codex_self_exe_with_linux_sandbox_helper_alias() -
call_id,
patch,
"done",
ApplyPatchModelOutput::Function,
ApplyPatchModelOutput::Freeform,
)
.await;
harness.submit("please apply helper alias patch").await?;
let out = harness
.apply_patch_output(call_id, ApplyPatchModelOutput::Function)
.apply_patch_output(call_id, ApplyPatchModelOutput::Freeform)
.await;
assert_regex_match(
r"(?s)^Exit code: 0.*Success\. Updated the following files:\nA helper-alias\.txt\n?$",
@@ -176,7 +258,6 @@ async fn apply_patch_cli_uses_codex_self_exe_with_linux_sandbox_helper_alias() -
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
async fn apply_patch_cli_multiple_operations_integration(
@@ -221,7 +302,6 @@ D delete.txt
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -249,7 +329,6 @@ async fn apply_patch_cli_multiple_chunks(model_output: ApplyPatchModelOutput) ->
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -278,7 +357,6 @@ async fn apply_patch_cli_moves_file_to_new_directory(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -307,7 +385,6 @@ async fn apply_patch_cli_updates_file_appends_trailing_newline(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -337,7 +414,6 @@ async fn apply_patch_cli_insert_only_hunk_modifies_file(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -369,7 +445,6 @@ async fn apply_patch_cli_move_overwrites_existing_destination(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -377,10 +452,6 @@ async fn apply_patch_cli_move_without_content_change_has_no_turn_diff(
model_output: ApplyPatchModelOutput,
) -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_remote!(
Ok(()),
"TurnDiffTracker currently reads the test-runner filesystem, not the remote executor filesystem",
);
let harness = apply_patch_harness().await?;
let test = harness.test();
@@ -413,7 +484,6 @@ async fn apply_patch_cli_move_without_content_change_has_no_turn_diff(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -441,7 +511,6 @@ async fn apply_patch_cli_add_overwrites_existing_file(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -473,7 +542,6 @@ async fn apply_patch_cli_rejects_invalid_hunk_header(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -509,7 +577,6 @@ async fn apply_patch_cli_reports_missing_context(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -545,7 +612,6 @@ async fn apply_patch_cli_reports_missing_target_file(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -582,7 +648,6 @@ async fn apply_patch_cli_delete_missing_file_reports_error(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -607,7 +672,6 @@ async fn apply_patch_cli_rejects_empty_patch(model_output: ApplyPatchModelOutput
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -634,7 +698,6 @@ async fn apply_patch_cli_delete_directory_reports_verification_error(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -679,9 +742,236 @@ async fn apply_patch_cli_rejects_path_traversal_outside_workspace(
Ok(())
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Shell ; "shell")]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc ; "shell_heredoc")]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc ; "shell_command_heredoc")]
async fn intercepted_apply_patch_verification_uses_local_sandbox(
model_output: ApplyPatchModelOutput,
) -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_remote!(Ok(()), "symlink setup needs local filesystem link creation");
let harness = apply_patch_harness().await?;
let denied_target = harness.path("denied-target.txt");
std::fs::write(&denied_target, "outside content\n")?;
let link_rel = "soft-link.txt";
create_file_symlink(&denied_target, &harness.path(link_rel))?;
let patch = format!(
r#"*** Begin Patch
*** Update File: {link_rel}
@@
-outside content
+pwned
*** End Patch"#
);
let call_id = "apply-sandboxed-read";
mount_apply_patch(&harness, call_id, &patch, "fail", model_output).await;
harness
.submit_with_permission_profile(
"attempt to read denied target via intercepted apply_patch",
workspace_write_with_unreadable_path(AbsolutePathBuf::try_from(denied_target.clone())?),
)
.await?;
let out = harness.apply_patch_output(call_id, model_output).await;
assert!(
out.contains("apply_patch verification failed"),
"expected sandboxed verification failure: {out}"
);
assert!(
out.contains("Failed to read"),
"expected read failure: {out}"
);
assert_eq!(
std::fs::read_to_string(&denied_target)?,
"outside content\n",
"verification failure should leave the denied target unchanged"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform ; "freeform")]
#[test_case(ApplyPatchModelOutput::Shell ; "shell")]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc ; "shell_heredoc")]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc ; "shell_command_heredoc")]
async fn apply_patch_cli_does_not_write_through_symlink_escape_outside_workspace(
model_output: ApplyPatchModelOutput,
) -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_remote!(
Ok(()),
"link escape setup needs local filesystem link creation"
);
let test_root = tempfile::tempdir_in(std::env::current_dir()?)?;
let work_dir = AbsolutePathBuf::try_from(test_root.path().join("work"))?;
let outside_dir = AbsolutePathBuf::try_from(test_root.path().join("outside"))?;
std::fs::create_dir_all(work_dir.as_path())?;
std::fs::create_dir_all(outside_dir.as_path())?;
let harness_work_dir = work_dir.clone();
let harness = apply_patch_harness_with(move |builder| {
builder.with_config(move |config| {
config.cwd = harness_work_dir;
})
})
.await?;
let original_contents = "original outside content\n";
let outside_file = outside_dir.join("victim.txt");
std::fs::write(&outside_file, original_contents)?;
let link_rel = "soft-link.txt";
let link_path = harness.path(link_rel);
match create_file_symlink(&outside_file, &link_path) {
Ok(()) => {}
Err(error) if cfg!(windows) => {
eprintln!("Skipping Windows symlink apply_patch sandbox test: {error}");
return Ok(());
}
Err(error) => return Err(error.into()),
}
let patch = format!(
r#"*** Begin Patch
*** Update File: {link_rel}
@@
-original outside content
+pwned
*** End Patch"#
);
let call_id = "apply-symlink-escape";
mount_apply_patch(&harness, call_id, &patch, "fail", model_output).await;
harness
.submit_with_permission_profile(
"attempt to escape workspace via apply_patch link",
workspace_write_with_read_only_root(outside_dir.clone()),
)
.await?;
let out = harness.apply_patch_output(call_id, model_output).await;
assert_eq!(
std::fs::read_to_string(&outside_file)?,
original_contents,
"symlink escape should not modify the outside victim; tool output: {out}",
);
let metadata = std::fs::symlink_metadata(&link_path)?;
assert!(metadata.file_type().is_symlink());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform ; "freeform")]
#[test_case(ApplyPatchModelOutput::Shell ; "shell")]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc ; "shell_heredoc")]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc ; "shell_command_heredoc")]
async fn apply_patch_cli_preserves_existing_hard_link_outside_workspace(
model_output: ApplyPatchModelOutput,
) -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_remote!(
Ok(()),
"link setup needs local filesystem hard link creation"
);
let test_root = tempfile::tempdir_in(std::env::current_dir()?)?;
let work_dir = AbsolutePathBuf::try_from(test_root.path().join("work"))?;
let outside_dir = AbsolutePathBuf::try_from(test_root.path().join("outside"))?;
std::fs::create_dir_all(work_dir.as_path())?;
std::fs::create_dir_all(outside_dir.as_path())?;
let harness_work_dir = work_dir.clone();
let harness = apply_patch_harness_with(move |builder| {
builder.with_config(move |config| {
config.cwd = harness_work_dir;
})
})
.await?;
let outside_file = outside_dir.join("victim.txt");
std::fs::write(&outside_file, "original outside content\n")?;
let link_rel = "hard-link.txt";
let link_path = harness.path(link_rel);
std::fs::hard_link(&outside_file, &link_path)?;
let patch = format!(
r#"*** Begin Patch
*** Update File: {link_rel}
@@
-original outside content
+updated through existing hard link
*** End Patch"#
);
let call_id = "apply-hard-link";
mount_apply_patch(&harness, call_id, &patch, "ok", model_output).await;
harness
.submit_with_permission_profile(
"update existing hard link via apply_patch",
workspace_write_with_read_only_root(outside_dir.clone()),
)
.await?;
let out = harness.apply_patch_output(call_id, model_output).await;
if cfg!(windows) {
assert!(
out.contains("patch rejected: writing outside of the project"),
"Windows sandboxing intentionally rejects writes through existing hard links to files outside the workspace; tool output: {out}"
);
assert_eq!(
std::fs::read_to_string(&outside_file)?,
"original outside content\n",
"Windows rejection must leave the outside hard-link target unchanged"
);
assert_eq!(
std::fs::read_to_string(&link_path)?,
"original outside content\n",
"Windows rejection must leave the workspace hard-link path unchanged"
);
std::fs::write(&outside_file, "post-reject outside write\n")?;
assert_eq!(
std::fs::read_to_string(&link_path)?,
"post-reject outside write\n",
"Windows rejection must not unlink or replace an existing hard link"
);
return Ok(());
}
assert!(
out.contains("Success. Updated the following files:"),
"apply_patch should intentionally allow updates through existing hard links; tool output: {out}"
);
assert_eq!(
std::fs::read_to_string(&outside_file)?,
"updated through existing hard link\n",
"apply_patch intentionally preserves existing hard-link semantics; the outside path observes the shared inode update"
);
assert_eq!(
std::fs::read_to_string(&link_path)?,
"updated through existing hard link\n",
"apply_patch intentionally preserves existing hard-link semantics; the workspace path observes the same update"
);
std::fs::write(&outside_file, "post-apply outside write\n")?;
assert_eq!(
std::fs::read_to_string(&link_path)?,
"post-apply outside write\n",
"apply_patch must not unlink or replace an existing hard link; later writes through either path should still be visible"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -731,7 +1021,6 @@ async fn apply_patch_cli_rejects_move_path_traversal_outside_workspace(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -1050,10 +1339,6 @@ async fn apply_patch_custom_tool_streaming_emits_updated_changes() -> Result<()>
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_patch_shell_command_heredoc_with_cd_emits_turn_diff() -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_remote!(
Ok(()),
"TurnDiffTracker currently reads the test-runner filesystem, not the remote executor filesystem",
);
let harness = apply_patch_harness_with(|builder| builder.with_model("gpt-5.4")).await?;
let test = harness.test();
@@ -1113,13 +1398,88 @@ async fn apply_patch_shell_command_heredoc_with_cd_emits_turn_diff() -> Result<(
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_patch_turn_diff_paths_stay_repo_relative_when_session_cwd_is_nested() -> Result<()> {
skip_if_no_network!(Ok(()));
let harness = apply_patch_harness_with(|builder| {
builder
.with_model("gpt-5.4")
.with_config(|config| {
config.cwd = config.cwd.join("subdir");
})
.with_workspace_setup(|cwd, fs| async move {
fs.create_directory(
&cwd,
CreateDirectoryOptions { recursive: true },
/*sandbox*/ None,
)
.await?;
let repo_root = cwd.parent().expect("nested cwd should have parent");
fs.write_file(
&repo_root.join(".git"),
b"gitdir: /tmp/fake-worktree\n".to_vec(),
/*sandbox*/ None,
)
.await?;
fs.write_file(
&repo_root.join("repo.txt"),
b"before\n".to_vec(),
/*sandbox*/ None,
)
.await?;
Ok(())
})
})
.await?;
let test = harness.test();
let codex = test.codex.clone();
let repo_root = harness
.test()
.config
.cwd
.parent()
.expect("nested cwd should have parent");
let call_id = "apply-nested-cwd-repo-relative";
let patch = "*** Begin Patch\n*** Update File: ../repo.txt\n@@\n-before\n+after\n*** End Patch";
mount_apply_patch(
&harness,
call_id,
patch,
"updated repo-relative path",
ApplyPatchModelOutput::Freeform,
)
.await;
submit_without_wait(&harness, "update file outside nested cwd but inside repo").await?;
let mut last_diff: Option<String> = None;
wait_for_event(&codex, |event| match event {
EventMsg::TurnDiff(ev) => {
last_diff = Some(ev.unified_diff.clone());
false
}
EventMsg::TurnComplete(_) => true,
_ => false,
})
.await;
let diff = last_diff.expect("expected TurnDiff event after update");
assert!(
diff.contains("diff --git a/repo.txt b/repo.txt"),
"diff should stay repo-relative: {diff:?}"
);
assert!(
!diff.contains(repo_root.as_path().to_string_lossy().as_ref()),
"diff should not leak absolute repo paths: {diff:?}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_patch_shell_command_failure_propagates_error_and_skips_diff() -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_remote!(
Ok(()),
"TurnDiffTracker currently reads the test-runner filesystem, not the remote executor filesystem",
);
let harness = apply_patch_harness_with(|builder| builder.with_model("gpt-5.4")).await?;
let test = harness.test();
@@ -1177,7 +1537,7 @@ async fn apply_patch_shell_command_failure_propagates_error_and_skips_diff() ->
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
async fn apply_patch_function_accepts_lenient_heredoc_wrapped_patch(
async fn apply_patch_shell_accepts_lenient_heredoc_wrapped_patch(
model_output: ApplyPatchModelOutput,
) -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -1198,7 +1558,6 @@ async fn apply_patch_function_accepts_lenient_heredoc_wrapped_patch(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -1220,7 +1579,6 @@ async fn apply_patch_cli_end_of_file_anchor(model_output: ApplyPatchModelOutput)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -1257,7 +1615,6 @@ async fn apply_patch_cli_missing_second_chunk_context_rejected(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
@@ -1265,10 +1622,6 @@ async fn apply_patch_emits_turn_diff_event_with_unified_diff(
model_output: ApplyPatchModelOutput,
) -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_remote!(
Ok(()),
"TurnDiffTracker currently reads the test-runner filesystem, not the remote executor filesystem",
);
let harness = apply_patch_harness().await?;
let test = harness.test();
@@ -1300,64 +1653,9 @@ async fn apply_patch_emits_turn_diff_event_with_unified_diff(
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
async fn apply_patch_turn_diff_for_rename_with_content_change(
model_output: ApplyPatchModelOutput,
) -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_remote!(
Ok(()),
"TurnDiffTracker currently reads the test-runner filesystem, not the remote executor filesystem",
);
let harness = apply_patch_harness().await?;
let test = harness.test();
let codex = test.codex.clone();
// Seed original file
harness.write_file("old.txt", "old\n").await?;
// 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";
mount_apply_patch(&harness, call_id, patch, "ok", model_output).await;
submit_without_wait(&harness, "rename with change").await?;
let mut last_diff: Option<String> = None;
wait_for_event(&codex, |event| match event {
EventMsg::TurnDiff(ev) => {
last_diff = Some(ev.unified_diff.clone());
false
}
EventMsg::TurnComplete(_) => 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(()));
skip_if_remote!(
Ok(()),
"TurnDiffTracker currently reads the test-runner filesystem, not the remote executor filesystem",
);
let harness = apply_patch_harness().await?;
let test = harness.test();
@@ -1370,12 +1668,12 @@ async fn apply_patch_aggregates_diff_across_multiple_tool_calls() -> Result<()>
let s1 = sse(vec![
ev_response_created("resp-1"),
ev_apply_patch_function_call(call1, patch1),
ev_apply_patch_custom_tool_call(call1, patch1),
ev_completed("resp-1"),
]);
let s2 = sse(vec![
ev_response_created("resp-2"),
ev_apply_patch_function_call(call2, patch2),
ev_apply_patch_custom_tool_call(call2, patch2),
ev_completed("resp-2"),
]);
let s3 = sse(vec![
@@ -1408,10 +1706,6 @@ async fn apply_patch_aggregates_diff_across_multiple_tool_calls() -> Result<()>
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_patch_aggregates_diff_preserves_success_after_failure() -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_remote!(
Ok(()),
"TurnDiffTracker currently reads the test-runner filesystem, not the remote executor filesystem",
);
let harness = apply_patch_harness().await?;
let test = harness.test();
@@ -1426,12 +1720,12 @@ async fn apply_patch_aggregates_diff_preserves_success_after_failure() -> Result
let responses = vec![
sse(vec![
ev_response_created("resp-1"),
ev_apply_patch_function_call(call_success, patch_success),
ev_apply_patch_custom_tool_call(call_success, patch_success),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_apply_patch_function_call(call_failure, patch_failure),
ev_apply_patch_custom_tool_call(call_failure, patch_failure),
ev_completed("resp-2"),
]),
sse(vec![
@@ -1468,7 +1762,7 @@ async fn apply_patch_aggregates_diff_preserves_success_after_failure() -> Result
"diff should include contents from successful patch: {diff}"
);
let failure_out = harness.function_call_stdout(call_failure).await;
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}"
@@ -1482,9 +1776,77 @@ async fn apply_patch_aggregates_diff_preserves_success_after_failure() -> Result
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_patch_clears_aggregated_diff_after_inexact_delta() -> Result<()> {
skip_if_no_network!(Ok(()));
let harness = apply_patch_harness_with(|builder| {
builder.with_workspace_setup(|cwd, fs| async move {
fs.write_file(
&cwd.join("binary.dat"),
vec![0xff, 0xfe, 0xfd],
/*sandbox*/ None,
)
.await?;
Ok(())
})
})
.await?;
let test = harness.test();
let codex = test.codex.clone();
let call_success = "agg-success";
let call_inexact = "agg-inexact";
let patch_success = "*** Begin Patch\n*** Add File: partial/success.txt\n+ok\n*** End Patch";
let patch_inexact = "*** Begin Patch\n*** Add File: binary.dat\n+text\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_inexact, patch_inexact),
ev_completed("resp-2"),
]),
sse(vec![
ev_assistant_message("msg-1", "done"),
ev_completed("resp-3"),
]),
];
mount_sse_sequence(harness.server(), responses).await;
submit_without_wait(&harness, "apply patch twice with inexact delta").await?;
let mut last_diff: Option<String> = None;
wait_for_event_with_timeout(
&codex,
|event| match event {
EventMsg::TurnDiff(ev) => {
last_diff = Some(ev.unified_diff.clone());
false
}
EventMsg::TurnComplete(_) => true,
_ => false,
},
Duration::from_secs(30),
)
.await;
assert_eq!(
last_diff.as_deref(),
Some(""),
"inexact delta should clear the aggregate diff"
);
assert_eq!(harness.read_file_text("partial/success.txt").await?, "ok\n");
assert_eq!(harness.read_file_text("binary.dat").await?, "text\n");
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
#[test_case(ApplyPatchModelOutput::ShellCommandViaHeredoc)]
+90 -44
View File
@@ -15,12 +15,13 @@ use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::ExecApprovalRequestEvent;
use codex_protocol::protocol::ExecPolicyAmendment;
use codex_protocol::protocol::GranularApprovalConfig;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::ReviewDecision;
use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::user_input::UserInput;
use core_test_support::managed_network_requirements_loader;
use core_test_support::responses::ev_apply_patch_function_call;
use core_test_support::responses::ev_apply_patch_custom_tool_call;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call;
@@ -108,7 +109,7 @@ enum ActionKind {
command: &'static str,
justification: Option<&'static str>,
},
ApplyPatchFunction {
ApplyPatchFreeform {
target: TargetPath,
content: &'static str,
},
@@ -131,7 +132,7 @@ impl ActionKind {
| ActionKind::RunCommand { .. }
| ActionKind::RunCommandWithPrefixRule { .. }
| ActionKind::RunUnifiedExecCommand { .. }
| ActionKind::ApplyPatchFunction { .. }
| ActionKind::ApplyPatchFreeform { .. }
| ActionKind::ApplyPatchShell { .. } => None,
}
}
@@ -264,11 +265,11 @@ impl ActionKind {
)?;
Ok((event, Some(command.to_string())))
}
ActionKind::ApplyPatchFunction { target, content } => {
ActionKind::ApplyPatchFreeform { target, content } => {
let (path, patch_path) = target.resolve_for_patch(test);
let _ = fs::remove_file(&path);
let patch = build_add_file_patch(&patch_path, content);
Ok((ev_apply_patch_function_call(call_id, &patch), None))
Ok((ev_apply_patch_custom_tool_call(call_id, &patch), None))
}
ActionKind::ApplyPatchShell { target, content } => {
let (path, patch_path) = target.resolve_for_patch(test);
@@ -807,7 +808,7 @@ async fn wait_for_spawned_thread(test: &TestCodex) -> Result<Arc<CodexThread>> {
let ids = test.thread_manager.list_thread_ids().await;
if let Some(thread_id) = ids
.iter()
.find(|id| **id != test.session_configured.session_id)
.find(|id| **id != test.session_configured.thread_id)
{
return test
.thread_manager
@@ -965,6 +966,46 @@ fn scenarios() -> Vec<ScenarioSpec> {
output_contains: "rejected by user",
},
},
ScenarioSpec {
name: "known_safe_escalation_on_request_requires_approval",
approval_policy: OnRequest,
sandbox_policy: workspace_write(false),
action: ActionKind::RunCommand {
command: "echo known-safe-escalation",
},
sandbox_permissions: SandboxPermissions::RequireEscalated,
features: vec![],
model_override: Some("gpt-5.2"),
outcome: Outcome::ExecApprovalWithAmendment {
decision: ReviewDecision::Denied,
expected_reason: None,
expected_execpolicy_amendment: Some(&["echo", "known-safe-escalation"]),
},
expectation: Expectation::CommandFailure {
output_contains: "rejected by user",
},
},
ScenarioSpec {
name: "known_safe_escalation_granular_sandbox_disabled_rejects",
approval_policy: Granular(GranularApprovalConfig {
sandbox_approval: false,
rules: true,
skill_approval: true,
request_permissions: true,
mcp_elicitations: true,
}),
sandbox_policy: workspace_write(false),
action: ActionKind::RunCommand {
command: "echo known-safe-escalation-granular-disabled",
},
sandbox_permissions: SandboxPermissions::RequireEscalated,
features: vec![],
model_override: Some("gpt-5.2"),
outcome: Outcome::Auto,
expectation: Expectation::CommandFailure {
output_contains: "you should not ask for escalated permissions",
},
},
ScenarioSpec {
name: "cat_heredoc_file_redirect_prefix_rule_requires_escalation_approval",
approval_policy: OnRequest,
@@ -1342,46 +1383,46 @@ fn scenarios() -> Vec<ScenarioSpec> {
},
},
ScenarioSpec {
name: "apply_patch_function_auto_inside_workspace",
name: "apply_patch_freeform_auto_inside_workspace",
approval_policy: OnRequest,
sandbox_policy: SandboxPolicy::DangerFullAccess,
action: ActionKind::ApplyPatchFunction {
target: TargetPath::Workspace("apply_patch_function.txt"),
content: "function-apply-patch",
action: ActionKind::ApplyPatchFreeform {
target: TargetPath::Workspace("apply_patch_freeform.txt"),
content: "freeform-apply-patch",
},
sandbox_permissions: SandboxPermissions::UseDefault,
features: vec![],
model_override: Some("gpt-5.4"),
outcome: Outcome::Auto,
expectation: Expectation::PatchApplied {
target: TargetPath::Workspace("apply_patch_function.txt"),
content: "function-apply-patch",
target: TargetPath::Workspace("apply_patch_freeform.txt"),
content: "freeform-apply-patch",
},
},
ScenarioSpec {
name: "apply_patch_function_danger_allows_outside_workspace",
name: "apply_patch_freeform_danger_allows_outside_workspace",
approval_policy: OnRequest,
sandbox_policy: SandboxPolicy::DangerFullAccess,
action: ActionKind::ApplyPatchFunction {
target: TargetPath::OutsideWorkspace("apply_patch_function_danger.txt"),
content: "function-patch-danger",
action: ActionKind::ApplyPatchFreeform {
target: TargetPath::OutsideWorkspace("apply_patch_freeform_danger.txt"),
content: "freeform-patch-danger",
},
sandbox_permissions: SandboxPermissions::UseDefault,
features: vec![Feature::ApplyPatchFreeform],
model_override: Some("gpt-5.4"),
outcome: Outcome::Auto,
expectation: Expectation::PatchApplied {
target: TargetPath::OutsideWorkspace("apply_patch_function_danger.txt"),
content: "function-patch-danger",
target: TargetPath::OutsideWorkspace("apply_patch_freeform_danger.txt"),
content: "freeform-patch-danger",
},
},
ScenarioSpec {
name: "apply_patch_function_outside_requires_patch_approval",
name: "apply_patch_freeform_outside_requires_patch_approval",
approval_policy: OnRequest,
sandbox_policy: workspace_write(false),
action: ActionKind::ApplyPatchFunction {
target: TargetPath::OutsideWorkspace("apply_patch_function_outside.txt"),
content: "function-patch-outside",
action: ActionKind::ApplyPatchFreeform {
target: TargetPath::OutsideWorkspace("apply_patch_freeform_outside.txt"),
content: "freeform-patch-outside",
},
sandbox_permissions: SandboxPermissions::UseDefault,
features: vec![],
@@ -1391,17 +1432,17 @@ fn scenarios() -> Vec<ScenarioSpec> {
expected_reason: None,
},
expectation: Expectation::PatchApplied {
target: TargetPath::OutsideWorkspace("apply_patch_function_outside.txt"),
content: "function-patch-outside",
target: TargetPath::OutsideWorkspace("apply_patch_freeform_outside.txt"),
content: "freeform-patch-outside",
},
},
ScenarioSpec {
name: "apply_patch_function_outside_denied_blocks_patch",
name: "apply_patch_freeform_outside_denied_blocks_patch",
approval_policy: OnRequest,
sandbox_policy: workspace_write(false),
action: ActionKind::ApplyPatchFunction {
target: TargetPath::OutsideWorkspace("apply_patch_function_outside_denied.txt"),
content: "function-patch-outside-denied",
action: ActionKind::ApplyPatchFreeform {
target: TargetPath::OutsideWorkspace("apply_patch_freeform_outside_denied.txt"),
content: "freeform-patch-outside-denied",
},
sandbox_permissions: SandboxPermissions::UseDefault,
features: vec![],
@@ -1411,7 +1452,7 @@ fn scenarios() -> Vec<ScenarioSpec> {
expected_reason: None,
},
expectation: Expectation::FileNotCreated {
target: TargetPath::OutsideWorkspace("apply_patch_function_outside_denied.txt"),
target: TargetPath::OutsideWorkspace("apply_patch_freeform_outside_denied.txt"),
message_contains: &["patch rejected by user"],
},
},
@@ -1436,12 +1477,12 @@ fn scenarios() -> Vec<ScenarioSpec> {
},
},
ScenarioSpec {
name: "apply_patch_function_unless_trusted_requires_patch_approval",
name: "apply_patch_freeform_unless_trusted_requires_patch_approval",
approval_policy: UnlessTrusted,
sandbox_policy: workspace_write(false),
action: ActionKind::ApplyPatchFunction {
target: TargetPath::Workspace("apply_patch_function_unless_trusted.txt"),
content: "function-patch-unless-trusted",
action: ActionKind::ApplyPatchFreeform {
target: TargetPath::Workspace("apply_patch_freeform_unless_trusted.txt"),
content: "freeform-patch-unless-trusted",
},
sandbox_permissions: SandboxPermissions::UseDefault,
features: vec![],
@@ -1451,24 +1492,24 @@ fn scenarios() -> Vec<ScenarioSpec> {
expected_reason: None,
},
expectation: Expectation::PatchApplied {
target: TargetPath::Workspace("apply_patch_function_unless_trusted.txt"),
content: "function-patch-unless-trusted",
target: TargetPath::Workspace("apply_patch_freeform_unless_trusted.txt"),
content: "freeform-patch-unless-trusted",
},
},
ScenarioSpec {
name: "apply_patch_function_never_rejects_outside_workspace",
name: "apply_patch_freeform_never_rejects_outside_workspace",
approval_policy: Never,
sandbox_policy: workspace_write(false),
action: ActionKind::ApplyPatchFunction {
target: TargetPath::OutsideWorkspace("apply_patch_function_never.txt"),
content: "function-patch-never",
action: ActionKind::ApplyPatchFreeform {
target: TargetPath::OutsideWorkspace("apply_patch_freeform_never.txt"),
content: "freeform-patch-never",
},
sandbox_permissions: SandboxPermissions::UseDefault,
features: vec![],
model_override: Some("gpt-5.4"),
outcome: Outcome::Auto,
expectation: Expectation::FileNotCreated {
target: TargetPath::OutsideWorkspace("apply_patch_function_never.txt"),
target: TargetPath::OutsideWorkspace("apply_patch_freeform_never.txt"),
message_contains: &[
"patch rejected: writing outside of the project; rejected by user approval settings",
],
@@ -1812,7 +1853,7 @@ async fn run_scenario_group(group: ScenarioGroup) -> Result<()> {
fn scenario_group(scenario: &ScenarioSpec) -> ScenarioGroup {
match &scenario.action {
ActionKind::ApplyPatchFunction { .. } | ActionKind::ApplyPatchShell { .. } => {
ActionKind::ApplyPatchFreeform { .. } | ActionKind::ApplyPatchShell { .. } => {
ScenarioGroup::ApplyPatch
}
ActionKind::RunUnifiedExecCommand { .. } => ScenarioGroup::UnifiedExec,
@@ -1982,7 +2023,12 @@ async fn run_scenario(scenario: &ScenarioSpec) -> Result<()> {
}
}
let output_item = results_mock.single_request().function_call_output(call_id);
let output_request = results_mock.single_request();
let output_item = if matches!(scenario.action, ActionKind::ApplyPatchFreeform { .. }) {
output_request.custom_tool_call_output(call_id)
} else {
output_request.function_call_output(call_id)
};
let result = parse_result(&output_item);
eprintln!(
"approval scenario {} result: exit_code={:?} stdout={:?}",
@@ -2035,7 +2081,7 @@ async fn approving_apply_patch_for_session_skips_future_prompts_for_same_file()
&server,
sse(vec![
ev_response_created("resp-1"),
ev_apply_patch_function_call(call_id_1, &patch_add),
ev_apply_patch_custom_tool_call(call_id_1, &patch_add),
ev_completed("resp-1"),
]),
)
@@ -2070,7 +2116,7 @@ async fn approving_apply_patch_for_session_skips_future_prompts_for_same_file()
&server,
sse(vec![
ev_response_created("resp-3"),
ev_apply_patch_function_call(call_id_2, &patch_update),
ev_apply_patch_custom_tool_call(call_id_2, &patch_update),
ev_completed("resp-3"),
]),
)
+26 -22
View File
@@ -2,7 +2,6 @@ use assert_cmd::Command as AssertCommand;
use codex_git_utils::collect_git_info;
use codex_login::CODEX_API_KEY_ENV_VAR;
use codex_protocol::protocol::GitInfo;
use codex_utils_cargo_bin::find_resource;
use core_test_support::fs_wait;
use core_test_support::responses;
use core_test_support::skip_if_no_network;
@@ -16,9 +15,12 @@ fn repo_root() -> std::path::PathBuf {
codex_utils_cargo_bin::repo_root().expect("failed to resolve repo root")
}
fn cli_responses_fixture() -> std::path::PathBuf {
#[expect(clippy::expect_used)]
find_resource!("tests/cli_responses_fixture.sse").expect("failed to resolve fixture path")
fn cli_sse_response() -> String {
responses::sse(vec![
responses::ev_response_created("resp-fixture"),
responses::ev_assistant_message("msg-fixture", "fixture hello"),
responses::ev_completed("resp-fixture"),
])
}
/// Tests streaming the Responses API through the CLI using a mock server.
@@ -262,37 +264,36 @@ async fn exec_cli_profile_applies_model_instructions_file() {
);
}
/// Tests streaming responses through the CLI using a local SSE fixture file.
/// This test:
/// 1. Uses a pre-recorded SSE response fixture instead of a live server
/// 2. Configures codex to read from this fixture via CODEX_RS_SSE_FIXTURE env var
/// 3. Sends a "hello?" prompt and verifies the response
/// 4. Ensures the fixture content is correctly streamed through the CLI
/// Tests streaming responses through the CLI using a local Responses API server.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responses_api_stream_cli() {
skip_if_no_network!();
let fixture = cli_responses_fixture();
let server = MockServer::start().await;
let resp_mock = responses::mount_sse_once(&server, cli_sse_response()).await;
let repo_root = repo_root();
let home = TempDir::new().unwrap();
let bin = codex_utils_cargo_bin::cargo_bin("codex").unwrap();
let mut cmd = AssertCommand::new(bin);
cmd.timeout(Duration::from_secs(30));
cmd.arg("exec")
.arg("--skip-git-repo-check")
.arg("-c")
.arg("openai_base_url=\"http://unused.local\"")
.arg(format!("openai_base_url=\"{}/v1\"", server.uri()))
.arg("-C")
.arg(&repo_root)
.arg("hello?");
cmd.env("CODEX_HOME", home.path())
.env("OPENAI_API_KEY", "dummy")
.env("CODEX_RS_SSE_FIXTURE", fixture);
.env("OPENAI_API_KEY", "dummy");
let output = cmd.output().unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("fixture hello"));
let request = resp_mock.single_request();
assert_eq!(request.path(), "/v1/responses");
}
/// End-to-end: create a session (writes rollout), verify the file, then resume and confirm append.
@@ -308,23 +309,25 @@ async fn integration_creates_and_checks_session_file() -> anyhow::Result<()> {
let marker = format!("integration-test-{}", Uuid::new_v4());
let prompt = format!("echo {marker}");
// 3. Use the same offline SSE fixture as responses_api_stream_cli so the test is hermetic.
let fixture = cli_responses_fixture();
// 3. Serve two hermetic SSE responses, one for the initial run and one for resume.
let server = MockServer::start().await;
let resp_mock =
responses::mount_sse_sequence(&server, vec![cli_sse_response(), cli_sse_response()]).await;
let repo_root = repo_root();
// 4. Run the codex CLI and invoke `exec`, which is what records a session.
let bin = codex_utils_cargo_bin::cargo_bin("codex").unwrap();
let mut cmd = AssertCommand::new(bin);
cmd.timeout(Duration::from_secs(30));
cmd.arg("exec")
.arg("--skip-git-repo-check")
.arg("-c")
.arg("openai_base_url=\"http://unused.local\"")
.arg(format!("openai_base_url=\"{}/v1\"", server.uri()))
.arg("-C")
.arg(&repo_root)
.arg(&prompt);
cmd.env("CODEX_HOME", home.path())
.env(CODEX_API_KEY_ENV_VAR, "dummy")
.env("CODEX_RS_SSE_FIXTURE", &fixture);
.env(CODEX_API_KEY_ENV_VAR, "dummy");
let output = cmd.output().unwrap();
assert!(
@@ -436,21 +439,22 @@ async fn integration_creates_and_checks_session_file() -> anyhow::Result<()> {
let prompt2 = format!("echo {marker2}");
let bin2 = codex_utils_cargo_bin::cargo_bin("codex").unwrap();
let mut cmd2 = AssertCommand::new(bin2);
cmd2.timeout(Duration::from_secs(30));
cmd2.arg("exec")
.arg("--skip-git-repo-check")
.arg("-c")
.arg("openai_base_url=\"http://unused.local\"")
.arg(format!("openai_base_url=\"{}/v1\"", server.uri()))
.arg("-C")
.arg(&repo_root)
.arg(&prompt2)
.arg("resume")
.arg("--last");
cmd2.env("CODEX_HOME", home.path())
.env("OPENAI_API_KEY", "dummy")
.env("CODEX_RS_SSE_FIXTURE", &fixture);
.env("OPENAI_API_KEY", "dummy");
let output2 = cmd2.output().unwrap();
assert!(output2.status.success(), "resume codex-cli run failed");
assert_eq!(resp_mock.requests().len(), 2);
// Find the new session file containing the resumed marker.
let marker2_clone = marker2.clone();
+53 -47
View File
@@ -5,7 +5,9 @@ use codex_core::NewThread;
use codex_core::Prompt;
use codex_core::ResponseEvent;
use codex_core::ThreadManager;
use codex_core::resolve_installation_id;
use codex_core::thread_store_from_config;
use codex_extension_api::empty_extension_registry;
use codex_features::Feature;
use codex_login::AuthManager;
use codex_login::CodexAuth;
@@ -724,7 +726,7 @@ async fn resume_replays_image_tool_outputs_with_detail() {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn includes_conversation_id_and_model_headers_in_request() {
async fn includes_session_id_thread_id_and_model_headers_in_request() {
skip_if_no_network!();
// Mock server
@@ -742,7 +744,8 @@ async fn includes_conversation_id_and_model_headers_in_request() {
.await
.expect("create new conversation");
let codex = test.codex.clone();
let session_id = test.session_configured.session_id;
let expected_session_id = test.session_configured.session_id;
let expected_thread_id = test.session_configured.thread_id;
codex
.submit(Op::UserInput {
@@ -762,6 +765,9 @@ async fn includes_conversation_id_and_model_headers_in_request() {
let request = resp_mock.single_request();
assert_eq!(request.path(), "/v1/responses");
let request_session_id = request.header("session_id").expect("session_id header");
let request_session_id_hyphenated = request.header("session-id").expect("session-id header");
let request_thread_id = request.header("thread_id").expect("thread_id header");
let request_thread_id_hyphenated = request.header("thread-id").expect("thread-id header");
let request_authorization = request
.header("authorization")
.expect("authorization header");
@@ -770,10 +776,21 @@ async fn includes_conversation_id_and_model_headers_in_request() {
let installation_id =
std::fs::read_to_string(test.codex_home_path().join(INSTALLATION_ID_FILENAME))
.expect("read installation id");
let thread_id_string = expected_thread_id.to_string();
assert_eq!(request_session_id, session_id.to_string());
assert_eq!(request_session_id, expected_session_id.to_string());
assert_eq!(
request_session_id_hyphenated,
expected_session_id.to_string()
);
assert_eq!(request_thread_id, thread_id_string.as_str());
assert_eq!(request_thread_id_hyphenated, thread_id_string.as_str());
assert_eq!(request_originator, originator().value);
assert_eq!(request_authorization, "Bearer Test API Key");
assert_eq!(
request_body["prompt_cache_key"].as_str(),
Some(thread_id_string.as_str())
);
assert_eq!(
request_body["client_metadata"]["x-codex-installation-id"].as_str(),
Some(installation_id.as_str())
@@ -865,9 +882,9 @@ async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuth
let config = Arc::new(config);
let model_info =
codex_core::test_support::construct_model_info_offline(model.as_str(), &config);
let conversation_id = ThreadId::new();
let thread_id = ThreadId::new();
let session_telemetry = SessionTelemetry::new(
conversation_id,
thread_id,
model.as_str(),
model_info.slug.as_str(),
/*account_id*/ None,
@@ -882,7 +899,8 @@ async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuth
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
"unused-api-key",
))),
conversation_id,
thread_id.into(),
thread_id,
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
provider,
SessionSource::Exec,
@@ -890,6 +908,7 @@ async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuth
/*enable_request_compression*/ false,
/*include_timing_metrics*/ false,
/*beta_features_header*/ None,
/*attestation_provider*/ None,
);
let mut client_session = client.new_session();
let mut prompt = Prompt::default();
@@ -998,7 +1017,8 @@ async fn chatgpt_auth_sends_correct_request() {
.await
.expect("create new conversation");
let codex = test.codex.clone();
let thread_id = test.session_configured.session_id;
let expected_session_id = test.session_configured.session_id;
let expected_thread_id = test.session_configured.thread_id;
codex
.submit(Op::UserInput {
@@ -1026,11 +1046,20 @@ async fn chatgpt_auth_sends_correct_request() {
.expect("chatgpt-account-id header");
let request_body = request.body_json();
let session_id = request.header("session_id").expect("session_id header");
let request_session_id = request.header("session_id").expect("session_id header");
let request_session_id_hyphenated = request.header("session-id").expect("session-id header");
let request_thread_id = request.header("thread_id").expect("thread_id header");
let request_thread_id_hyphenated = request.header("thread-id").expect("thread-id header");
let installation_id =
std::fs::read_to_string(test.codex_home_path().join(INSTALLATION_ID_FILENAME))
.expect("read installation id");
assert_eq!(session_id, thread_id.to_string());
assert_eq!(request_session_id, expected_session_id.to_string());
assert_eq!(
request_session_id_hyphenated,
expected_session_id.to_string()
);
assert_eq!(request_thread_id, expected_thread_id.to_string());
assert_eq!(request_thread_id_hyphenated, expected_thread_id.to_string());
assert_eq!(request_originator, originator().value);
assert_eq!(request_authorization, "Bearer Access Token");
@@ -1101,13 +1130,20 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() {
Ok(None) => panic!("No CodexAuth found in codex_home"),
Err(e) => panic!("Failed to load CodexAuth: {e}"),
};
let installation_id = resolve_installation_id(&config.codex_home)
.await
.expect("resolve installation id");
let thread_manager = ThreadManager::new(
&config,
auth_manager,
SessionSource::Exec,
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
empty_extension_registry(),
/*analytics_events_client*/ None,
thread_store_from_config(&config),
thread_store_from_config(&config, /*state_db*/ None),
/*state_db*/ None,
installation_id,
/*attestation_provider*/ None,
);
let NewThread { thread: codex, .. } = thread_manager
.start_thread(config.clone())
@@ -1662,7 +1698,7 @@ async fn includes_no_effort_in_request() -> anyhow::Result<()> {
.get("reasoning")
.and_then(|t| t.get("effort"))
.and_then(|v| v.as_str()),
Some("xhigh")
Some("medium")
);
Ok(())
@@ -1704,7 +1740,7 @@ async fn includes_default_reasoning_effort_in_request_when_defined_by_model_info
.get("reasoning")
.and_then(|t| t.get("effort"))
.and_then(|v| v.as_str()),
Some("xhigh")
Some("medium")
);
Ok(())
@@ -2268,11 +2304,11 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
let config = Arc::new(config);
let model_info =
codex_core::test_support::construct_model_info_offline(model.as_str(), &config);
let conversation_id = ThreadId::new();
let thread_id = ThreadId::new();
let auth_manager =
codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("Test API Key"));
let session_telemetry = SessionTelemetry::new(
conversation_id,
thread_id,
model.as_str(),
model_info.slug.as_str(),
/*account_id*/ None,
@@ -2286,7 +2322,8 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
let client = ModelClient::new(
/*auth_manager*/ None,
conversation_id,
thread_id.into(),
thread_id,
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
provider.clone(),
SessionSource::Exec,
@@ -2294,6 +2331,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
/*enable_request_compression*/ false,
/*include_timing_metrics*/ false,
/*beta_features_header*/ None,
/*attestation_provider*/ None,
);
let mut client_session = client.new_session();
@@ -2459,38 +2497,6 @@ async fn token_count_includes_rate_limits_snapshot() {
.await
.unwrap();
let first_token_event =
wait_for_event(&codex, |msg| matches!(msg, EventMsg::TokenCount(_))).await;
let rate_limit_only = match first_token_event {
EventMsg::TokenCount(ev) => ev,
_ => unreachable!(),
};
let rate_limit_json = serde_json::to_value(&rate_limit_only).unwrap();
pretty_assertions::assert_eq!(
rate_limit_json,
json!({
"info": null,
"rate_limits": {
"limit_id": "codex",
"limit_name": null,
"primary": {
"used_percent": 12.5,
"window_minutes": 10,
"resets_at": 1704069000
},
"secondary": {
"used_percent": 40.0,
"window_minutes": 60,
"resets_at": 1704074400
},
"credits": null,
"plan_type": null,
"rate_limit_reached_type": null
}
})
);
let token_event = wait_for_event(
&codex,
|msg| matches!(msg, EventMsg::TokenCount(ev) if ev.info.is_some()),
+192 -7
View File
@@ -15,6 +15,7 @@ use codex_otel::MetricsConfig;
use codex_otel::SessionTelemetry;
use codex_otel::TelemetryAuthMode;
use codex_otel::current_span_w3c_trace_context;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::account::PlanType;
use codex_protocol::config_types::ReasoningSummary;
@@ -57,6 +58,8 @@ const USER_AGENT_HEADER: &str = "user-agent";
const WS_V2_BETA_HEADER_VALUE: &str = "responses_websockets=2026-02-06";
const X_CLIENT_REQUEST_ID_HEADER: &str = "x-client-request-id";
const TEST_INSTALLATION_ID: &str = "11111111-1111-4111-8111-111111111111";
const X_CODEX_WS_STREAM_REQUEST_START_MS_CLIENT_METADATA_KEY: &str =
"x-codex-ws-stream-request-start-ms";
fn assert_request_trace_matches(body: &serde_json::Value, expected_trace: &W3cTraceContext) {
let client_metadata = body["client_metadata"]
@@ -87,7 +90,8 @@ fn assert_request_trace_matches(body: &serde_json::Value, expected_trace: &W3cTr
struct WebsocketTestHarness {
_codex_home: TempDir,
client: ModelClient,
conversation_id: ThreadId,
session_id: SessionId,
thread_id: ThreadId,
model_info: ModelInfo,
effort: Option<ReasoningEffortConfig>,
summary: ReasoningSummary,
@@ -125,7 +129,15 @@ async fn responses_websocket_streams_request() {
);
assert_eq!(
handshake.header(X_CLIENT_REQUEST_ID_HEADER),
Some(harness.conversation_id.to_string())
Some(harness.thread_id.to_string())
);
assert_eq!(
handshake.header("session_id"),
Some(harness.session_id.to_string())
);
assert_eq!(
handshake.header("thread_id"),
Some(harness.thread_id.to_string())
);
assert_eq!(
handshake.header(USER_AGENT_HEADER),
@@ -135,6 +147,13 @@ async fn responses_websocket_streams_request() {
body["client_metadata"]["x-codex-installation-id"].as_str(),
Some(TEST_INSTALLATION_ID)
);
let stream_request_start_ms = body["client_metadata"]
[X_CODEX_WS_STREAM_REQUEST_START_MS_CLIENT_METADATA_KEY]
.as_str()
.expect("missing websocket stream request start timestamp")
.parse::<i64>()
.expect("websocket stream request start timestamp should be an integer");
assert!(stream_request_start_ms > 0);
server.shutdown().await;
}
@@ -161,6 +180,168 @@ async fn responses_websocket_streams_without_feature_flag_when_provider_supports
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responses_websocket_sends_response_processed_when_feature_enabled() {
skip_if_no_network!();
let server = start_websocket_server(vec![vec![
vec![
ev_response_created("resp-prewarm"),
ev_completed("resp-prewarm"),
],
vec![
ev_response_created("resp-1"),
ev_assistant_message("msg-1", "hi"),
ev_completed("resp-1"),
],
vec![],
]])
.await;
let mut builder = test_codex().with_config(|config| {
config
.features
.enable(Feature::ResponsesWebsocketResponseProcessed)
.expect("test config should allow feature update");
});
let test = builder
.build_with_websocket_server(&server)
.await
.expect("build websocket codex");
test.submit_turn("hello")
.await
.expect("submission should send response.processed after processing");
let processed = server
.wait_for_request(/*connection_index*/ 0, /*request_index*/ 2)
.await;
assert_eq!(
processed.body_json(),
json!({
"type": "response.processed",
"response_id": "resp-1",
})
);
let connection = server.single_connection();
assert_eq!(connection.len(), 3);
assert_eq!(
connection[1].body_json()["type"].as_str(),
Some("response.create")
);
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responses_websocket_sends_response_processed_after_remote_compaction_v2() {
skip_if_no_network!();
let server = start_websocket_server(vec![vec![
vec![
ev_response_created("resp-prewarm"),
ev_completed("resp-prewarm"),
],
vec![
ev_response_created("resp-1"),
ev_assistant_message("msg-1", "hi"),
ev_completed("resp-1"),
],
vec![],
vec![
json!({
"type": "response.output_item.done",
"item": {
"type": "context_compaction",
"encrypted_content": "ENCRYPTED_CONTEXT_COMPACTION_SUMMARY",
}
}),
ev_completed("resp-compact"),
],
vec![],
]])
.await;
let mut builder = test_codex().with_config(|config| {
config
.features
.enable(Feature::RemoteCompactionV2)
.expect("test config should allow feature update");
config
.features
.enable(Feature::ResponsesWebsocketResponseProcessed)
.expect("test config should allow feature update");
});
let test = builder
.build_with_websocket_server(&server)
.await
.expect("build websocket codex");
test.submit_turn("hello")
.await
.expect("submission should send response.processed after processing");
test.codex
.submit(Op::Compact)
.await
.expect("compact submission should succeed");
wait_for_event(&test.codex, |msg| matches!(msg, EventMsg::TurnComplete(_))).await;
let compact_processed = server
.wait_for_request(/*connection_index*/ 0, /*request_index*/ 4)
.await;
assert_eq!(
compact_processed.body_json(),
json!({
"type": "response.processed",
"response_id": "resp-compact",
})
);
let connection = server.single_connection();
assert_eq!(connection.len(), 5);
assert_eq!(
connection[3].body_json()["type"].as_str(),
Some("response.create")
);
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responses_websocket_omits_response_processed_without_feature() {
skip_if_no_network!();
let server = start_websocket_server(vec![vec![
vec![
ev_response_created("resp-prewarm"),
ev_completed("resp-prewarm"),
],
vec![
ev_response_created("resp-1"),
ev_assistant_message("msg-1", "hi"),
ev_completed("resp-1"),
],
vec![],
]])
.await;
let mut builder = test_codex();
let test = builder
.build_with_websocket_server(&server)
.await
.expect("build websocket codex");
test.submit_turn("hello")
.await
.expect("submission should complete without response.processed");
let connection = server.single_connection();
assert_eq!(connection.len(), 2);
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responses_websocket_reuses_connection_with_per_turn_trace_payloads() {
skip_if_no_network!();
@@ -1827,7 +2008,8 @@ async fn websocket_harness_with_provider_options(
}
let config = Arc::new(config);
let model_info = codex_core::test_support::construct_model_info_offline(MODEL, &config);
let conversation_id = ThreadId::new();
let thread_id = ThreadId::new();
let session_id = SessionId::new();
let auth_manager =
codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("Test API Key"));
let exporter = InMemoryMetricExporter::default();
@@ -1837,7 +2019,7 @@ async fn websocket_harness_with_provider_options(
)
.expect("in-memory metrics client");
let session_telemetry = SessionTelemetry::new(
conversation_id,
thread_id,
MODEL,
model_info.slug.as_str(),
/*account_id*/ None,
@@ -1853,7 +2035,8 @@ async fn websocket_harness_with_provider_options(
let summary = ReasoningSummary::Auto;
let client = ModelClient::new(
/*auth_manager*/ None,
conversation_id,
session_id,
thread_id,
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
provider.clone(),
SessionSource::Exec,
@@ -1861,12 +2044,14 @@ async fn websocket_harness_with_provider_options(
/*enable_request_compression*/ false,
runtime_metrics_enabled,
/*beta_features_header*/ None,
/*attestation_provider*/ None,
);
WebsocketTestHarness {
_codex_home: codex_home,
client,
conversation_id,
session_id,
thread_id,
model_info,
effort,
summary,
@@ -1935,7 +2120,7 @@ async fn stream_until_complete_with_request_metadata(
&harness.session_telemetry,
harness.effort,
harness.summary,
service_tier,
service_tier.map(|service_tier| service_tier.request_value().to_string()),
turn_metadata_header,
&codex_rollout_trace::InferenceTraceContext::disabled(),
)
-3
View File
@@ -2463,7 +2463,6 @@ text(JSON.stringify(Object.getOwnPropertyNames(globalThis).sort()));
"Array",
"ArrayBuffer",
"AsyncDisposableStack",
"Atomics",
"BigInt",
"BigInt64Array",
"BigUint64Array",
@@ -2498,7 +2497,6 @@ text(JSON.stringify(Object.getOwnPropertyNames(globalThis).sort()));
"Reflect",
"RegExp",
"Set",
"SharedArrayBuffer",
"String",
"SuppressedError",
"Symbol",
@@ -2513,7 +2511,6 @@ text(JSON.stringify(Object.getOwnPropertyNames(globalThis).sort()));
"WeakMap",
"WeakRef",
"WeakSet",
"WebAssembly",
"__codexContentItems",
"add_content",
"decodeURI",
+2 -2
View File
@@ -7,7 +7,7 @@ use codex_protocol::protocol::Op;
use codex_protocol::protocol::ReviewDecision;
use codex_protocol::protocol::ReviewRequest;
use codex_protocol::protocol::ReviewTarget;
use core_test_support::responses::ev_apply_patch_function_call;
use core_test_support::responses::ev_apply_patch_custom_tool_call;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call;
@@ -127,7 +127,7 @@ async fn codex_delegate_forwards_patch_approval_and_proceeds_on_decision() {
let patch = "*** Begin Patch\n*** Add File: delegated.txt\n+hello\n*** End Patch\n";
let sse1 = sse(vec![
ev_response_created("resp-1"),
ev_apply_patch_function_call(call_id, patch),
ev_apply_patch_custom_tool_call(call_id, patch),
ev_completed("resp-1"),
]);
let review_json = serde_json::json!({
@@ -210,6 +210,60 @@ async fn collaboration_instructions_added_on_user_turn() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn collaboration_instructions_omitted_when_disabled() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let req = mount_sse_once(
&server,
sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]),
)
.await;
let mut builder = test_codex().with_config(|config| {
config.include_collaboration_mode_instructions = false;
});
let test = builder.build(&server).await?;
let collaboration_mode = collab_mode_with_instructions(Some("turn instructions"));
test.codex
.submit(Op::UserTurn {
environments: None,
items: vec![UserInput::Text {
text: "hello".into(),
text_elements: Vec::new(),
}],
cwd: test.config.cwd.to_path_buf(),
approval_policy: test.config.permissions.approval_policy.value(),
approvals_reviewer: None,
sandbox_policy: test.config.legacy_sandbox_policy(),
permission_profile: None,
model: test.session_configured.model.clone(),
effort: None,
summary: Some(
test.config
.model_reasoning_summary
.unwrap_or(codex_protocol::config_types::ReasoningSummary::Auto),
),
service_tier: None,
collaboration_mode: Some(collaboration_mode),
final_output_json_schema: None,
personality: None,
})
.await?;
wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
let input = req.single_request().input();
let dev_texts = developer_texts(&input);
assert_eq!(
count_messages_containing(&dev_texts, COLLABORATION_MODE_OPEN_TAG),
0
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn override_then_next_turn_uses_updated_collaboration_instructions() -> Result<()> {
skip_if_no_network!(Ok(()));
+246
View File
@@ -13,6 +13,8 @@ use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelsResponse;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::HookEventName;
use codex_protocol::protocol::HookRunStatus;
use codex_protocol::protocol::ItemCompletedEvent;
use codex_protocol::protocol::ItemStartedEvent;
use codex_protocol::protocol::Op;
@@ -23,6 +25,7 @@ use codex_protocol::user_input::UserInput;
use core_test_support::context_snapshot;
use core_test_support::context_snapshot::ContextSnapshotOptions;
use core_test_support::context_snapshot::ContextSnapshotRenderMode;
use core_test_support::hooks::trust_discovered_hooks;
use core_test_support::responses::ev_local_shell_call;
use core_test_support::responses::ev_reasoning_item;
use core_test_support::responses::mount_models_once;
@@ -47,7 +50,10 @@ use core_test_support::responses::sse_failed;
use core_test_support::responses::sse_response;
use core_test_support::responses::start_mock_server;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::fs;
use std::path::Path;
use wiremock::MockServer;
// --- Test helpers -----------------------------------------------------------
@@ -119,6 +125,107 @@ fn json_fragment(text: &str) -> String {
.to_string()
}
fn read_hook_inputs(path: &Path) -> Vec<Value> {
let text = fs::read_to_string(path)
.unwrap_or_else(|err| panic!("failed to read hook input log {}: {err}", path.display()));
text.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| {
serde_json::from_str(line)
.unwrap_or_else(|err| panic!("failed to parse hook input log line: {err}"))
})
.collect()
}
fn python_hook_command(script_path: &Path) -> String {
format!("python3 \"{}\"", script_path.display())
}
fn write_unsupported_blocking_pre_compact_hook(home: &Path) {
let script_path = home.join("pre_compact_block.py");
let log_path = home.join("pre_compact_block_log.jsonl");
let script = format!(
r#"import json
from pathlib import Path
import sys
payload = json.load(sys.stdin)
with Path(r"{log_path}").open("a", encoding="utf-8") as handle:
handle.write(json.dumps(payload) + "\n")
print(json.dumps({{"decision": "block", "reason": "blocked by policy"}}))
"#,
log_path = log_path.display(),
);
let hooks = json!({
"hooks": {
"PreCompact": [{
"matcher": "manual",
"hooks": [{
"type": "command",
"command": python_hook_command(&script_path),
"statusMessage": "checking compact policy",
}]
}]
}
});
fs::write(&script_path, script).expect("write pre compact hook script");
fs::write(home.join("hooks.json"), hooks.to_string()).expect("write hooks.json");
}
fn write_matching_compact_hooks(home: &Path) {
let auto_script_path = home.join("pre_compact_auto.py");
let auto_log_path = home.join("pre_compact_auto_log.jsonl");
let manual_post_script_path = home.join("post_compact_manual.py");
let manual_post_log_path = home.join("post_compact_manual_log.jsonl");
let auto_script = format!(
r#"import json
from pathlib import Path
import sys
payload = json.load(sys.stdin)
with Path(r"{auto_log_path}").open("a", encoding="utf-8") as handle:
handle.write(json.dumps(payload) + "\n")
"#,
auto_log_path = auto_log_path.display(),
);
let manual_post_script = format!(
r#"import json
from pathlib import Path
import sys
payload = json.load(sys.stdin)
with Path(r"{manual_post_log_path}").open("a", encoding="utf-8") as handle:
handle.write(json.dumps(payload) + "\n")
"#,
manual_post_log_path = manual_post_log_path.display(),
);
let hooks = json!({
"hooks": {
"PreCompact": [{
"matcher": "auto",
"hooks": [{
"type": "command",
"command": python_hook_command(&auto_script_path),
}]
}],
"PostCompact": [{
"matcher": "manual",
"hooks": [{
"type": "command",
"command": python_hook_command(&manual_post_script_path),
}]
}]
}
});
fs::write(&auto_script_path, auto_script).expect("write auto pre compact hook script");
fs::write(&manual_post_script_path, manual_post_script)
.expect("write manual post compact hook script");
fs::write(home.join("hooks.json"), hooks.to_string()).expect("write hooks.json");
}
fn non_openai_model_provider(server: &MockServer) -> ModelProviderInfo {
let mut provider =
built_in_model_providers(/* openai_base_url */ /*openai_base_url*/ None)["openai"].clone();
@@ -437,6 +544,145 @@ async fn summarize_context_three_requests_and_instructions() {
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn manual_pre_compact_block_decision_does_not_block_compaction() {
skip_if_no_network!();
let server = start_mock_server().await;
let first_turn = sse(vec![
ev_assistant_message("m0", FIRST_REPLY),
ev_completed_with_tokens("r0", /*total_tokens*/ 80),
]);
let compact_turn = sse(vec![
ev_assistant_message("m1", SUMMARY_TEXT),
ev_completed_with_tokens("r1", /*total_tokens*/ 100),
]);
let request_log = mount_sse_sequence(&server, vec![first_turn, compact_turn]).await;
let model_provider = non_openai_model_provider(&server);
let mut builder = test_codex()
.with_pre_build_hook(write_unsupported_blocking_pre_compact_hook)
.with_config(move |config| {
config.model_provider = model_provider;
trust_discovered_hooks(config);
set_test_compact_prompt(config);
});
let test = builder.build(&server).await.expect("create conversation");
let codex = test.codex.clone();
codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "hello before blocked compact".to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await
.expect("submit first user turn");
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
codex.submit(Op::Compact).await.expect("trigger compact");
let completed = wait_for_event_match(&codex, |ev| match ev {
EventMsg::HookCompleted(completed)
if completed.run.event_name == HookEventName::PreCompact =>
{
Some(completed.clone())
}
_ => None,
})
.await;
assert_eq!(completed.run.status, HookRunStatus::Failed);
wait_for_event(&codex, |ev| matches!(ev, EventMsg::Warning(_))).await;
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
let requests = request_log.requests();
assert_eq!(
requests.len(),
2,
"unsupported PreCompact block output should not prevent the compact request"
);
let hook_inputs = read_hook_inputs(&test.codex_home_path().join("pre_compact_block_log.jsonl"));
assert_eq!(hook_inputs.len(), 1);
let input = &hook_inputs[0];
assert_eq!(input["hook_event_name"], "PreCompact");
assert_eq!(input["trigger"], "manual");
assert!(input.get("reason").is_none());
assert!(input.get("phase").is_none());
assert!(input.get("implementation").is_none());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn compact_hooks_respect_matchers_and_post_runs_after_compaction() {
skip_if_no_network!();
let server = start_mock_server().await;
let first_turn = sse(vec![
ev_assistant_message("m0", FIRST_REPLY),
ev_completed_with_tokens("r0", /*total_tokens*/ 80),
]);
let compact_turn = sse(vec![
ev_assistant_message("m1", SUMMARY_TEXT),
ev_completed_with_tokens("r1", /*total_tokens*/ 100),
]);
let request_log = mount_sse_sequence(&server, vec![first_turn, compact_turn]).await;
let model_provider = non_openai_model_provider(&server);
let mut builder = test_codex()
.with_pre_build_hook(write_matching_compact_hooks)
.with_config(move |config| {
config.model_provider = model_provider;
trust_discovered_hooks(config);
set_test_compact_prompt(config);
});
let test = builder.build(&server).await.expect("create conversation");
let codex = test.codex.clone();
codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "hello before matched compact".to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await
.expect("submit first user turn");
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
codex.submit(Op::Compact).await.expect("trigger compact");
wait_for_event(&codex, |ev| matches!(ev, EventMsg::Warning(_))).await;
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
assert_eq!(request_log.requests().len(), 2);
assert!(
!test
.codex_home_path()
.join("pre_compact_auto_log.jsonl")
.exists(),
"auto matcher should not run for manual compaction"
);
let hook_inputs =
read_hook_inputs(&test.codex_home_path().join("post_compact_manual_log.jsonl"));
assert_eq!(hook_inputs.len(), 1);
let input = &hook_inputs[0];
assert_eq!(input["hook_event_name"], "PostCompact");
assert_eq!(input["trigger"], "manual");
assert!(input.get("compact_summary").is_none());
assert!(input.get("status").is_none());
assert!(input.get("error").is_none());
assert!(input.get("reason").is_none());
assert!(input.get("phase").is_none());
assert!(input.get("implementation").is_none());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn manual_compact_uses_custom_prompt() {
skip_if_no_network!();
+488
View File
@@ -5,7 +5,9 @@ use std::path::PathBuf;
use anyhow::Result;
use codex_core::compact::SUMMARY_PREFIX;
use codex_features::Feature;
use codex_login::CodexAuth;
use codex_protocol::config_types::ServiceTier;
use codex_protocol::dynamic_tools::DynamicToolSpec;
use codex_protocol::items::TurnItem;
use codex_protocol::models::ContentItem;
@@ -104,6 +106,23 @@ fn contains_defer_loading(value: &Value) -> bool {
}
}
fn canonical_json(value: &Value) -> Value {
match value {
Value::Object(map) => {
let mut entries = map.iter().collect::<Vec<_>>();
entries.sort_by(|(left_key, _), (right_key, _)| left_key.cmp(right_key));
Value::Object(
entries
.into_iter()
.map(|(key, value)| (key.clone(), canonical_json(value)))
.collect(),
)
}
Value::Array(values) => Value::Array(values.iter().map(canonical_json).collect()),
Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => value.clone(),
}
}
const PRETURN_CONTEXT_DIFF_CWD: &str = "/tmp/PRETURN_CONTEXT_DIFF_CWD";
const DUMMY_FUNCTION_NAME: &str = "test_tool";
const REMOTE_COMPACT_TURN_COMPLETE_TIMEOUT: Duration = Duration::from_secs(30);
@@ -272,6 +291,7 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> {
.await?;
let codex = harness.test().codex.clone();
let session_id = harness.test().session_configured.session_id.to_string();
let thread_id = harness.test().session_configured.thread_id.to_string();
let responses_mock = responses::mount_sse_sequence(
harness.server(),
@@ -340,6 +360,10 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> {
compact_request.header("session_id").as_deref(),
Some(session_id.as_str())
);
assert_eq!(
compact_request.header("thread_id").as_deref(),
Some(thread_id.as_str())
);
let compact_body = compact_request.body_json();
assert_eq!(
compact_body.get("model").and_then(|v| v.as_str()),
@@ -411,6 +435,465 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> {
Ok(())
}
async fn assert_remote_manual_compact_request_parity(
auth: CodexAuth,
configured_service_tier: Option<ServiceTier>,
expected_service_tier: Option<&str>,
snapshot_name: &str,
scenario: &str,
) -> Result<()> {
let mut builder = test_codex().with_auth(auth);
if let Some(service_tier) = configured_service_tier {
builder = builder.with_config(move |config| {
config.service_tier = Some(service_tier.request_value().to_string());
});
}
let harness = TestCodexHarness::with_builder(builder).await?;
let codex = harness.test().codex.clone();
let image_url =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGNgYAAAAAMAASsJTYQAAAAASUVORK5CYII="
.to_string();
let responses_mock = responses::mount_sse_sequence(
harness.server(),
vec![
responses::sse(vec![
responses::ev_assistant_message("turn-one-assistant", "TURN_ONE_ASSISTANT"),
responses::ev_completed("turn-one-response"),
]),
responses::sse(vec![
responses::ev_reasoning_item(
"turn-two-reasoning",
&["TURN_TWO_REASONING"],
&["turn two raw content"],
),
responses::ev_assistant_message("turn-two-assistant", "TURN_TWO_ASSISTANT"),
responses::ev_completed("turn-two-response"),
]),
responses::sse(vec![
responses::ev_function_call("turn-three-call", DUMMY_FUNCTION_NAME, "{}"),
responses::ev_completed("turn-three-call-response"),
]),
responses::sse(vec![
responses::ev_assistant_message("turn-three-assistant", "TURN_THREE_ASSISTANT"),
responses::ev_completed("turn-three-final-response"),
]),
responses::sse(vec![
responses::ev_local_shell_call(
"turn-four-local-shell",
"completed",
vec!["/bin/echo", "TURN_FOUR_LOCAL_SHELL"],
),
responses::ev_completed("turn-four-local-shell-response"),
]),
responses::sse(vec![
responses::ev_assistant_message("turn-four-assistant", "TURN_FOUR_ASSISTANT"),
responses::ev_completed("turn-four-final-response"),
]),
responses::sse(vec![
responses::ev_reasoning_item(
"turn-five-reasoning",
&["TURN_FIVE_REASONING"],
&["turn five raw content"],
),
responses::ev_assistant_message("turn-five-assistant", "TURN_FIVE_ASSISTANT"),
responses::ev_completed("turn-five-response"),
]),
],
)
.await;
let compact_mock = responses::mount_compact_user_history_with_summary_once(
harness.server(),
"REMOTE_CACHE_TIER_SUMMARY",
)
.await;
codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "TURN_ONE_USER".to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await?;
wait_for_turn_complete(&codex).await;
codex
.submit(Op::UserInput {
environments: None,
items: vec![
UserInput::Text {
text: "TURN_TWO_PREFIX".to_string(),
text_elements: Vec::new(),
},
UserInput::Text {
text: "TURN_TWO_SUFFIX".to_string(),
text_elements: Vec::new(),
},
],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await?;
wait_for_turn_complete(&codex).await;
codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "TURN_THREE_TOOL_USER".to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await?;
wait_for_turn_complete(&codex).await;
codex
.submit(Op::UserInput {
environments: None,
items: vec![
UserInput::Image { image_url },
UserInput::Text {
text: "TURN_FOUR_IMAGE_USER".to_string(),
text_elements: Vec::new(),
},
],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await?;
wait_for_turn_complete(&codex).await;
codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "TURN_FIVE_USER".to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await?;
wait_for_turn_complete(&codex).await;
codex.submit(Op::Compact).await?;
wait_for_turn_complete(&codex).await;
let response_requests = responses_mock.requests();
assert_eq!(
response_requests.len(),
7,
"expected five turns with one unsupported tool continuation and one local shell continuation"
);
assert_eq!(
compact_mock.requests().len(),
1,
"expected exactly one remote compact request"
);
let normal_request = response_requests
.last()
.cloned()
.expect("last turn request missing");
let compact_request = compact_mock.single_request();
let normal_body = normal_request.body_json();
let compact_body = compact_request.body_json();
let mut expected_compact_body_without_input = normal_body.clone();
let expected_compact_object = expected_compact_body_without_input
.as_object_mut()
.expect("responses request body should be an object");
for field in [
"input",
"client_metadata",
"include",
"store",
"stream",
"tool_choice",
] {
expected_compact_object.remove(field);
}
if expected_service_tier.is_none() {
expected_compact_object.remove("service_tier");
}
let mut compact_body_without_input = compact_body.clone();
compact_body_without_input
.as_object_mut()
.expect("compact request body should be an object")
.remove("input");
let canonical_compact_body_without_input = canonical_json(&compact_body_without_input);
let canonical_expected_compact_body_without_input =
canonical_json(&expected_compact_body_without_input);
assert_eq!(
json!({
"compact_body_without_input": canonical_compact_body_without_input,
"expected_compact_body_without_input": canonical_expected_compact_body_without_input,
"prompt_cache_key_matches_responses": compact_body["prompt_cache_key"] == normal_body["prompt_cache_key"],
"prompt_cache_key_present": compact_body["prompt_cache_key"].is_string(),
"service_tier": compact_body.get("service_tier").and_then(Value::as_str),
}),
json!({
"compact_body_without_input": canonical_expected_compact_body_without_input,
"expected_compact_body_without_input": canonical_expected_compact_body_without_input,
"prompt_cache_key_matches_responses": true,
"prompt_cache_key_present": true,
"service_tier": expected_service_tier,
}),
"compact requests should carry the same shared request fields as /responses"
);
insta::assert_snapshot!(
snapshot_name,
context_snapshot::format_request_body_diff_snapshot(
scenario,
"Last Normal /responses Request",
&normal_request,
"Remote /responses/compact Request",
&compact_request,
&ContextSnapshotOptions::default(),
)
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_manual_compact_api_auth_omits_service_tier_and_reuses_prompt_cache_key()
-> Result<()> {
skip_if_no_network!(Ok(()));
assert_remote_manual_compact_request_parity(
CodexAuth::from_api_key("dummy"),
Some(ServiceTier::Fast),
/*expected_service_tier*/ None,
"remote_manual_compact_api_auth_prompt_cache_key_request_diff",
"After five varied API-key-auth turns, remote manual compaction omits service_tier, reuses prompt_cache_key, and still omits responses-only fields.",
)
.await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_manual_compact_chatgpt_auth_reuses_service_tier_and_prompt_cache_key() -> Result<()>
{
skip_if_no_network!(Ok(()));
assert_remote_manual_compact_request_parity(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
Some(ServiceTier::Fast),
Some("priority"),
"remote_manual_compact_chatgpt_auth_service_tier_prompt_cache_key_request_diff",
"After five varied ChatGPT-auth turns, remote manual compaction reuses service_tier and prompt_cache_key while omitting responses-only fields.",
)
.await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_compact_v2_reuses_context_compaction_for_followups() -> Result<()> {
skip_if_no_network!(Ok(()));
let harness = TestCodexHarness::with_builder(
test_codex()
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_config(|config| {
let _ = config.features.enable(Feature::RemoteCompactionV2);
}),
)
.await?;
let codex = harness.test().codex.clone();
let responses_mock = responses::mount_sse_sequence(
harness.server(),
vec![
responses::sse(vec![
responses::ev_assistant_message("m1", "FIRST_REMOTE_REPLY"),
responses::ev_completed("resp-1"),
]),
responses::sse(vec![
serde_json::json!({
"type": "response.output_item.done",
"item": {
"type": "context_compaction",
"encrypted_content": "ENCRYPTED_CONTEXT_COMPACTION_SUMMARY",
}
}),
responses::ev_completed("resp-compact"),
]),
responses::sse(vec![
responses::ev_assistant_message("m2", "AFTER_COMPACT_REPLY"),
responses::ev_completed("resp-2"),
]),
],
)
.await;
codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "hello remote compact".into(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await?;
wait_for_turn_complete(&codex).await;
codex.submit(Op::Compact).await?;
wait_for_turn_complete(&codex).await;
codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "after compact".into(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await?;
wait_for_turn_complete(&codex).await;
let response_requests = responses_mock.requests();
let compact_request = &response_requests[1];
assert!(
compact_request
.header("x-codex-beta-features")
.as_deref()
.is_some_and(|value| value
.split(',')
.any(|feature| feature == "remote_compaction_v2")),
"expected compact request to advertise the remote_compaction_v2 beta feature"
);
assert_eq!(compact_request.path(), "/v1/responses");
let compact_body = compact_request.body_json().to_string();
assert!(
compact_body.contains("\"type\":\"context_compaction\""),
"expected v2 compaction request to include the context_compaction trigger item"
);
assert!(
!compact_body.contains("ENCRYPTED_CONTEXT_COMPACTION_SUMMARY"),
"expected v2 compaction trigger item to omit encrypted_content"
);
let follow_up_request = response_requests.last().expect("follow-up request missing");
let follow_up_body = follow_up_request.body_json().to_string();
assert!(
follow_up_body.contains("\"type\":\"context_compaction\""),
"expected follow-up request to preserve the v2 context_compaction item"
);
assert!(
follow_up_body.contains("ENCRYPTED_CONTEXT_COMPACTION_SUMMARY"),
"expected follow-up request to include the context compaction payload"
);
assert!(
follow_up_body.contains("hello remote compact"),
"expected v2 follow-up request to preserve retained original user messages"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_compact_v2_accepts_additional_output_items_before_context_compaction() -> Result<()>
{
skip_if_no_network!(Ok(()));
let harness = TestCodexHarness::with_builder(
test_codex()
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_config(|config| {
let _ = config.features.enable(Feature::RemoteCompactionV2);
}),
)
.await?;
let codex = harness.test().codex.clone();
let responses_mock = responses::mount_sse_sequence(
harness.server(),
vec![
responses::sse(vec![
responses::ev_assistant_message("m1", "FIRST_REMOTE_REPLY"),
responses::ev_completed("resp-1"),
]),
responses::sse(vec![
responses::ev_assistant_message("m-compact-noise", "IGNORED_COMPACT_REPLY"),
serde_json::json!({
"type": "response.output_item.done",
"item": {
"type": "context_compaction",
"encrypted_content": "ENCRYPTED_CONTEXT_COMPACTION_SUMMARY",
}
}),
responses::ev_completed("resp-compact"),
]),
responses::sse(vec![
responses::ev_assistant_message("m2", "AFTER_COMPACT_REPLY"),
responses::ev_completed("resp-2"),
]),
],
)
.await;
codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "hello remote compact".into(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await?;
wait_for_turn_complete(&codex).await;
codex.submit(Op::Compact).await?;
wait_for_turn_complete(&codex).await;
codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "after compact".into(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await?;
wait_for_turn_complete(&codex).await;
let response_requests = responses_mock.requests();
let follow_up_request = response_requests.last().expect("follow-up request missing");
let follow_up_body = follow_up_request.body_json().to_string();
assert!(
follow_up_body.contains("\"type\":\"context_compaction\""),
"expected follow-up request to preserve the v2 context_compaction item"
);
assert!(
follow_up_body.contains("ENCRYPTED_CONTEXT_COMPACTION_SUMMARY"),
"expected follow-up request to include the context compaction payload"
);
assert!(
!follow_up_body.contains("IGNORED_COMPACT_REPLY"),
"expected follow-up request to ignore unrelated output items from the compaction stream"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_compact_filters_deferred_dynamic_tools() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -515,6 +998,7 @@ async fn remote_compact_runs_automatically() -> Result<()> {
.await?;
let codex = harness.test().codex.clone();
let session_id = harness.test().session_configured.session_id.to_string();
let thread_id = harness.test().session_configured.thread_id.to_string();
mount_sse_once(
harness.server(),
@@ -566,6 +1050,10 @@ async fn remote_compact_runs_automatically() -> Result<()> {
.as_deref(),
Some(session_id.as_str())
);
assert_eq!(
compact_mock.single_request().header("thread_id").as_deref(),
Some(thread_id.as_str())
);
let follow_up_request = responses_mock.single_request();
let follow_up_body = follow_up_request.body_json().to_string();
assert!(follow_up_body.contains("REMOTE_COMPACTED_SUMMARY"));
@@ -855,6 +855,7 @@ async fn fork_thread(
nth_user_message,
config.clone(),
path,
/*thread_source*/ None,
/*persist_extended_history*/ false,
/*parent_trace*/ None,
))
@@ -115,38 +115,6 @@ async fn emits_deprecation_notice_for_experimental_instructions_file() -> anyhow
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn emits_deprecation_notice_for_notify() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mut builder = test_codex().with_config(|config| {
config.notify = Some(vec!["notify-send".to_string(), "Codex".to_string()]);
});
let TestCodex { codex, .. } = builder.build(&server).await?;
let notice = wait_for_event_match(&codex, |event| match event {
EventMsg::DeprecationNotice(ev) if ev.summary.contains("`notify`") => Some(ev.clone()),
_ => None,
})
.await;
let DeprecationNoticeEvent { summary, details } = notice;
assert_eq!(
summary,
"`notify` is deprecated and will be removed in a future release.".to_string(),
);
assert_eq!(
details.as_deref(),
Some(
"Switch to a `Stop` hook for end-of-turn automation. See https://developers.openai.com/codex/hooks."
),
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn emits_deprecation_notice_for_web_search_feature_flag_values() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
+4 -1
View File
@@ -101,6 +101,7 @@ async fn fork_thread_twice_drops_to_first_message() {
ForkSnapshot::TruncateBeforeNthUserMessage(1),
config_for_fork.clone(),
base_path.clone(),
/*thread_source*/ None,
/*persist_extended_history*/ false,
/*parent_trace*/ None,
)
@@ -125,6 +126,7 @@ async fn fork_thread_twice_drops_to_first_message() {
ForkSnapshot::TruncateBeforeNthUserMessage(0),
config_for_fork.clone(),
fork1_path.clone(),
/*thread_source*/ None,
/*persist_extended_history*/ false,
/*parent_trace*/ None,
)
@@ -193,10 +195,11 @@ async fn fork_thread_from_history_does_not_require_source_rollout_path() {
ForkSnapshot::Interrupted,
test.config.clone(),
InitialHistory::Resumed(ResumedHistory {
conversation_id: test.session_configured.session_id,
conversation_id: test.session_configured.thread_id,
history: source_items.clone(),
rollout_path: None,
}),
/*thread_source*/ None,
/*persist_extended_history*/ false,
/*parent_trace*/ None,
)
File diff suppressed because it is too large Load Diff
+116 -4
View File
@@ -9,7 +9,7 @@ use codex_config::types::AppToolApproval;
use codex_config::types::McpServerConfig;
use codex_config::types::McpServerTransportConfig;
use codex_core::config::Config;
use codex_features::Feature;
use core_test_support::hooks::trust_discovered_hooks;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call_with_namespace;
@@ -74,6 +74,50 @@ print(json.dumps({{
Ok(())
}
fn write_updating_pre_tool_use_hook(home: &Path, updated_message: &str) -> Result<()> {
let script_path = home.join("pre_tool_use_hook.py");
let log_path = home.join("pre_tool_use_hook_log.jsonl");
let updated_message_json =
serde_json::to_string(updated_message).context("serialize updated MCP message")?;
let script = format!(
r#"import json
from pathlib import Path
import sys
payload = json.load(sys.stdin)
with Path(r"{log_path}").open("a", encoding="utf-8") as handle:
handle.write(json.dumps(payload) + "\n")
print(json.dumps({{
"hookSpecificOutput": {{
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"updatedInput": {{ "message": {updated_message_json} }}
}}
}}))
"#,
log_path = log_path.display(),
updated_message_json = updated_message_json,
);
let hooks = serde_json::json!({
"hooks": {
"PreToolUse": [{
"matcher": RMCP_HOOK_MATCHER,
"hooks": [{
"type": "command",
"command": format!("python3 {}", script_path.display()),
"statusMessage": "rewriting MCP pre tool input",
}]
}]
}
});
fs::write(&script_path, script).context("write updating pre tool use hook script")?;
fs::write(home.join("hooks.json"), hooks.to_string()).context("write hooks.json")?;
Ok(())
}
fn write_post_tool_use_hook(home: &Path, additional_context: &str) -> Result<()> {
let script_path = home.join("post_tool_use_hook.py");
let log_path = home.join("post_tool_use_hook_log.jsonl");
@@ -205,9 +249,7 @@ fn enable_hooks_and_rmcp_server(
rmcp_test_server_bin: String,
approval_mode: AppToolApproval,
) {
if let Err(err) = config.features.enable(Feature::CodexHooks) {
panic!("test config should allow feature update: {err}");
}
trust_discovered_hooks(config);
insert_rmcp_test_server(config, rmcp_test_server_bin, approval_mode);
}
@@ -293,6 +335,76 @@ async fn pre_tool_use_blocks_mcp_tool_before_execution() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pre_tool_use_rewrites_mcp_tool_before_execution() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let call_id = "pretooluse-rmcp-echo-rewrite";
let rewritten_message = "rewritten mcp hook input";
let arguments = json!({ "message": RMCP_ECHO_MESSAGE }).to_string();
let call_mock = mount_sse_once(
&server,
sse(vec![
ev_response_created("resp-1"),
ev_function_call_with_namespace(call_id, RMCP_NAMESPACE, "echo", &arguments),
ev_completed("resp-1"),
]),
)
.await;
let final_mock = mount_sse_once(
&server,
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "mcp pre hook rewrote it"),
ev_completed("resp-2"),
]),
)
.await;
let rmcp_test_server_bin = stdio_server_bin()?;
let test = test_codex()
.with_pre_build_hook(move |home| {
if let Err(error) = write_updating_pre_tool_use_hook(home, rewritten_message) {
panic!("failed to write MCP updating pre tool use hook fixture: {error}");
}
})
.with_config(move |config| {
enable_hooks_and_rmcp_server(config, rmcp_test_server_bin, AppToolApproval::Approve);
})
.build(&server)
.await?;
test.submit_turn("call the rmcp echo tool with the MCP pre hook rewrite")
.await?;
let final_request = final_mock.single_request();
let output_item = final_request.function_call_output(call_id);
let output = output_item
.get("output")
.and_then(Value::as_str)
.expect("MCP tool output string");
assert!(
output.contains(&format!("ECHOING: {rewritten_message}")),
"MCP tool should execute the rewritten input",
);
assert!(
!output.contains(RMCP_ECHO_MESSAGE),
"MCP tool should not execute the original input",
);
let hook_inputs = read_hook_inputs(test.codex_home_path(), "pre_tool_use_hook_log.jsonl")?;
assert_eq!(hook_inputs.len(), 1);
assert_eq!(
hook_inputs[0]["tool_input"],
json!({ "message": RMCP_ECHO_MESSAGE }),
);
call_mock.single_request();
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn post_tool_use_records_mcp_tool_payload_and_context() -> Result<()> {
skip_if_no_network!(Ok(()));
+43 -8
View File
@@ -303,6 +303,15 @@ async fn web_search_item_is_emitted() -> anyhow::Result<()> {
})
.await?;
let started = wait_for_event_match(&codex, |ev| match ev {
EventMsg::ItemStarted(ItemStartedEvent {
item: TurnItem::WebSearch(item),
started_at_ms,
..
}) => Some((item.clone(), *started_at_ms)),
_ => None,
})
.await;
let begin = wait_for_event_match(&codex, |ev| match ev {
EventMsg::WebSearchBegin(event) => Some(event.clone()),
_ => None,
@@ -311,16 +320,20 @@ async fn web_search_item_is_emitted() -> anyhow::Result<()> {
let completed = wait_for_event_match(&codex, |ev| match ev {
EventMsg::ItemCompleted(ItemCompletedEvent {
item: TurnItem::WebSearch(item),
completed_at_ms,
..
}) => Some(item.clone()),
}) => Some((item.clone(), *completed_at_ms)),
_ => None,
})
.await;
assert_eq!(begin.call_id, "web-search-1");
assert_eq!(completed.id, begin.call_id);
assert_eq!(started.0.id, begin.call_id);
assert!(started.1 > 0);
assert_eq!(completed.0.id, begin.call_id);
assert!(completed.1 > 0);
assert_eq!(
completed.action,
completed.0.action,
WebSearchAction::Search {
query: Some("weather seattle".to_string()),
queries: None,
@@ -345,7 +358,7 @@ async fn image_generation_call_event_is_emitted() -> anyhow::Result<()> {
let call_id = "ig_image_saved_to_temp_dir_default";
let expected_saved_path = image_generation_artifact_path(
config.codex_home.as_path(),
&session_configured.session_id.to_string(),
&session_configured.thread_id.to_string(),
call_id,
);
let _ = std::fs::remove_file(&expected_saved_path);
@@ -369,11 +382,29 @@ async fn image_generation_call_event_is_emitted() -> anyhow::Result<()> {
})
.await?;
let started = wait_for_event_match(&codex, |ev| match ev {
EventMsg::ItemStarted(ItemStartedEvent {
item: TurnItem::ImageGeneration(item),
started_at_ms,
..
}) => Some((item.clone(), *started_at_ms)),
_ => None,
})
.await;
let begin = wait_for_event_match(&codex, |ev| match ev {
EventMsg::ImageGenerationBegin(event) => Some(event.clone()),
_ => None,
})
.await;
let completed = wait_for_event_match(&codex, |ev| match ev {
EventMsg::ItemCompleted(ItemCompletedEvent {
item: TurnItem::ImageGeneration(item),
completed_at_ms,
..
}) => Some((item.clone(), *completed_at_ms)),
_ => None,
})
.await;
let end = wait_for_event_match(&codex, |ev| match ev {
EventMsg::ImageGenerationEnd(event) => Some(event.clone()),
_ => None,
@@ -381,6 +412,10 @@ async fn image_generation_call_event_is_emitted() -> anyhow::Result<()> {
.await;
assert_eq!(begin.call_id, call_id);
assert_eq!(started.0.id, call_id);
assert!(started.1 > 0);
assert_eq!(completed.0.id, call_id);
assert!(completed.1 > 0);
assert_eq!(end.call_id, call_id);
assert_eq!(end.status, "completed");
assert_eq!(end.revised_prompt, Some("A tiny blue square".to_string()));
@@ -409,7 +444,7 @@ async fn image_generation_call_event_is_emitted_when_image_save_fails() -> anyho
} = test_codex().build(&server).await?;
let expected_saved_path = image_generation_artifact_path(
config.codex_home.as_path(),
&session_configured.session_id.to_string(),
&session_configured.thread_id.to_string(),
"ig_invalid",
);
let _ = std::fs::remove_file(&expected_saved_path);
@@ -512,8 +547,8 @@ async fn agent_message_content_delta_has_item_metadata() -> anyhow::Result<()> {
})
.await;
let session_id = session_configured.session_id.to_string();
assert_eq!(delta_event.thread_id, session_id);
let thread_id = session_configured.thread_id.to_string();
assert_eq!(delta_event.thread_id, thread_id);
assert_eq!(delta_event.turn_id, started_turn_id);
assert_eq!(delta_event.item_id, started_item.id);
assert_eq!(delta_event.delta, "streamed response");
@@ -579,7 +614,7 @@ async fn plan_mode_emits_plan_item_from_proposed_plan_block() -> anyhow::Result<
assert_eq!(
plan_delta.thread_id,
session_configured.session_id.to_string()
session_configured.thread_id.to_string()
);
assert_eq!(plan_delta.delta, "- Step 1\n- Step 2\n");
assert_eq!(plan_completed.text, "- Step 1\n- Step 2\n");
-157
View File
@@ -1,157 +0,0 @@
#![allow(clippy::expect_used, clippy::unwrap_used)]
use std::fs;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
use anyhow::Result;
use codex_config::config_toml::ProjectConfig;
use codex_protocol::config_types::TrustLevel;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::user_input::UserInput;
use core_test_support::responses;
use core_test_support::responses::ResponsesRequest;
use core_test_support::responses::mount_sse_sequence;
use core_test_support::responses::start_mock_server;
use core_test_support::test_codex::TestCodex;
use core_test_support::test_codex::test_codex;
use core_test_support::test_codex::turn_permission_fields;
use core_test_support::wait_for_event;
use tokio::time::timeout;
fn enable_trusted_project(config: &mut codex_core::config::Config) {
config.active_project = ProjectConfig {
trust_level: Some(TrustLevel::Trusted),
};
}
fn write_skill(home: &Path, name: &str, description: &str, body: &str) -> PathBuf {
let skill_dir = home.join("skills").join(name);
fs::create_dir_all(&skill_dir).expect("create skill dir");
let contents = format!("---\nname: {name}\ndescription: {description}\n---\n\n{body}\n");
let path = skill_dir.join("SKILL.md");
fs::write(&path, contents).expect("write skill");
path
}
fn contains_skill_body(request: &ResponsesRequest, skill_body: &str) -> bool {
request
.message_input_texts("user")
.iter()
.any(|text| text.contains(skill_body) && text.contains("<skill>"))
}
async fn submit_skill_turn(test: &TestCodex, skill_path: PathBuf, prompt: &str) -> Result<()> {
let session_model = test.session_configured.model.clone();
let (sandbox_policy, permission_profile) =
turn_permission_fields(PermissionProfile::Disabled, test.cwd_path());
test.codex
.submit(Op::UserTurn {
environments: None,
items: vec![
UserInput::Text {
text: prompt.to_string(),
text_elements: Vec::new(),
},
UserInput::Skill {
name: "demo".to_string(),
path: skill_path,
},
],
final_output_json_schema: None,
cwd: test.cwd_path().to_path_buf(),
approval_policy: AskForApproval::Never,
approvals_reviewer: None,
sandbox_policy,
permission_profile,
model: session_model,
effort: None,
summary: None,
service_tier: None,
collaboration_mode: None,
personality: None,
})
.await?;
wait_for_event(test.codex.as_ref(), |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn live_skills_reload_refreshes_skill_cache_after_skill_change() -> Result<()> {
let server = start_mock_server().await;
let responses = mount_sse_sequence(
&server,
vec![
responses::sse(vec![responses::ev_completed("resp-1")]),
responses::sse(vec![responses::ev_completed("resp-2")]),
],
)
.await;
let skill_v1 = "skill body v1";
let skill_v2 = "skill body v2";
let mut builder = test_codex()
.with_pre_build_hook(move |home| {
write_skill(home, "demo", "demo skill", skill_v1);
})
.with_config(|config| {
enable_trusted_project(config);
});
let test = builder.build(&server).await?;
let skill_path = dunce::canonicalize(test.codex_home_path().join("skills/demo/SKILL.md"))?;
submit_skill_turn(&test, skill_path.clone(), "please use $demo").await?;
let first_request = responses
.requests()
.first()
.cloned()
.expect("first request captured");
assert!(
contains_skill_body(&first_request, skill_v1),
"expected initial skill body in request"
);
write_skill(test.codex_home_path(), "demo", "demo skill", skill_v2);
let saw_skills_update = timeout(Duration::from_secs(5), async {
loop {
match test.codex.next_event().await {
Ok(event) => {
if matches!(event.msg, EventMsg::SkillsUpdateAvailable) {
break;
}
}
Err(err) => panic!("event stream ended unexpectedly: {err}"),
}
}
})
.await;
if saw_skills_update.is_err() {
// Some environments do not reliably surface file watcher events for
// skill changes. Clear the cache explicitly so we can still validate
// that the updated skill body is injected on the next turn.
test.thread_manager.skills_manager().clear_cache();
}
submit_skill_turn(&test, skill_path.clone(), "please use $demo again").await?;
let last_request = responses
.last_request()
.expect("request captured after skill update");
assert!(
contains_skill_body(&last_request, skill_v2),
"expected updated skill body after reload"
);
Ok(())
}
+8 -2
View File
@@ -1,5 +1,6 @@
// Aggregates all former standalone integration tests as modules.
use codex_apply_patch::CODEX_CORE_APPLY_PATCH_ARG1;
use codex_exec_server::CODEX_FS_HELPER_ARG1;
use codex_sandboxing::landlock::CODEX_LINUX_SANDBOX_ARG0;
use codex_test_binary_support::TestBinaryDispatchGuard;
use codex_test_binary_support::TestBinaryDispatchMode;
@@ -16,6 +17,9 @@ pub static CODEX_ALIASES_TEMP_DIR: Option<TestBinaryDispatchGuard> = {
if argv1 == Some(CODEX_CORE_APPLY_PATCH_ARG1) {
return TestBinaryDispatchMode::DispatchArg0Only;
}
if argv1 == Some(CODEX_FS_HELPER_ARG1) {
return TestBinaryDispatchMode::DispatchArg0Only;
}
if exe_name == CODEX_LINUX_SANDBOX_ARG0 {
return TestBinaryDispatchMode::DispatchArg0Only;
}
@@ -53,7 +57,6 @@ mod image_rollout;
mod items;
mod json_result;
mod live_cli;
mod live_reload;
mod model_overrides;
mod model_switching;
mod model_visible_layout;
@@ -61,6 +64,7 @@ mod models_cache_ttl;
mod models_etag_responses;
mod openai_file_mcp;
mod otel;
mod override_updates;
mod pending_input;
mod permissions_messages;
mod personality;
@@ -77,6 +81,7 @@ mod request_compression;
mod request_permissions;
#[cfg(not(target_os = "windows"))]
mod request_permissions_tool;
mod request_plugin_install;
mod request_user_input;
mod responses_api_proxy_headers;
mod resume;
@@ -98,7 +103,6 @@ mod stream_no_completed;
mod subagent_notifications;
mod tool_harness;
mod tool_parallelism;
mod tool_suggest;
mod tools;
mod truncation;
mod turn_state;
@@ -110,3 +114,5 @@ mod view_image;
mod web_search;
mod websocket_fallback;
mod window_headers;
#[cfg(target_os = "windows")]
mod windows_sandbox;
+59 -4
View File
@@ -9,6 +9,7 @@ use codex_protocol::models::PermissionProfile;
use codex_protocol::openai_models::ConfigShellToolType;
use codex_protocol::openai_models::InputModality;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelServiceTier;
use codex_protocol::openai_models::ModelVisibility;
use codex_protocol::openai_models::ModelsResponse;
use codex_protocol::openai_models::ReasoningEffort;
@@ -106,6 +107,7 @@ fn test_model_info(
supports_search_tool: false,
priority: 1,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
upgrade: None,
base_instructions: "base instructions".to_string(),
model_messages: None,
@@ -319,9 +321,28 @@ async fn flex_service_tier_is_applied_to_http_turn() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let model_slug = "test-flex-model";
let mut flex_model = test_model_info(
model_slug,
model_slug,
"supports flex tier",
default_input_modalities(),
);
flex_model.service_tiers = vec![ModelServiceTier {
id: ServiceTier::Flex.request_value().to_string(),
name: "flex".to_string(),
description: "Flexible processing.".to_string(),
}];
let resp_mock = mount_sse_once(&server, sse_completed("resp-1")).await;
let test = test_codex().build(&server).await?;
let mut builder = test_codex()
.with_model(model_slug)
.with_config(move |config| {
config.model_catalog = Some(ModelsResponse {
models: vec![flex_model],
});
});
let test = builder.build(&server).await?;
test.submit_turn_with_service_tier("flex turn", Some(ServiceTier::Flex))
.await?;
@@ -333,6 +354,39 @@ async fn flex_service_tier_is_applied_to_http_turn() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unsupported_service_tier_is_omitted_from_http_turn() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let model_slug = "test-no-tier-model";
let model = test_model_info(
model_slug,
model_slug,
"no service tiers",
default_input_modalities(),
);
let resp_mock = mount_sse_once(&server, sse_completed("resp-1")).await;
let mut builder = test_codex()
.with_model(model_slug)
.with_config(move |config| {
config.model_catalog = Some(ModelsResponse {
models: vec![model],
});
});
let test = builder.build(&server).await?;
test.submit_turn_with_service_tier("fast turn", Some(ServiceTier::Fast))
.await?;
let request = resp_mock.single_request();
let body = request.body_json();
assert_eq!(body.get("service_tier"), None);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn model_change_from_image_to_text_strips_prior_image_content() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -486,7 +540,7 @@ async fn generated_image_is_replayed_for_image_capable_models() -> Result<()> {
let test = builder.build(&server).await?;
let saved_path = image_generation_artifact_path(
test.codex_home_path(),
&test.session_configured.session_id.to_string(),
&test.session_configured.thread_id.to_string(),
"ig_123",
);
let _ = std::fs::remove_file(&saved_path);
@@ -600,7 +654,7 @@ async fn model_change_from_generated_image_to_text_preserves_prior_generated_ima
let test = builder.build(&server).await?;
let saved_path = image_generation_artifact_path(
test.codex_home_path(),
&test.session_configured.session_id.to_string(),
&test.session_configured.thread_id.to_string(),
"ig_123",
);
let _ = std::fs::remove_file(&saved_path);
@@ -716,7 +770,7 @@ async fn thread_rollback_after_generated_image_drops_entire_image_turn_history()
let test = builder.build(&server).await?;
let saved_path = image_generation_artifact_path(
test.codex_home_path(),
&test.session_configured.session_id.to_string(),
&test.session_configured.thread_id.to_string(),
"ig_rollback",
);
let _ = std::fs::remove_file(&saved_path);
@@ -818,6 +872,7 @@ async fn model_switch_to_smaller_model_updates_token_context_window() -> Result<
supports_search_tool: false,
priority: 1,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
upgrade: None,
base_instructions: "base instructions".to_string(),
model_messages: None,
@@ -341,6 +341,7 @@ fn test_remote_model(slug: &str, priority: i32) -> ModelInfo {
supported_in_api: true,
priority,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
upgrade: None,
base_instructions: "base instructions".to_string(),
model_messages: None,
+2 -3
View File
@@ -12,6 +12,7 @@ use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use core_test_support::apps_test_server::AppsTestServer;
use core_test_support::apps_test_server::DOCUMENT_EXTRACT_TEXT_RESOURCE_URI;
use core_test_support::hooks::trust_discovered_hooks;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call_with_namespace;
@@ -162,9 +163,7 @@ async fn codex_apps_file_params_upload_local_paths_before_mcp_tool_call() -> Res
})
.with_config(move |config| {
configure_apps(config, apps_server.chatgpt_base_url.as_str());
if let Err(err) = config.features.enable(Feature::CodexHooks) {
panic!("test config should allow feature update: {err}");
}
trust_discovered_hooks(config);
});
let test = builder.build(&server).await?;
tokio::fs::write(test.cwd.path().join("report.txt"), b"hello world").await?;
+37 -21
View File
@@ -1,6 +1,7 @@
use codex_core::config::Constrained;
use codex_features::Feature;
use codex_protocol::models::PermissionProfile;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
@@ -595,8 +596,9 @@ async fn turn_and_completed_response_spans_record_token_usage() {
)
.await;
let TestCodex { codex, .. } = test_codex()
let test = test_codex()
.with_config(|config| {
config.model_reasoning_effort = Some(ReasoningEffort::High);
config
.features
.disable(Feature::GhostCommit)
@@ -606,6 +608,8 @@ async fn turn_and_completed_response_spans_record_token_usage() {
.await
.unwrap();
let TestCodex { codex, .. } = test;
codex
.submit(Op::UserInput {
environments: None,
@@ -625,7 +629,9 @@ async fn turn_and_completed_response_spans_record_token_usage() {
assert!(
logs.lines().any(|line| {
line.contains("handle_responses{otel.name=\"completed\"")
line.contains("handle_responses{")
&& line.contains("otel.name=\"completed\"")
&& line.contains("codex.request.reasoning_effort=high")
&& line.contains("gen_ai.usage.input_tokens=3")
&& line.contains("gen_ai.usage.cache_read.input_tokens=1")
&& line.contains("gen_ai.usage.output_tokens=5")
@@ -637,6 +643,7 @@ async fn turn_and_completed_response_spans_record_token_usage() {
assert!(
logs.lines().any(|line| {
line.contains("turn{otel.name=\"session_task.turn\"")
&& line.contains("codex.turn.reasoning_effort=high")
&& line.contains("codex.turn.token_usage.input_tokens=3")
&& line.contains("codex.turn.token_usage.cached_input_tokens=1")
&& line.contains("codex.turn.token_usage.non_cached_input_tokens=2")
@@ -708,13 +715,18 @@ async fn handle_responses_span_records_response_kind_and_tool_name() {
let logs = String::from_utf8(buffer.lock().unwrap().clone()).unwrap();
assert!(
logs.contains("handle_responses{otel.name=\"function_call\"")
&& logs.contains("tool_name=\"nonexistent\"")
&& logs.contains("from=\"output_item_done\""),
logs.lines().any(|line| {
line.contains("handle_responses{")
&& line.contains("otel.name=\"function_call\"")
&& line.contains("tool_name=\"nonexistent\"")
&& line.contains("from=\"output_item_done\"")
}),
"missing handle_responses span with function call metadata\nlogs:\n{logs}"
);
assert!(
logs.contains("handle_responses{otel.name=\"completed\""),
logs.lines().any(|line| {
line.contains("handle_responses{") && line.contains("otel.name=\"completed\"")
}),
"missing handle_responses span for completion\nlogs:\n{logs}"
);
}
@@ -766,7 +778,9 @@ async fn record_responses_sets_span_fields_for_response_events() {
.await;
let TestCodex { codex, .. } = test_codex()
.with_model("gpt-5.4")
.with_config(|config| {
config.model_reasoning_effort = Some(ReasoningEffort::High);
config
.features
.disable(Feature::GhostCommit)
@@ -806,22 +820,24 @@ async fn record_responses_sets_span_fields_for_response_events() {
];
for (name, from, tool_name) in expected {
let otel_name = format!("otel.name=\"{name}\"");
let from_field = from.map(|from| format!("from=\"{from}\""));
let tool_name_field = tool_name.map(|tool_name| format!("tool_name=\"{tool_name}\""));
assert!(
logs.contains(&format!("handle_responses{{otel.name=\"{name}\"")),
"missing otel.name={name}\nlogs:\n{logs}"
logs.lines().any(|line| {
line.contains("handle_responses{")
&& line.contains(&otel_name)
&& line.contains("codex.request.reasoning_effort=high")
&& from_field
.as_ref()
.is_none_or(|from_field| line.contains(from_field))
&& tool_name_field
.as_ref()
.is_none_or(|tool_name_field| line.contains(tool_name_field))
}),
"missing span fields for {name}\nlogs:\n{logs}"
);
if let Some(from) = from {
assert!(
logs.contains(&format!("from=\"{from}\"")),
"missing from={from} for {name}\nlogs:\n{logs}"
);
}
if let Some(tool_name) = tool_name {
assert!(
logs.contains(&format!("tool_name=\"{tool_name}\"")),
"missing tool_name={tool_name} for {name}\nlogs:\n{logs}"
);
}
}
}
@@ -875,7 +891,7 @@ async fn handle_response_item_records_tool_result_for_custom_tool_call() {
.await
.unwrap();
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TokenCount(_))).await;
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
logs_assert(|lines: &[&str]| {
let line = lines
+17 -105
View File
@@ -1,25 +1,15 @@
use anyhow::Result;
use codex_core::config::Constrained;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::COLLABORATION_MODE_CLOSE_TAG;
use codex_protocol::protocol::COLLABORATION_MODE_OPEN_TAG;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::RolloutItem;
use codex_protocol::protocol::RolloutLine;
use codex_protocol::protocol::ENVIRONMENT_CONTEXT_OPEN_TAG;
use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::Settings;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
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 pretty_assertions::assert_eq;
use std::path::Path;
use std::time::Duration;
use tempfile::TempDir;
fn collab_mode_with_instructions(instructions: Option<&str>) -> CollaborationMode {
@@ -33,77 +23,9 @@ fn collab_mode_with_instructions(instructions: Option<&str>) -> CollaborationMod
}
}
fn collab_xml(text: &str) -> String {
format!("{COLLABORATION_MODE_OPEN_TAG}{text}{COLLABORATION_MODE_CLOSE_TAG}")
}
async fn read_rollout_text(path: &Path) -> anyhow::Result<String> {
for _ in 0..50 {
if path.exists()
&& let Ok(text) = std::fs::read_to_string(path)
&& !text.trim().is_empty()
{
return Ok(text);
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
Ok(std::fs::read_to_string(path)?)
}
fn rollout_developer_texts(text: &str) -> Vec<String> {
let mut texts = Vec::new();
for line in text.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let rollout: RolloutLine = match serde_json::from_str(trimmed) {
Ok(rollout) => rollout,
Err(_) => continue,
};
if let RolloutItem::ResponseItem(ResponseItem::Message { role, content, .. }) =
rollout.item
&& role == "developer"
{
for item in content {
if let ContentItem::InputText { text } = item {
texts.push(text);
}
}
}
}
texts
}
fn rollout_environment_texts(text: &str) -> Vec<String> {
let mut texts = Vec::new();
for line in text.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let rollout: RolloutLine = match serde_json::from_str(trimmed) {
Ok(rollout) => rollout,
Err(_) => continue,
};
if let RolloutItem::ResponseItem(ResponseItem::Message { role, content, .. }) =
rollout.item
&& role == "user"
{
for item in content {
if let ContentItem::InputText { text } = item
&& text.starts_with(ENVIRONMENT_CONTEXT_OPEN_TAG)
{
texts.push(text);
}
}
}
}
texts
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn override_turn_context_without_user_turn_does_not_record_permissions_update() -> Result<()> {
async fn override_turn_context_without_user_turn_does_not_record_permissions_update() -> Result<()>
{
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -133,22 +55,17 @@ async fn override_turn_context_without_user_turn_does_not_record_permissions_upd
wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::ShutdownComplete)).await;
let rollout_path = test.codex.rollout_path().expect("rollout path");
let rollout_text = read_rollout_text(&rollout_path).await?;
let developer_texts = rollout_developer_texts(&rollout_text);
let approval_texts: Vec<&String> = developer_texts
.iter()
.filter(|text| text.contains("`approval_policy`"))
.collect();
assert!(
approval_texts.is_empty(),
"did not expect permissions updates before a new user turn: {approval_texts:?}"
!rollout_path.exists(),
"did not expect a rollout before a new user turn"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn override_turn_context_without_user_turn_does_not_record_environment_update() -> Result<()> {
async fn override_turn_context_without_user_turn_does_not_record_environment_update() -> Result<()>
{
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -176,18 +93,17 @@ async fn override_turn_context_without_user_turn_does_not_record_environment_upd
wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::ShutdownComplete)).await;
let rollout_path = test.codex.rollout_path().expect("rollout path");
let rollout_text = read_rollout_text(&rollout_path).await?;
let env_texts = rollout_environment_texts(&rollout_text);
assert!(
env_texts.is_empty(),
"did not expect environment updates before a new user turn: {env_texts:?}"
!rollout_path.exists(),
"did not expect a rollout before a new user turn"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn override_turn_context_without_user_turn_does_not_record_collaboration_update() -> Result<()> {
async fn override_turn_context_without_user_turn_does_not_record_collaboration_update() -> Result<()>
{
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -216,14 +132,10 @@ async fn override_turn_context_without_user_turn_does_not_record_collaboration_u
wait_for_event(&test.codex, |ev| matches!(ev, EventMsg::ShutdownComplete)).await;
let rollout_path = test.codex.rollout_path().expect("rollout path");
let rollout_text = read_rollout_text(&rollout_path).await?;
let developer_texts = rollout_developer_texts(&rollout_text);
let collab_text = collab_xml(collab_text);
let collab_count = developer_texts
.iter()
.filter(|text| text.as_str() == collab_text.as_str())
.count();
assert_eq!(collab_count, 0);
assert!(
!rollout_path.exists(),
"did not expect a rollout before a new user turn"
);
Ok(())
}
+3 -3
View File
@@ -164,11 +164,11 @@ async fn submit_queue_only_agent_mail(codex: &CodexThread, text: &str) {
.await
.unwrap_or_else(|err| panic!("submit queue-only agent mail: {err}"));
codex
.submit(Op::ListMcpTools)
.submit(Op::RealtimeConversationListVoices)
.await
.unwrap_or_else(|err| panic!("submit list-mcp-tools barrier: {err}"));
.unwrap_or_else(|err| panic!("submit list-voices barrier: {err}"));
wait_for_event(codex, |event| {
matches!(event, EventMsg::McpListToolsResponse(_))
matches!(event, EventMsg::RealtimeConversationListVoicesResponse(_))
})
.await;
}
@@ -497,6 +497,7 @@ async fn resume_and_fork_append_permissions_messages() -> Result<()> {
ForkSnapshot::Interrupted,
fork_config.clone(),
rollout_path,
/*thread_source*/ None,
/*persist_extended_history*/ false,
/*parent_trace*/ None,
)
+2
View File
@@ -579,6 +579,7 @@ async fn remote_model_friendly_personality_instructions_with_feature() -> anyhow
supported_in_api: true,
priority: 1,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
upgrade: None,
base_instructions: "base instructions".to_string(),
model_messages: Some(ModelMessages {
@@ -687,6 +688,7 @@ async fn user_turn_personality_remote_model_template_includes_update_message() -
supported_in_api: true,
priority: 1,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
upgrade: None,
base_instructions: "base instructions".to_string(),
model_messages: Some(ModelMessages {
@@ -66,6 +66,7 @@ async fn write_rollout_with_user_event(dir: &Path, thread_id: ThreadId) -> io::R
originator: "test_originator".to_string(),
cli_version: "test_version".to_string(),
source: SessionSource::Cli,
thread_source: None,
agent_path: None,
agent_nickname: None,
agent_role: None,
@@ -111,6 +112,7 @@ async fn write_rollout_with_meta_only(dir: &Path, thread_id: ThreadId) -> io::Re
originator: "test_originator".to_string(),
cli_version: "test_version".to_string(),
source: SessionSource::Cli,
thread_source: None,
agent_path: None,
agent_nickname: None,
agent_role: None,
@@ -141,7 +143,8 @@ async fn migration_marker_exists_no_sessions_no_change() -> io::Result<()> {
let marker_path = temp.path().join(PERSONALITY_MIGRATION_FILENAME);
tokio::fs::write(&marker_path, "v1\n").await?;
let status = maybe_migrate_personality(temp.path(), &ConfigToml::default()).await?;
let status =
maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?;
assert_eq!(status, PersonalityMigrationStatus::SkippedMarker);
assert_eq!(
@@ -155,7 +158,8 @@ async fn migration_marker_exists_no_sessions_no_change() -> io::Result<()> {
async fn no_marker_no_sessions_no_change() -> io::Result<()> {
let temp = TempDir::new()?;
let status = maybe_migrate_personality(temp.path(), &ConfigToml::default()).await?;
let status =
maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?;
assert_eq!(status, PersonalityMigrationStatus::SkippedNoSessions);
assert_eq!(
@@ -174,7 +178,8 @@ async fn no_marker_sessions_sets_personality() -> io::Result<()> {
let temp = TempDir::new()?;
write_session_with_user_event(temp.path()).await?;
let status = maybe_migrate_personality(temp.path(), &ConfigToml::default()).await?;
let status =
maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?;
assert_eq!(status, PersonalityMigrationStatus::Applied);
assert_eq!(
@@ -194,7 +199,7 @@ async fn no_marker_sessions_preserves_existing_config_fields() -> io::Result<()>
tokio::fs::write(temp.path().join("config.toml"), "model = \"gpt-5.4\"\n").await?;
let config_toml = read_config_toml(temp.path()).await?;
let status = maybe_migrate_personality(temp.path(), &config_toml).await?;
let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?;
assert_eq!(status, PersonalityMigrationStatus::Applied);
let persisted = read_config_toml(temp.path()).await?;
@@ -208,7 +213,8 @@ async fn no_marker_meta_only_rollout_is_treated_as_no_sessions() -> io::Result<(
let temp = TempDir::new()?;
write_session_with_meta_only(temp.path()).await?;
let status = maybe_migrate_personality(temp.path(), &ConfigToml::default()).await?;
let status =
maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?;
assert_eq!(status, PersonalityMigrationStatus::SkippedNoSessions);
assert_eq!(
@@ -228,7 +234,7 @@ async fn no_marker_explicit_global_personality_skips_migration() -> io::Result<(
write_session_with_user_event(temp.path()).await?;
let config_toml = parse_config_toml("personality = \"friendly\"\n")?;
let status = maybe_migrate_personality(temp.path(), &config_toml).await?;
let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?;
assert_eq!(
status,
@@ -258,7 +264,7 @@ personality = "friendly"
"#,
)?;
let status = maybe_migrate_personality(temp.path(), &config_toml).await?;
let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?;
assert_eq!(
status,
@@ -281,7 +287,7 @@ async fn marker_short_circuits_invalid_profile_resolution() -> io::Result<()> {
tokio::fs::write(temp.path().join(PERSONALITY_MIGRATION_FILENAME), "v1\n").await?;
let config_toml = parse_config_toml("profile = \"missing\"\n")?;
let status = maybe_migrate_personality(temp.path(), &config_toml).await?;
let status = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None).await?;
assert_eq!(status, PersonalityMigrationStatus::SkippedMarker);
Ok(())
@@ -292,7 +298,7 @@ async fn invalid_selected_profile_returns_error_and_does_not_write_marker() -> i
let temp = TempDir::new()?;
let config_toml = parse_config_toml("profile = \"missing\"\n")?;
let err = maybe_migrate_personality(temp.path(), &config_toml)
let err = maybe_migrate_personality(temp.path(), &config_toml, /*state_db*/ None)
.await
.expect_err("missing profile should fail");
@@ -309,8 +315,10 @@ async fn applied_migration_is_idempotent_on_second_run() -> io::Result<()> {
let temp = TempDir::new()?;
write_session_with_user_event(temp.path()).await?;
let first_status = maybe_migrate_personality(temp.path(), &ConfigToml::default()).await?;
let second_status = maybe_migrate_personality(temp.path(), &ConfigToml::default()).await?;
let first_status =
maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?;
let second_status =
maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?;
assert_eq!(first_status, PersonalityMigrationStatus::Applied);
assert_eq!(second_status, PersonalityMigrationStatus::SkippedMarker);
@@ -324,7 +332,8 @@ async fn no_marker_archived_sessions_sets_personality() -> io::Result<()> {
let temp = TempDir::new()?;
write_archived_session_with_user_event(temp.path()).await?;
let status = maybe_migrate_personality(temp.path(), &ConfigToml::default()).await?;
let status =
maybe_migrate_personality(temp.path(), &ConfigToml::default(), /*state_db*/ None).await?;
assert_eq!(status, PersonalityMigrationStatus::Applied);
assert_eq!(
+1 -45
View File
@@ -74,6 +74,7 @@ fn write_plugin_mcp_plugin(home: &TempDir, command: &str) {
"mcpServers": {{
"sample": {{
"command": "{command}",
"cwd": ".",
"startup_timeout_sec": 60.0
}}
}}
@@ -98,20 +99,6 @@ fn write_plugin_app_plugin(home: &TempDir) {
.expect("write plugin app config");
}
async fn build_plugin_test_codex(
server: &MockServer,
codex_home: Arc<TempDir>,
) -> Result<Arc<codex_core::CodexThread>> {
let mut builder = test_codex()
.with_home(codex_home)
.with_auth(CodexAuth::from_api_key("Test API Key"));
Ok(builder
.build(server)
.await
.expect("create new conversation")
.codex)
}
async fn build_analytics_plugin_test_codex(
server: &MockServer,
codex_home: Arc<TempDir>,
@@ -447,34 +434,3 @@ async fn explicit_plugin_mentions_track_plugin_used_analytics() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn plugin_mcp_tools_are_listed() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let codex_home = Arc::new(TempDir::new()?);
let rmcp_test_server_bin = stdio_server_bin()?;
write_plugin_mcp_plugin(codex_home.as_ref(), &rmcp_test_server_bin);
let codex = build_plugin_test_codex(&server, codex_home).await?;
wait_for_sample_mcp_ready(&codex).await?;
codex.submit(Op::ListMcpTools).await?;
let list_event = wait_for_event_with_timeout(
&codex,
|ev| matches!(ev, EventMsg::McpListToolsResponse(_)),
Duration::from_secs(10),
)
.await;
let EventMsg::McpListToolsResponse(tool_list) = list_event else {
unreachable!("event guard guarantees McpListToolsResponse");
};
let mut available_tools: Vec<&str> = tool_list.tools.keys().map(String::as_str).collect();
available_tools.sort_unstable();
assert!(
tool_list.tools.contains_key("mcp__sample__echo")
&& tool_list.tools.contains_key("mcp__sample__image"),
"expected plugin MCP tools to be listed; discovered tools: {available_tools:?}"
);
Ok(())
}
+7 -13
View File
@@ -1,7 +1,6 @@
#![allow(clippy::unwrap_used)]
use codex_apply_patch::APPLY_PATCH_TOOL_INSTRUCTIONS;
use codex_core::shell::Shell;
use codex_core::shell::default_user_shell;
use codex_features::Feature;
use codex_protocol::config_types::CollaborationMode;
@@ -46,8 +45,7 @@ fn text_user_input_parts(texts: Vec<String>) -> serde_json::Value {
})
}
fn assert_default_env_context(text: &str, cwd: &str, shell: &Shell) {
let shell_name = shell.name();
fn assert_default_env_context(text: &str, cwd: &str) {
assert!(
text.starts_with(ENVIRONMENT_CONTEXT_OPEN_TAG),
"expected environment context fragment: {text}"
@@ -57,7 +55,7 @@ fn assert_default_env_context(text: &str, cwd: &str, shell: &Shell) {
"expected cwd in environment context: {text}"
);
assert!(
text.contains(&format!("<shell>{shell_name}</shell>")),
text.contains(&format!("<shell>{}</shell>", default_user_shell().name())),
"expected shell in environment context: {text}"
);
assert!(
@@ -181,13 +179,13 @@ async fn prompt_tools_are_consistent_across_requests() -> anyhow::Result<()> {
"update_plan",
"request_user_input",
"apply_patch",
"web_search",
"view_image",
"spawn_agent",
"send_input",
"resume_agent",
"wait_agent",
"close_agent",
"web_search",
]);
let body0 = req1.single_request().body_json();
@@ -365,12 +363,11 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests
"expected user instructions in UI message: {ui_text}"
);
let shell = default_user_shell();
let cwd_str = config.cwd.to_string_lossy();
let env_text = input1[1]["content"][1]["text"]
.as_str()
.expect("environment context text");
assert_default_env_context(env_text, &cwd_str, &shell);
assert_default_env_context(env_text, &cwd_str);
assert_eq!(
input1[1]["content"][1]["type"].as_str(),
Some("input_text"),
@@ -785,9 +782,8 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() -> anyhow::Res
let env_text = expected_env_msg_2["content"][0]["text"]
.as_str()
.expect("environment context text");
let shell = default_user_shell();
let expected_cwd = new_cwd.path().display().to_string();
assert_default_env_context(env_text, &expected_cwd, &shell);
assert_default_env_context(env_text, &expected_cwd);
let mut expected_body2 = body1_input.to_vec();
expected_body2.push(expected_settings_update_msg);
expected_body2.push(expected_env_msg_2);
@@ -891,13 +887,12 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() -> a
let expected_permissions_msg = body1["input"][0].clone();
let expected_ui_msg = body1["input"][1].clone();
let shell = default_user_shell();
let default_cwd_lossy = default_cwd.to_string_lossy();
let expected_env_text_1 = expected_ui_msg["content"][1]["text"]
.as_str()
.expect("cached environment context text")
.to_string();
assert_default_env_context(&expected_env_text_1, &default_cwd_lossy, &shell);
assert_default_env_context(&expected_env_text_1, &default_cwd_lossy);
let expected_contextual_user_msg_1 = text_user_input_parts(vec![
expected_ui_msg["content"][0]["text"]
@@ -1023,12 +1018,11 @@ async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Resu
let expected_permissions_msg = body1["input"][0].clone();
let expected_ui_msg = body1["input"][1].clone();
let shell = default_user_shell();
let expected_env_text_1 = expected_ui_msg["content"][1]["text"]
.as_str()
.expect("cached environment context text")
.to_string();
assert_default_env_context(&expected_env_text_1, &default_cwd.to_string_lossy(), &shell);
assert_default_env_context(&expected_env_text_1, &default_cwd.to_string_lossy());
let expected_contextual_user_msg_1 = text_user_input_parts(vec![
expected_ui_msg["content"][0]["text"]
.as_str()
@@ -29,6 +29,7 @@ async fn build_prompt_input_includes_context_and_user_message() -> Result<()> {
text: "hello from debug prompt".to_string(),
text_elements: Vec::new(),
}],
/*state_db*/ None,
)
.await?;
@@ -120,6 +120,21 @@ fn websocket_request_instructions(
.map(str::to_owned)
}
async fn wait_for_websocket_request(
server: &core_test_support::responses::WebSocketTestServer,
connection_index: usize,
request_index: usize,
) -> Result<core_test_support::responses::WebSocketRequest> {
timeout(
Duration::from_secs(2),
server.wait_for_request(connection_index, request_index),
)
.await
.with_context(|| {
format!("timed out waiting for websocket request {connection_index}/{request_index}")
})
}
fn expected_realtime_backend_prompt() -> String {
REALTIME_BACKEND_PROMPT
.trim_end()
@@ -456,6 +471,7 @@ async fn conversation_webrtc_start_posts_generated_session() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let sideband_accept_delay = Duration::from_millis(1000);
let capture = RealtimeCallRequestCapture::new();
Mock::given(method("POST"))
.and(path_regex(".*/realtime/calls$"))
@@ -468,12 +484,15 @@ async fn conversation_webrtc_start_posts_generated_session() -> Result<()> {
.mount(&server)
.await;
let realtime_server = start_websocket_server_with_headers(vec![WebSocketConnectionConfig {
requests: vec![vec![json!({
"type": "session.updated",
"session": { "id": "sess_webrtc", "instructions": "backend prompt" }
})]],
requests: vec![
vec![json!({
"type": "session.updated",
"session": { "id": "sess_webrtc", "instructions": "backend prompt" }
})],
vec![],
],
response_headers: Vec::new(),
accept_delay: None,
accept_delay: Some(sideband_accept_delay),
close_after_requests: false,
}])
.await;
@@ -510,6 +529,16 @@ async fn conversation_webrtc_start_posts_generated_session() -> Result<()> {
.await
.unwrap_or_else(|err: ErrorEvent| panic!("conversation call create failed: {err:?}"));
assert_eq!(created.sdp, "v=answer\r\n");
assert!(
realtime_server.handshakes().is_empty(),
"SDP should be emitted before the delayed sideband websocket joins"
);
test.codex
.submit(Op::RealtimeConversationText(ConversationTextParams {
text: "queued before sideband".to_string(),
}))
.await?;
let session_updated = wait_for_event_match(&test.codex, |msg| match msg {
EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent {
@@ -566,9 +595,12 @@ async fn conversation_webrtc_start_posts_generated_session() -> Result<()> {
// Phase 3: the server joins that same call over the direct sideband WebSocket, sends the
// ordinary session.update, and keeps the conversation alive until the client closes it.
let session_update = realtime_server
.wait_for_request(/*connection_index*/ 0, /*request_index*/ 0)
.await;
let session_update = wait_for_websocket_request(
&realtime_server,
/*connection_index*/ 0,
/*request_index*/ 0,
)
.await?;
assert_eq!(
session_update.body_json()["type"].as_str(),
Some("session.update")
@@ -578,6 +610,16 @@ async fn conversation_webrtc_start_posts_generated_session() -> Result<()> {
.context("session.update should include instructions")?
.contains("startup context")
);
let queued_text = wait_for_websocket_request(
&realtime_server,
/*connection_index*/ 0,
/*request_index*/ 1,
)
.await?;
assert_eq!(
websocket_request_text(&queued_text).as_deref(),
Some("queued before sideband")
);
let handshake = realtime_server.single_handshake();
assert_eq!(
handshake.uri(),
@@ -603,6 +645,179 @@ async fn conversation_webrtc_start_posts_generated_session() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn conversation_webrtc_close_while_sideband_connecting_drops_pending_join() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
Mock::given(method("POST"))
.and(path_regex(".*/realtime/calls$"))
.respond_with(
ResponseTemplate::new(200)
.insert_header("Location", "/v1/realtime/calls/calls/rtc_close_pending")
.set_body_string("v=answer\r\n"),
)
.mount(&server)
.await;
let realtime_server = start_websocket_server_with_headers(vec![WebSocketConnectionConfig {
requests: vec![vec![]],
response_headers: Vec::new(),
accept_delay: Some(Duration::from_millis(500)),
close_after_requests: false,
}])
.await;
let realtime_ws_base_url = realtime_server.uri().to_string();
let mut builder = test_codex().with_config(move |config| {
config.experimental_realtime_ws_backend_prompt = Some("backend prompt".to_string());
config.experimental_realtime_ws_model = Some("realtime-test-model".to_string());
config.experimental_realtime_ws_startup_context = Some(String::new());
config.experimental_realtime_ws_base_url = Some(realtime_ws_base_url);
config.realtime.version = RealtimeWsVersion::V1;
});
let test = builder.build(&server).await?;
test.codex
.submit(Op::RealtimeConversationStart(ConversationStartParams {
output_modality: RealtimeOutputModality::Audio,
prompt: Some(Some("backend prompt".to_string())),
realtime_session_id: None,
transport: Some(ConversationStartTransport::Webrtc {
sdp: "v=offer\r\n".to_string(),
}),
voice: None,
}))
.await?;
let sdp = wait_for_event_match(&test.codex, |msg| match msg {
EventMsg::RealtimeConversationSdp(created) => Some(created.sdp.clone()),
_ => None,
})
.await;
assert_eq!(sdp, "v=answer\r\n");
assert!(
realtime_server.handshakes().is_empty(),
"sideband websocket should still be pending when SDP is emitted"
);
test.codex.submit(Op::RealtimeConversationClose).await?;
let closed = wait_for_event_match(&test.codex, |msg| match msg {
EventMsg::RealtimeConversationClosed(closed) => Some(closed.clone()),
_ => None,
})
.await;
assert_eq!(closed.reason.as_deref(), Some("requested"));
let stale_event = timeout(Duration::from_millis(700), async {
wait_for_event_match(&test.codex, |msg| match msg {
EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent {
payload: RealtimeEvent::Error(message),
}) => Some(format!("stale realtime error: {message}")),
EventMsg::RealtimeConversationClosed(closed) => {
Some(format!("stale close event: {:?}", closed.reason))
}
_ => None,
})
.await
})
.await;
assert!(
stale_event.is_err(),
"pending sideband task leaked after close: {:?}",
stale_event.ok()
);
assert!(
realtime_server.handshakes().is_empty(),
"pending sideband task should abort before websocket handshake completes"
);
realtime_server.shutdown().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn conversation_webrtc_sideband_connect_failure_closes_with_error() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
Mock::given(method("POST"))
.and(path_regex(".*/realtime/calls$"))
.respond_with(
ResponseTemplate::new(200)
.insert_header("Location", "/v1/realtime/calls/calls/rtc_sideband_failure")
.set_body_string("v=answer\r\n"),
)
.mount(&server)
.await;
let mut builder = test_codex().with_config(|config| {
config.experimental_realtime_ws_backend_prompt = Some("backend prompt".to_string());
config.experimental_realtime_ws_model = Some("realtime-test-model".to_string());
config.experimental_realtime_ws_startup_context = Some(String::new());
config.experimental_realtime_ws_base_url = Some("http://127.0.0.1:1".to_string());
// Keep the failure-path test inside wait_for_event's timeout on Windows,
// where refused localhost websocket connects can take around two seconds.
config.model_provider.request_max_retries = Some(0);
config.realtime.version = RealtimeWsVersion::V1;
});
let test = builder.build(&server).await?;
test.codex
.submit(Op::RealtimeConversationStart(ConversationStartParams {
output_modality: RealtimeOutputModality::Audio,
prompt: Some(Some("backend prompt".to_string())),
realtime_session_id: None,
transport: Some(ConversationStartTransport::Webrtc {
sdp: "v=offer\r\n".to_string(),
}),
voice: None,
}))
.await?;
let started = wait_for_event_match(&test.codex, |msg| match msg {
EventMsg::RealtimeConversationStarted(started) => Some(started.clone()),
_ => None,
})
.await;
assert!(started.realtime_session_id.is_some());
let sdp = wait_for_event_match(&test.codex, |msg| match msg {
EventMsg::RealtimeConversationSdp(created) => Some(created.sdp.clone()),
_ => None,
})
.await;
assert_eq!(sdp, "v=answer\r\n");
let err = wait_for_event_match(&test.codex, |msg| match msg {
EventMsg::RealtimeConversationRealtime(RealtimeConversationRealtimeEvent {
payload: RealtimeEvent::Error(message),
}) => Some(message.clone()),
_ => None,
})
.await;
assert!(!err.is_empty());
let closed = wait_for_event_match(&test.codex, |msg| match msg {
EventMsg::RealtimeConversationClosed(closed) => Some(closed.clone()),
_ => None,
})
.await;
assert_eq!(closed.reason.as_deref(), Some("error"));
test.codex
.submit(Op::RealtimeConversationText(ConversationTextParams {
text: "after sideband failure".to_string(),
}))
.await?;
let err = wait_for_event_match(&test.codex, |msg| match msg {
EventMsg::Error(err) => Some(err.clone()),
_ => None,
})
.await;
assert_eq!(err.message, "conversation is not running");
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn conversation_start_uses_openai_env_key_fallback_with_chatgpt_auth() -> Result<()> {
if std::env::var_os(REALTIME_CONVERSATION_TEST_SUBPROCESS_ENV_VAR).is_none() {
+587
View File
@@ -1,25 +1,135 @@
use anyhow::Context;
use anyhow::Result;
use codex_config::types::ApprovalsReviewer;
use codex_core::config::Constrained;
use codex_exec_server::CopyOptions;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::FileSystemSandboxContext;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_exec_server::REMOTE_ENVIRONMENT_ID;
use codex_exec_server::RemoveOptions;
use codex_features::Feature;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::ApplyPatchApprovalRequestEvent;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::ReviewDecision;
use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::user_input::UserInput;
use codex_utils_absolute_path::AbsolutePathBuf;
use core_test_support::PathBufExt;
use core_test_support::PathExt;
use core_test_support::get_remote_test_env;
use core_test_support::responses::ev_apply_patch_custom_tool_call;
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_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::test_codex::test_env;
use core_test_support::wait_for_event;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tempfile::TempDir;
async fn unified_exec_test(server: &wiremock::MockServer) -> Result<TestCodex> {
let mut builder = test_codex().with_config(|config| {
config.use_experimental_unified_exec_tool = true;
let result = config.features.enable(Feature::UnifiedExec);
assert!(
result.is_ok(),
"unified exec should enable for test: {result:?}",
);
});
builder.build_remote_aware(server).await
}
async fn submit_turn_with_approval_and_environments(
test: &TestCodex,
prompt: &str,
environments: Vec<TurnEnvironmentSelection>,
) -> Result<()> {
test.codex
.submit(Op::UserTurn {
environments: Some(environments),
items: vec![UserInput::Text {
text: prompt.into(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
cwd: test.cwd.path().to_path_buf(),
approval_policy: AskForApproval::OnRequest,
approvals_reviewer: Some(ApprovalsReviewer::User),
sandbox_policy: SandboxPolicy::new_workspace_write_policy(),
permission_profile: None,
model: test.session_configured.model.clone(),
effort: None,
summary: None,
service_tier: None,
collaboration_mode: None,
personality: None,
})
.await?;
Ok(())
}
async fn expect_patch_approval(
test: &TestCodex,
expected_call_id: &str,
) -> ApplyPatchApprovalRequestEvent {
let event = wait_for_event(&test.codex, |event| {
matches!(
event,
EventMsg::ApplyPatchApprovalRequest(_) | EventMsg::TurnComplete(_)
)
})
.await;
match event {
EventMsg::ApplyPatchApprovalRequest(approval) => {
assert_eq!(approval.call_id, expected_call_id);
approval
}
EventMsg::TurnComplete(_) => panic!("expected patch approval request before completion"),
other => panic!("unexpected event: {other:?}"),
}
}
async fn wait_for_completion_without_patch_approval(test: &TestCodex) {
let event = wait_for_event(&test.codex, |event| {
matches!(
event,
EventMsg::ApplyPatchApprovalRequest(_) | EventMsg::TurnComplete(_)
)
})
.await;
match event {
EventMsg::TurnComplete(_) => {}
EventMsg::ApplyPatchApprovalRequest(event) => {
panic!("unexpected patch approval request: {:?}", event.call_id)
}
other => panic!("unexpected event: {other:?}"),
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_test_env_can_connect_and_use_filesystem() -> Result<()> {
@@ -121,6 +231,483 @@ fn remote_exec(script: &str) -> Result<()> {
Ok(())
}
async fn exec_command_routing_output(
test: &TestCodex,
server: &wiremock::MockServer,
call_id: &str,
arguments: Value,
environments: Option<Vec<TurnEnvironmentSelection>>,
) -> Result<String> {
let response_mock = mount_sse_sequence(
server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call(call_id, "exec_command", &serde_json::to_string(&arguments)?),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
]),
],
)
.await;
test.submit_turn_with_environments("route exec command", environments)
.await?;
response_mock
.function_call_output_text(call_id)
.with_context(|| format!("missing function_call_output for {call_id}"))
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn exec_command_routes_to_selected_remote_environment() -> Result<()> {
skip_if_no_network!(Ok(()));
let Some(_remote_env) = get_remote_test_env() else {
return Ok(());
};
let server = start_mock_server().await;
let test = unified_exec_test(&server).await?;
let local_cwd = TempDir::new()?;
fs::write(local_cwd.path().join("marker.txt"), "local-routing")?;
let local_selection = TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: local_cwd.path().abs(),
};
let remote_cwd = PathBuf::from(format!(
"/tmp/codex-remote-routing-{}",
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
let remote_marker_name = "marker.txt";
test.fs()
.create_directory(
&remote_cwd,
CreateDirectoryOptions { recursive: true },
/*sandbox*/ None,
)
.await?;
test.fs()
.write_file(
&remote_cwd.join(remote_marker_name),
b"remote-routing".to_vec(),
/*sandbox*/ None,
)
.await?;
let remote_selection = TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd.clone(),
};
let multi_env_output = exec_command_routing_output(
&test,
&server,
"call-multi-env",
json!({
"shell": "/bin/sh",
"cmd": format!("cat {remote_marker_name}"),
"login": false,
"yield_time_ms": 1_000,
"environment_id": REMOTE_ENVIRONMENT_ID,
}),
Some(vec![local_selection, remote_selection]),
)
.await?;
assert!(
multi_env_output.contains("remote-routing"),
"unexpected multi-env output: {multi_env_output}",
);
assert!(
!multi_env_output.contains("local-routing"),
"multi-env command should not route to local: {multi_env_output}",
);
test.fs()
.remove(
&remote_cwd,
RemoveOptions {
recursive: true,
force: true,
},
/*sandbox*/ None,
)
.await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_patch_freeform_routes_to_selected_remote_environment() -> Result<()> {
skip_if_no_network!(Ok(()));
let Some(_remote_env) = get_remote_test_env() else {
return Ok(());
};
let server = start_mock_server().await;
let mut builder = test_codex().with_config(|config| {
config.include_apply_patch_tool = true;
});
let test = builder.build_remote_aware(&server).await?;
let local_cwd = TempDir::new()?;
let file_name = "apply_patch_remote_freeform.txt";
let remote_cwd = PathBuf::from(format!(
"/tmp/codex-remote-apply-patch-freeform-{}",
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
test.fs()
.create_directory(
&remote_cwd,
CreateDirectoryOptions { recursive: true },
/*sandbox*/ None,
)
.await?;
let patch = format!(
"*** Begin Patch\n*** Environment ID: {REMOTE_ENVIRONMENT_ID}\n*** Add File: {file_name}\n+patched remote freeform\n*** End Patch"
);
let call_id = "apply-patch-remote-freeform";
mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_apply_patch_custom_tool_call(call_id, &patch),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
]),
],
)
.await;
test.submit_turn_with_environments(
"apply patch to remote environment",
Some(vec![
TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: local_cwd.path().abs(),
},
TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd.clone(),
},
]),
)
.await?;
let remote_contents = test
.fs()
.read_file_text(&remote_cwd.join(file_name), /*sandbox*/ None)
.await?;
assert_eq!(remote_contents, "patched remote freeform\n");
assert!(
!local_cwd.path().join(file_name).exists(),
"freeform apply_patch should not create the file in the local environment"
);
test.fs()
.remove(
&remote_cwd,
RemoveOptions {
recursive: true,
force: true,
},
/*sandbox*/ None,
)
.await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
skip_if_no_network!(Ok(()));
let Some(_remote_env) = get_remote_test_env() else {
return Ok(());
};
let server = start_mock_server().await;
let mut builder = test_codex().with_config(|config| {
config.include_apply_patch_tool = true;
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
config.approvals_reviewer = ApprovalsReviewer::User;
});
let test = builder.build_remote_aware(&server).await?;
let local_cwd = TempDir::new()?;
let remote_cwd = PathBuf::from(format!(
"/tmp/codex-remote-apply-patch-approval-cwd-{}",
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
test.fs()
.create_directory(
&remote_cwd,
CreateDirectoryOptions { recursive: true },
/*sandbox*/ None,
)
.await?;
let target_path = PathBuf::from(format!(
"/tmp/codex-apply-patch-approval-scope-{}.txt",
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
let _ = fs::remove_file(&target_path);
test.fs()
.remove(
&target_path,
RemoveOptions {
recursive: false,
force: true,
},
/*sandbox*/ None,
)
.await?;
let environments = vec![
TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: local_cwd.path().abs(),
},
TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd.clone(),
},
];
let local_patch = format!(
"*** Begin Patch\n*** Environment ID: {LOCAL_ENVIRONMENT_ID}\n*** Add File: {}\n+local\n*** End Patch",
target_path.display()
);
let remote_patch = format!(
"*** Begin Patch\n*** Environment ID: {REMOTE_ENVIRONMENT_ID}\n*** Add File: {}\n+remote\n*** End Patch",
target_path.display()
);
let remote_update_patch = format!(
"*** Begin Patch\n*** Environment ID: {REMOTE_ENVIRONMENT_ID}\n*** Update File: {}\n@@\n-remote\n+remote updated\n*** End Patch",
target_path.display()
);
mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-local-1"),
ev_apply_patch_custom_tool_call("call-local", &local_patch),
ev_completed("resp-local-1"),
]),
sse(vec![
ev_response_created("resp-local-2"),
ev_assistant_message("msg-local", "done"),
ev_completed("resp-local-2"),
]),
sse(vec![
ev_response_created("resp-remote-1"),
ev_apply_patch_custom_tool_call("call-remote", &remote_patch),
ev_completed("resp-remote-1"),
]),
sse(vec![
ev_response_created("resp-remote-2"),
ev_assistant_message("msg-remote", "done"),
ev_completed("resp-remote-2"),
]),
sse(vec![
ev_response_created("resp-remote-3"),
ev_apply_patch_custom_tool_call("call-remote-followup", &remote_update_patch),
ev_completed("resp-remote-3"),
]),
sse(vec![
ev_response_created("resp-remote-4"),
ev_assistant_message("msg-remote-followup", "done"),
ev_completed("resp-remote-4"),
]),
],
)
.await;
submit_turn_with_approval_and_environments(
&test,
"apply patch in local environment",
environments.clone(),
)
.await?;
let approval = expect_patch_approval(&test, "call-local").await;
test.codex
.submit(Op::PatchApproval {
id: approval.call_id,
decision: ReviewDecision::ApprovedForSession,
})
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
assert_eq!(fs::read_to_string(&target_path)?, "local\n");
submit_turn_with_approval_and_environments(
&test,
"apply patch in remote environment",
environments.clone(),
)
.await?;
let approval = expect_patch_approval(&test, "call-remote").await;
test.codex
.submit(Op::PatchApproval {
id: approval.call_id,
decision: ReviewDecision::ApprovedForSession,
})
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
assert_eq!(
test.fs()
.read_file_text(&target_path, /*sandbox*/ None)
.await?,
"remote\n"
);
submit_turn_with_approval_and_environments(
&test,
"apply patch again in remote environment",
environments,
)
.await?;
wait_for_completion_without_patch_approval(&test).await;
assert_eq!(
test.fs()
.read_file_text(&target_path, /*sandbox*/ None)
.await?,
"remote updated\n"
);
let _ = fs::remove_file(&target_path);
test.fs()
.remove(
&target_path,
RemoveOptions {
recursive: false,
force: true,
},
/*sandbox*/ None,
)
.await?;
test.fs()
.remove(
&remote_cwd,
RemoveOptions {
recursive: true,
force: true,
},
/*sandbox*/ None,
)
.await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn apply_patch_intercepted_exec_command_routes_to_selected_remote_environment() -> Result<()>
{
skip_if_no_network!(Ok(()));
let Some(_remote_env) = get_remote_test_env() else {
return Ok(());
};
let server = start_mock_server().await;
let test = unified_exec_test(&server).await?;
let local_cwd = TempDir::new()?;
let file_name = "apply_patch_remote_exec.txt";
let remote_cwd = PathBuf::from(format!(
"/tmp/codex-remote-apply-patch-exec-{}",
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
test.fs()
.create_directory(
&remote_cwd,
CreateDirectoryOptions { recursive: true },
/*sandbox*/ None,
)
.await?;
let patch =
format!("*** Begin Patch\n*** Add File: {file_name}\n+patched remote exec\n*** End Patch");
let command = format!("apply_patch <<'EOF'\n{patch}\nEOF\n");
let call_id = "apply-patch-remote-exec";
mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call(
call_id,
"exec_command",
&serde_json::to_string(&json!({
"shell": "/bin/sh",
"cmd": command,
"login": false,
"yield_time_ms": 5_000,
"environment_id": REMOTE_ENVIRONMENT_ID,
}))?,
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
]),
],
)
.await;
test.submit_turn_with_environments(
"apply patch through exec command to remote environment",
Some(vec![
TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: local_cwd.path().abs(),
},
TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd.clone(),
},
]),
)
.await?;
let remote_contents = test
.fs()
.read_file_text(&remote_cwd.join(file_name), /*sandbox*/ None)
.await?;
assert_eq!(remote_contents, "patched remote exec\n");
assert!(
!local_cwd.path().join(file_name).exists(),
"intercepted apply_patch should not create the file in the local environment"
);
test.fs()
.remove(
&remote_cwd,
RemoveOptions {
recursive: true,
force: true,
},
/*sandbox*/ None,
)
.await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_test_env_sandboxed_read_allows_readable_root() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -533,6 +533,7 @@ async fn remote_models_remote_model_uses_unified_exec() -> Result<()> {
supports_search_tool: false,
priority: 1,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
upgrade: None,
base_instructions: "base instructions".to_string(),
model_messages: None,
@@ -789,6 +790,7 @@ async fn remote_models_apply_remote_base_instructions() -> Result<()> {
supports_search_tool: false,
priority: 1,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
upgrade: None,
base_instructions: remote_base.to_string(),
model_messages: None,
@@ -1279,6 +1281,7 @@ fn test_remote_model_with_policy(
supports_search_tool: false,
priority,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
upgrade: None,
base_instructions: "base instructions".to_string(),
model_messages: None,
@@ -17,7 +17,7 @@ use codex_protocol::request_permissions::RequestPermissionProfile;
use codex_protocol::request_permissions::RequestPermissionsResponse;
use codex_protocol::user_input::UserInput;
use codex_utils_absolute_path::AbsolutePathBuf;
use core_test_support::responses::ev_apply_patch_function_call;
use core_test_support::responses::ev_apply_patch_custom_tool_call;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call;
@@ -264,7 +264,7 @@ async fn approved_folder_write_request_permissions_unblocks_later_exec_without_s
"write outside the workspace",
approval_policy,
permission_profile,
/*approvals_reviewer*/ None,
Some(ApprovalsReviewer::User),
)
.await?;
@@ -340,6 +340,7 @@ async fn apply_patch_after_request_permissions(strict_auto_review: bool) -> Resu
let permission_profile_for_config = permission_profile.clone();
let mut builder = test_codex().with_config(move |config| {
config.include_apply_patch_tool = true;
config.permissions.approval_policy = Constrained::allow_any(approval_policy);
config
.permissions
@@ -367,7 +368,10 @@ async fn apply_patch_after_request_permissions(strict_auto_review: bool) -> Resu
} else {
"patched-via-request-permissions"
};
let requested_file = requested_dir.path().join(requested_file_name);
let requested_file = requested_dir
.path()
.canonicalize()?
.join(requested_file_name);
let requested_permissions = requested_directory_write_permissions(requested_dir.path());
let normalized_requested_permissions =
normalized_directory_write_permissions(requested_dir.path())?;
@@ -390,7 +394,7 @@ async fn apply_patch_after_request_permissions(strict_auto_review: bool) -> Resu
]),
sse(vec![
ev_response_created(&format!("{response_prefix}-2")),
ev_apply_patch_function_call("apply-patch-call", &patch),
ev_apply_patch_custom_tool_call("apply-patch-call", &patch),
ev_completed(&format!("{response_prefix}-2")),
]),
];
@@ -422,7 +426,7 @@ async fn apply_patch_after_request_permissions(strict_auto_review: bool) -> Resu
"patch outside the workspace",
approval_policy,
permission_profile,
strict_auto_review.then_some(ApprovalsReviewer::User),
Some(ApprovalsReviewer::User),
)
.await?;
@@ -463,8 +467,7 @@ async fn apply_patch_after_request_permissions(strict_auto_review: bool) -> Resu
EventMsg::TurnComplete(_) => {}
EventMsg::ApplyPatchApprovalRequest(approval) => {
panic!(
"unexpected apply_patch approval request after granted permissions: {:?}",
approval.call_id
"unexpected apply_patch approval request after granted permissions: {approval:?}",
)
}
other => panic!("unexpected event: {other:?}"),
@@ -472,7 +475,22 @@ async fn apply_patch_after_request_permissions(strict_auto_review: bool) -> Resu
}
let patch_output = responses
.function_call_output_text("apply-patch-call")
.requests()
.into_iter()
.find_map(|request| {
request
.input()
.into_iter()
.find(|item| {
item.get("type").and_then(Value::as_str) == Some("custom_tool_call_output")
&& item.get("call_id").and_then(Value::as_str) == Some("apply-patch-call")
})
.and_then(|item| {
item.get("output")
.and_then(Value::as_str)
.map(str::to_string)
})
})
.map(|output| json!({ "output": output }))
.unwrap_or_else(|| panic!("expected apply-patch-call output"));
let (exit_code, stdout) = parse_result(&patch_output);
@@ -22,7 +22,7 @@ use core_test_support::test_codex::test_codex;
use serde_json::Value;
const TOOL_SEARCH_TOOL_NAME: &str = "tool_search";
const TOOL_SUGGEST_TOOL_NAME: &str = "tool_suggest";
const REQUEST_PLUGIN_INSTALL_TOOL_NAME: &str = "request_plugin_install";
const DISCOVERABLE_GMAIL_ID: &str = "connector_68df038e0ba48191908c8434991bbac2";
fn tool_names(body: &Value) -> Vec<String> {
@@ -89,7 +89,8 @@ fn configure_apps_without_search_tool(config: &mut Config, apps_base_url: &str)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tool_suggest_is_available_without_search_tool_after_discovery_attempts() -> Result<()> {
async fn request_plugin_install_is_available_without_search_tool_after_discovery_attempts()
-> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -125,18 +126,23 @@ async fn tool_suggest_is_available_without_search_tool_after_discovery_attempts(
"tools list should not include {TOOL_SEARCH_TOOL_NAME}: {tools:?}"
);
assert!(
tools.iter().any(|name| name == TOOL_SUGGEST_TOOL_NAME),
"tools list should include {TOOL_SUGGEST_TOOL_NAME}: {tools:?}"
tools
.iter()
.any(|name| name == REQUEST_PLUGIN_INSTALL_TOOL_NAME),
"tools list should include {REQUEST_PLUGIN_INSTALL_TOOL_NAME}: {tools:?}"
);
let description =
function_tool_description(&body, TOOL_SUGGEST_TOOL_NAME).expect("description");
function_tool_description(&body, REQUEST_PLUGIN_INSTALL_TOOL_NAME).expect("description");
assert!(description.contains(
"Use this tool only to ask the user to install one known plugin or connector from the list below"
));
assert!(description.contains(
"`tool_search` is not available, or it has already been called and did not find or make the requested tool callable."
));
assert!(description.contains(
"Only use when the user explicitly asks to use that exact listed plugin or connector."
));
assert!(description.contains("IMPORTANT: DO NOT call this tool in parallel with other tools."));
assert!(!description.contains("tool_search fails to find a good match"));
@@ -17,6 +17,7 @@ use core_test_support::responses;
use core_test_support::responses::ResponsesRequest;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_completed_with_tokens;
use core_test_support::responses::ev_function_call;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::sse;
@@ -30,6 +31,8 @@ use core_test_support::wait_for_event_match;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tokio::time::Duration;
use tokio::time::timeout;
fn call_output(req: &ResponsesRequest, call_id: &str) -> String {
let raw = req.function_call_output(call_id);
@@ -118,6 +121,7 @@ async fn request_user_input_round_trip_for_mode(mode: ModeKind) -> anyhow::Resul
let first_response = sse(vec![
ev_response_created("resp-1"),
ev_function_call(call_id, "request_user_input", &request_args),
ev_rate_limits(),
ev_completed("resp-1"),
]);
responses::mount_sse_once(&server, first_response).await;
@@ -169,6 +173,22 @@ async fn request_user_input_round_trip_for_mode(mode: ModeKind) -> anyhow::Resul
assert_eq!(request.call_id, call_id);
assert_eq!(request.questions.len(), 1);
assert_eq!(request.questions[0].is_other, true);
assert!(
timeout(Duration::from_millis(200), async {
loop {
let event = match codex.next_event().await {
Ok(event) => event,
Err(err) => panic!("event stream should stay open: {err}"),
};
if matches!(event.msg, EventMsg::TokenCount(_)) {
return;
}
}
})
.await
.is_err(),
"TokenCount should wait until request_user_input resolves"
);
let mut answers = HashMap::new();
answers.insert(
@@ -185,6 +205,7 @@ async fn request_user_input_round_trip_for_mode(mode: ModeKind) -> anyhow::Resul
})
.await?;
wait_for_event(&codex, |event| matches!(event, EventMsg::TokenCount(_))).await;
wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await;
let req = second_mock.single_request();
@@ -202,6 +223,118 @@ async fn request_user_input_round_trip_for_mode(mode: ModeKind) -> anyhow::Resul
Ok(())
}
fn ev_rate_limits() -> Value {
json!({
"type": "codex.rate_limits",
"plan_type": "plus",
"rate_limits": {
"allowed": true,
"limit_reached": false,
"primary": {
"used_percent": 42,
"window_minutes": 60,
"reset_at": 1700000000
},
"secondary": null
},
"code_review_rate_limits": null,
"credits": null,
"promo": null
})
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn request_user_input_interrupt_emits_deferred_token_count() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let TestCodex {
codex,
cwd,
session_configured,
..
} = test_codex().build(&server).await?;
let call_id = "user-input-interrupt";
let request_args = json!({
"questions": [{
"id": "confirm_path",
"header": "Confirm",
"question": "Proceed with the plan?",
"options": [{
"label": "Yes (Recommended)",
"description": "Continue the current plan."
}, {
"label": "No",
"description": "Stop and revisit the approach."
}]
}]
})
.to_string();
let response = sse(vec![
ev_response_created("resp-interrupt"),
ev_function_call(call_id, "request_user_input", &request_args),
ev_completed_with_tokens("resp-interrupt", /*total_tokens*/ 77),
]);
responses::mount_sse_once(&server, response).await;
let (sandbox_policy, permission_profile) =
turn_permission_fields(PermissionProfile::Disabled, cwd.path());
codex
.submit(Op::UserTurn {
environments: None,
items: vec![UserInput::Text {
text: "please confirm".into(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
cwd: cwd.path().to_path_buf(),
approval_policy: AskForApproval::Never,
approvals_reviewer: None,
sandbox_policy,
permission_profile,
model: session_configured.model.clone(),
effort: None,
summary: None,
service_tier: None,
collaboration_mode: Some(CollaborationMode {
mode: ModeKind::Plan,
settings: Settings {
model: session_configured.model,
reasoning_effort: None,
developer_instructions: None,
},
}),
personality: None,
})
.await?;
let request = wait_for_event_match(&codex, |event| match event {
EventMsg::RequestUserInput(request) => Some(request.clone()),
_ => None,
})
.await;
codex.submit(Op::Interrupt).await?;
let token_count = wait_for_event_match(&codex, |event| match event {
EventMsg::TokenCount(token_count) => Some(token_count.clone()),
_ => None,
})
.await;
assert_eq!(
token_count
.info
.map(|info| info.total_token_usage.total_tokens),
Some(77)
);
wait_for_event(&codex, |event| matches!(event, EventMsg::TurnAborted(_))).await;
assert_eq!(request.call_id, call_id);
Ok(())
}
async fn assert_request_user_input_rejected<F>(mode_name: &str, build_mode: F) -> anyhow::Result<()>
where
F: FnOnce(String) -> CollaborationMode,
-4
View File
@@ -109,7 +109,6 @@ async fn resume_includes_initial_messages_from_rollout_events() -> Result<()> {
[
EventMsg::TurnStarted(_),
EventMsg::UserMessage(_),
EventMsg::TokenCount(_),
EventMsg::AgentMessage(_),
EventMsg::TokenCount(_),
EventMsg::TurnComplete(_),
@@ -126,7 +125,6 @@ async fn resume_includes_initial_messages_from_rollout_events() -> Result<()> {
[
EventMsg::TurnStarted(started),
EventMsg::UserMessage(first_user),
EventMsg::TokenCount(_),
EventMsg::AgentMessage(assistant_message),
EventMsg::TokenCount(_),
EventMsg::TurnComplete(completed),
@@ -196,7 +194,6 @@ async fn resume_includes_initial_messages_from_reasoning_events() -> Result<()>
[
EventMsg::TurnStarted(_),
EventMsg::UserMessage(_),
EventMsg::TokenCount(_),
EventMsg::AgentReasoning(_),
EventMsg::AgentReasoningRawContent(_),
EventMsg::AgentMessage(_),
@@ -215,7 +212,6 @@ async fn resume_includes_initial_messages_from_reasoning_events() -> Result<()>
[
EventMsg::TurnStarted(started),
EventMsg::UserMessage(first_user),
EventMsg::TokenCount(_),
EventMsg::AgentReasoning(reasoning),
EventMsg::AgentReasoningRawContent(raw),
EventMsg::AgentMessage(assistant_message),
+42 -57
View File
@@ -242,31 +242,42 @@ fn copy_binary_to_remote_env(
Ok(remote_path)
}
async fn wait_for_mcp_tool(fixture: &TestCodex, tool_name: &str) -> anyhow::Result<()> {
let tools_ready_deadline = Instant::now() + Duration::from_secs(30);
loop {
fixture.codex.submit(Op::ListMcpTools).await?;
let list_event = wait_for_event_with_timeout(
&fixture.codex,
|ev| matches!(ev, EventMsg::McpListToolsResponse(_)),
Duration::from_secs(10),
)
.await;
let EventMsg::McpListToolsResponse(tool_list) = list_event else {
unreachable!("event guard guarantees McpListToolsResponse");
};
if tool_list.tools.contains_key(tool_name) {
return Ok(());
}
let available_tools: Vec<&str> = tool_list.tools.keys().map(String::as_str).collect();
if Instant::now() >= tools_ready_deadline {
panic!(
"timed out waiting for MCP tool {tool_name} to become available; discovered tools: {available_tools:?}"
);
}
sleep(Duration::from_millis(200)).await;
async fn wait_for_mcp_server(fixture: &TestCodex, server_name: &str) -> anyhow::Result<()> {
let startup_event = wait_for_event_with_timeout(
&fixture.codex,
|ev| match ev {
EventMsg::McpStartupComplete(summary) => {
summary.ready.iter().any(|server| server == server_name)
|| summary
.failed
.iter()
.any(|failure| failure.server == server_name)
|| summary.cancelled.iter().any(|server| server == server_name)
}
_ => false,
},
Duration::from_secs(70),
)
.await;
let EventMsg::McpStartupComplete(summary) = startup_event else {
unreachable!("event guard guarantees McpStartupComplete");
};
if let Some(failure) = summary
.failed
.iter()
.find(|failure| failure.server == server_name)
{
let error = &failure.error;
anyhow::bail!("MCP server {server_name} failed to start: {error}");
}
if summary.cancelled.iter().any(|server| server == server_name) {
anyhow::bail!("MCP server {server_name} startup was cancelled");
}
ensure!(
summary.ready.iter().any(|server| server == server_name),
"expected MCP server {server_name} to be ready; startup summary: {summary:?}"
);
Ok(())
}
#[derive(Default)]
@@ -731,7 +742,6 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta() -> anyhow::Result<()>
let call_id = "sandbox-meta-call";
let server_name = "rmcp";
let namespace = format!("mcp__{server_name}__");
let tool_name = format!("{namespace}sandbox_meta");
let call_mock = mount_sse_once(
&server,
@@ -767,30 +777,7 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta() -> anyhow::Result<()>
.build_remote_aware(&server)
.await?;
let tools_ready_deadline = Instant::now() + Duration::from_secs(30);
loop {
fixture.codex.submit(Op::ListMcpTools).await?;
let list_event = wait_for_event_with_timeout(
&fixture.codex,
|ev| matches!(ev, EventMsg::McpListToolsResponse(_)),
Duration::from_secs(10),
)
.await;
let EventMsg::McpListToolsResponse(tool_list) = list_event else {
unreachable!("event guard guarantees McpListToolsResponse");
};
if tool_list.tools.contains_key(&tool_name) {
break;
}
let available_tools: Vec<&str> = tool_list.tools.keys().map(String::as_str).collect();
if Instant::now() >= tools_ready_deadline {
panic!(
"timed out waiting for MCP tool {tool_name} to become available; discovered tools: {available_tools:?}"
);
}
sleep(Duration::from_millis(200)).await;
}
wait_for_mcp_server(&fixture, server_name).await?;
fixture
.submit_turn_with_permission_profile(
@@ -1039,7 +1026,6 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> {
let call_id = "img-1";
let server_name = "rmcp";
let tool_name = format!("mcp__{server_name}__image");
let namespace = format!("mcp__{server_name}__");
// First stream: model decides to call the image tool.
@@ -1086,7 +1072,7 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> {
})
.build_remote_aware(&server)
.await?;
wait_for_mcp_tool(&fixture, &tool_name).await?;
wait_for_mcp_server(&fixture, server_name).await?;
fixture
.codex
@@ -1176,7 +1162,6 @@ async fn stdio_image_responses_preserve_original_detail_metadata() -> anyhow::Re
let call_id = "img-original-detail-1";
let server_name = "rmcp";
let tool_name = format!("mcp__{server_name}__image_scenario");
let namespace = format!("mcp__{server_name}__");
mount_sse_once(
@@ -1219,7 +1204,7 @@ async fn stdio_image_responses_preserve_original_detail_metadata() -> anyhow::Re
})
.build_remote_aware(&server)
.await?;
wait_for_mcp_tool(&fixture, &tool_name).await?;
wait_for_mcp_server(&fixture, server_name).await?;
fixture
.codex
@@ -1283,6 +1268,7 @@ async fn stdio_image_responses_are_sanitized_for_text_only_model() -> anyhow::Re
supported_in_api: true,
priority: 1,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
upgrade: None,
base_instructions: "base instructions".to_string(),
model_messages: None,
@@ -1954,7 +1940,6 @@ async fn streamable_http_with_oauth_round_trip_impl() -> anyhow::Result<()> {
let call_id = "call-789";
let server_name = "rmcp_http_oauth";
let tool_name = format!("mcp__{server_name}__echo");
let namespace = format!("mcp__{server_name}__");
mount_sse_once(
@@ -2035,9 +2020,9 @@ async fn streamable_http_with_oauth_round_trip_impl() -> anyhow::Result<()> {
})
.build_remote_aware(&server)
.await?;
// Phase 5: wait for MCP discovery to publish the expected tool before the
// turn is submitted, which keeps failures tied to server startup/discovery.
wait_for_mcp_tool(&fixture, &tool_name).await?;
// Phase 5: wait for MCP startup before the turn is submitted, which keeps
// failures tied to server startup/discovery.
wait_for_mcp_server(&fixture, server_name).await?;
// Phase 6: submit the user turn that should invoke the OAuth-backed tool.
fixture
+41 -26
View File
@@ -4,7 +4,6 @@ use std::path::Path;
use std::path::PathBuf;
use chrono::Utc;
use codex_core::EventPersistenceMode;
use codex_core::RolloutRecorder;
use codex_core::RolloutRecorderParams;
use codex_core::config::ConfigBuilder;
@@ -14,6 +13,7 @@ use codex_core::find_thread_path_by_id_str;
use codex_protocol::ThreadId;
use codex_protocol::models::BaseInstructions;
use codex_protocol::protocol::SessionSource;
use codex_rollout::StateDbHandle;
use codex_state::StateRuntime;
use codex_state::ThreadMetadataBuilder;
use pretty_assertions::assert_eq;
@@ -27,7 +27,13 @@ fn write_minimal_rollout_with_id_in_subdir(codex_home: &Path, subdir: &str, id:
std::fs::create_dir_all(&sessions).unwrap();
let file = sessions.join(format!("rollout-2024-01-01T00-00-00-{id}.jsonl"));
let mut f = std::fs::File::create(&file).unwrap();
write_minimal_rollout_with_id_at_path(&file, id);
file
}
fn write_minimal_rollout_with_id_at_path(file: &Path, id: Uuid) {
let mut f = std::fs::File::create(file).unwrap();
// Minimal first line: session_meta with the id so content search can find it
writeln!(
f,
@@ -46,8 +52,6 @@ fn write_minimal_rollout_with_id_in_subdir(codex_home: &Path, subdir: &str, id:
})
)
.unwrap();
file
}
/// Create sessions/YYYY/MM/DD and write a minimal rollout file containing the
@@ -56,7 +60,11 @@ fn write_minimal_rollout_with_id(codex_home: &Path, id: Uuid) -> PathBuf {
write_minimal_rollout_with_id_in_subdir(codex_home, "sessions", id)
}
async fn upsert_thread_metadata(codex_home: &Path, thread_id: ThreadId, rollout_path: PathBuf) {
async fn upsert_thread_metadata(
codex_home: &Path,
thread_id: ThreadId,
rollout_path: PathBuf,
) -> StateDbHandle {
let runtime = StateRuntime::init(codex_home.to_path_buf(), "test-provider".to_string())
.await
.unwrap();
@@ -73,6 +81,7 @@ async fn upsert_thread_metadata(codex_home: &Path, thread_id: ThreadId, rollout_
builder.cwd = codex_home.to_path_buf();
let metadata = builder.build("test-provider");
runtime.upsert_thread(&metadata).await.unwrap();
runtime
}
#[tokio::test]
@@ -81,9 +90,10 @@ async fn find_locates_rollout_file_by_id() {
let id = Uuid::new_v4();
let expected = write_minimal_rollout_with_id(home.path(), id);
let found = find_thread_path_by_id_str(home.path(), &id.to_string())
.await
.unwrap();
let found =
find_thread_path_by_id_str(home.path(), &id.to_string(), /*state_db_ctx*/ None)
.await
.unwrap();
assert_eq!(found.unwrap(), expected);
}
@@ -97,9 +107,10 @@ async fn find_handles_gitignore_covering_codex_home_directory() {
let id = Uuid::new_v4();
let expected = write_minimal_rollout_with_id(&codex_home, id);
let found = find_thread_path_by_id_str(&codex_home, &id.to_string())
.await
.unwrap();
let found =
find_thread_path_by_id_str(&codex_home, &id.to_string(), /*state_db_ctx*/ None)
.await
.unwrap();
assert_eq!(found, Some(expected));
}
@@ -113,11 +124,11 @@ async fn find_prefers_sqlite_path_by_id() {
"sessions/2030/12/30/rollout-2030-12-30T00-00-00-{id}.jsonl"
));
std::fs::create_dir_all(db_path.parent().unwrap()).unwrap();
std::fs::write(&db_path, "").unwrap();
write_minimal_rollout_with_id_at_path(&db_path, id);
write_minimal_rollout_with_id(home.path(), id);
upsert_thread_metadata(home.path(), thread_id, db_path.clone()).await;
let state_db = upsert_thread_metadata(home.path(), thread_id, db_path.clone()).await;
let found = find_thread_path_by_id_str(home.path(), &id.to_string())
let found = find_thread_path_by_id_str(home.path(), &id.to_string(), Some(&state_db))
.await
.unwrap();
@@ -134,9 +145,9 @@ async fn find_falls_back_to_filesystem_when_sqlite_has_no_match() {
let unrelated_path = home
.path()
.join("sessions/2030/12/30/rollout-2030-12-30T00-00-00-unrelated.jsonl");
upsert_thread_metadata(home.path(), unrelated_thread_id, unrelated_path).await;
let state_db = upsert_thread_metadata(home.path(), unrelated_thread_id, unrelated_path).await;
let found = find_thread_path_by_id_str(home.path(), &id.to_string())
let found = find_thread_path_by_id_str(home.path(), &id.to_string(), Some(&state_db))
.await
.unwrap();
@@ -150,9 +161,10 @@ async fn find_ignores_granular_gitignore_rules() {
let expected = write_minimal_rollout_with_id(home.path(), id);
std::fs::write(home.path().join("sessions/.gitignore"), "*.jsonl\n").unwrap();
let found = find_thread_path_by_id_str(home.path(), &id.to_string())
.await
.unwrap();
let found =
find_thread_path_by_id_str(home.path(), &id.to_string(), /*state_db_ctx*/ None)
.await
.unwrap();
assert_eq!(found, Some(expected));
}
@@ -173,12 +185,10 @@ async fn find_locates_rollout_file_written_by_recorder() -> std::io::Result<()>
thread_id,
/*forked_from_id*/ None,
SessionSource::Exec,
/*thread_source*/ None,
BaseInstructions::default(),
Vec::new(),
EventPersistenceMode::Limited,
),
/*state_db_ctx*/ None,
/*state_builder*/ None,
)
.await?;
recorder.persist().await?;
@@ -197,7 +207,8 @@ async fn find_locates_rollout_file_written_by_recorder() -> std::io::Result<()>
),
)?;
let found = find_thread_meta_by_name_str(home.path(), thread_name).await?;
let found =
find_thread_meta_by_name_str(home.path(), thread_name, /*state_db_ctx*/ None).await?;
let (path, session_meta) = found.expect("expected rollout path to be found");
assert_eq!(session_meta.meta.id, thread_id);
@@ -214,9 +225,13 @@ async fn find_archived_locates_rollout_file_by_id() {
let id = Uuid::new_v4();
let expected = write_minimal_rollout_with_id_in_subdir(home.path(), "archived_sessions", id);
let found = find_archived_thread_path_by_id_str(home.path(), &id.to_string())
.await
.unwrap();
let found = find_archived_thread_path_by_id_str(
home.path(),
&id.to_string(),
/*state_db_ctx*/ None,
)
.await
.unwrap();
assert_eq!(found, Some(expected));
}
@@ -59,7 +59,7 @@ fn disabled_text_turn(test: &TestCodex, text: &str) -> Op {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn openai_model_header_mismatch_emits_warning_event_and_warning_item() -> Result<()> {
async fn openai_model_header_mismatch_emits_warning_event() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -92,36 +92,6 @@ async fn openai_model_header_mismatch_emits_warning_event_and_warning_item() ->
assert!(warning.message.contains(REQUESTED_MODEL));
assert!(warning.message.contains(SERVER_MODEL));
let warning_item = wait_for_event(&test.codex, |event| {
matches!(
event,
EventMsg::RawResponseItem(raw)
if matches!(
&raw.item,
ResponseItem::Message { content, .. }
if content.iter().any(|item| matches!(
item,
ContentItem::InputText { text } if text.starts_with("Warning: ")
))
)
)
})
.await;
let EventMsg::RawResponseItem(raw) = warning_item else {
panic!("expected raw response item event");
};
let ResponseItem::Message { role, content, .. } = raw.item else {
panic!("expected warning to be recorded as a message item");
};
assert_eq!(role, "user");
let warning_text = content.iter().find_map(|item| match item {
ContentItem::InputText { text } => Some(text.as_str()),
_ => None,
});
let warning_text = warning_text.expect("warning message should include input_text content");
assert!(warning_text.contains(REQUESTED_MODEL));
assert!(warning_text.contains(SERVER_MODEL));
let _ = wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
+470 -1
View File
@@ -24,6 +24,7 @@ use core_test_support::apps_test_server::CALENDAR_CREATE_EVENT_RESOURCE_URI;
use core_test_support::responses::ResponsesRequest;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call_with_namespace;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::ev_tool_search_call;
use core_test_support::responses::mount_sse_once;
@@ -98,6 +99,18 @@ fn tool_search_output_tools(request: &ResponsesRequest, call_id: &str) -> Vec<Va
.unwrap_or_default()
}
fn tool_search_output_has_namespace_child(
request: &ResponsesRequest,
call_id: &str,
namespace: &str,
tool_name: &str,
) -> bool {
let output = json!({
"tools": tool_search_output_tools(request, call_id),
});
namespace_child_tool(&output, namespace, tool_name).is_some()
}
fn configure_search_capable_model(config: &mut Config) {
let mut model_catalog = bundled_models_response()
.unwrap_or_else(|err| panic!("bundled models.json should parse: {err}"));
@@ -570,6 +583,7 @@ async fn tool_search_returns_deferred_tools_without_follow_up_tool_injection() -
let requests = mock.requests();
assert_eq!(requests.len(), 3);
let first_request_body = requests[0].body_json();
let apps_tool_call = server
.received_requests()
@@ -597,6 +611,10 @@ async fn tool_search_returns_deferred_tools_without_follow_up_tool_injection() -
apps_tool_call.pointer("/params/_meta/x-codex-turn-metadata/session_id"),
Some(&json!(test.session_configured.session_id.to_string()))
);
assert_eq!(
apps_tool_call.pointer("/params/_meta/x-codex-turn-metadata/thread_id"),
Some(&json!(test.session_configured.thread_id.to_string()))
);
assert!(
apps_tool_call
.pointer("/params/_meta/x-codex-turn-metadata/turn_id")
@@ -604,6 +622,22 @@ async fn tool_search_returns_deferred_tools_without_follow_up_tool_injection() -
.is_some_and(|turn_id| !turn_id.is_empty()),
"apps tools/call should include turn metadata turn_id: {apps_tool_call:?}"
);
assert_eq!(
apps_tool_call
.pointer("/params/_meta/x-codex-turn-metadata/model")
.and_then(Value::as_str),
Some("gpt-5.4")
);
let first_request_reasoning_effort = first_request_body
.pointer("/reasoning/effort")
.and_then(Value::as_str)
.expect("first response request should include reasoning effort");
assert_eq!(
apps_tool_call
.pointer("/params/_meta/x-codex-turn-metadata/reasoning_effort")
.and_then(Value::as_str),
Some(first_request_reasoning_effort)
);
let mcp_turn_started_at_unix_ms = apps_tool_call
.pointer("/params/_meta/x-codex-turn-metadata/turn_started_at_unix_ms")
.and_then(Value::as_i64)
@@ -626,7 +660,6 @@ async fn tool_search_returns_deferred_tools_without_follow_up_tool_injection() -
Some(mcp_turn_started_at_unix_ms)
);
let first_request_body = requests[0].body_json();
let first_request_tools = tool_names(&first_request_body);
assert!(
first_request_tools
@@ -1029,3 +1062,439 @@ async fn tool_search_indexes_only_enabled_non_app_mcp_tools() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tool_search_surfaced_mcp_tool_errors_are_returned_to_model() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let apps_server = AppsTestServer::mount_searchable(&server).await?;
let search_call_id = "tool-search-rmcp-echo";
let tool_call_id = "rmcp-echo-error";
let mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_tool_search_call(
search_call_id,
&json!({
"query": "Echo back the provided message and include environment data.",
"limit": 8,
}),
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_function_call_with_namespace(tool_call_id, "mcp__rmcp__", "echo", "{}"),
ev_completed("resp-2"),
]),
sse(vec![
ev_response_created("resp-3"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-3"),
]),
],
)
.await;
let rmcp_test_server_bin = stdio_server_bin()?;
let mut builder =
configured_builder(apps_server.chatgpt_base_url.clone()).with_config(move |config| {
config
.features
.enable(Feature::ToolSearchAlwaysDeferMcpTools)
.expect("test config should allow feature update");
let mut servers = config.mcp_servers.get().clone();
servers.insert(
"rmcp".to_string(),
McpServerConfig {
transport: McpServerTransportConfig::Stdio {
command: rmcp_test_server_bin,
args: Vec::new(),
env: None,
env_vars: Vec::new(),
cwd: None,
},
experimental_environment: None,
enabled: true,
required: false,
disabled_reason: None,
startup_timeout_sec: Some(Duration::from_secs(10)),
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: Some(vec!["echo".to_string()]),
disabled_tools: None,
scopes: None,
oauth_resource: None,
supports_parallel_tool_calls: false,
tools: HashMap::new(),
},
);
config
.mcp_servers
.set(servers)
.expect("test mcp servers should accept any configuration");
});
let test = builder.build(&server).await?;
test.codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "Find the rmcp echo tool and call it.".to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await?;
let EventMsg::McpToolCallEnd(end) = wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::McpToolCallEnd(_))
})
.await
else {
unreachable!("event guard guarantees McpToolCallEnd");
};
assert_eq!(end.call_id, tool_call_id);
assert!(!end.is_success());
let tool_error = end
.result
.as_ref()
.expect_err("rmcp echo error should stay in the MCP result");
assert!(
tool_error.contains("tool call error:")
&& tool_error.contains("missing field")
&& tool_error.contains("message"),
"MCP invocation should report the execution failure: {tool_error}"
);
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
let requests = mock.requests();
assert_eq!(requests.len(), 3);
let first_request_tools = tool_names(&requests[0].body_json());
assert!(
first_request_tools
.iter()
.any(|name| name == TOOL_SEARCH_TOOL_NAME),
"first request should advertise tool_search: {first_request_tools:?}"
);
assert!(
!first_request_tools.iter().any(|name| name == "mcp__rmcp__"),
"deferred rmcp namespace should not be directly exposed before search: {first_request_tools:?}"
);
assert!(
tool_search_output_has_namespace_child(&requests[1], search_call_id, "mcp__rmcp__", "echo"),
"tool_search should return the rmcp echo tool"
);
let output = requests[2].function_call_output(tool_call_id);
let output_text = match output.get("output") {
Some(Value::String(text)) => text.clone(),
Some(Value::Array(items)) => items
.iter()
.filter_map(|item| item.get("text").and_then(Value::as_str))
.collect::<Vec<_>>()
.join("\n"),
other => panic!("unexpected MCP error output payload: {other:?}"),
};
assert!(
output_text.contains("missing field") && output_text.contains("message"),
"MCP error output should be model visible: {output_text}"
);
assert!(
!output_text.contains("unsupported call"),
"search-surfaced MCP calls should not fall through to unsupported call: {output_text}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tool_search_uses_non_app_mcp_server_instructions_as_namespace_description() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let apps_server = AppsTestServer::mount_searchable(&server).await?;
let search_call_id = "tool-search-echo";
let mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_tool_search_call(
search_call_id,
&json!({
"query": "Echo back the provided message and include environment data.",
"limit": 8,
}),
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
]),
],
)
.await;
let rmcp_test_server_bin = stdio_server_bin()?;
let mut builder =
configured_builder(apps_server.chatgpt_base_url.clone()).with_config(move |config| {
let mut servers = config.mcp_servers.get().clone();
servers.insert(
"rmcp".to_string(),
McpServerConfig {
transport: McpServerTransportConfig::Stdio {
command: rmcp_test_server_bin,
args: Vec::new(),
env: None,
env_vars: Vec::new(),
cwd: None,
},
experimental_environment: None,
enabled: true,
required: false,
disabled_reason: None,
startup_timeout_sec: Some(Duration::from_secs(10)),
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: Some(vec!["echo".to_string()]),
disabled_tools: None,
scopes: None,
oauth_resource: None,
supports_parallel_tool_calls: false,
tools: HashMap::new(),
},
);
config
.mcp_servers
.set(servers)
.expect("test mcp servers should accept any configuration");
});
let test = builder.build(&server).await?;
test.submit_turn_with_approval_and_permission_profile(
"Find the rmcp echo tool.",
AskForApproval::Never,
PermissionProfile::Disabled,
)
.await?;
let requests = mock.requests();
assert_eq!(requests.len(), 2);
let tools = tool_search_output_tools(&requests[1], search_call_id);
let rmcp_namespace = tools
.iter()
.find(|tool| tool.get("name").and_then(Value::as_str) == Some("mcp__rmcp__"))
.expect("tool_search should return the rmcp namespace");
assert_eq!(
rmcp_namespace.get("description").and_then(Value::as_str),
Some("Use these tools to exercise the rmcp test server.")
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tool_search_matches_mcp_tools_by_distinct_name_description_and_schema_terms() -> Result<()>
{
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let apps_server = AppsTestServer::mount_searchable(&server).await?;
let query_cases = [
("tool-search-mcp-raw-name", "calendar_timezone_option_99"),
("tool-search-mcp-description", "uploaded document"),
("tool-search-mcp-schema", "starts_at"),
];
let mock = mount_sse_sequence(
&server,
vec![
sse(std::iter::once(ev_response_created("resp-1"))
.chain(query_cases.into_iter().map(|(call_id, query)| {
ev_tool_search_call(
call_id,
&json!({
"query": query,
"limit": 8,
}),
)
}))
.chain(std::iter::once(ev_completed("resp-1")))
.collect()),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
]),
],
)
.await;
let mut builder = configured_builder(apps_server.chatgpt_base_url.clone());
let test = builder.build(&server).await?;
test.submit_turn_with_approval_and_permission_profile(
"Search for calendar tooling.",
AskForApproval::Never,
PermissionProfile::Disabled,
)
.await?;
let requests = mock.requests();
assert_eq!(requests.len(), 2);
assert!(
tool_search_output_has_namespace_child(
&requests[1],
"tool-search-mcp-raw-name",
SEARCH_CALENDAR_NAMESPACE,
"_timezone_option_99"
),
"expected raw MCP tool-name query to surface _timezone_option_99: {:?}",
tool_search_output_tools(&requests[1], "tool-search-mcp-raw-name")
);
assert!(
tool_search_output_has_namespace_child(
&requests[1],
"tool-search-mcp-description",
SEARCH_CALENDAR_NAMESPACE,
"_extract_text"
),
"expected MCP description query to surface _extract_text: {:?}",
tool_search_output_tools(&requests[1], "tool-search-mcp-description")
);
assert!(
tool_search_output_has_namespace_child(
&requests[1],
"tool-search-mcp-schema",
SEARCH_CALENDAR_NAMESPACE,
SEARCH_CALENDAR_CREATE_TOOL
),
"expected MCP schema query to surface {SEARCH_CALENDAR_CREATE_TOOL}: {:?}",
tool_search_output_tools(&requests[1], "tool-search-mcp-schema")
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn tool_search_matches_dynamic_tools_by_name_description_namespace_and_schema_terms()
-> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let query_cases = [
("tool-search-dynamic-name", "quasar_ping_beacon"),
("tool-search-dynamic-spaces", "quasar ping beacon"),
("tool-search-dynamic-description", "saffron metronome"),
("tool-search-dynamic-namespace", "orbit_ops"),
("tool-search-dynamic-schema", "chrono_spec"),
];
let mock = mount_sse_sequence(
&server,
vec![
sse(std::iter::once(ev_response_created("resp-1"))
.chain(query_cases.into_iter().map(|(call_id, query)| {
ev_tool_search_call(
call_id,
&json!({
"query": query,
"limit": 8,
}),
)
}))
.chain(std::iter::once(ev_completed("resp-1")))
.collect()),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
]),
],
)
.await;
let dynamic_tool = DynamicToolSpec {
namespace: Some("orbit_ops".to_string()),
name: "quasar_ping_beacon".to_string(),
description: "Trigger the saffron metronome workflow for reminder follow-ups.".to_string(),
input_schema: json!({
"type": "object",
"properties": {
"chrono_spec": { "type": "string" },
"targetThreadId": { "type": "string" },
},
"required": ["chrono_spec"],
"additionalProperties": false,
}),
defer_loading: true,
};
let mut builder = test_codex().with_config(configure_search_capable_model);
let base_test = builder.build(&server).await?;
let new_thread = base_test
.thread_manager
.start_thread_with_tools(
base_test.config.clone(),
vec![dynamic_tool],
/*persist_extended_history*/ false,
)
.await?;
let mut test = base_test;
test.codex = new_thread.thread;
test.session_configured = new_thread.session_configured;
test.codex
.submit(Op::UserInput {
environments: None,
items: vec![UserInput::Text {
text: "Search for the dynamic tool".to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
})
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
let requests = mock.requests();
assert_eq!(requests.len(), 2);
for call_id in [
"tool-search-dynamic-name",
"tool-search-dynamic-spaces",
"tool-search-dynamic-description",
"tool-search-dynamic-namespace",
"tool-search-dynamic-schema",
] {
assert!(
tool_search_output_has_namespace_child(
&requests[1],
call_id,
"orbit_ops",
"quasar_ping_beacon"
),
"expected query {call_id} to surface the quasar_ping_beacon tool: {:?}",
tool_search_output_tools(&requests[1], call_id)
);
}
Ok(())
}
@@ -472,7 +472,6 @@ $"#;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
async fn apply_patch_custom_tool_output_is_structured(
@@ -518,7 +517,6 @@ A {file_name}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
async fn apply_patch_custom_tool_call_creates_file(
@@ -566,7 +564,6 @@ A {file_name}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
async fn apply_patch_custom_tool_call_updates_existing_file(
@@ -619,7 +616,6 @@ M {file_name}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
async fn apply_patch_custom_tool_call_reports_failure_output(
@@ -664,20 +660,17 @@ async fn apply_patch_custom_tool_call_reports_failure_output(
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(ApplyPatchModelOutput::Freeform)]
#[test_case(ApplyPatchModelOutput::Function)]
#[test_case(ApplyPatchModelOutput::Shell)]
#[test_case(ApplyPatchModelOutput::ShellViaHeredoc)]
async fn apply_patch_function_call_output_is_structured(
output_type: ApplyPatchModelOutput,
) -> Result<()> {
async fn apply_patch_tool_output_is_structured(output_type: ApplyPatchModelOutput) -> Result<()> {
skip_if_no_network!(Ok(()));
let harness = apply_patch_harness().await?;
let call_id = "apply-patch-function";
let file_name = "function_apply_patch.txt";
let file_name = "freeform_apply_patch.txt";
let patch =
format!("*** Begin Patch\n*** Add File: {file_name}\n+via function call\n*** End Patch\n");
format!("*** Begin Patch\n*** Add File: {file_name}\n+via apply_patch\n*** End Patch\n");
mount_apply_patch(
&harness,
call_id,
@@ -689,7 +682,7 @@ async fn apply_patch_function_call_output_is_structured(
harness
.test()
.submit_turn_with_permission_profile(
"apply the patch via function-call apply_patch",
"apply the patch via freeform apply_patch",
PermissionProfile::Disabled,
)
.await?;
-284
View File
@@ -2,20 +2,13 @@
#![allow(clippy::unwrap_used, clippy::expect_used)]
use anyhow::Result;
use codex_core::ThreadManager;
use codex_core::thread_store_from_config;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::EnvironmentManager;
use codex_exec_server::ExecServerRuntimePaths;
use codex_exec_server::ExecutorFileSystem;
use codex_login::CodexAuth;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::SessionSource;
use codex_protocol::user_input::UserInput;
use codex_utils_absolute_path::AbsolutePathBuf;
use core_test_support::load_default_config_for_test;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_response_created;
@@ -25,11 +18,7 @@ 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::test_codex::turn_permission_fields;
use pretty_assertions::assert_eq;
use std::fs;
use std::path::Path;
use std::sync::Arc;
use tempfile::TempDir;
async fn write_repo_skill(
cwd: AbsolutePathBuf,
@@ -52,22 +41,6 @@ async fn write_repo_skill(
Ok(())
}
fn write_home_skill(codex_home: &Path, dir: &str, name: &str, description: &str) -> Result<()> {
let skill_dir = codex_home.join("skills").join(dir);
fs::create_dir_all(&skill_dir)?;
let contents = format!("---\nname: {name}\ndescription: {description}\n---\n\n# Body\n");
fs::write(skill_dir.join("SKILL.md"), contents)?;
Ok(())
}
fn system_skill_md_path(home: impl AsRef<Path>, name: &str) -> std::path::PathBuf {
home.as_ref()
.join("skills")
.join(".system")
.join(name)
.join("SKILL.md")
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn user_turn_includes_skill_instructions() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -148,260 +121,3 @@ async fn user_turn_includes_skill_instructions() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_skills_includes_repo_and_home_skills_remote_aware() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mut builder = test_codex()
.with_pre_build_hook(|home| {
write_home_skill(home, "home-demo", "home-demo", "from home")
.expect("write home skill");
})
.with_workspace_setup(|cwd, fs| async move {
write_repo_skill(cwd, fs, "repo-demo", "from repo", "# Body").await
});
let test = builder.build_remote_aware(&server).await?;
test.codex
.submit(Op::ListSkills {
cwds: Vec::new(),
force_reload: true,
})
.await?;
let response =
core_test_support::wait_for_event_match(test.codex.as_ref(), |event| match event {
codex_protocol::protocol::EventMsg::ListSkillsResponse(response) => {
Some(response.clone())
}
_ => None,
})
.await;
let cwd = test.config.cwd.as_path();
let skills = response
.skills
.iter()
.find(|entry| entry.cwd.as_path() == cwd)
.map(|entry| entry.skills.clone())
.unwrap_or_default();
let repo_skill = skills
.iter()
.find(|skill| skill.name == "repo-demo")
.expect("expected repo skill");
assert_eq!(repo_skill.scope, codex_protocol::protocol::SkillScope::Repo);
let repo_path = repo_skill.path.to_string_lossy().replace('\\', "/");
assert!(
repo_path.ends_with("/.agents/skills/repo-demo/SKILL.md"),
"unexpected repo skill path: {repo_path}"
);
let home_skill = skills
.iter()
.find(|skill| skill.name == "home-demo")
.expect("expected home skill");
assert_eq!(home_skill.scope, codex_protocol::protocol::SkillScope::User);
let home_path = home_skill.path.to_string_lossy().replace('\\', "/");
assert!(
home_path.ends_with("/skills/home-demo/SKILL.md"),
"unexpected home skill path: {home_path}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_skills_skips_cwd_roots_when_environment_disabled() -> Result<()> {
let codex_home = TempDir::new()?;
let cwd = TempDir::new()?;
write_home_skill(
codex_home.path(),
"home-disabled",
"home-disabled",
"from home",
)?;
let repo_skill_dir = cwd
.path()
.join(".agents")
.join("skills")
.join("repo-disabled");
fs::create_dir_all(&repo_skill_dir)?;
fs::write(
repo_skill_dir.join("SKILL.md"),
"---\nname: repo-disabled\ndescription: from repo\n---\n\n# Body\n",
)?;
let mut config = load_default_config_for_test(&codex_home).await;
config.cwd = AbsolutePathBuf::from_absolute_path_checked(cwd.path())?;
let thread_manager = ThreadManager::new(
&config,
codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("dummy")),
SessionSource::Exec,
Arc::new(EnvironmentManager::disabled_for_tests(
ExecServerRuntimePaths::new(
std::env::current_exe()?,
/*codex_linux_sandbox_exe*/ None,
)?,
)),
/*analytics_events_client*/ None,
thread_store_from_config(&config),
);
let new_thread = thread_manager.start_thread(config.clone()).await?;
let cwd = config.cwd.to_path_buf();
new_thread
.thread
.submit(Op::ListSkills {
cwds: vec![cwd.clone()],
force_reload: true,
})
.await?;
let response =
core_test_support::wait_for_event_match(new_thread.thread.as_ref(), |event| match event {
codex_protocol::protocol::EventMsg::ListSkillsResponse(response) => {
Some(response.clone())
}
_ => None,
})
.await;
assert_eq!(response.skills.len(), 1);
assert_eq!(response.skills[0].cwd, cwd);
assert_eq!(response.skills[0].errors.len(), 0);
assert!(
response.skills[0]
.skills
.iter()
.any(|skill| skill.name == "home-disabled")
);
assert!(
response.skills[0]
.skills
.iter()
.all(|skill| skill.name != "repo-disabled")
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn skill_load_errors_surface_in_session_configured() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mut builder = test_codex().with_pre_build_hook(|home| {
let skill_dir = home.join("skills").join("broken");
fs::create_dir_all(&skill_dir).unwrap();
fs::write(skill_dir.join("SKILL.md"), "not yaml").unwrap();
});
let test = builder.build(&server).await?;
test.codex
.submit(Op::ListSkills {
cwds: Vec::new(),
force_reload: false,
})
.await?;
let response =
core_test_support::wait_for_event_match(test.codex.as_ref(), |event| match event {
codex_protocol::protocol::EventMsg::ListSkillsResponse(response) => {
Some(response.clone())
}
_ => None,
})
.await;
let cwd = test.cwd_path();
let (skills, errors) = response
.skills
.iter()
.find(|entry| entry.cwd.as_path() == cwd)
.map(|entry| (entry.skills.clone(), entry.errors.clone()))
.unwrap_or_default();
assert!(
skills.iter().all(|skill| {
!skill
.path
.to_string_lossy()
.ends_with("skills/broken/SKILL.md")
}),
"expected broken skill not loaded, got {skills:?}"
);
assert_eq!(errors.len(), 1, "expected one load error");
let error_path = errors[0].path.to_string_lossy();
assert!(
error_path.ends_with("skills/broken/SKILL.md"),
"unexpected error path: {error_path}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn list_skills_includes_system_cache_entries() -> Result<()> {
skip_if_no_network!(Ok(()));
const SYSTEM_SKILL_NAME: &str = "skill-creator";
let server = start_mock_server().await;
let mut builder = test_codex().with_pre_build_hook(|home| {
let system_skill_path = system_skill_md_path(home, SYSTEM_SKILL_NAME);
assert!(
!system_skill_path.exists(),
"expected embedded system skills not yet installed, but {system_skill_path:?} exists"
);
});
let test = builder.build(&server).await?;
let system_skill_path = system_skill_md_path(test.codex_home_path(), SYSTEM_SKILL_NAME);
assert!(
system_skill_path.exists(),
"expected embedded system skills installed to {system_skill_path:?}"
);
let system_skill_contents = fs::read_to_string(&system_skill_path)?;
let expected_name_line = format!("name: {SYSTEM_SKILL_NAME}");
assert!(
system_skill_contents.contains(&expected_name_line),
"expected embedded system skill file, got:\n{system_skill_contents}"
);
test.codex
.submit(Op::ListSkills {
cwds: Vec::new(),
force_reload: true,
})
.await?;
let response =
core_test_support::wait_for_event_match(test.codex.as_ref(), |event| match event {
codex_protocol::protocol::EventMsg::ListSkillsResponse(response) => {
Some(response.clone())
}
_ => None,
})
.await;
let cwd = test.cwd_path();
let (skills, _errors) = response
.skills
.iter()
.find(|entry| entry.cwd.as_path() == cwd)
.map(|entry| (entry.skills.clone(), entry.errors.clone()))
.unwrap_or_default();
let skill = skills
.iter()
.find(|skill| skill.name == SYSTEM_SKILL_NAME)
.expect("expected system skill to be present");
assert_eq!(skill.scope, codex_protocol::protocol::SkillScope::System);
let path_str = skill.path.to_string_lossy().replace('\\', "/");
let expected_path_suffix = format!("/skills/.system/{SYSTEM_SKILL_NAME}/SKILL.md");
assert!(
path_str.ends_with(&expected_path_suffix),
"unexpected skill path: {path_str}"
);
Ok(())
}
@@ -0,0 +1,44 @@
---
source: core/tests/suite/compact_remote.rs
expression: "context_snapshot::format_request_body_diff_snapshot(scenario,\n\"Last Normal /responses Request\", &normal_request,\n\"Remote /responses/compact Request\", &compact_request,\n&ContextSnapshotOptions::default(),)"
---
Scenario: After five varied API-key-auth turns, remote manual compaction omits service_tier, reuses prompt_cache_key, and still omits responses-only fields.
--- Last Normal /responses Request
+++ Remote /responses/compact Request
- "client_metadata": {
- "x-codex-installation-id": "<UUID>"
- },
- "include": [
- "reasoning.encrypted_content"
- ],
+ },
+ {
+ "content": [
+ {
+ "text": "turn five raw content",
+ "type": "reasoning_text"
+ }
+ ],
+ "encrypted_content": "YmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYnR1cm4gZml2ZSByYXcgY29udGVudA==",
+ "summary": [
+ {
+ "text": "TURN_FIVE_REASONING",
+ "type": "summary_text"
+ }
+ ],
+ "type": "reasoning"
+ },
+ {
+ "content": [
+ {
+ "text": "TURN_FIVE_ASSISTANT",
+ "type": "output_text"
+ }
+ ],
+ "role": "assistant",
+ "type": "message"
- "service_tier": "priority",
- "store": false,
- "stream": true,
- "tool_choice": "auto",
@@ -0,0 +1,43 @@
---
source: core/tests/suite/compact_remote.rs
expression: "context_snapshot::format_request_body_diff_snapshot(scenario,\n\"Last Normal /responses Request\", &normal_request,\n\"Remote /responses/compact Request\", &compact_request,\n&ContextSnapshotOptions::default(),)"
---
Scenario: After five varied ChatGPT-auth turns, remote manual compaction reuses service_tier and prompt_cache_key while omitting responses-only fields.
--- Last Normal /responses Request
+++ Remote /responses/compact Request
- "client_metadata": {
- "x-codex-installation-id": "<UUID>"
- },
- "include": [
- "reasoning.encrypted_content"
- ],
+ },
+ {
+ "content": [
+ {
+ "text": "turn five raw content",
+ "type": "reasoning_text"
+ }
+ ],
+ "encrypted_content": "YmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYnR1cm4gZml2ZSByYXcgY29udGVudA==",
+ "summary": [
+ {
+ "text": "TURN_FIVE_REASONING",
+ "type": "summary_text"
+ }
+ ],
+ "type": "reasoning"
+ },
+ {
+ "content": [
+ {
+ "text": "TURN_FIVE_ASSISTANT",
+ "type": "output_text"
+ }
+ ],
+ "role": "assistant",
+ "type": "message"
- "store": false,
- "stream": true,
- "tool_choice": "auto",
@@ -67,6 +67,7 @@ fn test_model_info(
supports_search_tool: false,
priority: 1,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
upgrade: None,
base_instructions: "base instructions".to_string(),
model_messages: None,
+6 -5
View File
@@ -48,7 +48,7 @@ async fn new_thread_is_recorded_in_state_db() -> Result<()> {
});
let test = builder.build(&server).await?;
let thread_id = test.session_configured.session_id;
let thread_id = test.session_configured.thread_id;
let rollout_path = test.codex.rollout_path().expect("rollout path");
let db_path = codex_state::state_db_path(test.config.sqlite_home.as_path());
@@ -144,6 +144,7 @@ async fn backfill_scans_existing_rollouts() -> Result<()> {
originator: "test".to_string(),
cli_version: "test".to_string(),
source: SessionSource::default(),
thread_source: None,
agent_path: None,
agent_nickname: None,
agent_role: None,
@@ -261,7 +262,7 @@ async fn user_messages_persist_in_state_db() -> Result<()> {
test.submit_turn("another message").await?;
let db = test.codex.state_db().expect("state db enabled");
let thread_id = test.session_configured.session_id;
let thread_id = test.session_configured.thread_id;
let mut metadata = None;
for _ in 0..100 {
@@ -304,7 +305,7 @@ async fn web_search_marks_thread_memory_mode_polluted_when_configured() -> Resul
});
let test = builder.build(&server).await?;
let db = test.codex.state_db().expect("state db enabled");
let thread_id = test.session_configured.session_id;
let thread_id = test.session_configured.thread_id;
test.submit_turn("search the web").await?;
@@ -396,7 +397,7 @@ async fn mcp_call_marks_thread_memory_mode_polluted_when_configured() -> Result<
});
let test = builder.build(&server).await?;
let db = test.codex.state_db().expect("state db enabled");
let thread_id = test.session_configured.session_id;
let thread_id = test.session_configured.thread_id;
let cwd = test.cwd_path().to_path_buf();
let (sandbox_policy, permission_profile) =
turn_permission_fields(PermissionProfile::read_only(), cwd.as_path());
@@ -477,7 +478,7 @@ async fn tool_call_logs_include_thread_id() -> Result<()> {
});
let test = builder.build(&server).await?;
let db = test.codex.state_db().expect("state db enabled");
let expected_thread_id = test.session_configured.session_id.to_string();
let expected_thread_id = test.session_configured.thread_id.to_string();
test.submit_turn("run a shell command").await?;
@@ -116,7 +116,7 @@ async fn wait_for_spawned_thread_id(test: &TestCodex) -> Result<String> {
let ids = test.thread_manager.list_thread_ids().await;
if let Some(spawned_id) = ids
.iter()
.find(|id| **id != test.session_configured.session_id)
.find(|id| **id != test.session_configured.thread_id)
{
return Ok(spawned_id.to_string());
}
+27 -9
View File
@@ -14,7 +14,7 @@ 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_apply_patch_custom_tool_call;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_function_call;
@@ -47,6 +47,24 @@ fn call_output(req: &ResponsesRequest, call_id: &str) -> (String, Option<bool>)
(content, success)
}
fn custom_call_output(req: &ResponsesRequest, call_id: &str) -> (String, Option<bool>) {
let raw = req.custom_tool_call_output(call_id);
assert_eq!(
raw.get("call_id").and_then(Value::as_str),
Some(call_id),
"mismatched call_id in custom_tool_call_output"
);
let (content_opt, success) = match req.custom_tool_call_output_content_and_success(call_id) {
Some(values) => values,
None => panic!("custom_tool_call_output present"),
};
let content = match content_opt {
Some(c) => c,
None => panic!("custom_tool_call_output content present"),
};
(content, success)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shell_tool_executes_command_and_streams_output() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
@@ -107,10 +125,10 @@ async fn shell_tool_executes_command_and_streams_output() -> anyhow::Result<()>
let req = second_mock.single_request();
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);
assert_regex_match(
r"(?s)^Exit code: 0\nWall time: [0-9]+(?:\.[0-9]+)? seconds\nOutput:\ntool harness\n?$",
&output_text,
);
Ok(())
}
@@ -328,7 +346,7 @@ async fn apply_patch_tool_executes_and_emits_patch_events() -> anyhow::Result<()
let first_response = sse(vec![
ev_response_created("resp-1"),
ev_apply_patch_function_call(call_id, &patch_content),
ev_apply_patch_custom_tool_call(call_id, &patch_content),
ev_completed("resp-1"),
]);
responses::mount_sse_once(&server, first_response).await;
@@ -419,7 +437,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_text, _success_flag) = call_output(&req, call_id);
let (output_text, _success_flag) = custom_call_output(&req, call_id);
let expected_pattern = format!(
r"(?s)^Exit code: 0
@@ -466,7 +484,7 @@ async fn apply_patch_reports_parse_diagnostics() -> anyhow::Result<()> {
let first_response = sse(vec![
ev_response_created("resp-1"),
ev_apply_patch_function_call(call_id, patch_content),
ev_apply_patch_custom_tool_call(call_id, patch_content),
ev_completed("resp-1"),
]);
responses::mount_sse_once(&server, first_response).await;
@@ -507,7 +525,7 @@ async fn apply_patch_reports_parse_diagnostics() -> anyhow::Result<()> {
wait_for_event(&codex, |event| matches!(event, EventMsg::TurnComplete(_))).await;
let req = second_mock.single_request();
let (output_text, success_flag) = call_output(&req, call_id);
let (output_text, success_flag) = custom_call_output(&req, call_id);
assert!(
output_text.contains("apply_patch verification failed"),
+17 -176
View File
@@ -1,16 +1,12 @@
#![cfg(not(target_os = "windows"))]
#![allow(clippy::unwrap_used, clippy::expect_used)]
use std::collections::HashMap;
use std::fs;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use anyhow::Context;
use anyhow::Result;
use codex_config::types::McpServerConfig;
use codex_config::types::McpServerTransportConfig;
use codex_core::sandboxing::SandboxPermissions;
use codex_features::Feature;
use codex_protocol::models::PermissionProfile;
@@ -33,13 +29,10 @@ 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::skip_if_sandbox;
use core_test_support::stdio_server_bin;
use core_test_support::test_codex::test_codex;
use regex_lite::Regex;
use serde_json::Value;
use serde_json::json;
use serial_test::serial;
use tempfile::TempDir;
fn tool_names(body: &Value) -> Vec<String> {
body.get("tools")
@@ -58,24 +51,6 @@ fn tool_names(body: &Value) -> Vec<String> {
.unwrap_or_default()
}
fn ev_namespaced_function_call(
call_id: &str,
namespace: &str,
name: &str,
arguments: &str,
) -> Value {
json!({
"type": "response.output_item.done",
"item": {
"type": "function_call",
"call_id": call_id,
"namespace": namespace,
"name": name,
"arguments": arguments,
}
})
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn empty_turn_environments_omits_environment_backed_tools() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -206,149 +181,6 @@ async fn custom_tool_unknown_returns_custom_output_error() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial(mcp_test_value)]
async fn historical_unavailable_mcp_call_is_exposed_as_placeholder_tool() -> Result<()> {
skip_if_no_network!(Ok(()));
let historical_call_id = "historical-mcp-call";
let retry_call_id = "retry-mcp-call";
let server_name = "rmcp";
let unavailable_tool_namespace = "mcp__rmcp__";
let unavailable_tool_name = "echo";
let unavailable_tool_display_name = "mcp__rmcp__echo";
let server = start_mock_server().await;
let rmcp_test_server_bin = match stdio_server_bin() {
Ok(bin) => bin,
Err(err) => {
eprintln!("test_stdio_server binary not available, skipping test: {err}");
return Ok(());
}
};
let codex_home = Arc::new(TempDir::new()?);
let mut builder = test_codex()
.with_model("gpt-5.4")
.with_home(Arc::clone(&codex_home))
.with_config(move |config| {
config
.features
.enable(Feature::UnavailableDummyTools)
.expect("unavailable dummy tools should be enabled for this test");
let mut servers = config.mcp_servers.get().clone();
servers.insert(
server_name.to_string(),
McpServerConfig {
transport: McpServerTransportConfig::Stdio {
command: rmcp_test_server_bin,
args: Vec::new(),
env: Some(HashMap::new()),
env_vars: Vec::new(),
cwd: None,
},
experimental_environment: None,
enabled: true,
required: false,
supports_parallel_tool_calls: false,
disabled_reason: None,
startup_timeout_sec: Some(Duration::from_secs(10)),
tool_timeout_sec: None,
default_tools_approval_mode: None,
enabled_tools: None,
disabled_tools: None,
scopes: None,
oauth_resource: None,
tools: HashMap::new(),
},
);
config
.mcp_servers
.set(servers)
.expect("test mcp servers should accept any configuration");
});
let test = builder.build(&server).await?;
let first_turn_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_namespaced_function_call(
historical_call_id,
unavailable_tool_namespace,
unavailable_tool_name,
r#"{"message":"ping"}"#,
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "rmcp echo tool completed"),
ev_completed("resp-2"),
]),
],
)
.await;
test.submit_turn("call the rmcp echo tool").await?;
let rollout_path = test.codex.rollout_path().context("rollout path")?;
assert_eq!(first_turn_mock.requests().len(), 2);
drop(test);
let retry_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-3"),
ev_namespaced_function_call(
retry_call_id,
unavailable_tool_namespace,
unavailable_tool_name,
r#"{"message":"ping again"}"#,
),
ev_completed("resp-3"),
]),
sse(vec![
ev_response_created("resp-4"),
ev_assistant_message("msg-2", "done"),
ev_completed("resp-4"),
]),
],
)
.await;
let mut resume_builder = test_codex().with_model("gpt-5.4").with_config(|config| {
config
.features
.enable(Feature::UnavailableDummyTools)
.expect("unavailable dummy tools should be enabled for this test");
});
let test = resume_builder
.resume(&server, codex_home, rollout_path)
.await?;
test.submit_turn("retry the rmcp echo tool").await?;
let requests = retry_mock.requests();
assert_eq!(requests.len(), 2);
let first_request_tools = tool_names(&requests[0].body_json());
assert!(
first_request_tools
.iter()
.any(|name| name == unavailable_tool_display_name),
"historical unavailable MCP call should add a placeholder tool; got {first_request_tools:?}"
);
let output_text = requests[1]
.function_call_output_text(retry_call_id)
.context("placeholder tool output present")?;
assert!(output_text.contains("not currently available"));
assert!(
!output_text.contains("unsupported call"),
"placeholder handler should answer instead of falling back to unsupported call: {output_text}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shell_escalated_permissions_rejected_then_ok() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -433,15 +265,10 @@ async fn shell_escalated_permissions_rejected_then_ok() -> Result<()> {
.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),
"expected exit code 0 after rerunning without escalation",
assert_regex_match(
r"(?s)^Exit code: 0\nWall time: [0-9]+(?:\.[0-9]+)? seconds\nOutput:\nshell ok\n?$",
&success_output,
);
let stdout = output_json["output"].as_str().unwrap_or_default();
let stdout_pattern = r"(?s)^shell ok\n?$";
assert_regex_match(stdout_pattern, stdout);
Ok(())
}
@@ -772,6 +599,20 @@ async fn shell_timeout_includes_timeout_prefix_and_metadata() -> Result<()> {
"timeout output missing `command timed out`: {stdout}"
);
} else {
let normalized_output = output_str
.replace("\r\n", "\n")
.replace('\r', "\n")
.trim_end_matches('\n')
.to_string();
let shell_output_pattern = r"(?s)^Exit code: 124\nWall time: [0-9]+(?:\.[0-9]+)? seconds\nOutput:\ncommand timed out after [0-9]+ milliseconds\n(?:.*)?$";
if Regex::new(shell_output_pattern)
.expect("shell timeout output regex should compile")
.is_match(&normalized_output)
{
return Ok(());
}
// Fallback: accept the signal classification path to deflake the test.
let signal_pattern = r"(?is)^execution error:.*signal.*$";
assert_regex_match(signal_pattern, output_str);
+14 -45
View File
@@ -17,6 +17,7 @@ use codex_protocol::protocol::Op;
use codex_protocol::protocol::SandboxPolicy;
use codex_protocol::user_input::UserInput;
use core_test_support::assert_regex_match;
use core_test_support::managed_network_requirements_loader;
use core_test_support::process::process_is_alive;
use core_test_support::process::wait_for_pid_file;
use core_test_support::process::wait_for_process_exit;
@@ -872,13 +873,7 @@ async fn unified_exec_short_lived_network_denial_emits_failed_end_event() -> Res
async fn unified_exec_network_denial_test(
server: &wiremock::MockServer,
) -> Result<(TestCodex, SandboxPolicy)> {
use codex_config::ConfigLayerStack;
use codex_config::ConfigLayerStackOrdering;
use codex_config::Constrained;
use codex_config::NetworkConstraints;
use codex_config::NetworkRequirementsToml;
use codex_config::RequirementSource;
use codex_config::Sourced;
use std::sync::Arc;
use tempfile::TempDir;
@@ -901,46 +896,20 @@ allow_local_binding = true
*network_access = true;
}
let sandbox_policy_for_config = sandbox_policy.clone();
let mut builder = test_codex().with_home(home).with_config(move |config| {
config.use_experimental_unified_exec_tool = true;
config
.features
.enable(Feature::UnifiedExec)
.expect("test config should allow feature update");
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::Never);
config.permissions.permission_profile = Constrained::allow_any(
PermissionProfile::from_legacy_sandbox_policy(&sandbox_policy_for_config),
);
let layers = config
.config_layer_stack
.get_layers(
ConfigLayerStackOrdering::LowestPrecedenceFirst,
/*include_disabled*/ true,
)
.into_iter()
.cloned()
.collect();
let mut requirements = config.config_layer_stack.requirements().clone();
requirements.network = Some(Sourced::new(
NetworkConstraints {
enabled: Some(true),
allow_local_binding: Some(true),
..Default::default()
},
RequirementSource::CloudRequirements,
));
let mut requirements_toml = config.config_layer_stack.requirements_toml().clone();
requirements_toml.network = Some(NetworkRequirementsToml {
enabled: Some(true),
allow_local_binding: Some(true),
..Default::default()
let mut builder = test_codex()
.with_home(home)
.with_cloud_requirements(managed_network_requirements_loader())
.with_config(move |config| {
config.use_experimental_unified_exec_tool = true;
config
.features
.enable(Feature::UnifiedExec)
.expect("test config should allow feature update");
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::Never);
config.permissions.permission_profile = Constrained::allow_any(
PermissionProfile::from_legacy_sandbox_policy(&sandbox_policy_for_config),
);
});
config.config_layer_stack =
match ConfigLayerStack::new(layers, requirements, requirements_toml) {
Ok(stack) => stack,
Err(err) => panic!("rebuild config layer stack with network requirements: {err}"),
};
});
let test = builder.build_remote_aware(server).await?;
assert!(
test.config.permissions.network.is_some(),
+268
View File
@@ -4,6 +4,9 @@ use anyhow::Context;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_exec_server::REMOTE_ENVIRONMENT_ID;
use codex_exec_server::RemoveOptions;
use codex_login::CodexAuth;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::models::PermissionProfile;
@@ -15,16 +18,26 @@ use codex_protocol::openai_models::ModelsResponse;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::openai_models::ReasoningEffortPreset;
use codex_protocol::openai_models::TruncationPolicyConfig;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::user_input::UserInput;
use core_test_support::PathBufExt;
use core_test_support::PathExt;
use core_test_support::get_remote_test_env;
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_models_once;
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;
@@ -39,8 +52,13 @@ use image::Rgba;
use image::load_from_memory;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::fs;
use std::io::Cursor;
use std::path::PathBuf;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tempfile::TempDir;
use tokio::time::Duration;
use wiremock::BodyPrintLimit;
use wiremock::MockServer;
@@ -390,6 +408,255 @@ async fn view_image_tool_attaches_local_image() -> anyhow::Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn view_image_routes_to_selected_local_environment() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mut builder = test_codex();
let test = builder.build(&server).await?;
write_workspace_file(
&test,
"local.png",
png_bytes(/*width*/ 1, /*height*/ 1, [0, 255, 0, 255])?,
)
.await?;
let call_id = "call-view-image-local-env";
let response_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call(
call_id,
"view_image",
&json!({
"path": "local.png",
"environment_id": LOCAL_ENVIRONMENT_ID,
})
.to_string(),
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
]),
],
)
.await;
test.submit_turn_with_environments(
"route local view image",
Some(vec![TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: test.config.cwd.clone(),
}]),
)
.await?;
let output = response_mock
.last_request()
.context("missing request containing local view_image output")?
.function_call_output(call_id);
let output_items = output
.get("output")
.and_then(Value::as_array)
.context("view_image output should be content items")?;
assert_eq!(output_items.len(), 1);
let image_url = output_items[0]
.get("image_url")
.and_then(Value::as_str)
.context("view_image output should include image_url")?;
assert!(
image_url.starts_with("data:image/png;base64,"),
"unexpected image_url: {image_url}",
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn view_image_tool_applies_local_sandbox_read_denies() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mut builder = test_codex();
let test = builder.build(&server).await?;
let rel_path = "denied.png";
let denied_path = test.config.cwd.join(rel_path);
write_workspace_file(
&test,
rel_path,
png_bytes(/*width*/ 1, /*height*/ 1, [0, 255, 0, 255])?,
)
.await?;
let call_id = "call-view-image-outside-cwd";
let response_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call(
call_id,
"view_image",
&json!({ "path": rel_path }).to_string(),
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
]),
],
)
.await;
let mut file_system_sandbox_policy = FileSystemSandboxPolicy::default();
file_system_sandbox_policy
.entries
.push(FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: denied_path.clone(),
},
access: FileSystemAccessMode::None,
});
let permission_profile = PermissionProfile::from_runtime_permissions(
&file_system_sandbox_policy,
NetworkSandboxPolicy::Restricted,
);
test.submit_turn_with_permission_profile("attach the denied image", permission_profile)
.await?;
let request = response_mock
.last_request()
.context("missing request containing sandboxed view_image output")?;
assert!(
request.inputs_of_type("input_image").is_empty(),
"sandboxed local view_image should not attach denied images"
);
let output_text = request
.function_call_output_content_and_success(call_id)
.and_then(|(content, _)| content)
.context("sandboxed view_image error text present")?;
let expected_locate_prefix = format!("unable to locate image at `{}`:", denied_path.display());
let expected_read_prefix = format!("unable to read image at `{}`:", denied_path.display());
assert!(
output_text.starts_with(&expected_locate_prefix)
|| output_text.starts_with(&expected_read_prefix),
"expected error to start with `{expected_locate_prefix}` or `{expected_read_prefix}` but got `{output_text}`"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let Some(_remote_env) = get_remote_test_env() else {
return Ok(());
};
let server = start_mock_server().await;
let mut builder = test_codex();
let test = builder.build_remote_aware(&server).await?;
let local_cwd = TempDir::new()?;
fs::write(local_cwd.path().join("remote.png"), b"not a remote image")?;
let local_selection = TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: local_cwd.path().abs(),
};
let remote_cwd = PathBuf::from(format!(
"/tmp/codex-view-image-routing-{}",
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
let image_path = remote_cwd.join("remote.png");
test.fs()
.create_directory(
&remote_cwd,
CreateDirectoryOptions { recursive: true },
/*sandbox*/ None,
)
.await?;
let png = BASE64_STANDARD.decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",
)?;
test.fs()
.write_file(&image_path, png, /*sandbox*/ None)
.await?;
let remote_selection = TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: remote_cwd.clone(),
};
let call_id = "call-view-image-multi-env";
let response_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call(
call_id,
"view_image",
&json!({
"path": "remote.png",
"environment_id": REMOTE_ENVIRONMENT_ID,
})
.to_string(),
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
]),
],
)
.await;
test.submit_turn_with_environments(
"route view image",
Some(vec![local_selection, remote_selection]),
)
.await?;
let output = response_mock
.last_request()
.context("missing request containing view_image output")?
.function_call_output(call_id)
.clone();
let output_items = output
.get("output")
.and_then(Value::as_array)
.context("view_image output should be content items")?;
assert_eq!(output_items.len(), 1);
let image_url = output_items[0]
.get("image_url")
.and_then(Value::as_str)
.context("view_image output should include image_url")?;
assert!(
image_url.starts_with("data:image/png;base64,"),
"unexpected image_url: {image_url}",
);
test.fs()
.remove(
&remote_cwd,
RemoveOptions {
recursive: true,
force: true,
},
/*sandbox*/ None,
)
.await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn view_image_tool_can_preserve_original_resolution_when_requested_on_gpt5_3_codex()
-> anyhow::Result<()> {
@@ -1085,6 +1352,7 @@ async fn view_image_tool_returns_unsupported_message_for_text_only_model() -> an
supports_search_tool: false,
priority: 1,
additional_speed_tiers: Vec::new(),
service_tiers: Vec::new(),
upgrade: None,
base_instructions: "base instructions".to_string(),
model_messages: None,
@@ -72,6 +72,7 @@ async fn window_id_advances_after_compact_persists_on_resume_and_resets_on_fork(
/*snapshot*/ 0usize,
resumed.config.clone(),
rollout_path,
/*thread_source*/ None,
/*persist_extended_history*/ false,
/*parent_trace*/ None,
)
@@ -0,0 +1,243 @@
use anyhow::Context;
use codex_core::exec::ExecCapturePolicy;
use codex_core::exec::ExecParams;
use codex_core::exec::process_exec_tool_call;
use codex_core::sandboxing::SandboxPermissions;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::exec_output::ExecToolCallOutput;
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSpecialPath;
use codex_protocol::permissions::NetworkSandboxPolicy;
use core_test_support::PathExt;
use pretty_assertions::assert_eq;
use serial_test::serial;
use std::collections::HashMap;
use std::ffi::OsString;
use std::path::Path;
use tempfile::TempDir;
struct EnvVarGuard {
key: &'static str,
original: Option<OsString>,
}
impl EnvVarGuard {
fn set(key: &'static str, value: &std::ffi::OsStr) -> Self {
let original = std::env::var_os(key);
unsafe {
std::env::set_var(key, value);
}
Self { key, original }
}
}
impl Drop for EnvVarGuard {
fn drop(&mut self) {
unsafe {
match &self.original {
Some(value) => std::env::set_var(self.key, value),
None => std::env::remove_var(self.key),
}
}
}
}
fn stage_windows_sandbox_helpers() -> anyhow::Result<()> {
let test_exe = std::env::current_exe().context("resolve current Windows test executable")?;
let test_exe_dir = test_exe
.parent()
.context("Windows test executable should have a parent directory")?;
let resources_dir = test_exe_dir.join("codex-resources");
std::fs::create_dir_all(&resources_dir)?;
for helper_name in ["codex-windows-sandbox-setup", "codex-command-runner"] {
let helper = codex_utils_cargo_bin::cargo_bin(helper_name)?;
let file_name = Path::new(helper_name).with_extension("exe");
std::fs::copy(helper, resources_dir.join(file_name))?;
}
Ok(())
}
#[tokio::test]
#[serial(codex_home)]
async fn windows_restricted_token_rejects_exact_and_glob_deny_read_policy() -> anyhow::Result<()> {
let temp_home = TempDir::new()?;
let _codex_home_guard = EnvVarGuard::set("CODEX_HOME", temp_home.path().as_os_str());
let workspace = TempDir::new()?;
let cwd = dunce::canonicalize(workspace.path())?.abs();
let secret = cwd.join("secret.env");
let future_secret = cwd.join("future.env");
let public = cwd.join("public.txt");
std::fs::write(&secret, "glob secret\n")?;
std::fs::write(&public, "public ok\n")?;
let file_system_sandbox_policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Read,
},
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
},
access: FileSystemAccessMode::Write,
},
FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: "**/*.env".to_string(),
},
access: FileSystemAccessMode::None,
},
FileSystemSandboxEntry {
path: FileSystemPath::Path {
path: future_secret,
},
access: FileSystemAccessMode::None,
},
]);
let permission_profile = PermissionProfile::from_runtime_permissions(
&file_system_sandbox_policy,
NetworkSandboxPolicy::Restricted,
);
let err = process_exec_tool_call(
ExecParams {
command: vec![
"cmd.exe".to_string(),
"/D".to_string(),
"/C".to_string(),
"type secret.env >NUL 2>NUL & echo exact secret 1>future.env 2>NUL & type future.env 2>NUL & type public.txt & exit /B 0"
.to_string(),
],
cwd: cwd.clone(),
expiration: 10_000.into(),
capture_policy: ExecCapturePolicy::ShellTool,
env: HashMap::new(),
network: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level: WindowsSandboxLevel::RestrictedToken,
windows_sandbox_private_desktop: false,
justification: None,
arg0: None,
},
&permission_profile,
&cwd,
&None,
/*use_legacy_landlock*/ false,
/*stdout_stream*/ None,
)
.await
.expect_err("restricted-token sandbox should reject deny-read restrictions");
assert_eq!(
err.to_string(),
"unsupported operation: windows unelevated restricted-token sandbox cannot enforce deny-read restrictions directly; refusing to run unsandboxed"
);
Ok(())
}
#[tokio::test]
#[serial(codex_home)]
async fn windows_elevated_enforces_exact_and_glob_deny_read_policy() -> anyhow::Result<()> {
let temp_home = TempDir::new()?;
let _codex_home_guard = EnvVarGuard::set("CODEX_HOME", temp_home.path().as_os_str());
stage_windows_sandbox_helpers()?;
let workspace = TempDir::new()?;
let cwd = dunce::canonicalize(workspace.path())?.abs();
let glob_secret = cwd.join("secret.env");
let exact_secret = cwd.join("exact-secret.txt");
let public = cwd.join("public.txt");
std::fs::write(&glob_secret, "glob secret\n")?;
std::fs::write(&exact_secret, "exact secret\n")?;
std::fs::write(&public, "public ok\n")?;
let file_system_sandbox_policy = FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
access: FileSystemAccessMode::Read,
},
FileSystemSandboxEntry {
path: FileSystemPath::Special {
value: FileSystemSpecialPath::project_roots(/*subpath*/ None),
},
access: FileSystemAccessMode::Write,
},
FileSystemSandboxEntry {
path: FileSystemPath::GlobPattern {
pattern: "**/*.env".to_string(),
},
access: FileSystemAccessMode::None,
},
FileSystemSandboxEntry {
path: FileSystemPath::Path { path: exact_secret },
access: FileSystemAccessMode::None,
},
]);
let permission_profile = PermissionProfile::from_runtime_permissions(
&file_system_sandbox_policy,
NetworkSandboxPolicy::Restricted,
);
let ExecToolCallOutput {
exit_code,
stdout,
stderr,
..
} = process_exec_tool_call(
ExecParams {
command: vec![
"cmd.exe".to_string(),
"/D".to_string(),
"/C".to_string(),
"(type secret.env 1>NUL 2>NUL && echo GLOB-READ || echo GLOB-DENIED) & (type exact-secret.txt 1>NUL 2>NUL && echo EXACT-READ || echo EXACT-DENIED) & type public.txt".to_string(),
],
cwd: cwd.clone(),
expiration: 10_000.into(),
capture_policy: ExecCapturePolicy::ShellTool,
env: HashMap::new(),
network: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level: WindowsSandboxLevel::Elevated,
windows_sandbox_private_desktop: false,
justification: None,
arg0: None,
},
&permission_profile,
&cwd,
&None,
/*use_legacy_landlock*/ false,
/*stdout_stream*/ None,
)
.await?;
assert_eq!(exit_code, 0, "sandboxed command should complete");
assert!(
stdout.text.contains("GLOB-DENIED"),
"glob deny-read should block the secret: {stdout:?}"
);
assert!(
!stdout.text.contains("GLOB-READ"),
"glob deny-read should not allow the secret: {stdout:?}"
);
assert!(
stdout.text.contains("EXACT-DENIED"),
"exact deny-read should block the secret: {stdout:?}"
);
assert!(
!stdout.text.contains("EXACT-READ"),
"exact deny-read should not allow the secret: {stdout:?}"
);
assert!(
stdout.text.contains("public ok"),
"allowed reads should still work: {stdout:?}"
);
assert_eq!(stderr.text, "");
Ok(())
}