merge main into resume fork optimization

This commit is contained in:
anais
2026-06-23 08:53:41 -07:00
554 changed files with 19603 additions and 5441 deletions
@@ -266,7 +266,7 @@ fn format_request_body_snapshot(
request: &ResponsesRequest,
options: &ContextSnapshotOptions,
) -> String {
let mut body = request.body_json();
let mut body = crate::responses::strip_metadata_from_json(request.body_json());
canonicalize_json_snapshot_value(&mut body, options);
serde_json::to_string_pretty(&body).expect("request body should serialize")
}
+39 -4
View File
@@ -98,6 +98,35 @@ fn decode_body_bytes(body: &[u8], content_encoding: Option<&str>) -> Vec<u8> {
}
}
/// Returns a response item without internal transport metadata for semantic assertions.
pub fn strip_metadata(mut item: ResponseItem) -> ResponseItem {
item.clear_internal_chat_message_metadata_passthrough();
item
}
/// Returns response items without internal transport metadata for semantic assertions.
pub fn strip_metadata_from_items(items: &[ResponseItem]) -> Vec<ResponseItem> {
items.iter().cloned().map(strip_metadata).collect()
}
/// Returns JSON without internal transport metadata for semantic assertions.
pub fn strip_metadata_from_json(value: Value) -> Value {
match value {
Value::Array(values) => {
Value::Array(values.into_iter().map(strip_metadata_from_json).collect())
}
Value::Object(mut map) => {
map.remove("internal_chat_message_metadata_passthrough");
Value::Object(
map.into_iter()
.map(|(key, value)| (key, strip_metadata_from_json(value)))
.collect(),
)
}
value => value,
}
}
impl ResponsesRequest {
pub fn body_json(&self) -> Value {
let body = decode_body_bytes(
@@ -684,7 +713,7 @@ pub fn user_message_item(text: &str) -> ResponseItem {
text: text.to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
}
}
@@ -1092,11 +1121,17 @@ pub async fn mount_compact_user_history_with_summary_sequence(
)
})
.collect::<Vec<Value>>();
// Append a synthetic compaction item as the newest item.
output.push(serde_json::json!({
let compaction_turn_id = body_json["client_metadata"]["turn_id"].as_str();
// Match Responses API: generated compaction items inherit the compact request turn.
let mut compaction_item = serde_json::json!({
"type": "compaction",
"encrypted_content": summary_text,
}));
});
if let Some(turn_id) = compaction_turn_id {
compaction_item["internal_chat_message_metadata_passthrough"] =
serde_json::json!({ "turn_id": turn_id });
}
output.push(compaction_item);
ResponseTemplate::new(200)
.insert_header("content-type", "application/json")
.set_body_json(serde_json::json!({ "output": output }))
+4 -4
View File
@@ -998,7 +998,7 @@ impl TestCodexHarness {
) -> Result<()> {
let abs_path = self.path_abs(rel);
if let Some(parent) = abs_path.parent() {
let parent_uri = PathUri::from_path(&parent)?;
let parent_uri = PathUri::from_host_native_path(&parent)?;
self.test
.fs()
.create_directory(
@@ -1008,7 +1008,7 @@ impl TestCodexHarness {
)
.await?;
}
let abs_path_uri = PathUri::from_path(&abs_path)?;
let abs_path_uri = PathUri::from_host_native_path(&abs_path)?;
self.test
.fs()
.write_file(
@@ -1022,7 +1022,7 @@ impl TestCodexHarness {
pub async fn read_file_text(&self, rel: impl AsRef<Path>) -> Result<String> {
let path = self.path_abs(rel);
let path_uri = PathUri::from_path(&path)?;
let path_uri = PathUri::from_host_native_path(&path)?;
Ok(self
.test
.fs()
@@ -1032,7 +1032,7 @@ impl TestCodexHarness {
pub async fn create_dir_all(&self, rel: impl AsRef<Path>) -> Result<()> {
let path = self.path_abs(rel);
let path_uri = PathUri::from_path(&path)?;
let path_uri = PathUri::from_host_native_path(&path)?;
self.test
.fs()
.create_directory(
+3 -3
View File
@@ -141,7 +141,7 @@ async fn responses_stream_includes_subagent_header_on_review() {
text: "hello".into(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
}];
let mut stream = client_session
@@ -273,7 +273,7 @@ async fn responses_stream_includes_subagent_header_on_other() {
text: "hello".into(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
}];
let mut stream = client_session
@@ -391,7 +391,7 @@ async fn responses_respects_model_info_overrides_from_config() {
text: "hello".into(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
}];
let mut stream = client_session
+14 -3
View File
@@ -2,7 +2,7 @@ use anyhow::Result;
use codex_features::Feature;
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_function_call_with_namespace;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::mount_sse_once_match;
use core_test_support::responses::sse;
@@ -15,6 +15,7 @@ use std::time::Duration;
const FIRST_PROMPT: &str = "spawn the first worker";
const FIRST_TASK: &str = "first worker task";
const SECOND_TASK: &str = "second worker task";
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
fn body_contains(request: &wiremock::Request, text: &str) -> bool {
serde_json::from_slice::<serde_json::Value>(&request.body)
@@ -47,7 +48,12 @@ async fn v2_nested_spawn_checks_shared_active_execution_capacity() -> Result<()>
|request: &wiremock::Request| body_contains(request, FIRST_PROMPT),
sse(vec![
ev_response_created("first-response"),
ev_function_call("first-call", "spawn_agent", &first_args),
ev_function_call_with_namespace(
"first-call",
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&first_args,
),
ev_completed("first-response"),
]),
)
@@ -63,7 +69,12 @@ async fn v2_nested_spawn_checks_shared_active_execution_capacity() -> Result<()>
},
sse(vec![
ev_response_created("first-worker-response"),
ev_function_call("second-call", "spawn_agent", &second_args),
ev_function_call_with_namespace(
"second-call",
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&second_args,
),
ev_completed("first-worker-response"),
]),
)
+85 -1
View File
@@ -1,6 +1,10 @@
use anyhow::Result;
use codex_features::Feature;
use codex_protocol::config_types::ServiceTier;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::ThreadSettingsOverrides;
use codex_protocol::user_input::UserInput;
use core_test_support::responses::WebSocketConnectionConfig;
use core_test_support::responses::ev_assistant_message;
use core_test_support::responses::ev_completed;
@@ -10,12 +14,89 @@ use core_test_support::responses::start_websocket_server;
use core_test_support::responses::start_websocket_server_with_headers;
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 serde_json::Value;
use std::time::Duration;
const WS_V2_BETA_HEADER_VALUE: &str = "responses_websockets=2026-02-06";
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn websocket_model_switch_to_responses_lite_omits_top_level_tools() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_websocket_server(vec![vec![
vec![ev_response_created("warm-1"), ev_completed("warm-1")],
vec![ev_response_created("resp-1"), ev_completed("resp-1")],
vec![ev_response_created("resp-2"), ev_completed("resp-2")],
]])
.await;
let mut builder = test_codex()
.with_model_info_override("gpt-5.4", |model_info| {
model_info.use_responses_lite = true;
})
.with_model("gpt-5.3-codex");
let test = builder.build_with_websocket_server(&server).await?;
test.submit_turn("non-lite turn").await?;
test.codex
.submit(Op::UserInput {
items: vec![UserInput::Text {
text: "lite turn".into(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
additional_context: Default::default(),
thread_settings: ThreadSettingsOverrides {
model: Some("gpt-5.4".to_string()),
..Default::default()
},
})
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
assert_eq!(server.handshakes().len(), 1);
let connection = server.single_connection();
assert_eq!(connection.len(), 3);
let non_lite_turn = connection
.get(1)
.expect("missing non-lite turn request")
.body_json();
let lite_turn = connection
.get(2)
.expect("missing lite turn request")
.body_json();
assert_eq!(non_lite_turn["model"].as_str(), Some("gpt-5.3-codex"));
assert_eq!(lite_turn["model"].as_str(), Some("gpt-5.4"));
assert!(
non_lite_turn
.get("tools")
.and_then(Value::as_array)
.is_some_and(|tools| !tools.is_empty())
);
assert_eq!(lite_turn.get("previous_response_id"), None);
assert_eq!(lite_turn.get("tools"), None);
assert_eq!(lite_turn.get("instructions"), None);
let additional_tools = lite_turn
.get("input")
.and_then(Value::as_array)
.and_then(|input| input.first())
.filter(|item| item.get("type").and_then(Value::as_str) == Some("additional_tools"))
.and_then(|item| item.get("tools"))
.and_then(Value::as_array)
.expect("lite turn should start with an additional_tools item");
assert!(!additional_tools.is_empty());
server.shutdown().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn websocket_test_codex_shell_chain() -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -175,11 +256,14 @@ async fn websocket_v2_test_codex_shell_chain() -> Result<()> {
skip_if_no_network!(Ok(()));
let call_id = "shell-command-call";
let mut shell_command_call = ev_shell_command_call(call_id, "echo websocket");
shell_command_call["item"]["internal_chat_message_metadata_passthrough"] =
serde_json::json!({"turn_id": "turn-123"});
let server = start_websocket_server(vec![vec![
vec![ev_response_created("warm-1"), ev_completed("warm-1")],
vec![
ev_response_created("resp-1"),
ev_shell_command_call(call_id, "echo websocket"),
shell_command_call,
ev_completed("resp-1"),
],
vec![
+18 -17
View File
@@ -141,8 +141,8 @@ async fn agents_override_is_preferred_over_agents_md() -> Result<()> {
agents_instructions(test_codex().with_workspace_setup(|cwd, fs| async move {
let agents_md = cwd.join("AGENTS.md");
let override_md = cwd.join("AGENTS.override.md");
let agents_md_uri = PathUri::from_path(&agents_md)?;
let override_md_uri = PathUri::from_path(&override_md)?;
let agents_md_uri = PathUri::from_host_native_path(&agents_md)?;
let override_md_uri = PathUri::from_host_native_path(&override_md)?;
fs.write_file(&agents_md_uri, b"base doc".to_vec(), /*sandbox*/ None)
.await?;
fs.write_file(
@@ -177,8 +177,8 @@ async fn configured_fallback_is_used_when_agents_candidate_is_directory() -> Res
.with_workspace_setup(|cwd, fs| async move {
let agents_dir = cwd.join("AGENTS.md");
let fallback = cwd.join("WORKFLOW.md");
let agents_dir_uri = PathUri::from_path(&agents_dir)?;
let fallback_uri = PathUri::from_path(&fallback)?;
let agents_dir_uri = PathUri::from_host_native_path(&agents_dir)?;
let fallback_uri = PathUri::from_host_native_path(&fallback)?;
fs.create_directory(
&agents_dir_uri,
CreateDirectoryOptions { recursive: true },
@@ -220,10 +220,10 @@ async fn agents_docs_are_concatenated_from_project_root_to_cwd() -> Result<()> {
let root_agents = root.join("AGENTS.md");
let git_marker = root.join(".git");
let nested_agents = nested.join("AGENTS.md");
let nested_uri = PathUri::from_path(&nested)?;
let root_agents_uri = PathUri::from_path(&root_agents)?;
let git_marker_uri = PathUri::from_path(&git_marker)?;
let nested_agents_uri = PathUri::from_path(&nested_agents)?;
let nested_uri = PathUri::from_host_native_path(&nested)?;
let root_agents_uri = PathUri::from_host_native_path(&root_agents)?;
let git_marker_uri = PathUri::from_host_native_path(&git_marker)?;
let nested_agents_uri = PathUri::from_host_native_path(&nested_agents)?;
fs.create_directory(
&nested_uri,
@@ -363,7 +363,7 @@ async fn selected_environment_sources_match_model_visible_instructions() -> Resu
let mut builder = test_codex()
.with_home(home)
.with_workspace_setup(|cwd, fs| async move {
let agents_md_uri = PathUri::from_path(cwd.join("AGENTS.md"))?;
let agents_md_uri = PathUri::from_host_native_path(cwd.join("AGENTS.md"))?;
fs.write_file(
&agents_md_uri,
b"project doc".to_vec(),
@@ -420,7 +420,8 @@ async fn loads_user_instructions_without_a_primary_environment() -> Result<()> {
.with_home(Arc::clone(&home))
.with_user_instructions_provider(provider.clone())
.with_workspace_setup(|cwd, fs| async move {
let project_agents_uri = PathUri::from_path(cwd.join(GLOBAL_AGENTS_FILENAME))?;
let project_agents_uri =
PathUri::from_host_native_path(cwd.join(GLOBAL_AGENTS_FILENAME))?;
fs.write_file(
&project_agents_uri,
PROJECT_INSTRUCTIONS.as_bytes().to_vec(),
@@ -505,7 +506,7 @@ async fn fresh_thread_composes_global_before_project_and_reports_sources() -> Re
let mut builder = test_codex()
.with_home(Arc::clone(&home))
.with_workspace_setup(|cwd, fs| async move {
let agents_md_uri = PathUri::from_path(cwd.join("AGENTS.md"))?;
let agents_md_uri = PathUri::from_host_native_path(cwd.join("AGENTS.md"))?;
fs.write_file(
&agents_md_uri,
PROJECT_INSTRUCTIONS.as_bytes().to_vec(),
@@ -534,7 +535,7 @@ async fn fresh_thread_composes_global_before_project_and_reports_sources() -> Re
)?;
test.fs()
.write_file(
&PathUri::from_path(&project_source)?,
&PathUri::from_host_native_path(&project_source)?,
NEW_PROJECT_INSTRUCTIONS.as_bytes().to_vec(),
/*sandbox*/ None,
)
@@ -631,7 +632,7 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho
.with_user_instructions_provider(provider.clone())
.with_workspace_setup(|cwd, fs| async move {
fs.write_file(
&PathUri::from_path(cwd.join(GLOBAL_AGENTS_FILENAME))?,
&PathUri::from_host_native_path(cwd.join(GLOBAL_AGENTS_FILENAME))?,
b"remote project instructions".to_vec(),
/*sandbox*/ None,
)
@@ -658,7 +659,7 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho
},
TurnEnvironmentSelection {
environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
cwd: PathUri::from_path(local_root.path())?,
cwd: PathUri::from_host_native_path(local_root.path())?,
},
],
thread_extension_init: Default::default(),
@@ -671,7 +672,7 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho
vec![
PathUri::from_abs_path(&global_source),
PathUri::from_abs_path(&remote_source),
PathUri::from_path(&local_source)?,
PathUri::from_host_native_path(&local_source)?,
]
);
@@ -684,7 +685,7 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho
)?;
test.fs()
.write_file(
&PathUri::from_path(test.config.cwd.join(GLOBAL_AGENTS_OVERRIDE_FILENAME))?,
&PathUri::from_host_native_path(test.config.cwd.join(GLOBAL_AGENTS_OVERRIDE_FILENAME))?,
b"new remote project instructions".to_vec(),
/*sandbox*/ None,
)
@@ -712,7 +713,7 @@ async fn multi_environment_thread_loads_every_project_and_keeps_creation_snapsho
vec![
PathUri::from_abs_path(&global_source),
PathUri::from_abs_path(&remote_source),
PathUri::from_path(&local_source)?,
PathUri::from_host_native_path(&local_source)?,
]
);
+6 -6
View File
@@ -1329,7 +1329,7 @@ async fn apply_patch_turn_diff_paths_stay_repo_relative_when_session_cwd_is_nest
config.cwd = config.cwd.join("subdir");
})
.with_workspace_setup(|cwd, fs| async move {
let cwd_uri = PathUri::from_path(&cwd)?;
let cwd_uri = PathUri::from_host_native_path(&cwd)?;
fs.create_directory(
&cwd_uri,
CreateDirectoryOptions { recursive: true },
@@ -1337,8 +1337,8 @@ async fn apply_patch_turn_diff_paths_stay_repo_relative_when_session_cwd_is_nest
)
.await?;
let repo_root = cwd.parent().expect("nested cwd should have parent");
let git_uri = PathUri::from_path(repo_root.join(".git"))?;
let repo_file_uri = PathUri::from_path(repo_root.join("repo.txt"))?;
let git_uri = PathUri::from_host_native_path(repo_root.join(".git"))?;
let repo_file_uri = PathUri::from_host_native_path(repo_root.join("repo.txt"))?;
fs.write_file(
&git_uri,
b"gitdir: /tmp/fake-worktree\n".to_vec(),
@@ -1586,7 +1586,7 @@ async fn apply_patch_turn_diff_tracks_local_and_remote_environment_paths() -> Re
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
let shared_cwd_uri = PathUri::from_path(&shared_cwd)?;
let shared_cwd_uri = PathUri::from_host_native_path(&shared_cwd)?;
let _ = fs::remove_dir_all(shared_cwd.as_path());
test.fs()
.remove(
@@ -1689,7 +1689,7 @@ async fn apply_patch_turn_diff_tracks_local_and_remote_environment_paths() -> Re
assert_eq!(
test.fs()
.read_file_text(
&PathUri::from_path(shared_cwd.join(file_name))?,
&PathUri::from_host_native_path(shared_cwd.join(file_name))?,
/*sandbox*/ None,
)
.await?,
@@ -1859,7 +1859,7 @@ async fn apply_patch_clears_aggregated_diff_after_inexact_delta() -> Result<()>
let harness = apply_patch_harness_with(|builder| {
builder.with_workspace_setup(|cwd, fs| async move {
let binary_path_uri = PathUri::from_path(cwd.join("binary.dat"))?;
let binary_path_uri = PathUri::from_host_native_path(cwd.join("binary.dat"))?;
fs.write_file(
&binary_path_uri,
vec![0xff, 0xfe, 0xfd],
+94 -27
View File
@@ -66,6 +66,7 @@ use core_test_support::responses::mount_sse_once_match;
use core_test_support::responses::mount_sse_sequence;
use core_test_support::responses::sse;
use core_test_support::responses::sse_failed;
use core_test_support::responses::strip_metadata_from_json;
use core_test_support::responses_metadata as test_responses_metadata;
use core_test_support::skip_if_no_network;
use core_test_support::test_codex::TestCodex;
@@ -186,7 +187,66 @@ fn assert_codex_client_metadata(
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn non_openai_responses_requests_omit_item_turn_metadata() {
async fn openai_stateless_responses_requests_preserve_item_turn_metadata_across_turns() {
let server = MockServer::start().await;
let response_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp1"),
ev_assistant_message("msg-1", "first answer"),
ev_completed("resp1"),
]),
sse(vec![ev_response_created("resp2"), ev_completed("resp2")]),
],
)
.await;
let test = test_codex().build(&server).await.unwrap();
test.submit_turn("turn one").await.unwrap();
test.submit_turn("turn two").await.unwrap();
let requests = response_mock.requests();
assert_eq!(requests.len(), 2);
let first = requests[0].body_json();
let second = requests[1].body_json();
let first_turn_id = first["client_metadata"]["turn_id"]
.as_str()
.expect("first request should include turn id");
let second_turn_id = second["client_metadata"]["turn_id"]
.as_str()
.expect("second request should include turn id");
assert_ne!(first_turn_id, second_turn_id);
let first_input = first["input"].as_array().expect("first input");
let second_input = second["input"].as_array().expect("second input");
assert_eq!(&second_input[..first_input.len()], first_input.as_slice());
for item in first_input {
assert_eq!(
item["internal_chat_message_metadata_passthrough"]["turn_id"].as_str(),
Some(first_turn_id)
);
}
let item_turn_id = |text: &str| {
second_input
.iter()
.find(|item| {
item["content"].as_array().is_some_and(|content| {
content
.iter()
.any(|content_item| content_item["text"].as_str() == Some(text))
})
})
.and_then(|item| item["internal_chat_message_metadata_passthrough"]["turn_id"].as_str())
};
assert_eq!(item_turn_id("turn one"), Some(first_turn_id));
assert_eq!(item_turn_id("first answer"), Some(first_turn_id));
assert_eq!(item_turn_id("turn two"), Some(second_turn_id));
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn non_openai_responses_requests_omit_item_passthrough_metadata() {
let server = MockServer::start().await;
let response_mock = mount_sse_once(
&server,
@@ -230,8 +290,9 @@ async fn non_openai_responses_requests_omit_item_turn_metadata() {
assert!(!input.is_empty(), "request should include input items");
for item in input {
assert!(
item.get("metadata").is_none(),
"input item should omit metadata: {item}"
item.get("internal_chat_message_metadata_passthrough")
.is_none(),
"input item should omit internal chat message metadata passthrough: {item}"
);
assert!(
item.get("id").is_none(),
@@ -516,6 +577,7 @@ async fn resume_includes_initial_messages_and_sends_prior_items() {
"timestamp": "2024-01-01T00:00:00.000Z",
"type": "session_meta",
"payload": {
"session_id": convo_id,
"id": convo_id,
"timestamp": "2024-01-01T00:00:00Z",
"instructions": "be nice",
@@ -536,7 +598,7 @@ async fn resume_includes_initial_messages_and_sends_prior_items() {
text: "resumed user message".to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
};
let prior_user_json = serde_json::to_value(&prior_user).unwrap();
writeln!(
@@ -558,7 +620,7 @@ async fn resume_includes_initial_messages_and_sends_prior_items() {
text: "resumed system instruction".to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
};
let prior_system_json = serde_json::to_value(&prior_system).unwrap();
writeln!(
@@ -580,7 +642,7 @@ async fn resume_includes_initial_messages_and_sends_prior_items() {
text: "resumed assistant message".to_string(),
}],
phase: Some(MessagePhase::Commentary),
metadata: None,
internal_chat_message_metadata_passthrough: None,
};
let prior_item_json = serde_json::to_value(&prior_item).unwrap();
writeln!(
@@ -723,15 +785,17 @@ async fn resume_replays_legacy_js_repl_image_rollout_shapes() {
call_id: "legacy-js-call".to_string(),
name: "js_repl".to_string(),
input: "console.log('legacy image flow')".to_string(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
};
let legacy_image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
let thread_id = ThreadId::default();
let rollout = vec![
RolloutLine {
timestamp: "2024-01-01T00:00:00.000Z".to_string(),
item: RolloutItem::SessionMeta(SessionMetaLine {
meta: SessionMeta {
id: ThreadId::default(),
session_id: thread_id.into(),
id: thread_id,
parent_thread_id: None,
timestamp: "2024-01-01T00:00:00Z".to_string(),
cwd: ".".into(),
@@ -754,7 +818,7 @@ async fn resume_replays_legacy_js_repl_image_rollout_shapes() {
call_id: "legacy-js-call".to_string(),
name: None,
output: FunctionCallOutputPayload::from_text("legacy js_repl stdout".to_string()),
metadata: None,
internal_chat_message_metadata_passthrough: None,
}),
},
RolloutLine {
@@ -767,7 +831,7 @@ async fn resume_replays_legacy_js_repl_image_rollout_shapes() {
detail: Some(DEFAULT_IMAGE_DETAIL),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
}),
},
];
@@ -857,15 +921,17 @@ async fn resume_replays_legacy_js_repl_image_rollout_shapes() {
async fn resume_replays_image_tool_outputs_with_detail() {
skip_if_no_network!();
let image_url = "data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEAAUAmJaACdLoB+AADsAD+8ut//NgVzXPv9//S4P0uD9Lg/9KQAAA=";
let image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
let function_call_id = "view-image-call";
let custom_call_id = "js-repl-call";
let thread_id = ThreadId::default();
let rollout = vec![
RolloutLine {
timestamp: "2024-01-01T00:00:00.000Z".to_string(),
item: RolloutItem::SessionMeta(SessionMetaLine {
meta: SessionMeta {
id: ThreadId::default(),
session_id: thread_id.into(),
id: thread_id,
parent_thread_id: None,
timestamp: "2024-01-01T00:00:00Z".to_string(),
cwd: ".".into(),
@@ -883,9 +949,9 @@ async fn resume_replays_image_tool_outputs_with_detail() {
id: None,
name: "view_image".to_string(),
namespace: None,
arguments: "{\"path\":\"/tmp/example.webp\"}".to_string(),
arguments: "{\"path\":\"/tmp/example.png\"}".to_string(),
call_id: function_call_id.to_string(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
}),
},
RolloutLine {
@@ -899,7 +965,7 @@ async fn resume_replays_image_tool_outputs_with_detail() {
detail: Some(ImageDetail::Original),
},
]),
metadata: None,
internal_chat_message_metadata_passthrough: None,
}),
},
RolloutLine {
@@ -910,7 +976,7 @@ async fn resume_replays_image_tool_outputs_with_detail() {
call_id: custom_call_id.to_string(),
name: "js_repl".to_string(),
input: "console.log('image flow')".to_string(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
}),
},
RolloutLine {
@@ -925,7 +991,7 @@ async fn resume_replays_image_tool_outputs_with_detail() {
detail: Some(ImageDetail::Original),
},
]),
metadata: None,
internal_chat_message_metadata_passthrough: None,
}),
},
];
@@ -1174,7 +1240,7 @@ async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuth
text: "hello".to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
});
let mut stream = client_session
@@ -1379,6 +1445,7 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() {
AuthCredentialsStoreMode::File,
/*chatgpt_base_url*/ None,
AuthKeyringBackendKind::default(),
/*auth_route_config*/ None,
)
.await
.expect("Failed to load CodexAuth")
@@ -2788,7 +2855,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
text: "content".into(),
}]),
encrypted_content: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
});
prompt.input.push(ResponseItem::Message {
id: Some("message-id".into()),
@@ -2797,7 +2864,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
text: "message".into(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
});
prompt.input.push(ResponseItem::WebSearchCall {
id: Some("web-search-id".into()),
@@ -2806,7 +2873,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
query: Some("weather".into()),
queries: None,
}),
metadata: None,
internal_chat_message_metadata_passthrough: None,
});
prompt.input.push(ResponseItem::FunctionCall {
id: Some("function-id".into()),
@@ -2814,13 +2881,13 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
namespace: None,
arguments: "{}".into(),
call_id: "function-call-id".into(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
});
prompt.input.push(ResponseItem::FunctionCallOutput {
id: None,
call_id: "function-call-id".into(),
output: FunctionCallOutputPayload::from_text("ok".into()),
metadata: None,
internal_chat_message_metadata_passthrough: None,
});
prompt.input.push(ResponseItem::LocalShellCall {
id: Some("local-shell-id".into()),
@@ -2833,7 +2900,7 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
env: None,
user: None,
}),
metadata: None,
internal_chat_message_metadata_passthrough: None,
});
prompt.input.push(ResponseItem::CustomToolCall {
id: Some("custom-tool-id".into()),
@@ -2841,14 +2908,14 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
call_id: "custom-tool-call-id".into(),
name: "custom_tool".into(),
input: "{}".into(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
});
prompt.input.push(ResponseItem::CustomToolCallOutput {
id: None,
call_id: "custom-tool-call-id".into(),
name: None,
output: FunctionCallOutputPayload::from_text("ok".into()),
metadata: None,
internal_chat_message_metadata_passthrough: None,
});
let mut stream = client_session
@@ -3605,7 +3672,7 @@ async fn history_dedupes_streamed_and_final_messages_across_turns() {
let tail_len = r3_tail_expected.as_array().unwrap().len();
let actual_tail = &r3_input_array[r3_input_array.len() - tail_len..];
assert_eq!(
serde_json::Value::Array(actual_tail.to_vec()),
strip_metadata_from_json(serde_json::Value::Array(actual_tail.to_vec())),
r3_tail_expected,
"request 3 tail mismatch",
);
@@ -1564,10 +1564,13 @@ async fn responses_websocket_uses_incremental_create_on_prefix() {
async fn responses_websocket_forwards_turn_metadata_on_initial_and_incremental_create() {
skip_if_no_network!();
let mut first_output_item = ev_assistant_message("msg-1", "assistant output");
first_output_item["item"]["internal_chat_message_metadata_passthrough"] =
json!({"turn_id": "turn-123"});
let server = start_websocket_server(vec![vec![
vec![
ev_response_created("resp-1"),
ev_assistant_message("msg-1", "assistant output"),
first_output_item,
ev_completed("resp-1"),
],
vec![ev_response_created("resp-2"), ev_completed("resp-2")],
@@ -1577,9 +1580,11 @@ async fn responses_websocket_forwards_turn_metadata_on_initial_and_incremental_c
let harness = websocket_harness(&server).await;
let mut client_session = harness.client.new_session();
let prompt_one = prompt_with_input(vec![message_item("hello")]);
let mut prior_assistant_output = assistant_message_item("msg-1", "assistant output");
prior_assistant_output.set_turn_id_if_missing("turn-123");
let prompt_two = prompt_with_input(vec![
message_item("hello"),
assistant_message_item("msg-1", "assistant output"),
prior_assistant_output,
message_item("second"),
]);
let first_responses_metadata = turn_metadata(&harness, Some("turn-123"));
@@ -2059,7 +2064,7 @@ fn message_item(text: &str) -> ResponseItem {
role: "user".into(),
content: vec![ContentItem::InputText { text: text.into() }],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
}
}
@@ -2069,7 +2074,7 @@ fn assistant_message_item(id: &str, text: &str) -> ResponseItem {
role: "assistant".into(),
content: vec![ContentItem::OutputText { text: text.into() }],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
}
}
+6 -14
View File
@@ -2681,7 +2681,7 @@ async fn code_mode_can_output_images_via_global_helper() -> Result<()> {
&server,
"use exec to return images",
r#"
image("data:image/png;base64,AAA");
image("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==");
"#,
)
.await?;
@@ -2706,7 +2706,7 @@ image("data:image/png;base64,AAA");
items[1],
serde_json::json!({
"type": "input_image",
"image_url": "data:image/png;base64,AAA",
"image_url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==",
"detail": "high"
}),
);
@@ -2715,17 +2715,14 @@ image("data:image/png;base64,AAA");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn resize_all_images_replaces_malformed_code_mode_image() -> Result<()> {
async fn code_mode_replaces_malformed_image() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let (_test, second_mock) = run_code_mode_turn_with_config(
let (_test, second_mock) = run_code_mode_turn(
&server,
"use exec to return an image",
r#"image("data:image/png;base64,AAA");"#,
|config| {
let _ = config.features.enable(Feature::ResizeAllImages);
},
)
.await?;
@@ -2746,7 +2743,7 @@ async fn resize_all_images_replaces_malformed_code_mode_image() -> Result<()> {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn resize_all_images_resizes_explicit_original_code_mode_image() -> Result<()> {
async fn code_mode_resizes_explicit_original_image() -> Result<()> {
skip_if_no_network!(Ok(()));
let original_dimensions = (6401, 100);
@@ -2772,12 +2769,7 @@ async fn resize_all_images_resizes_explicit_original_code_mode_image() -> Result
"use exec to return a large original-detail image",
&code,
"gpt-5.3-codex",
|config| {
config
.features
.enable(Feature::ResizeAllImages)
.expect("resize_all_images should be enabled");
},
|_| {},
)
.await?;
+215 -7
View File
@@ -1,5 +1,6 @@
use anyhow::Result;
use anyhow::anyhow;
use codex_core::CodexThread;
use codex_core::compact::SUMMARIZATION_PROMPT;
use codex_core::compact::SUMMARY_PREFIX;
use codex_core::config::Config;
@@ -35,6 +36,7 @@ use core_test_support::responses;
use core_test_support::responses::ev_reasoning_item;
use core_test_support::responses::mount_models_once;
use core_test_support::skip_if_no_network;
use core_test_support::test_codex::TestCodex;
use core_test_support::test_codex::local_selections;
use core_test_support::test_codex::test_codex;
use core_test_support::test_codex::turn_permission_fields;
@@ -92,6 +94,48 @@ const REMOTE_V2_SUMMARY: &str = "global-instructions-remote-v2-summary";
pub(super) const COMPACT_WARNING_MESSAGE: &str = "Heads up: Long threads and multiple compactions can cause the model to be less accurate. Start a new thread when possible to keep threads small and targeted.";
async fn build_auto_compaction_disabled_codex(server: &MockServer) -> TestCodex {
let mut model_provider = non_openai_model_provider(server);
model_provider.stream_max_retries = Some(0);
test_codex()
.with_config(move |config| {
config.model_provider = model_provider;
set_test_compact_prompt(config);
config.model_context_window = Some(100);
config.model_auto_compact_token_limit = Some(90);
let _ = config.features.disable(Feature::AutoCompaction);
})
.build(server)
.await
.expect("build codex")
}
async fn submit_context_window_exceeded_turn(codex: &Arc<CodexThread>, text: &str) {
codex
.submit(Op::UserInput {
items: vec![UserInput::Text {
text: text.to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
additional_context: Default::default(),
thread_settings: Default::default(),
})
.await
.expect("submit context window exceeded turn");
let error_message = wait_for_event_match(codex, |event| match event {
EventMsg::Error(err) => Some(err.message.clone()),
_ => None,
})
.await;
wait_for_event(codex, |event| matches!(event, EventMsg::TurnComplete(_))).await;
assert!(
error_message.contains("ran out of room in the model's context window"),
"expected context window exceeded message, got {error_message}"
);
}
fn ev_shell_command_call(call_id: &str, command: &str) -> serde_json::Value {
ev_function_call(
call_id,
@@ -1993,12 +2037,12 @@ async fn auto_compact_runs_after_resume_when_token_usage_is_over_limit() {
text: remote_summary.to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
codex_protocol::models::ResponseItem::Compaction {
id: None,
encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
];
let compact_mock =
@@ -2276,6 +2320,93 @@ async fn pre_sampling_compact_runs_when_comp_hash_changes() {
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn auto_compaction_feature_disabled_skips_comp_hash_model_switch_compaction() {
skip_if_no_network!();
let server = MockServer::start().await;
let previous_model = "gpt-5.3-codex";
let next_model = "gpt-5.2";
let models_mock = mount_models_once(
&server,
ModelsResponse {
models: vec![
model_info_with_optional_comp_hash(previous_model, Some("hash-a")),
model_info_with_optional_comp_hash(next_model, Some("hash-b")),
],
},
)
.await;
let request_log = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_assistant_message("m1", "before switch"),
ev_completed_with_tokens("r1", /*total_tokens*/ 100),
]),
sse(vec![
ev_assistant_message("m2", "after switch"),
ev_completed_with_tokens("r2", /*total_tokens*/ 100),
]),
],
)
.await;
let model_provider = non_openai_model_provider(&server);
let mut builder = test_codex()
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_model(previous_model)
.with_config(move |config| {
config.model_provider = model_provider;
set_test_compact_prompt(config);
let _ = config.features.disable(Feature::AutoCompaction);
});
let test = builder.build(&server).await.expect("build test codex");
test.codex
.submit(disabled_permission_user_turn(
"before switch",
test.cwd.path().to_path_buf(),
previous_model.to_string(),
))
.await
.expect("submit first user turn");
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
test.codex
.submit(disabled_permission_user_turn(
"after switch",
test.cwd.path().to_path_buf(),
next_model.to_string(),
))
.await
.expect("submit second user turn");
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
let requests = request_log.requests();
assert_eq!(models_mock.requests().len(), 1);
assert_eq!(
requests.len(),
2,
"disabled auto-compaction should skip compaction on a comp-hash model switch"
);
let first = requests[0].body_json();
let second = requests[1].body_json();
assert_eq!(first["model"].as_str(), Some(previous_model));
assert_eq!(second["model"].as_str(), Some(next_model));
assert!(second.to_string().contains("before switch"));
assert!(second.to_string().contains("after switch"));
assert!(
!body_contains_text(&second.to_string(), SUMMARIZATION_PROMPT),
"disabled auto-compaction should preserve history instead of requesting a summary"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn pre_sampling_compact_skips_when_either_comp_hash_is_missing() {
skip_if_no_network!();
@@ -3655,6 +3786,45 @@ async fn snapshot_request_shape_mid_turn_continuation_compaction() {
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn auto_compaction_feature_disabled_skips_mid_turn_compaction() {
skip_if_no_network!();
let server = start_mock_server().await;
let over_limit_tokens = 100 * 95 / 100 + 1;
let first_turn = sse(vec![
ev_function_call(DUMMY_CALL_ID, DUMMY_FUNCTION_NAME, "{}"),
ev_completed_with_tokens("r1", over_limit_tokens),
]);
let request_log = mount_sse_sequence(
&server,
vec![
first_turn,
sse_failed(
"response-failed",
"context_length_exceeded",
CONTEXT_LIMIT_MESSAGE,
),
],
)
.await;
let test = build_auto_compaction_disabled_codex(&server).await;
submit_context_window_exceeded_turn(&test.codex, FUNCTION_CALL_LIMIT_MSG).await;
let requests = request_log.requests();
assert_eq!(requests.len(), 2);
let continuation_request = &requests[1];
continuation_request.function_call_output(DUMMY_CALL_ID);
assert!(
!body_contains_text(
&continuation_request.body_json().to_string(),
SUMMARIZATION_PROMPT
),
"disabled auto-compaction should continue without a compaction request"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn auto_compact_clamps_config_limit_to_context_window() {
skip_if_no_network!();
@@ -3993,12 +4163,12 @@ async fn auto_compact_counts_encrypted_reasoning_before_last_user() {
text: "REMOTE_COMPACT_SUMMARY".to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
codex_protocol::models::ResponseItem::Compaction {
id: None,
encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
];
let compact_mock =
@@ -4121,12 +4291,12 @@ async fn auto_compact_runs_when_reasoning_header_clears_between_turns() {
text: "REMOTE_COMPACT_SUMMARY".to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
codex_protocol::models::ResponseItem::Compaction {
id: None,
encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
];
let compact_mock =
@@ -4233,7 +4403,7 @@ async fn snapshot_request_shape_pre_turn_compaction_including_incoming_user_mess
)
.await
.expect("override thread settings");
let image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGNgYAAAAAMAASsJTYQAAAAASUVORK5CYII="
let image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="
.to_string();
codex
.submit(Op::UserInput {
@@ -4488,6 +4658,44 @@ async fn snapshot_request_shape_pre_turn_compaction_context_window_exceeded() {
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn auto_compaction_feature_disabled_skips_pre_turn_compaction() {
skip_if_no_network!();
let server = start_mock_server().await;
let first_turn = sse(vec![
ev_assistant_message("m1", FIRST_REPLY),
ev_completed_with_tokens("r1", /*total_tokens*/ 500),
]);
let request_log = mount_sse_sequence(
&server,
vec![
first_turn,
sse_failed(
"response-failed",
"context_length_exceeded",
CONTEXT_LIMIT_MESSAGE,
),
],
)
.await;
let test = build_auto_compaction_disabled_codex(&server).await;
test.submit_turn("USER_ONE")
.await
.expect("submit first turn");
submit_context_window_exceeded_turn(&test.codex, "USER_TWO").await;
let requests = request_log.requests();
assert_eq!(requests.len(), 2);
let second_request_body = requests[1].body_json().to_string();
assert!(second_request_body.contains("USER_TWO"));
assert!(
!body_contains_text(&second_request_body, SUMMARIZATION_PROMPT),
"disabled auto-compaction should sample without a pre-turn compaction request"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn snapshot_request_shape_manual_compact_without_previous_user_messages() {
skip_if_no_network!();
+9 -9
View File
@@ -159,7 +159,7 @@ fn compacted_summary_only_output(summary: &str) -> Vec<ResponseItem> {
vec![ResponseItem::Compaction {
id: None,
encrypted_content: summary_with_prefix(summary),
metadata: None,
internal_chat_message_metadata_passthrough: None,
}]
}
@@ -333,7 +333,7 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> {
let compacted_history = vec![ResponseItem::Compaction {
id: None,
encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
}];
let compact_mock = responses::mount_compact_json_once(
harness.server(),
@@ -2361,7 +2361,7 @@ async fn remote_compact_persists_replacement_history_in_rollout() -> Result<()>
ResponseItem::Compaction {
id: None,
encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
ResponseItem::Message {
id: None,
@@ -2370,7 +2370,7 @@ async fn remote_compact_persists_replacement_history_in_rollout() -> Result<()>
text: "COMPACTED_ASSISTANT_NOTE".to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
];
let compact_mock = responses::mount_compact_json_once(
@@ -2512,12 +2512,12 @@ async fn remote_compact_and_resume_refresh_stale_developer_instructions() -> Res
text: stale_developer_message.to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
ResponseItem::Compaction {
id: None,
encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
];
let compact_mock = responses::mount_compact_json_once(
@@ -2655,12 +2655,12 @@ async fn remote_compact_refreshes_stale_developer_instructions_without_resume()
text: stale_developer_message.to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
ResponseItem::Compaction {
id: None,
encrypted_content: "ENCRYPTED_COMPACTION_SUMMARY".to_string(),
metadata: None,
internal_chat_message_metadata_passthrough: None,
},
];
let compact_mock = responses::mount_compact_json_once(
@@ -4067,7 +4067,7 @@ async fn snapshot_request_shape_remote_mid_turn_compaction_summary_only_reinject
let compacted_history = vec![ResponseItem::Compaction {
id: None,
encrypted_content: summary_with_prefix("REMOTE_SUMMARY_ONLY"),
metadata: None,
internal_chat_message_metadata_passthrough: None,
}];
let compact_mock = responses::mount_compact_json_once(
harness.server(),
@@ -924,6 +924,7 @@ fn normalize_value(value: Value) -> Value {
Value::Array(values) => Value::Array(values.into_iter().map(normalize_value).collect()),
Value::Object(map) => Value::Object(
map.into_iter()
.filter(|(key, _value)| key != "internal_chat_message_metadata_passthrough")
.map(|(key, value)| (key, normalize_value(value)))
.collect(),
),
@@ -42,9 +42,11 @@ use wiremock::matchers::path;
const TINY_PNG_BYTES: &[u8] = &[
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0,
0, 0, 31, 21, 196, 137, 0, 0, 0, 11, 73, 68, 65, 84, 120, 156, 99, 96, 0, 2, 0, 0, 5, 0, 1,
122, 94, 171, 63, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
0, 0, 31, 21, 196, 137, 0, 0, 0, 13, 73, 68, 65, 84, 120, 156, 99, 248, 207, 192, 240, 31, 0,
5, 0, 1, 255, 137, 153, 61, 29, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,
];
const TINY_PNG_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
const TINY_PNG_DATA_URL: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
fn image_generation_extensions(auth: &CodexAuth) -> Arc<ExtensionRegistry<Config>> {
let auth_manager = codex_core::test_support::auth_manager_from_auth(auth.clone());
@@ -148,7 +150,7 @@ async fn extension_tool_uses_granted_turn_permissions() -> Result<()> {
.and(path("/v1/images/edits"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"created": 1,
"data": [{"b64_json": "cG5n"}],
"data": [{"b64_json": TINY_PNG_BASE64}],
})))
.expect(1)
.mount(&server)
@@ -299,7 +301,7 @@ async fn extension_tool_uses_granted_turn_permissions() -> Result<()> {
let output = request.function_call_output(image_call_id);
let image = &output["output"][0];
assert_eq!(image["type"], "input_image");
assert_eq!(image["image_url"], "data:image/png;base64,cG5n");
assert_eq!(image["image_url"], TINY_PNG_DATA_URL);
Ok(())
}
+3 -1
View File
@@ -1,3 +1,5 @@
use std::sync::Arc;
use codex_core::ForkSnapshot;
use codex_core::NewThread;
use codex_core::parse_turn_item;
@@ -196,7 +198,7 @@ async fn fork_thread_from_history_does_not_require_source_rollout_path() {
test.config.clone(),
InitialHistory::Resumed(ResumedHistory {
conversation_id: test.session_configured.thread_id,
history: source_items.clone(),
history: Arc::new(source_items.clone()),
rollout_path: None,
}),
/*thread_source*/ None,
@@ -17,6 +17,7 @@ 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::responses::start_websocket_server;
use core_test_support::skip_if_no_network;
use core_test_support::skip_if_sandbox;
use core_test_support::test_codex::local_selections;
@@ -30,6 +31,85 @@ use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
use tempfile::TempDir;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn guardian_session_prewarms_and_is_reused_for_first_review() -> Result<()> {
skip_if_no_network!(Ok(()));
let tool_args = json!({
"cmd": "true",
"sandbox_permissions": SandboxPermissions::RequireEscalated,
"justification": "Exercise Guardian approval routing.",
})
.to_string();
let server = start_websocket_server(vec![
vec![vec![ev_response_created("warm-1"), ev_completed("warm-1")]],
vec![vec![ev_response_created("warm-2"), ev_completed("warm-2")]],
vec![vec![
ev_response_created("approval-request"),
ev_function_call("approval-call", "exec_command", &tool_args),
ev_completed("approval-request"),
]],
vec![vec![
ev_response_created("guardian-review"),
ev_completed("guardian-review"),
]],
])
.await;
let mut builder = test_codex().with_config(|config| {
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
config.approvals_reviewer = ApprovalsReviewer::AutoReview;
});
let test = builder.build_with_websocket_server(&server).await?;
let (first, second) = tokio::time::timeout(Duration::from_secs(5), async {
tokio::join!(
server.wait_for_request(/*connection_index*/ 0, /*request_index*/ 0),
server.wait_for_request(/*connection_index*/ 1, /*request_index*/ 0)
)
})
.await?;
let prewarm_requests = [first.body_json(), second.body_json()];
let guardian_prewarm = prewarm_requests
.iter()
.find(|request| {
request["client_metadata"]["x-openai-subagent"].as_str() == Some("guardian")
})
.expect("guardian startup prewarm request");
assert_eq!(guardian_prewarm["generate"].as_bool(), Some(false));
let guardian_thread_id = guardian_prewarm["client_metadata"]["thread_id"]
.as_str()
.expect("guardian thread id");
test.codex
.submit(
vec![UserInput::Text {
text: "run a command that requires Guardian review".into(),
text_elements: Vec::new(),
}]
.into(),
)
.await?;
let guardian_review = tokio::time::timeout(
Duration::from_secs(5),
server.wait_for_request(/*connection_index*/ 3, /*request_index*/ 0),
)
.await?
.body_json();
assert_eq!(
guardian_review["client_metadata"]["x-openai-subagent"].as_str(),
Some("guardian")
);
assert_eq!(
guardian_review["client_metadata"]["thread_id"].as_str(),
Some(guardian_thread_id)
);
assert_eq!(guardian_review.get("generate"), None);
test.codex.shutdown_and_wait().await?;
server.shutdown().await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn guardian_review_session_does_not_inherit_legacy_notify() -> Result<()> {
skip_if_no_network!(Ok(()));
+5 -5
View File
@@ -178,10 +178,10 @@ async fn copy_paste_local_image_persists_rollout_request_shape() -> anyhow::Resu
},
],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
};
assert_eq!(actual, expected);
assert_eq!(responses::strip_metadata(actual), expected);
Ok(())
}
@@ -200,7 +200,7 @@ async fn drag_drop_image_persists_rollout_request_shape() -> anyhow::Result<()>
..
} = test_codex().build(&server).await?;
let image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGNgYAAAAAMAASsJTYQAAAAASUVORK5CYII=".to_string();
let image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==".to_string();
let response = sse(vec![
ev_response_created("resp-1"),
@@ -269,10 +269,10 @@ async fn drag_drop_image_persists_rollout_request_shape() -> anyhow::Result<()>
},
],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
};
assert_eq!(actual, expected);
assert_eq!(responses::strip_metadata(actual), expected);
Ok(())
}
@@ -35,10 +35,6 @@ async fn code_mode_only_exposes_direct_model_only_mcp_namespaces() -> Result<()>
.features
.enable(Feature::CodeModeOnly)
.expect("test config should allow feature update");
config
.features
.enable(Feature::ToolSearchAlwaysDeferMcpTools)
.expect("test config should allow feature update");
config.code_mode.direct_only_tool_namespaces =
vec![SEARCH_CALENDAR_NAMESPACE.to_string()];
});
+1
View File
@@ -104,6 +104,7 @@ mod review;
mod rmcp_client;
mod rollout_budget;
mod rollout_list_find;
mod safety_buffering;
mod safety_check_downgrade;
mod search_tool;
mod shell_command;
@@ -22,6 +22,7 @@ use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::mount_models_once;
use core_test_support::responses::mount_sse_once;
use core_test_support::responses::mount_sse_sequence;
use core_test_support::responses::sse;
use core_test_support::skip_if_no_network;
use core_test_support::submit_thread_settings;
@@ -36,6 +37,13 @@ use tokio::time::sleep;
const CHILD_MODEL: &str = "test-multi-agent-child";
const ROOT_MODEL: &str = "test-multi-agent-root";
const ROOT_PROMPT: &str = "spawn a child";
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
const UNSUPPORTED_CODE_MODE_WARNING: &str = "does not advertise Code Mode support";
struct RemoteModelResponse {
body: Value,
warnings: Vec<String>,
}
fn remote_model(slug: &str) -> ModelInfo {
ModelInfo {
@@ -81,10 +89,10 @@ async fn wait_for_model_available(manager: &SharedModelsManager, slug: &str) ->
}
}
async fn response_body_for_remote_model(
async fn response_for_remote_model(
remote_model: ModelInfo,
configure: impl FnOnce(&mut Config) + Send + 'static,
) -> Result<Value> {
) -> Result<RemoteModelResponse> {
let server = responses::start_mock_server().await;
let model_slug = remote_model.slug.clone();
let models_mock = mount_models_once(
@@ -133,12 +141,28 @@ async fn response_body_for_remote_model(
thread_settings: Default::default(),
})
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
let mut warnings = Vec::new();
loop {
match wait_for_event(&test.codex, |_| true).await {
EventMsg::Warning(warning) => warnings.push(warning.message),
EventMsg::TurnComplete(_) => break,
_ => {}
}
}
Ok(response_mock.single_request().body_json())
Ok(RemoteModelResponse {
body: response_mock.single_request().body_json(),
warnings,
})
}
async fn response_body_for_remote_model(
remote_model: ModelInfo,
configure: impl FnOnce(&mut Config) + Send + 'static,
) -> Result<Value> {
Ok(response_for_remote_model(remote_model, configure)
.await?
.body)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -180,6 +204,117 @@ async fn remote_tool_mode_selector_overrides_feature_flags() -> Result<()> {
]
);
let unsupported_model = remote_model("test-tool-mode-unsupported");
let unsupported_response = response_for_remote_model(unsupported_model, |config| {
config
.features
.enable(Feature::CodeModeOnly)
.expect("test config should allow feature update");
})
.await?;
assert!(
tool_names(&unsupported_response.body)
.iter()
.any(|name| name == codex_code_mode::PUBLIC_TOOL_NAME)
);
assert_eq!(
unsupported_response
.warnings
.iter()
.filter(|warning| warning.contains(UNSUPPORTED_CODE_MODE_WARNING))
.count(),
1
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unsupported_code_mode_warning_is_emitted_each_turn() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let model_slug = "test-tool-mode-warning-each-turn";
let models_mock = mount_models_once(
&server,
ModelsResponse {
models: vec![remote_model(model_slug)],
},
)
.await;
let response_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_assistant_message("msg-2", "done"),
ev_completed("resp-2"),
]),
],
)
.await;
let test = test_codex()
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_config(|config| {
config
.features
.enable(Feature::CodeMode)
.expect("test config should allow feature update");
})
.build(&server)
.await?;
let models_manager = test.thread_manager.get_models_manager();
let available_model = wait_for_model_available(&models_manager, model_slug).await;
assert_eq!(available_model.model, model_slug);
assert_eq!(models_mock.requests().len(), 1);
submit_thread_settings(
&test.codex,
ThreadSettingsOverrides {
model: Some(model_slug.to_string()),
..Default::default()
},
)
.await?;
let mut warning_counts = Vec::new();
for prompt in ["first turn", "second turn"] {
test.codex
.submit(Op::UserInput {
items: vec![UserInput::Text {
text: prompt.to_string(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
additional_context: Default::default(),
thread_settings: Default::default(),
})
.await?;
let mut warning_count = 0;
loop {
match wait_for_event(&test.codex, |_| true).await {
EventMsg::Warning(warning)
if warning.message.contains(UNSUPPORTED_CODE_MODE_WARNING) =>
{
warning_count += 1;
}
EventMsg::TurnComplete(_) => break,
_ => {}
}
}
warning_counts.push(warning_count);
}
assert_eq!(warning_counts, vec![1, 1]);
assert_eq!(response_mock.requests().len(), 2);
Ok(())
}
@@ -201,7 +336,7 @@ async fn remote_multi_agent_selector_overrides_feature_flags() -> Result<()> {
.expect("test config should allow feature update");
})
.await?;
assert!(tool_names(&v2_body).contains(&"send_message".to_string()));
assert!(tool_names(&v2_body).contains(&MULTI_AGENT_V2_NAMESPACE.to_string()));
let mut disabled_model = remote_model("test-multi-agent-disabled");
disabled_model.multi_agent_version = Some(MultiAgentVersion::Disabled);
@@ -215,7 +350,12 @@ async fn remote_multi_agent_selector_overrides_feature_flags() -> Result<()> {
let disabled_tools = tool_names(&disabled_body);
assert!(disabled_tools.iter().all(|name| !matches!(
name.as_str(),
"multi_agent_v1" | "spawn_agent" | "send_message" | "wait_agent" | "list_agents"
"multi_agent_v1"
| MULTI_AGENT_V2_NAMESPACE
| "spawn_agent"
| "send_message"
| "wait_agent"
| "list_agents"
)));
Ok(())
@@ -298,7 +438,7 @@ async fn remote_multi_agent_selector_uses_model_selected_before_first_turn() ->
.expect("expected response request")
.body_json(),
)
.contains(&"send_message".to_string()),
.contains(&MULTI_AGENT_V2_NAMESPACE.to_string()),
),
(1, Some(MultiAgentVersion::V2), true)
);
+1 -1
View File
@@ -506,7 +506,7 @@ async fn model_change_from_image_to_text_strips_prior_image_content() -> Result<
let _ = models_manager
.list_models(RefreshStrategy::OnlineIfUncached)
.await;
let image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGNgYAAAAAMAASsJTYQAAAAASUVORK5CYII="
let image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="
.to_string();
test.codex
+120 -127
View File
@@ -19,6 +19,7 @@ use pretty_assertions::assert_eq;
use serde_json::Value;
const NO_SPAWN_TEXT: &str = "Do not spawn sub-agents unless the user explicitly asks for sub-agents, delegation, or parallel agent work.";
const NO_MODE_TEXT: &str = "Multi-agent delegation mode instructions are inactive.";
const PROACTIVE_TEXT: &str = "Proactive multi-agent delegation is active.";
fn developer_texts(input: &[Value]) -> Vec<&str> {
@@ -66,7 +67,7 @@ async fn multi_agent_mode_is_sticky_and_emits_only_on_change() -> Result<()> {
let server = start_mock_server().await;
let responses = mount_sse_sequence(
&server,
(1..=3)
(1..=5)
.map(|index| {
sse(vec![
ev_response_created(&format!("resp-{index}")),
@@ -82,18 +83,24 @@ async fn multi_agent_mode_is_sticky_and_emits_only_on_change() -> Result<()> {
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
config
.features
.enable(Feature::MultiAgentMode)
.expect("test config should allow feature update");
})
.build(&server)
.await?;
submit_turn(&test.codex, "turn one", /*mode*/ None).await?;
assert_eq!(test.codex.config_snapshot().await.multi_agent_mode, None);
assert_eq!(
test.codex.config_snapshot().await.multi_agent_mode,
MultiAgentMode::ExplicitRequestOnly
);
submit_turn(&test.codex, "turn two", Some(MultiAgentMode::Proactive)).await?;
submit_turn(&test.codex, "turn three", /*mode*/ None).await?;
submit_turn(&test.codex, "turn four", Some(MultiAgentMode::None)).await?;
submit_turn(&test.codex, "turn five", /*mode*/ None).await?;
assert_eq!(
test.codex.config_snapshot().await.multi_agent_mode,
MultiAgentMode::None
);
let requests = responses.requests();
let inputs = requests
@@ -103,6 +110,8 @@ async fn multi_agent_mode_is_sticky_and_emits_only_on_change() -> Result<()> {
let first = developer_texts(&inputs[0]);
let second = developer_texts(&inputs[1]);
let third = developer_texts(&inputs[2]);
let fourth = developer_texts(&inputs[3]);
let fifth = developer_texts(&inputs[4]);
assert_eq!(
(
@@ -128,12 +137,102 @@ async fn multi_agent_mode_is_sticky_and_emits_only_on_change() -> Result<()> {
),
(2, 1, 1)
);
assert_eq!(
(
count_containing(&fourth, MULTI_AGENT_MODE_OPEN_TAG),
count_containing(&fourth, NO_SPAWN_TEXT),
count_containing(&fourth, PROACTIVE_TEXT),
count_containing(&fourth, NO_MODE_TEXT),
),
(3, 1, 1, 1)
);
assert_eq!(
(
count_containing(&fifth, MULTI_AGENT_MODE_OPEN_TAG),
count_containing(&fifth, NO_SPAWN_TEXT),
count_containing(&fifth, PROACTIVE_TEXT),
count_containing(&fifth, NO_MODE_TEXT),
),
(3, 1, 1, 1)
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn multi_agent_mode_feature_uses_explicit_mode_when_disabled() -> Result<()> {
async fn multi_agent_mode_none_omits_instructions_and_survives_resume() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let responses = mount_sse_sequence(
&server,
(1..=2)
.map(|index| {
sse(vec![
ev_response_created(&format!("resp-{index}")),
ev_completed(&format!("resp-{index}")),
])
})
.collect(),
)
.await;
let initial = test_codex()
.with_config(|config| {
config
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
})
.build(&server)
.await?;
let home = initial.home.clone();
let rollout_path = initial
.session_configured
.rollout_path
.clone()
.expect("rollout path");
submit_turn(&initial.codex, "before resume", Some(MultiAgentMode::None)).await?;
assert_eq!(
initial.codex.config_snapshot().await.multi_agent_mode,
MultiAgentMode::None
);
drop(initial);
let mut resume_builder = test_codex().with_config(|config| {
config
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
});
let resumed = resume_builder.resume(&server, home, rollout_path).await?;
submit_turn(&resumed.codex, "after resume", /*mode*/ None).await?;
assert_eq!(
resumed.codex.config_snapshot().await.multi_agent_mode,
MultiAgentMode::None
);
let requests = responses.requests();
assert_eq!(requests.len(), 2);
for request in requests {
let input = request.input();
let texts = developer_texts(&input);
assert_eq!(
(
count_containing(&texts, MULTI_AGENT_MODE_OPEN_TAG),
count_containing(&texts, NO_SPAWN_TEXT),
count_containing(&texts, PROACTIVE_TEXT),
count_containing(&texts, NO_MODE_TEXT),
),
(0, 0, 0, 0)
);
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn multi_agent_mode_applies_without_usage_hint_text() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -148,21 +247,21 @@ async fn multi_agent_mode_feature_uses_explicit_mode_when_disabled() -> Result<(
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
config.multi_agent_v2.root_agent_usage_hint_text = None;
})
.build(&server)
.await?;
submit_turn(&test.codex, "hello", /*mode*/ None).await?;
submit_turn(&test.codex, "hello", Some(MultiAgentMode::Proactive)).await?;
let input = responses.single_request().input();
let texts = developer_texts(&input);
assert_eq!(
(
count_containing(&texts, MULTI_AGENT_MODE_OPEN_TAG),
count_containing(&texts, NO_SPAWN_TEXT),
count_containing(&texts, PROACTIVE_TEXT),
),
(1, 1, 0)
(1, 1)
);
Ok(())
@@ -175,7 +274,7 @@ async fn resume_compares_against_previous_effective_multi_agent_mode() -> Result
let server = start_mock_server().await;
let responses = mount_sse_sequence(
&server,
(1..=4)
(1..=2)
.map(|index| {
sse(vec![
ev_response_created(&format!("resp-{index}")),
@@ -214,18 +313,14 @@ async fn resume_compares_against_previous_effective_multi_agent_mode() -> Result
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
config
.features
.enable(Feature::MultiAgentMode)
.expect("test config should allow feature update");
});
let resumed = resume_builder.resume(&server, home, rollout_path).await?;
submit_turn(
&resumed.codex,
"after resume",
Some(MultiAgentMode::Proactive),
)
.await?;
submit_turn(&resumed.codex, "after resume", /*mode*/ None).await?;
assert_eq!(
resumed.codex.config_snapshot().await.multi_agent_mode,
MultiAgentMode::Proactive
);
let requests = responses.requests();
let resumed_input = requests[1].input();
@@ -236,108 +331,14 @@ async fn resume_compares_against_previous_effective_multi_agent_mode() -> Result
count_containing(&texts, NO_SPAWN_TEXT),
count_containing(&texts, PROACTIVE_TEXT),
),
(2, 1, 1)
);
let resumed_rollout_path = resumed
.session_configured
.rollout_path
.clone()
.expect("resumed rollout path");
let resumed_home = resumed.home.clone();
drop(resumed);
let mut same_mode_resume_builder = test_codex().with_config(|config| {
config
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
config
.features
.enable(Feature::MultiAgentMode)
.expect("test config should allow feature update");
});
let resumed_same_mode = same_mode_resume_builder
.resume(&server, resumed_home, resumed_rollout_path)
.await?;
submit_turn(
&resumed_same_mode.codex,
"after same-mode resume",
/*mode*/ None,
)
.await?;
assert_eq!(
resumed_same_mode
.codex
.config_snapshot()
.await
.multi_agent_mode,
Some(MultiAgentMode::Proactive)
);
let requests = responses.requests();
let resumed_same_mode_input = requests[2].input();
let texts = developer_texts(&resumed_same_mode_input);
assert_eq!(
(
count_containing(&texts, MULTI_AGENT_MODE_OPEN_TAG),
count_containing(&texts, NO_SPAWN_TEXT),
count_containing(&texts, PROACTIVE_TEXT),
),
(2, 1, 1)
);
let resumed_same_mode_rollout_path = resumed_same_mode
.session_configured
.rollout_path
.clone()
.expect("same-mode resumed rollout path");
let resumed_same_mode_home = resumed_same_mode.home.clone();
drop(resumed_same_mode);
let mut disabled_mode_resume_builder = test_codex().with_config(|config| {
config
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow feature update");
});
let resumed_disabled_mode = disabled_mode_resume_builder
.resume(
&server,
resumed_same_mode_home,
resumed_same_mode_rollout_path,
)
.await?;
submit_turn(
&resumed_disabled_mode.codex,
"after disabled-mode resume",
/*mode*/ None,
)
.await?;
assert_eq!(
resumed_disabled_mode
.codex
.config_snapshot()
.await
.multi_agent_mode,
Some(MultiAgentMode::Proactive)
);
let requests = responses.requests();
let resumed_disabled_mode_input = requests[3].input();
let texts = developer_texts(&resumed_disabled_mode_input);
assert_eq!(
(
count_containing(&texts, MULTI_AGENT_MODE_OPEN_TAG),
count_containing(&texts, NO_SPAWN_TEXT),
count_containing(&texts, PROACTIVE_TEXT),
),
(3, 2, 1)
(1, 0, 1)
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn explicit_multi_agent_mode_is_retained_without_multi_agent_v2() -> Result<()> {
async fn multi_agent_mode_is_retained_without_multi_agent_v2() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -346,21 +347,13 @@ async fn explicit_multi_agent_mode_is_retained_without_multi_agent_v2() -> Resul
sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]),
)
.await;
let test = test_codex()
.with_config(|config| {
config
.features
.enable(Feature::MultiAgentMode)
.expect("test config should allow feature update");
})
.build(&server)
.await?;
let test = test_codex().build(&server).await?;
submit_turn(&test.codex, "hello", Some(MultiAgentMode::Proactive)).await?;
assert_eq!(
test.codex.config_snapshot().await.multi_agent_mode,
Some(MultiAgentMode::Proactive)
MultiAgentMode::Proactive
);
let input = responses.single_request().input();
let texts = developer_texts(&input);
@@ -74,7 +74,7 @@ async fn approved_network_host_for_one_environment_still_prompts_in_another() ->
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
let remote_cwd_uri = PathUri::from_path(&remote_cwd)?;
let remote_cwd_uri = PathUri::from_host_native_path(&remote_cwd)?;
test.fs()
.create_directory(
&remote_cwd_uri,
+24 -8
View File
@@ -22,7 +22,9 @@ 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_sequence;
use core_test_support::responses::namespace_child_tool;
use core_test_support::responses::sse;
use core_test_support::responses::start_mock_server;
use core_test_support::test_codex::TestCodex;
@@ -142,18 +144,29 @@ async fn run_extract_turn(test: &TestCodex, server: &MockServer) -> Result<Respo
vec![
sse(vec![
ev_response_created("resp-1"),
ev_tool_search_call(
"extract-search-1",
&json!({
"query": "extract text from uploaded document",
"limit": 1,
}),
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_function_call_with_namespace(
"extract-call-1",
DOCUMENT_EXTRACT_NAMESPACE,
DOCUMENT_EXTRACT_TOOL,
&json!({"file": "report.txt"}).to_string(),
),
ev_completed("resp-1"),
ev_completed("resp-2"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_response_created("resp-3"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
ev_completed("resp-3"),
]),
],
)
@@ -190,13 +203,16 @@ async fn codex_apps_file_params_upload_environment_files_before_mcp_tool_call()
let mock = run_extract_turn(&test, &server).await?;
let requests = mock.requests();
let body = requests[0].body_json();
let search_output = requests[1].tool_search_output("extract-search-1");
let missing_tool_message = format!(
"missing tool {DOCUMENT_EXTRACT_NAMESPACE}{DOCUMENT_EXTRACT_TOOL} in /v1/responses request: {body:?}"
"missing tool {DOCUMENT_EXTRACT_NAMESPACE}{DOCUMENT_EXTRACT_TOOL} in tool_search output: {search_output:?}"
);
let extract_tool = requests[0]
.tool_by_name(DOCUMENT_EXTRACT_NAMESPACE, DOCUMENT_EXTRACT_TOOL)
.expect(&missing_tool_message);
let extract_tool = namespace_child_tool(
&search_output,
DOCUMENT_EXTRACT_NAMESPACE,
DOCUMENT_EXTRACT_TOOL,
)
.expect(&missing_tool_message);
assert_eq!(
extract_tool.pointer("/parameters/properties/file"),
Some(&json!({
+30 -2
View File
@@ -3,6 +3,7 @@ use codex_features::Feature;
use codex_otel::SessionTelemetry;
use codex_otel::TelemetryAuthMode;
use codex_protocol::ThreadId;
use codex_protocol::config_types::ServiceTier;
use codex_protocol::models::PermissionProfile;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::AskForApproval;
@@ -114,9 +115,17 @@ fn extract_log_field_does_not_confuse_similar_keys() {
async fn responses_api_emits_api_request_event() {
let server = start_mock_server().await;
mount_sse_once(&server, sse(vec![ev_completed("done")])).await;
let response_mock = mount_sse_once(&server, sse(vec![ev_completed("done")])).await;
let TestCodex { codex, .. } = test_codex().build(&server).await.unwrap();
let TestCodex { codex, .. } = test_codex()
.with_model("gpt-5.4")
.with_config(|config| {
config.service_tier = Some(ServiceTier::Fast.request_value().to_string());
config.model_reasoning_effort = Some(ReasoningEffort::High);
})
.build(&server)
.await
.unwrap();
codex
.submit(Op::UserInput {
@@ -134,6 +143,10 @@ async fn responses_api_emits_api_request_event() {
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
let request_body = response_mock.single_request().body_json();
assert_eq!(request_body["service_tier"].as_str(), Some("priority"));
assert_eq!(request_body["reasoning"]["effort"].as_str(), Some("high"));
logs_assert(|lines: &[&str]| {
lines
.iter()
@@ -142,6 +155,21 @@ async fn responses_api_emits_api_request_event() {
.unwrap_or_else(|| Err("expected codex.api_request event".to_string()))
});
logs_assert(|lines: &[&str]| {
lines
.iter()
.find(|line| {
line.contains("codex.sse_event")
&& line.contains("event.kind=response.completed")
&& line.contains("service_tier=\"priority\"")
&& line.contains("model_reasoning_effort=\"high\"")
})
.map(|_| Ok(()))
.unwrap_or_else(|| {
Err("expected response.completed event with inference attributes".to_string())
})
});
logs_assert(|lines: &[&str]| {
lines
.iter()
+4 -1
View File
@@ -20,6 +20,7 @@ use core_test_support::responses;
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_function_call_with_namespace;
use core_test_support::responses::ev_message_item_added;
use core_test_support::responses::ev_output_text_delta;
use core_test_support::responses::ev_reasoning_item;
@@ -290,11 +291,13 @@ async fn steer_interrupts_wait_agent_and_is_sent_in_follow_up_request() {
const WAIT_CALL_ID: &str = "wait-call";
const INITIAL_PROMPT: &str = "wait for an agent";
const STEER_PROMPT: &str = "stop waiting and continue";
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
let first_chunks = vec![
chunk(ev_response_created("resp-1")),
chunk(ev_function_call(
chunk(ev_function_call_with_namespace(
WAIT_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"wait_agent",
r#"{"timeout_ms":10000}"#,
)),
@@ -59,6 +59,7 @@ async fn write_rollout_with_user_event(dir: &Path, thread_id: ThreadId) -> io::R
let session_meta = SessionMetaLine {
meta: SessionMeta {
session_id: thread_id.into(),
id: thread_id,
forked_from_id: None,
parent_thread_id: None,
@@ -109,6 +110,7 @@ async fn write_rollout_with_meta_only(dir: &Path, thread_id: ThreadId) -> io::Re
let session_meta = SessionMetaLine {
meta: SessionMeta {
session_id: thread_id.into(),
id: thread_id,
forked_from_id: None,
parent_thread_id: None,
+89 -84
View File
@@ -12,9 +12,15 @@ use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use core_test_support::apps_test_server::AppsTestServer;
use core_test_support::apps_test_server::SEARCH_CALENDAR_CREATE_TOOL;
use core_test_support::responses::ResponseMock;
use core_test_support::responses::ResponsesRequest;
use core_test_support::responses::ev_completed;
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;
use core_test_support::responses::mount_sse_sequence;
use core_test_support::responses::namespace_child_tool;
use core_test_support::responses::sse;
use core_test_support::responses::start_mock_server;
use core_test_support::skip_if_no_network;
@@ -29,6 +35,10 @@ use wiremock::MockServer;
const SAMPLE_PLUGIN_CONFIG_NAME: &str = "sample@test";
const SAMPLE_PLUGIN_DISPLAY_NAME: &str = "sample";
const SAMPLE_PLUGIN_DESCRIPTION: &str = "inspect sample data";
const SAMPLE_PLUGIN_APP_NAMESPACE: &str = "mcp__codex_apps__google_calendar";
const SAMPLE_PLUGIN_MCP_NAMESPACE: &str = "mcp__sample";
const PLUGIN_APP_SEARCH_CALL_ID: &str = "plugin-app-search";
const PLUGIN_MCP_SEARCH_CALL_ID: &str = "plugin-mcp-search";
fn sample_plugin_root(home: &TempDir) -> std::path::PathBuf {
home.path().join("plugins/cache/test/sample/local")
@@ -145,21 +155,53 @@ async fn build_apps_enabled_plugin_test_codex(
.expect("create new conversation"))
}
fn tool_names(body: &serde_json::Value) -> Vec<String> {
body.get("tools")
.and_then(serde_json::Value::as_array)
.map(|tools| {
tools
.iter()
.filter_map(|tool| {
tool.get("name")
.or_else(|| tool.get("type"))
.and_then(serde_json::Value::as_str)
.map(str::to_string)
})
.collect()
})
.unwrap_or_default()
async fn mount_plugin_tool_search_turn(server: &MockServer) -> ResponseMock {
mount_sse_sequence(
server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_tool_search_call(
PLUGIN_APP_SEARCH_CALL_ID,
&serde_json::json!({"query": "create calendar event"}),
),
ev_tool_search_call(
PLUGIN_MCP_SEARCH_CALL_ID,
&serde_json::json!({"query": "echo"}),
),
ev_completed("resp-1"),
]),
sse(vec![ev_response_created("resp-2"), ev_completed("resp-2")]),
],
)
.await
}
fn assert_plugin_provenance(tool: &serde_json::Value) {
let description = tool
.get("description")
.and_then(serde_json::Value::as_str)
.expect("plugin tool description should be present");
assert!(
description.contains("This tool is part of plugin `sample`."),
"expected plugin provenance in tool description: {description:?}"
);
}
fn searched_plugin_tools(
request: &ResponsesRequest,
) -> (Option<serde_json::Value>, Option<serde_json::Value>) {
let app_output = request.tool_search_output(PLUGIN_APP_SEARCH_CALL_ID);
let mcp_output = request.tool_search_output(PLUGIN_MCP_SEARCH_CALL_ID);
(
namespace_child_tool(
&app_output,
SAMPLE_PLUGIN_APP_NAMESPACE,
SEARCH_CALENDAR_CREATE_TOOL,
)
.cloned(),
namespace_child_tool(&mcp_output, SAMPLE_PLUGIN_MCP_NAMESPACE, "echo").cloned(),
)
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -237,11 +279,7 @@ async fn explicit_plugin_mentions_use_apps_for_chatgpt_dual_surface_plugins() ->
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let apps_server = AppsTestServer::mount_with_connector_name(&server, "Google Calendar").await?;
let mock = mount_sse_once(
&server,
sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]),
)
.await;
let mock = mount_plugin_tool_search_turn(&server).await;
let codex_home = Arc::new(TempDir::new()?);
let rmcp_test_server_bin = match stdio_server_bin() {
@@ -275,7 +313,8 @@ async fn explicit_plugin_mentions_use_apps_for_chatgpt_dual_surface_plugins() ->
.await?;
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
let request = mock.single_request();
let requests = mock.requests();
let request = &requests[0];
let developer_messages = request.message_input_texts("developer");
assert!(
developer_messages
@@ -295,28 +334,18 @@ async fn explicit_plugin_mentions_use_apps_for_chatgpt_dual_surface_plugins() ->
.any(|text| text.contains("Apps from this plugin")),
"expected visible plugin app guidance: {developer_messages:?}"
);
let request_body = request.body_json();
let request_tools = tool_names(&request_body);
assert!(
request_tools
.iter()
.any(|name| name == "mcp__codex_apps__google_calendar"),
"expected plugin app tools to become visible for this turn: {request_tools:?}"
request
.tool_by_name(SAMPLE_PLUGIN_MCP_NAMESPACE, "echo")
.is_none(),
"plugin MCP tool should not leak into the request for ChatGPT auth"
);
let (calendar_tool, echo_tool) = searched_plugin_tools(&requests[1]);
let calendar_tool = calendar_tool.expect("plugin app tool should be searchable");
assert_plugin_provenance(&calendar_tool);
assert!(
request.tool_by_name("mcp__sample", "echo").is_none(),
"expected plugin MCP tool to be suppressed for ChatGPT auth"
);
let calendar_tool = request
.tool_by_name("mcp__codex_apps__google_calendar", "_create_event")
.expect("plugin app tool should be present");
let calendar_description = calendar_tool
.get("description")
.and_then(serde_json::Value::as_str)
.expect("plugin app tool description should be present");
assert!(
calendar_description.contains("This tool is part of plugin `sample`."),
"expected plugin app provenance in tool description: {calendar_description:?}"
echo_tool.is_none(),
"plugin MCP tool should be suppressed for ChatGPT auth"
);
Ok(())
@@ -327,11 +356,7 @@ async fn explicit_plugin_mentions_keep_non_conflicting_mcp_for_chatgpt_auth() ->
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let apps_server = AppsTestServer::mount_with_connector_name(&server, "Google Calendar").await?;
let mock = mount_sse_once(
&server,
sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]),
)
.await;
let mock = mount_plugin_tool_search_turn(&server).await;
let codex_home = Arc::new(TempDir::new()?);
let rmcp_test_server_bin = match stdio_server_bin() {
@@ -365,7 +390,8 @@ async fn explicit_plugin_mentions_keep_non_conflicting_mcp_for_chatgpt_auth() ->
.await?;
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
let request = mock.single_request();
let requests = mock.requests();
let request = &requests[0];
let developer_messages = request.message_input_texts("developer");
assert!(
developer_messages
@@ -379,25 +405,13 @@ async fn explicit_plugin_mentions_keep_non_conflicting_mcp_for_chatgpt_auth() ->
.any(|text| text.contains("Apps from this plugin")),
"expected plugin app guidance: {developer_messages:?}"
);
let request_body = request.body_json();
let request_tools = tool_names(&request_body);
let (calendar_tool, echo_tool) = searched_plugin_tools(&requests[1]);
assert!(
request_tools
.iter()
.any(|name| name == "mcp__codex_apps__google_calendar"),
"expected plugin app tools to become visible for this turn: {request_tools:?}"
);
let echo_tool = request
.tool_by_name("mcp__sample", "echo")
.expect("plugin MCP tool should remain present");
let echo_description = echo_tool
.get("description")
.and_then(serde_json::Value::as_str)
.expect("plugin MCP tool description should be present");
assert!(
echo_description.contains("This tool is part of plugin `sample`."),
"expected plugin MCP provenance in tool description: {echo_description:?}"
calendar_tool.is_some(),
"plugin app tool should be searchable"
);
let echo_tool = echo_tool.expect("plugin MCP tool should remain searchable");
assert_plugin_provenance(&echo_tool);
Ok(())
}
@@ -406,11 +420,7 @@ async fn explicit_plugin_mentions_keep_non_conflicting_mcp_for_chatgpt_auth() ->
async fn explicit_plugin_mentions_use_mcp_for_api_key_dual_surface_plugins() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mock = mount_sse_once(
&server,
sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]),
)
.await;
let mock = mount_plugin_tool_search_turn(&server).await;
let codex_home = Arc::new(TempDir::new()?);
let rmcp_test_server_bin = match stdio_server_bin() {
@@ -454,7 +464,8 @@ async fn explicit_plugin_mentions_use_mcp_for_api_key_dual_surface_plugins() ->
.await?;
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
let request = mock.single_request();
let requests = mock.requests();
let request = &requests[0];
let developer_messages = request.message_input_texts("developer");
assert!(
developer_messages
@@ -474,25 +485,19 @@ async fn explicit_plugin_mentions_use_mcp_for_api_key_dual_surface_plugins() ->
.any(|text| text.contains("Apps from this plugin")),
"expected plugin app guidance to be suppressed for API-key auth: {developer_messages:?}"
);
let request_body = request.body_json();
let request_tools = tool_names(&request_body);
assert!(
!request_tools
.iter()
.any(|name| name == "mcp__codex_apps__google_calendar"),
"expected plugin app tools to be hidden for API-key auth: {request_tools:?}"
request
.tool_by_name(SAMPLE_PLUGIN_APP_NAMESPACE, SEARCH_CALENDAR_CREATE_TOOL)
.is_none(),
"plugin app tool should not leak into the request for API-key auth"
);
let echo_tool = request
.tool_by_name("mcp__sample", "echo")
.expect("plugin MCP tool should be present");
let echo_description = echo_tool
.get("description")
.and_then(serde_json::Value::as_str)
.expect("plugin MCP tool description should be present");
let (calendar_tool, echo_tool) = searched_plugin_tools(&requests[1]);
assert!(
echo_description.contains("This tool is part of plugin `sample`."),
"expected plugin MCP provenance in tool description: {echo_description:?}"
calendar_tool.is_none(),
"plugin app tool should be hidden for API-key auth"
);
let echo_tool = echo_tool.expect("plugin MCP tool should be searchable");
assert_plugin_provenance(&echo_tool);
Ok(())
}
+28 -13
View File
@@ -25,6 +25,7 @@ use core_test_support::responses::ev_response_created;
use core_test_support::responses::mount_sse_once;
use core_test_support::responses::sse;
use core_test_support::responses::start_mock_server;
use core_test_support::responses::strip_metadata_from_json;
use core_test_support::skip_if_no_network;
use core_test_support::test_codex::TestCodex;
use core_test_support::test_codex::local_selections;
@@ -54,6 +55,13 @@ fn text_user_input_parts(texts: Vec<String>) -> serde_json::Value {
})
}
fn assert_eq_without_metadata(left: serde_json::Value, right: serde_json::Value) {
assert_eq!(
strip_metadata_from_json(left),
strip_metadata_from_json(right)
);
}
fn assert_default_env_context(text: &str, cwd: &str) {
assert_env_context_fragment(text);
assert!(
@@ -384,16 +392,18 @@ async fn prefixes_context_and_instructions_once_and_consistently_across_requests
Some("input_text"),
"expected environment context bundled after UI message in cached contextual message"
);
assert_eq!(input1[2], text_user_input("hello 1".to_string()));
assert_eq_without_metadata(input1[2].clone(), text_user_input("hello 1".to_string()));
let body2 = req2.single_request().body_json();
let input2 = body2["input"].as_array().expect("input array");
assert_eq!(
&input2[..input1.len()],
input1.as_slice(),
"expected cached prefix to be reused"
assert_eq_without_metadata(
serde_json::Value::Array(input2[..input1.len()].to_vec()),
serde_json::Value::Array(input1.to_vec()),
);
assert_eq_without_metadata(
input2[input1.len()].clone(),
text_user_input("hello 2".to_string()),
);
assert_eq!(input2[input1.len()], text_user_input("hello 2".to_string()));
Ok(())
}
@@ -523,7 +533,10 @@ async fn overrides_turn_context_but_keeps_cached_prefix_and_key_constant() -> an
expected_body2.push(expected_permissions_msg_2);
expected_body2.push(expected_env_msg_2);
expected_body2.push(expected_user_message_2);
assert_eq!(body2["input"], serde_json::Value::Array(expected_body2));
assert_eq_without_metadata(
body2["input"].clone(),
serde_json::Value::Array(expected_body2),
);
Ok(())
}
@@ -810,7 +823,10 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() -> anyhow::Res
expected_body2.push(expected_settings_update_msg);
expected_body2.push(expected_env_msg_2);
expected_body2.push(expected_user_message_2);
assert_eq!(body2["input"], serde_json::Value::Array(expected_body2));
assert_eq_without_metadata(
body2["input"].clone(),
serde_json::Value::Array(expected_body2),
);
Ok(())
}
@@ -818,7 +834,6 @@ async fn per_turn_overrides_keep_cached_prefix_and_key_constant() -> anyhow::Res
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn send_user_turn_with_no_changes_does_not_send_environment_context() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
use pretty_assertions::assert_eq;
let server = start_mock_server().await;
let req1 = mount_sse_once(
@@ -940,7 +955,7 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() -> a
expected_contextual_user_msg_1.clone(),
expected_user_message_1.clone(),
]);
assert_eq!(body1["input"], expected_input_1);
assert_eq_without_metadata(body1["input"].clone(), expected_input_1);
let expected_user_message_2 = text_user_input("hello 2".to_string());
let expected_input_2 = serde_json::Value::Array(vec![
@@ -949,7 +964,7 @@ async fn send_user_turn_with_no_changes_does_not_send_environment_context() -> a
expected_user_message_1,
expected_user_message_2,
]);
assert_eq!(body2["input"], expected_input_2);
assert_eq_without_metadata(body2["input"].clone(), expected_input_2);
Ok(())
}
@@ -1079,7 +1094,7 @@ async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Resu
expected_contextual_user_msg_1.clone(),
expected_user_message_1.clone(),
]);
assert_eq!(body1["input"], expected_input_1);
assert_eq_without_metadata(body1["input"].clone(), expected_input_1);
let body1_input = body1["input"].as_array().expect("input array");
let expected_settings_update_msg = body2["input"][body1_input.len()].clone();
@@ -1118,7 +1133,7 @@ async fn send_user_turn_with_changes_sends_environment_context() -> anyhow::Resu
expected_env_update_msg,
expected_user_message_2,
]);
assert_eq!(body2["input"], expected_input_2);
assert_eq_without_metadata(body2["input"].clone(), expected_input_2);
Ok(())
}
@@ -8,6 +8,7 @@ use codex_home::CodexHomeUserInstructionsProvider;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::user_input::UserInput;
use core_test_support::responses::strip_metadata;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
@@ -49,9 +50,12 @@ async fn build_prompt_input_includes_context_and_user_message() -> Result<()> {
text: "hello from debug prompt".to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
};
assert_eq!(input.last(), Some(&expected_user_message));
assert_eq!(
input.last().cloned().map(strip_metadata),
Some(expected_user_message)
);
assert!(input.iter().any(|item| {
let ResponseItem::Message { content, .. } = item else {
return false;
@@ -2350,7 +2350,7 @@ async fn conversation_startup_context_current_thread_selects_many_turns_by_budge
role: "user".to_string(),
content: vec![ContentItem::InputText { text: user_turn }],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
}),
RolloutItem::ResponseItem(ResponseItem::Message {
id: None,
@@ -2359,7 +2359,7 @@ async fn conversation_startup_context_current_thread_selects_many_turns_by_budge
text: assistant_turn,
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
}),
]
})
+389 -32
View File
@@ -26,6 +26,8 @@ use codex_protocol::protocol::TurnEnvironmentSelection;
use codex_protocol::request_permissions::PermissionGrantScope;
use codex_protocol::request_permissions::RequestPermissionProfile;
use codex_protocol::request_permissions::RequestPermissionsResponse;
use codex_protocol::request_user_input::RequestUserInputAnswer;
use codex_protocol::request_user_input::RequestUserInputResponse;
use codex_protocol::user_input::UserInput;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
@@ -49,9 +51,13 @@ use core_test_support::test_codex::local;
use core_test_support::test_codex::test_codex;
use core_test_support::test_codex::test_env;
use core_test_support::wait_for_event;
use core_test_support::wait_for_event_match;
use futures::SinkExt;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
@@ -59,6 +65,12 @@ use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use tempfile::TempDir;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::time::timeout;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::accept_async;
use tokio_tungstenite::tungstenite::Message;
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;
@@ -75,6 +87,7 @@ async fn submit_turn_with_approval_and_environments(
test: &TestCodex,
prompt: &str,
environments: Vec<TurnEnvironmentSelection>,
approval_policy: AskForApproval,
) -> Result<()> {
let turn_environment_selections = codex_protocol::protocol::TurnEnvironmentSelections::new(
test.config.cwd.clone(),
@@ -91,7 +104,7 @@ async fn submit_turn_with_approval_and_environments(
additional_context: Default::default(),
thread_settings: codex_protocol::protocol::ThreadSettingsOverrides {
environments: Some(turn_environment_selections),
approval_policy: Some(AskForApproval::OnRequest),
approval_policy: Some(approval_policy),
approvals_reviewer: Some(ApprovalsReviewer::User),
sandbox_policy: Some(SandboxPolicy::new_read_only_policy()),
collaboration_mode: Some(codex_protocol::config_types::CollaborationMode {
@@ -160,7 +173,7 @@ async fn remote_test_env_can_connect_and_use_filesystem() -> Result<()> {
let file_system = test_env.environment().get_filesystem();
let file_path_abs = test_env.cwd().join("remote-test-env-ok");
let file_path_uri = PathUri::from_path(&file_path_abs)?;
let file_path_uri = PathUri::from_host_native_path(&file_path_abs)?;
let payload = b"remote-test-env-ok".to_vec();
file_system
@@ -301,8 +314,152 @@ async fn explicit_remote_shell_runs_in_remote_cwd() -> Result<()> {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deferred_executor_reaches_model_before_remote_environment_is_ready() -> Result<()> {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
async fn remote_sandbox_denial_requests_approval_and_retries() -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_wine_exec!(Ok(()), "requires the Docker-backed POSIX executor");
let Some(_remote_env) = get_remote_test_env() else {
return Ok(());
};
const CALL_ID: &str = "remote-sandbox-denial";
const CONTENTS: &str = "remote sandbox retry succeeded";
let server = start_mock_server().await;
let test = unified_exec_test(&server).await?;
let nonce = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
let remote_cwd = PathBuf::from(format!("/tmp/codex-remote-denial-cwd-{nonce}")).abs();
let target_path = PathBuf::from(format!("/tmp/codex-remote-denial-target-{nonce}")).abs();
let remote_cwd_uri = PathUri::from_host_native_path(&remote_cwd)?;
let target_uri = PathUri::from_host_native_path(&target_path)?;
test.fs()
.create_directory(
&remote_cwd_uri,
CreateDirectoryOptions { recursive: true },
/*sandbox*/ None,
)
.await?;
test.fs()
.remove(
&target_uri,
RemoveOptions {
recursive: false,
force: true,
},
/*sandbox*/ None,
)
.await?;
let command = format!("printf {CONTENTS:?} > {target_path:?} && cat {target_path:?}");
let response_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-remote-denial-1"),
ev_function_call(
CALL_ID,
"exec_command",
&json!({
"shell": "/bin/sh",
"cmd": command,
"login": false,
"yield_time_ms": 5_000,
"environment_id": REMOTE_ENVIRONMENT_ID,
})
.to_string(),
),
ev_completed("resp-remote-denial-1"),
]),
sse(vec![
ev_response_created("resp-remote-denial-2"),
ev_assistant_message("msg-remote-denial", "done"),
ev_completed("resp-remote-denial-2"),
]),
],
)
.await;
submit_turn_with_approval_and_environments(
&test,
"retry a sandbox-denied command in the remote environment",
vec![TurnEnvironmentSelection {
environment_id: REMOTE_ENVIRONMENT_ID.to_string(),
cwd: PathUri::from_abs_path(&remote_cwd),
}],
AskForApproval::OnFailure,
)
.await?;
let event = wait_for_event(&test.codex, |event| {
matches!(
event,
EventMsg::ExecApprovalRequest(_) | EventMsg::TurnComplete(_)
)
})
.await;
let EventMsg::ExecApprovalRequest(approval) = event else {
panic!("expected remote sandbox approval before completion: {event:?}");
};
assert_eq!(approval.call_id, CALL_ID);
assert_eq!(
approval.environment_id.as_deref(),
Some(REMOTE_ENVIRONMENT_ID)
);
assert_eq!(
approval.reason.as_deref(),
Some("command failed; retry without sandbox?")
);
test.codex
.submit(Op::ExecApproval {
id: approval.effective_approval_id(),
turn_id: None,
decision: ReviewDecision::Approved,
})
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
assert!(
response_mock
.function_call_output_text(CALL_ID)
.is_some_and(|output| output.contains(CONTENTS)),
"approved retry should return the remote command output"
);
assert_eq!(
test.fs()
.read_file_text(&target_uri, /*sandbox*/ None)
.await?,
CONTENTS
);
test.fs()
.remove(
&target_uri,
RemoveOptions {
recursive: false,
force: true,
},
/*sandbox*/ None,
)
.await?;
test.fs()
.remove(
&remote_cwd_uri,
RemoveOptions {
recursive: true,
force: true,
},
/*sandbox*/ None,
)
.await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deferred_executor_does_not_duplicate_initial_environment_context() -> Result<()> {
let server = start_mock_server().await;
let response_mock = mount_sse_once(
&server,
@@ -313,23 +470,216 @@ async fn deferred_executor_reaches_model_before_remote_environment_is_ready() ->
]),
)
.await;
let mut builder = test_codex().with_config(|config| {
assert!(config.features.enable(Feature::DeferredExecutor).is_ok());
});
let test = builder.build(&server).await?;
test.submit_turn("report the environment").await?;
let user_context = response_mock.single_request().message_input_texts("user");
assert_eq!(
user_context
.iter()
.filter(|text| text.contains("<environment_context>"))
.count(),
1
);
Ok(())
}
async fn read_exec_server_json(websocket: &mut WebSocketStream<TcpStream>) -> Value {
loop {
match timeout(Duration::from_secs(5), websocket.next())
.await
.expect("websocket read should not time out")
.expect("websocket should stay open")
.expect("websocket frame should read")
{
Message::Text(text) => {
return serde_json::from_str(text.as_ref()).expect("valid JSON-RPC message");
}
Message::Binary(bytes) => {
return serde_json::from_slice(bytes.as_ref()).expect("valid JSON-RPC message");
}
Message::Ping(_) | Message::Pong(_) => {}
other => panic!("expected JSON-RPC message, got {other:?}"),
}
}
}
async fn serve_environment_info(listener: TcpListener) {
let (stream, _) = listener.accept().await.expect("connection");
let mut websocket = accept_async(stream).await.expect("websocket handshake");
let initialize = read_exec_server_json(&mut websocket).await;
assert_eq!(initialize["method"], "initialize");
websocket
.send(Message::Text(
json!({
"id": initialize["id"],
"result": { "sessionId": "test-session" }
})
.to_string()
.into(),
))
.await
.expect("initialize response");
let initialized = read_exec_server_json(&mut websocket).await;
assert_eq!(initialized["method"], "initialized");
let info = read_exec_server_json(&mut websocket).await;
assert_eq!(info["method"], "environment/info");
websocket
.send(Message::Text(
json!({
"id": info["id"],
"result": { "shell": { "name": "zsh", "path": "/bin/zsh" } }
})
.to_string()
.into(),
))
.await
.expect("environment info response");
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn deferred_executor_updates_model_context_after_startup() -> Result<()> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let server = start_mock_server().await;
let user_input_call_id = "wait-for-startup";
let response_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call(
user_input_call_id,
"request_user_input",
&json!({
"questions": [{
"id": "continue",
"header": "Continue",
"question": "Continue after startup?",
"options": [{
"label": "Yes (Recommended)",
"description": "Continue the test."
}, {
"label": "No",
"description": "Stop the test."
}]
}]
})
.to_string(),
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_function_call(
"update-plan",
"update_plan",
&json!({
"explanation": "Continue after startup.",
"plan": [{"step": "Finish", "status": "completed"}]
})
.to_string(),
),
ev_completed("resp-2"),
]),
sse(vec![
ev_response_created("resp-3"),
ev_assistant_message("msg-3", "done"),
ev_completed("resp-3"),
]),
],
)
.await;
let mut builder = test_codex()
.with_exec_server_url(format!("ws://{}", listener.local_addr()?))
.with_config(|config| {
assert!(config.features.enable(Feature::DeferredExecutor).is_ok());
assert!(
config
.features
.enable(Feature::DefaultModeRequestUserInput)
.is_ok()
);
});
let test = tokio::time::timeout(Duration::from_secs(5), builder.build(&server))
let test = timeout(Duration::from_secs(5), builder.build(&server))
.await
.context("thread startup should not wait for the remote environment")??;
tokio::time::timeout(
Duration::from_secs(5),
test.submit_turn("respond before the environment is ready"),
)
.await
.context("turn should reach the model before the remote environment is ready")??;
response_mock.single_request();
test.codex
.submit(Op::UserInput {
items: vec![UserInput::Text {
text: "wait for the environment".into(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
additional_context: Default::default(),
thread_settings: Default::default(),
})
.await?;
let request = wait_for_event_match(&test.codex, |event| match event {
EventMsg::RequestUserInput(request) => Some(request.clone()),
_ => None,
})
.await;
serve_environment_info(listener).await;
test.codex
.submit(Op::UserInputAnswer {
id: request.turn_id,
response: RequestUserInputResponse {
answers: HashMap::from([(
"continue".to_string(),
RequestUserInputAnswer {
answers: vec!["Yes (Recommended)".to_string()],
},
)]),
},
})
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
let requests = response_mock.requests();
assert_eq!(requests.len(), 3);
assert!(
requests[0]
.message_input_texts("user")
.iter()
.any(|text| text.contains("<status>starting</status>"))
);
let ready_user_context = requests[1].message_input_texts("user");
assert_eq!(
ready_user_context
.iter()
.filter(|text| text.contains("<shell>zsh</shell>"))
.count(),
1
);
let final_user_context = requests[2].message_input_texts("user");
assert_eq!(
final_user_context
.iter()
.filter(|text| text.contains("<status>starting</status>"))
.count(),
1
);
assert_eq!(
final_user_context
.iter()
.filter(|text| text.contains("<shell>zsh</shell>"))
.count(),
1
);
Ok(())
}
@@ -451,8 +801,8 @@ async fn exec_command_routes_to_selected_remote_environment() -> Result<()> {
))
.abs();
let remote_marker_name = "marker.txt";
let remote_cwd_uri = PathUri::from_path(&remote_cwd)?;
let remote_marker_uri = PathUri::from_path(remote_cwd.join(remote_marker_name))?;
let remote_cwd_uri = PathUri::from_host_native_path(&remote_cwd)?;
let remote_marker_uri = PathUri::from_host_native_path(remote_cwd.join(remote_marker_name))?;
test.fs()
.create_directory(
&remote_cwd_uri,
@@ -550,7 +900,7 @@ async fn remote_request_permissions_grant_unblocks_later_remote_exec() -> Result
let local_write_root = local_cwd.path().join(relative_write_root);
let local_target_path = local_cwd.path().join(relative_target_path);
fs::create_dir(&local_write_root)?;
let remote_write_root_uri = PathUri::from_path(&remote_write_root)?;
let remote_write_root_uri = PathUri::from_host_native_path(&remote_write_root)?;
test.fs()
.create_directory(
&remote_write_root_uri,
@@ -630,6 +980,7 @@ async fn remote_request_permissions_grant_unblocks_later_remote_exec() -> Result
cwd: PathUri::from_abs_path(&remote_cwd),
},
],
AskForApproval::OnRequest,
)
.await?;
@@ -689,7 +1040,7 @@ async fn remote_request_permissions_grant_unblocks_later_remote_exec() -> Result
assert_eq!(
test.fs()
.read_file_text(
&PathUri::from_path(&remote_target_path)?,
&PathUri::from_host_native_path(&remote_target_path)?,
/*sandbox*/ None,
)
.await?,
@@ -733,7 +1084,7 @@ async fn apply_patch_freeform_routes_to_selected_remote_environment() -> Result<
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
let remote_cwd_uri = PathUri::from_path(&remote_cwd)?;
let remote_cwd_uri = PathUri::from_host_native_path(&remote_cwd)?;
test.fs()
.create_directory(
&remote_cwd_uri,
@@ -778,7 +1129,7 @@ async fn apply_patch_freeform_routes_to_selected_remote_environment() -> Result<
let remote_contents = test
.fs()
.read_file_text(
&PathUri::from_path(remote_cwd.join(file_name))?,
&PathUri::from_host_native_path(remote_cwd.join(file_name))?,
/*sandbox*/ None,
)
.await?;
@@ -823,7 +1174,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
let remote_cwd_uri = PathUri::from_path(&remote_cwd)?;
let remote_cwd_uri = PathUri::from_host_native_path(&remote_cwd)?;
test.fs()
.create_directory(
&remote_cwd_uri,
@@ -837,7 +1188,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
let target_path_uri = PathUri::from_path(&target_path)?;
let target_path_uri = PathUri::from_host_native_path(&target_path)?;
let _ = fs::remove_file(&target_path);
test.fs()
.remove(
@@ -911,6 +1262,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
&test,
"apply patch in local environment",
environments.clone(),
AskForApproval::OnRequest,
)
.await?;
let approval = expect_patch_approval(&test, "call-local").await;
@@ -930,6 +1282,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
&test,
"apply patch in remote environment",
environments.clone(),
AskForApproval::OnRequest,
)
.await?;
let approval = expect_patch_approval(&test, "call-remote").await;
@@ -954,6 +1307,7 @@ async fn apply_patch_approvals_are_remembered_per_environment() -> Result<()> {
&test,
"apply patch again in remote environment",
environments,
AskForApproval::OnRequest,
)
.await?;
wait_for_completion_without_patch_approval(&test).await;
@@ -1008,7 +1362,7 @@ async fn apply_patch_intercepted_exec_command_routes_to_selected_remote_environm
SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis()
))
.abs();
let remote_cwd_uri = PathUri::from_path(&remote_cwd)?;
let remote_cwd_uri = PathUri::from_host_native_path(&remote_cwd)?;
test.fs()
.create_directory(
&remote_cwd_uri,
@@ -1063,7 +1417,7 @@ async fn apply_patch_intercepted_exec_command_routes_to_selected_remote_environm
let remote_contents = test
.fs()
.read_file_text(
&PathUri::from_path(remote_cwd.join(file_name))?,
&PathUri::from_host_native_path(remote_cwd.join(file_name))?,
/*sandbox*/ None,
)
.await?;
@@ -1101,8 +1455,8 @@ async fn remote_test_env_sandboxed_read_allows_readable_root() -> Result<()> {
let allowed_dir = PathBuf::from(format!("/tmp/codex-remote-readable-{}", std::process::id()));
let file_path = allowed_dir.join("note.txt");
let allowed_dir_uri = PathUri::from_path(&allowed_dir)?;
let file_path_uri = PathUri::from_path(&file_path)?;
let allowed_dir_uri = PathUri::from_host_native_path(&allowed_dir)?;
let file_path_uri = PathUri::from_host_native_path(&file_path)?;
file_system
.create_directory(
&allowed_dir_uri,
@@ -1162,7 +1516,7 @@ async fn remote_test_env_sandboxed_read_rejects_symlink_parent_dotdot_escape() -
))?;
let requested_path =
PathUri::from_path(allowed_dir.join("link").join("..").join("secret.txt"))?;
PathUri::from_host_native_path(allowed_dir.join("link").join("..").join("secret.txt"))?;
let sandbox = read_only_sandbox(allowed_dir.clone());
let error = match file_system.read_file(&requested_path, Some(&sandbox)).await {
Ok(_) => anyhow::bail!("read should fail after path normalization"),
@@ -1210,7 +1564,7 @@ async fn remote_test_env_remove_removes_symlink_not_target() -> Result<()> {
let sandbox = workspace_write_sandbox(allowed_dir.clone());
file_system
.remove(
&PathUri::from_path(&symlink_path)?,
&PathUri::from_host_native_path(&symlink_path)?,
RemoveOptions {
recursive: false,
force: false,
@@ -1228,13 +1582,16 @@ async fn remote_test_env_remove_removes_symlink_not_target() -> Result<()> {
.is_ok();
assert!(!symlink_exists);
let outside = file_system
.read_file_text(&PathUri::from_path(&outside_file)?, /*sandbox*/ None)
.read_file_text(
&PathUri::from_host_native_path(&outside_file)?,
/*sandbox*/ None,
)
.await?;
assert_eq!(outside, "outside");
file_system
.remove(
&PathUri::from_path(&root)?,
&PathUri::from_host_native_path(&root)?,
RemoveOptions {
recursive: true,
force: true,
@@ -1276,8 +1633,8 @@ async fn remote_test_env_copy_preserves_symlink_source() -> Result<()> {
let sandbox = workspace_write_sandbox(allowed_dir.clone());
file_system
.copy(
&PathUri::from_path(&source_symlink)?,
&PathUri::from_path(&copied_symlink)?,
&PathUri::from_host_native_path(&source_symlink)?,
&PathUri::from_host_native_path(&copied_symlink)?,
CopyOptions { recursive: false },
Some(&sandbox),
)
@@ -1310,7 +1667,7 @@ async fn remote_test_env_copy_preserves_symlink_source() -> Result<()> {
file_system
.remove(
&PathUri::from_path(&root)?,
&PathUri::from_host_native_path(&root)?,
RemoveOptions {
recursive: true,
force: true,
+100 -30
View File
@@ -54,8 +54,72 @@ fn has_hosted_tool(tools: &[Value], tool_type: &str) -> bool {
.any(|tool| tool.get("type").and_then(Value::as_str) == Some(tool_type))
}
fn additional_tools(body: &Value) -> Result<&[Value]> {
body["input"]
.as_array()
.context("Responses request input should be an array")?
.first()
.filter(|item| item.get("type").and_then(Value::as_str) == Some("additional_tools"))
.context("Responses request should start with additional_tools")?["tools"]
.as_array()
.map(Vec::as_slice)
.context("additional_tools tools should be an array")
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responses_lite_strips_data_image_detail_without_resize_all_images() -> Result<()> {
async fn responses_lite_uses_input_items_for_instructions_and_tools() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_once(
&server,
responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_completed("resp-1"),
]),
)
.await;
let mut builder = test_codex()
.with_model_info_override("gpt-5.4", |model_info| {
model_info.use_responses_lite = true;
})
.with_config(|config| {
config.base_instructions = Some("test instructions".to_string());
});
let test = builder.build(&server).await?;
test.submit_turn("hello").await?;
let body = response_mock.single_request().body_json();
assert!(body.get("instructions").is_none());
assert!(body.get("tools").is_none());
let input = body["input"]
.as_array()
.context("Responses request input should be an array")?;
assert_eq!(input[0]["type"], "additional_tools");
assert_eq!(input[0]["role"], "developer");
assert_eq!(
input[1],
serde_json::json!({
"type": "message",
"role": "developer",
"content": [{
"type": "input_text",
"text": "test instructions",
}],
})
);
let tools = additional_tools(&body)?;
assert!(!tools.is_empty());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn responses_lite_prepares_images() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
@@ -68,6 +132,7 @@ async fn responses_lite_strips_data_image_detail_without_resize_all_images() ->
)
.await;
let image_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
let remote_image_url = "https://example.com/image.png";
let mut builder = test_codex().with_model_info_override("gpt-5.4", |model_info| {
model_info.use_responses_lite = true;
configure_image_capable_model(model_info);
@@ -76,10 +141,16 @@ async fn responses_lite_strips_data_image_detail_without_resize_all_images() ->
test.codex
.submit(Op::UserInput {
items: vec![UserInput::Image {
image_url: image_url.to_string(),
detail: Some(ImageDetail::Original),
}],
items: vec![
UserInput::Image {
image_url: image_url.to_string(),
detail: Some(ImageDetail::Original),
},
UserInput::Image {
image_url: remote_image_url.to_string(),
detail: Some(ImageDetail::High),
},
],
final_output_json_schema: None,
responsesapi_client_metadata: None,
additional_context: Default::default(),
@@ -92,20 +163,27 @@ async fn responses_lite_strips_data_image_detail_without_resize_all_images() ->
.await;
let request = response_mock.single_request();
let input = request.input();
let image = input
.iter()
.filter_map(|item| item.get("content").and_then(Value::as_array))
.flatten()
.find(|item| item.get("type").and_then(Value::as_str) == Some("input_image"))
.context("request should contain an image")?;
let user_content = request
.input()
.into_iter()
.rev()
.find(|item| item.get("role").and_then(Value::as_str) == Some("user"))
.and_then(|item| item.get("content").and_then(Value::as_array).cloned())
.context("request should contain user content")?;
assert_eq!(
image,
&serde_json::json!({
"type": "input_image",
"image_url": image_url
})
user_content,
vec![
serde_json::json!({
"type": "input_image",
"image_url": image_url
}),
serde_json::json!({
"type": "input_text",
"text": "image content omitted because remote image URLs are not supported"
}),
]
);
assert!(!request.body_json().to_string().contains(remote_image_url));
Ok(())
}
@@ -144,17 +222,10 @@ async fn responses_lite_uses_standalone_web_search_and_image_generation() -> Res
request.header(RESPONSES_LITE_HEADER).as_deref(),
Some("true")
);
request
.tool_by_name("web", "run")
.context("Responses Lite should expose standalone web search")?;
request
.tool_by_name("image_gen", "imagegen")
.context("Responses Lite should expose standalone image generation")?;
let body = request.body_json();
let tools = body["tools"]
.as_array()
.context("Responses request tools should be an array")?;
assert!(body.get("tools").is_none());
let tools = additional_tools(&body)?;
assert!(!tools.is_empty());
assert!(!has_hosted_tool(tools, "web_search"));
assert!(!has_hosted_tool(tools, "image_generation"));
@@ -242,9 +313,8 @@ async fn responses_lite_omits_hosted_tools_without_standalone_extensions() -> Re
test.submit_turn("Do not use hosted tools").await?;
let body = response_mock.single_request().body_json();
let tools = body["tools"]
.as_array()
.context("Responses request tools should be an array")?;
assert!(body.get("tools").is_none());
let tools = additional_tools(&body)?;
assert!(!has_hosted_tool(tools, "web_search"));
assert!(!has_hosted_tool(tools, "image_generation"));
+4 -2
View File
@@ -1,5 +1,7 @@
#![allow(clippy::unwrap_used)]
use std::sync::Arc;
use codex_core::NewThread;
use codex_login::CodexAuth;
use codex_protocol::ThreadId;
@@ -51,7 +53,7 @@ fn resume_history(
InitialHistory::Resumed(ResumedHistory {
conversation_id: ThreadId::default(),
history: vec![
history: Arc::new(vec![
RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent {
turn_id: turn_id.clone(),
trace_id: None,
@@ -75,7 +77,7 @@ fn resume_history(
duration_ms: None,
time_to_first_token_ms: None,
})),
],
]),
rollout_path: Some(rollout_path.to_path_buf()),
})
}
+3 -2
View File
@@ -511,6 +511,7 @@ async fn review_input_isolated_from_parent_history() {
"timestamp": "2024-01-01T00:00:00.000Z",
"type": "session_meta",
"payload": {
"session_id": convo_id,
"id": convo_id,
"timestamp": "2024-01-01T00:00:00Z",
"cwd": ".",
@@ -531,7 +532,7 @@ async fn review_input_isolated_from_parent_history() {
text: "parent: earlier user message".to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
};
let user_json = serde_json::to_value(&user).unwrap();
let user_line = serde_json::json!({
@@ -551,7 +552,7 @@ async fn review_input_isolated_from_parent_history() {
text: "parent: assistant reply".to_string(),
}],
phase: None,
metadata: None,
internal_chat_message_metadata_passthrough: None,
};
let assistant_json = serde_json::to_value(&assistant).unwrap();
let assistant_line = serde_json::json!({
+35 -28
View File
@@ -24,10 +24,11 @@ use codex_core::config::Config;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::Environment;
use codex_exec_server::HttpRequestParams;
use codex_features::Feature;
use codex_login::CodexAuth;
use codex_mcp::MCP_SANDBOX_STATE_META_CAPABILITY;
use codex_mcp::SandboxState;
use codex_models_manager::manager::RefreshStrategy;
use codex_utils_path_uri::LegacyAppPathString;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::models::PermissionProfile;
@@ -298,7 +299,7 @@ fn stdio_transport_with_cwd(
args: Vec::new(),
env,
env_vars,
cwd,
cwd: cwd.map(|cwd| LegacyAppPathString::from_path(&cwd)),
}
}
@@ -540,20 +541,33 @@ async fn stdio_server_round_trip() -> anyhow::Result<()> {
let server = responses::start_mock_server().await;
let call_id = "call-123";
let search_call_id = "search-rmcp-echo";
let server_name = "rmcp";
let namespace = format!("mcp__{server_name}");
let call_mock = mount_sse_once(
mount_sse_once(
&server,
responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_tool_search_call(
search_call_id,
&json!({"query": "echo message and environment data"}),
),
responses::ev_completed("resp-1"),
]),
)
.await;
let call_mock = mount_sse_once(
&server,
responses::sse(vec![
responses::ev_response_created("resp-2"),
responses::ev_function_call_with_namespace(
call_id,
&namespace,
"echo",
"{\"message\":\"ping\"}",
),
responses::ev_completed("resp-1"),
responses::ev_completed("resp-2"),
]),
)
.await;
@@ -561,7 +575,7 @@ async fn stdio_server_round_trip() -> anyhow::Result<()> {
&server,
responses::sse(vec![
responses::ev_assistant_message("msg-1", "rmcp echo tool completed successfully."),
responses::ev_completed("resp-2"),
responses::ev_completed("resp-3"),
]),
)
.await;
@@ -646,13 +660,14 @@ async fn stdio_server_round_trip() -> anyhow::Result<()> {
wait_for_event(&fixture.codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
let output_item = final_mock.single_request().function_call_output(call_id);
let request = call_mock.single_request();
let search_output = call_mock
.single_request()
.tool_search_output(search_call_id);
assert!(
request.tool_by_name(&namespace, "echo").is_some(),
"direct MCP tool should be sent as a namespace child tool: {:?}",
request.body_json()
responses::namespace_child_tool(&search_output, &namespace, "echo").is_some(),
"tool_search should surface the RMCP echo tool: {search_output:?}"
);
let output_item = final_mock.single_request().function_call_output(call_id);
let output_text = output_item
.get("output")
@@ -734,7 +749,7 @@ async fn stdio_server_uses_configured_cwd_before_runtime_fallback() -> anyhow::R
let fixture = test_codex()
.with_workspace_setup(|cwd, fs| async move {
let configured_cwd = cwd.join("mcp-configured-cwd");
let configured_cwd_uri = PathUri::from_path(&configured_cwd)?;
let configured_cwd_uri = PathUri::from_host_native_path(&configured_cwd)?;
fs.create_directory(
&configured_cwd_uri,
CreateDirectoryOptions { recursive: true },
@@ -861,7 +876,7 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta() -> anyhow::Result<()>
let server_name = "rmcp";
let namespace = format!("mcp__{server_name}");
let call_mock = mount_sse_once(
mount_sse_once(
&server,
responses::sse(vec![
responses::ev_response_created("resp-1"),
@@ -904,13 +919,6 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta() -> anyhow::Result<()>
)
.await?;
let request = call_mock.single_request();
assert!(
request.tool_by_name(&namespace, "sandbox_meta").is_some(),
"direct MCP tool should be sent as a namespace child tool: {:?}",
request.body_json()
);
let output_item = final_mock.single_request().function_call_output(call_id);
let output_text = output_item
.get("output")
@@ -926,13 +934,16 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta() -> anyhow::Result<()>
let sandbox_meta = meta
.get(MCP_SANDBOX_STATE_META_CAPABILITY)
.expect("sandbox state metadata should be present");
assert_eq!(sandbox_meta.get("sandboxPolicy"), None);
let expected_sandbox_cwd = PathUri::from_abs_path(&fixture.config.cwd).to_string();
let sandbox_state: SandboxState = serde_json::from_value(sandbox_meta.clone())?;
assert_eq!(
sandbox_meta.get("sandboxCwd").and_then(Value::as_str),
Some(expected_sandbox_cwd.as_str())
sandbox_state,
SandboxState {
permission_profile: PermissionProfile::read_only(),
codex_linux_sandbox_exe: fixture.config.codex_linux_sandbox_exe.clone(),
sandbox_cwd: PathUri::from_abs_path(&fixture.config.cwd),
use_legacy_landlock: false,
}
);
assert_eq!(sandbox_meta.get("useLegacyLandlock"), Some(&json!(false)));
server.verify().await;
@@ -1455,10 +1466,6 @@ async fn stdio_image_responses_resize_large_image() -> anyhow::Result<()> {
let rmcp_test_server_bin = remote_aware_stdio_server_bin()?;
let fixture = test_codex()
.with_config(move |config| {
config
.features
.enable(Feature::ResizeAllImages)
.expect("resize_all_images should be enabled");
insert_mcp_server(
config,
server_name,
+30 -26
View File
@@ -10,7 +10,7 @@ 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_function_call_with_namespace;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::mount_sse_once_match;
use core_test_support::responses::mount_sse_sequence;
@@ -25,12 +25,16 @@ use std::time::Duration;
use test_case::test_case;
use tokio::time::timeout;
const ROLLOUT_BUDGET: RolloutBudgetConfig = RolloutBudgetConfig {
limit_tokens: 100,
reminder_interval_tokens: 25,
sampling_token_weight: 1.0,
prefill_token_weight: 1.0,
};
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
fn rollout_budget() -> RolloutBudgetConfig {
RolloutBudgetConfig {
limit_tokens: 100,
reminder_at_remaining_tokens: vec![75, 50, 25],
sampling_token_weight: 1.0,
prefill_token_weight: 1.0,
}
}
fn rollout_budget_texts(request: &ResponsesRequest) -> Vec<String> {
request
@@ -51,7 +55,7 @@ fn wire_request_contains(request: &wiremock::Request, text: &str) -> bool {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn adds_weighted_initial_and_periodic_reminders() -> Result<()> {
async fn adds_weighted_initial_and_threshold_reminders() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -83,7 +87,7 @@ async fn adds_weighted_initial_and_periodic_reminders() -> Result<()> {
config.rollout_budget = Some(RolloutBudgetConfig {
sampling_token_weight: 2.0,
prefill_token_weight: 0.5,
..ROLLOUT_BUDGET
..rollout_budget()
});
})
.build(&server)
@@ -128,7 +132,12 @@ async fn subagent_usage_draws_from_the_shared_budget() -> Result<()> {
|request: &wiremock::Request| wire_request_contains(request, ROOT_PROMPT),
sse(vec![
ev_response_created("root-1"),
ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args),
ev_function_call_with_namespace(
SPAWN_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&spawn_args,
),
ev_completed_with_tokens("root-1", /*total_tokens*/ 10),
]),
)
@@ -171,7 +180,7 @@ async fn subagent_usage_draws_from_the_shared_budget() -> Result<()> {
.features
.enable(Feature::MultiAgentV2)
.expect("test config should allow multi-agent v2");
config.rollout_budget = Some(ROLLOUT_BUDGET);
config.rollout_budget = Some(rollout_budget());
})
.build(&server)
.await?;
@@ -218,8 +227,8 @@ async fn exhausted_budget_aborts_current_and_later_turns() -> Result<()> {
.with_config(|config| {
config.rollout_budget = Some(RolloutBudgetConfig {
limit_tokens: 30,
reminder_interval_tokens: 10,
..ROLLOUT_BUDGET
reminder_at_remaining_tokens: vec![20, 10],
..rollout_budget()
});
})
.build(&server)
@@ -282,25 +291,20 @@ async fn compaction_budget_exhaustion_aborts_without_error_or_retry(remote_v2: b
])
};
let responses = mount_sse_sequence(&server, vec![compact_response]).await;
let mut model_provider = built_in_model_providers(/*openai_base_url*/ None)["openai"].clone();
model_provider.base_url = Some(format!("{}/v1", server.uri()));
model_provider.supports_websockets = false;
if !remote_v2 {
model_provider.name = "OpenAI-compatible test provider".to_string();
}
let test = test_codex()
.with_config(move |config| {
config.model_provider = model_provider;
config.rollout_budget = Some(RolloutBudgetConfig {
limit_tokens: 10,
reminder_interval_tokens: 5,
..ROLLOUT_BUDGET
reminder_at_remaining_tokens: vec![5],
..rollout_budget()
});
if remote_v2 {
config
.features
.enable(Feature::RemoteCompactionV2)
.expect("test config should allow remote compaction v2");
} else {
config.model_provider.name = "OpenAI-compatible test provider".to_string();
}
})
.build(&server)
@@ -354,8 +358,8 @@ async fn restates_the_current_remainder_after_compaction() -> Result<()> {
.with_config(move |config| {
config.model_provider = model_provider;
config.rollout_budget = Some(RolloutBudgetConfig {
reminder_interval_tokens: 50,
..ROLLOUT_BUDGET
reminder_at_remaining_tokens: vec![50],
..rollout_budget()
});
})
.build(&server)
@@ -409,8 +413,8 @@ async fn restates_the_current_remainder_after_rollback() -> Result<()> {
let test = test_codex()
.with_config(|config| {
config.rollout_budget = Some(RolloutBudgetConfig {
reminder_interval_tokens: 50,
..ROLLOUT_BUDGET
reminder_at_remaining_tokens: vec![50],
..rollout_budget()
});
})
.build(&server)
@@ -42,6 +42,7 @@ fn write_minimal_rollout_with_id_at_path(file: &Path, id: Uuid) {
"timestamp": "2024-01-01T00:00:00.000Z",
"type": "session_meta",
"payload": {
"session_id": id,
"id": id,
"timestamp": "2024-01-01T00:00:00Z",
"cwd": ".",
@@ -0,0 +1,74 @@
use anyhow::Ok;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::SafetyBufferingEvent;
use codex_protocol::user_input::UserInput;
use core_test_support::responses::ev_completed;
use core_test_support::responses::ev_response_created;
use core_test_support::responses::mount_response_once;
use core_test_support::responses::sse;
use core_test_support::responses::sse_response;
use core_test_support::responses::start_mock_server;
use core_test_support::skip_if_no_network;
use core_test_support::test_codex::test_codex;
use core_test_support::wait_for_event;
use core_test_support::wait_for_event_match;
use pretty_assertions::assert_eq;
use serde_json::json;
const FASTER_MODEL: &str = "faster-model";
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn emits_safety_buffering_with_the_requested_model() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mut created = ev_response_created("resp-1");
created["safety_buffering"] = json!({
"use_cases": ["cyber"],
"reasons": ["policy-check"],
});
mount_response_once(
&server,
sse_response(sse(vec![created, ev_completed("resp-1")]))
.insert_header("x-codex-safety-buffering-enabled", "true")
.insert_header("x-codex-safety-buffering-faster-model", FASTER_MODEL),
)
.await;
let test = test_codex().build(&server).await?;
test.codex
.submit(Op::UserInput {
items: vec![UserInput::Text {
text: "Check this request".into(),
text_elements: Vec::new(),
}],
final_output_json_schema: None,
responsesapi_client_metadata: None,
additional_context: Default::default(),
thread_settings: Default::default(),
})
.await?;
let event = wait_for_event_match(&test.codex, |event| match event {
EventMsg::SafetyBuffering(event) => Some(event.clone()),
_ => None,
})
.await;
assert_eq!(
event,
SafetyBufferingEvent {
model: test.session_configured.model.clone(),
use_cases: vec!["cyber".to_string()],
reasons: vec!["policy-check".to_string()],
show_buffering_ui: true,
faster_model: Some(FASTER_MODEL.to_string()),
}
);
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
Ok(())
}
+32 -38
View File
@@ -4,7 +4,6 @@
use anyhow::Result;
use codex_config::types::McpServerConfig;
use codex_config::types::McpServerTransportConfig;
use codex_features::Feature;
use codex_login::CodexAuth;
use codex_protocol::dynamic_tools::DynamicToolCallOutputContentItem;
use codex_protocol::dynamic_tools::DynamicToolFunctionSpec;
@@ -30,7 +29,6 @@ use core_test_support::apps_test_server::SEARCH_CALENDAR_APP_ONLY_TOOL;
use core_test_support::apps_test_server::SEARCH_CALENDAR_CREATE_TOOL;
use core_test_support::apps_test_server::SEARCH_CALENDAR_LIST_TOOL;
use core_test_support::apps_test_server::SEARCH_CALENDAR_NAMESPACE;
use core_test_support::apps_test_server::apps_enabled_builder;
use core_test_support::apps_test_server::configure_search_capable_apps;
use core_test_support::apps_test_server::configure_search_capable_model;
use core_test_support::apps_test_server::recorded_apps_tool_call_by_call_id;
@@ -180,7 +178,7 @@ async fn search_tool_enabled_by_default_adds_tool_search() -> Result<()> {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn always_defer_feature_hides_small_app_tool_sets() -> Result<()> {
async fn small_app_tool_sets_are_deferred_by_default() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -195,13 +193,7 @@ async fn always_defer_feature_hides_small_app_tool_sets() -> Result<()> {
)
.await;
let mut builder =
configured_builder(apps_server.chatgpt_base_url.clone()).with_config(|config| {
config
.features
.enable(Feature::ToolSearchAlwaysDeferMcpTools)
.expect("test config should allow feature update");
});
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(
@@ -232,30 +224,42 @@ async fn app_only_tools_are_not_visible_or_runnable_by_direct_model_calls() -> R
let server = start_mock_server().await;
let apps_server =
AppsTestServer::mount_with_app_only_tool(&server, AppsTestToolLoading::Direct).await?;
let search_call_id = "app-only-search";
let call_id = "app-only-direct-call";
let mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_tool_search_call(
search_call_id,
&json!({
"query": "create calendar event",
"limit": 8,
}),
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_function_call_with_namespace(
call_id,
SEARCH_CALENDAR_NAMESPACE,
SEARCH_CALENDAR_APP_ONLY_TOOL,
"{}",
),
ev_completed("resp-1"),
ev_completed("resp-2"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_response_created("resp-3"),
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
ev_completed("resp-3"),
]),
],
)
.await;
let mut builder = apps_enabled_builder(apps_server.chatgpt_base_url.clone());
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(
"Try to call the app-only calendar tool.",
@@ -266,25 +270,25 @@ async fn app_only_tools_are_not_visible_or_runnable_by_direct_model_calls() -> R
let requests = mock.requests();
assert!(
namespace_child_tool(
&requests[0].body_json(),
tool_search_output_has_namespace_child(
&requests[1],
search_call_id,
SEARCH_CALENDAR_NAMESPACE,
SEARCH_CALENDAR_CREATE_TOOL
)
.is_some(),
"visible tool from the app-only tool's connector should be declared"
),
"visible tool from the app-only tool's connector should be searchable"
);
assert!(
namespace_child_tool(
&requests[0].body_json(),
!tool_search_output_has_namespace_child(
&requests[1],
search_call_id,
SEARCH_CALENDAR_NAMESPACE,
SEARCH_CALENDAR_APP_ONLY_TOOL
)
.is_none(),
"app-only tool should not be declared to a direct model"
),
"app-only tool should not be returned to the model by tool_search"
);
assert!(
requests[1]
requests[2]
.function_call_output(call_id)
.get("output")
.and_then(Value::as_str)
@@ -423,7 +427,7 @@ async fn search_tool_hides_apps_tools_without_search() -> Result<()> {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn explicit_app_mentions_respect_always_defer() -> Result<()> {
async fn explicit_app_mentions_leave_app_tools_deferred() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -438,13 +442,7 @@ async fn explicit_app_mentions_respect_always_defer() -> Result<()> {
)
.await;
let mut builder =
configured_builder(apps_server.chatgpt_base_url.clone()).with_config(|config| {
config
.features
.enable(Feature::ToolSearchAlwaysDeferMcpTools)
.expect("test config should allow feature update");
});
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(
@@ -458,7 +456,7 @@ async fn explicit_app_mentions_respect_always_defer() -> Result<()> {
let tools = tool_names(&body);
assert!(
tools.iter().any(|name| name == TOOL_SEARCH_TOOL_NAME),
"explicit app mentions should leave app tools deferred when always-defer is active: {tools:?}"
"explicit app mentions should leave app tools deferred: {tools:?}"
);
assert!(
namespace_child_tool(
@@ -1214,10 +1212,6 @@ async fn tool_search_surfaced_mcp_tool_errors_are_returned_to_model() -> Result<
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(),
+2 -2
View File
@@ -31,7 +31,7 @@ async fn write_repo_skill(
body: &str,
) -> Result<()> {
let skill_dir = cwd.join(".agents").join("skills").join(name);
let skill_dir_uri = PathUri::from_path(&skill_dir)?;
let skill_dir_uri = PathUri::from_host_native_path(&skill_dir)?;
fs.create_directory(
&skill_dir_uri,
CreateDirectoryOptions { recursive: true },
@@ -40,7 +40,7 @@ async fn write_repo_skill(
.await?;
let contents = format!("---\nname: {name}\ndescription: {description}\n---\n\n{body}\n");
let path = skill_dir.join("SKILL.md");
let path_uri = PathUri::from_path(&path)?;
let path_uri = PathUri::from_host_native_path(&path)?;
fs.write_file(&path_uri, contents.into_bytes(), /*sandbox*/ None)
.await?;
Ok(())
@@ -1,5 +1,6 @@
---
source: core/tests/suite/token_budget.rs
assertion_line: 545
expression: snapshot
---
Scenario: New context window tool installs fresh full context before the next follow-up request.
@@ -8,7 +9,7 @@ Scenario: New context window tool installs fresh full context before the next fo
00:message/developer[3]:
[01] <PERMISSIONS_INSTRUCTIONS>
[02] <SKILLS_INSTRUCTIONS>
[03] <token_budget>\nThread id <THREAD_ID>.\nCurrent context window id <UUID>.\nYou have 121600 tokens left in this context window.\n</token_budget>
[03] <context_window>\nThread id: <THREAD_ID>\nFirst context window id: <FIRST_WINDOW_ID>\nCurrent context window id: <WINDOW_ID>\nPrevious context window id: <FIRST_WINDOW_ID>\n</context_window>
01:message/user:<ENVIRONMENT_CONTEXT:cwd=<CWD>>
02:function_call/update_plan
03:function_call_output:Plan updated
@@ -356,6 +356,7 @@ async fn backfill_scans_existing_rollouts() -> Result<()> {
fs::create_dir_all(parent).expect("should create rollout directory");
let session_meta_line = SessionMetaLine {
meta: SessionMeta {
session_id: thread_id.into(),
id: thread_id,
forked_from_id: None,
parent_thread_id: None,
@@ -17,7 +17,6 @@ use core_test_support::hooks::trust_discovered_hooks;
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;
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;
@@ -28,6 +27,7 @@ use core_test_support::responses::namespace_child_tool;
use core_test_support::responses::sse;
use core_test_support::responses::sse_response;
use core_test_support::responses::start_mock_server;
use core_test_support::responses::strip_metadata_from_json;
use core_test_support::skip_if_no_network;
use core_test_support::test_codex::TestCodex;
use core_test_support::test_codex::local_selections;
@@ -47,6 +47,7 @@ use wiremock::MockServer;
const SPAWN_CALL_ID: &str = "spawn-call-1";
const MULTI_AGENT_V1_NAMESPACE: &str = "multi_agent_v1";
const MULTI_AGENT_V2_NAMESPACE: &str = "collaboration";
const TURN_0_FORK_PROMPT: &str = "seed fork context";
const TURN_1_PROMPT: &str = "spawn a child and continue";
const TURN_2_NO_WAIT_PROMPT: &str = "follow up without wait";
@@ -62,6 +63,23 @@ const SUBAGENT_STOP_CONTINUATION: &str = "continue only the child";
const INTERNAL_SUBAGENT_PROMPT: &str = "internal subagent: review";
fn body_contains(req: &wiremock::Request, text: &str) -> bool {
decoded_body(req)
.and_then(|body| String::from_utf8(body).ok())
.is_some_and(|body| body.contains(text))
}
fn request_has_input_type(req: &wiremock::Request, ty: &str) -> bool {
decoded_body(req)
.and_then(|body| serde_json::from_slice::<Value>(&body).ok())
.and_then(|body| body.get("input").and_then(Value::as_array).cloned())
.is_some_and(|items| {
items
.iter()
.any(|item| item.get("type").and_then(Value::as_str) == Some(ty))
})
}
fn decoded_body(req: &wiremock::Request) -> Option<Vec<u8>> {
let is_zstd = req
.headers
.get("content-encoding")
@@ -71,14 +89,11 @@ fn body_contains(req: &wiremock::Request, text: &str) -> bool {
.split(',')
.any(|entry| entry.trim().eq_ignore_ascii_case("zstd"))
});
let bytes = if is_zstd {
if is_zstd {
zstd::stream::decode_all(std::io::Cursor::new(&req.body)).ok()
} else {
Some(req.body.clone())
};
bytes
.and_then(|body| String::from_utf8(body).ok())
.is_some_and(|body| body.contains(text))
}
}
fn has_subagent_notification(req: &ResponsesRequest) -> bool {
@@ -1039,14 +1054,19 @@ async fn encrypted_multi_agent_v2_spawn_sends_agent_message_to_child() -> Result
|req: &wiremock::Request| body_contains(req, TURN_1_PROMPT),
sse(vec![
ev_response_created("resp-parent-1"),
ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args),
ev_function_call_with_namespace(
SPAWN_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&spawn_args,
),
ev_completed("resp-parent-1"),
]),
)
.await;
let child_request_log = mount_sse_once_match(
&server,
|req: &wiremock::Request| body_contains(req, "\"type\":\"agent_message\""),
|req: &wiremock::Request| request_has_input_type(req, "agent_message"),
sse(vec![
ev_response_created("resp-child-1"),
ev_completed("resp-child-1"),
@@ -1056,7 +1076,7 @@ async fn encrypted_multi_agent_v2_spawn_sends_agent_message_to_child() -> Result
mount_sse_once_match(
&server,
|req: &wiremock::Request| {
body_contains(req, SPAWN_CALL_ID) && !body_contains(req, "\"type\":\"agent_message\"")
body_contains(req, SPAWN_CALL_ID) && !request_has_input_type(req, "agent_message")
},
sse(vec![
ev_response_created("resp-parent-2"),
@@ -1085,14 +1105,11 @@ async fn encrypted_multi_agent_v2_spawn_sends_agent_message_to_child() -> Result
.pop()
.expect("child request");
assert_eq!(
child_request.inputs_of_type("agent_message"),
vec![json!({
strip_metadata_from_json(Value::Array(child_request.inputs_of_type("agent_message"))),
Value::Array(vec![json!({
"type": "agent_message",
"author": "/root",
"recipient": "/root/worker",
"metadata": {
"source_call_id": SPAWN_CALL_ID,
},
"content": [
{
"type": "input_text",
@@ -1103,7 +1120,7 @@ async fn encrypted_multi_agent_v2_spawn_sends_agent_message_to_child() -> Result
"encrypted_content": encrypted_message,
},
],
})]
})])
);
Ok(())
@@ -1131,7 +1148,12 @@ async fn plaintext_multi_agent_v2_completion_sends_agent_message(
|req: &wiremock::Request| body_contains(req, TURN_1_PROMPT),
sse(vec![
ev_response_created("resp-parent-1"),
ev_function_call(SPAWN_CALL_ID, "spawn_agent", &spawn_args),
ev_function_call_with_namespace(
SPAWN_CALL_ID,
MULTI_AGENT_V2_NAMESPACE,
"spawn_agent",
&spawn_args,
),
ev_completed("resp-parent-1"),
]),
)
@@ -1146,7 +1168,7 @@ async fn plaintext_multi_agent_v2_completion_sends_agent_message(
};
let child_request = mount_response_once_match(
&server,
|req: &wiremock::Request| body_contains(req, "\"type\":\"agent_message\""),
|req: &wiremock::Request| request_has_input_type(req, "agent_message"),
sse_response(sse(child_events)).set_delay(Duration::from_secs(1)),
)
.await;
@@ -1185,7 +1207,12 @@ async fn plaintext_multi_agent_v2_completion_sends_agent_message(
},
sse(vec![
ev_response_created("resp-parent-3"),
ev_function_call("wait-agent-call", "wait_agent", "{}"),
ev_function_call_with_namespace(
"wait-agent-call",
MULTI_AGENT_V2_NAMESPACE,
"wait_agent",
"{}",
),
ev_completed("resp-parent-3"),
]),
)
@@ -1231,8 +1258,8 @@ async fn plaintext_multi_agent_v2_completion_sends_agent_message(
.pop()
.expect("agent message request");
assert_eq!(
request.inputs_of_type("agent_message"),
vec![json!({
strip_metadata_from_json(Value::Array(request.inputs_of_type("agent_message"))),
Value::Array(vec![json!({
"type": "agent_message",
"author": "/root/worker",
"recipient": "/root",
@@ -1240,7 +1267,7 @@ async fn plaintext_multi_agent_v2_completion_sends_agent_message(
"type": "input_text",
"text": notification,
}],
})]
})])
);
Ok(())
+229 -133
View File
@@ -1,6 +1,11 @@
use anyhow::Result;
use codex_config::types::McpServerConfig;
use codex_config::types::McpServerTransportConfig;
use codex_core::config::TokenBudgetConfig;
use codex_features::Feature;
use codex_model_provider_info::built_in_model_providers;
use codex_protocol::protocol::CONTEXT_WINDOW_CLOSE_TAG;
use codex_protocol::protocol::CONTEXT_WINDOW_OPEN_TAG;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use core_test_support::PathBufExt;
@@ -17,24 +22,52 @@ 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::stdio_server_bin;
use core_test_support::test_codex::local;
use core_test_support::test_codex::test_codex;
use core_test_support::wait_for_event;
use core_test_support::wait_for_mcp_server;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::collections::HashMap;
use std::time::Duration;
const CONFIGURED_CONTEXT_WINDOW: i64 = 128_000;
const EFFECTIVE_CONTEXT_WINDOW: i64 = CONFIGURED_CONTEXT_WINDOW * 95 / 100;
fn token_budget_texts(request: &ResponsesRequest) -> Vec<String> {
fn token_budget_contexts(request: &ResponsesRequest) -> Vec<String> {
let context_window_prefix = format!("{CONTEXT_WINDOW_OPEN_TAG}\nThread id: ");
request
.message_input_texts("developer")
.into_iter()
.filter(|text| text.starts_with("<token_budget>"))
.filter(|text| text.starts_with(&context_window_prefix))
.collect()
}
fn token_budget_window_ids(
text: &str,
thread_id: codex_protocol::ThreadId,
) -> (String, Option<String>, String) {
let captures = assert_regex_match(
&format!(
r"^{CONTEXT_WINDOW_OPEN_TAG}\nThread id: {thread_id}\nFirst context window id: ([0-9a-f-]{{36}})\nCurrent context window id: ([0-9a-f-]{{36}})(?:\nPrevious context window id: ([0-9a-f-]{{36}}))?\n{CONTEXT_WINDOW_CLOSE_TAG}$"
),
text,
);
let first_window_id = captures
.get(1)
.expect("first window id capture")
.as_str()
.to_string();
let window_id = captures
.get(2)
.expect("window id capture")
.as_str()
.to_string();
let previous_window_id = captures.get(3).map(|capture| capture.as_str().to_string());
(first_window_id, previous_window_id, window_id)
}
fn tool_names(request: &ResponsesRequest) -> Vec<String> {
request
.body_json()
@@ -81,16 +114,14 @@ async fn token_budget_context_is_only_emitted_with_full_context() -> Result<()>
assert_eq!(requests.len(), 2);
let thread_id = test.session_configured.thread_id;
let initial_token_budget = token_budget_texts(&requests[0]);
let initial_token_budget = token_budget_contexts(&requests[0]);
assert_eq!(initial_token_budget.len(), 1);
assert_regex_match(
&format!(
r"^<token_budget>\nThread id {thread_id}\.\nCurrent context window id [0-9a-f-]{{36}}\.\nYou have {EFFECTIVE_CONTEXT_WINDOW} tokens left in this context window\.\n</token_budget>$"
),
&initial_token_budget[0],
);
let (first_window_id, previous_window_id, window_id) =
token_budget_window_ids(&initial_token_budget[0], thread_id);
assert_eq!(previous_window_id, None);
assert_eq!(first_window_id, window_id);
assert_eq!(
token_budget_texts(&requests[1]),
token_budget_contexts(&requests[1]),
initial_token_budget,
"steady-state context update should not advance the context window"
);
@@ -99,7 +130,90 @@ async fn token_budget_context_is_only_emitted_with_full_context() -> Result<()>
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn token_budget_remaining_context_emits_on_first_threshold_crossing() -> Result<()> {
async fn token_budget_context_injects_plain_thread_hint_text() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let rmcp_test_server_bin = stdio_server_bin()?;
let test = test_codex()
.with_config(move |config| {
config.model_context_window = Some(CONFIGURED_CONTEXT_WINDOW);
config
.features
.enable(Feature::TokenBudget)
.expect("test config should allow token budget");
let mut servers = config.mcp_servers.get().clone();
servers.insert(
"notes".to_string(),
McpServerConfig {
transport: McpServerTransportConfig::Stdio {
command: rmcp_test_server_bin,
args: Vec::new(),
env: None,
env_vars: Vec::new(),
cwd: None,
},
environment_id: "local".to_string(),
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: None,
oauth_resource: None,
tools: HashMap::new(),
},
);
config
.mcp_servers
.set(servers)
.expect("test mcp servers should accept any configuration");
})
.build(&server)
.await?;
wait_for_mcp_server(&test.codex, "notes").await?;
let responses = mount_sse_sequence(
&server,
vec![sse(vec![
ev_response_created("resp-1"),
ev_completed("resp-1"),
])],
)
.await;
test.submit_turn("inject the history hint").await?;
let request = responses.single_request();
let thread_id = test.session_configured.thread_id;
let token_budgets = token_budget_contexts(&request);
assert_eq!(token_budgets.len(), 1);
let captures = assert_regex_match(
&format!(
r"^{CONTEXT_WINDOW_OPEN_TAG}\nThread id: {thread_id}\nFirst context window id: ([0-9a-f-]{{36}})\nCurrent context window id: ([0-9a-f-]{{36}})\nmanual history hint for thread {thread_id}\nunstructured notes/thread_hint fixture result\n{CONTEXT_WINDOW_CLOSE_TAG}$"
),
&token_budgets[0],
);
assert_eq!(
captures.get(1).expect("first window id capture").as_str(),
captures.get(2).expect("current window id capture").as_str()
);
assert!(
!tool_names(&request)
.iter()
.any(|name| name == "mcp__notes__thread_hint"),
"thread_hint should be hidden from model tool exposure"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn token_budget_reminder_emits_after_crossing_compaction_threshold() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
@@ -108,27 +222,19 @@ async fn token_budget_remaining_context_emits_on_first_threshold_crossing() -> R
vec![
sse(vec![
ev_response_created("resp-1"),
ev_completed_with_tokens("resp-1", /*total_tokens*/ 2_500),
ev_completed_with_tokens("resp-1", /*total_tokens*/ 8_000),
]),
sse(vec![
ev_response_created("resp-2"),
ev_completed_with_tokens("resp-2", /*total_tokens*/ 3_000),
]),
sse(vec![
ev_response_created("resp-3"),
ev_completed_with_tokens("resp-3", /*total_tokens*/ 5_000),
]),
sse(vec![
ev_response_created("resp-4"),
ev_completed_with_tokens("resp-4", /*total_tokens*/ 8_000),
]),
sse(vec![ev_response_created("resp-5"), ev_completed("resp-5")]),
sse(vec![ev_response_created("resp-2"), ev_completed("resp-2")]),
],
)
.await;
let test = test_codex()
.with_config(|config| {
config.model_context_window = Some(10_000);
config.token_budget = Some(TokenBudgetConfig {
reminder_threshold_tokens: Some(2_000),
..TokenBudgetConfig::default()
});
config
.features
.enable(Feature::TokenBudget)
@@ -137,54 +243,23 @@ async fn token_budget_remaining_context_emits_on_first_threshold_crossing() -> R
.build(&server)
.await?;
for turn in 1..=5 {
test.submit_turn(&format!("turn {turn}")).await?;
}
test.submit_turn("cross threshold").await?;
test.submit_turn("observe reminder").await?;
let requests = responses.requests();
assert_eq!(requests.len(), 5);
let thread_id = test.session_configured.thread_id;
let full_context = token_budget_texts(&requests[0]);
assert_eq!(full_context.len(), 1);
assert_regex_match(
&format!(
r"^<token_budget>\nThread id {thread_id}\.\nCurrent context window id [0-9a-f-]{{36}}\.\nYou have 9500 tokens left in this context window\.\n</token_budget>$"
),
&full_context[0],
);
let full_context = full_context[0].clone();
let threshold_25 =
"<token_budget>\nYou have 7000 tokens left in this context window.\n</token_budget>"
.to_string();
let threshold_50 =
"<token_budget>\nYou have 4500 tokens left in this context window.\n</token_budget>"
.to_string();
let threshold_75 =
"<token_budget>\nYou have 1500 tokens left in this context window.\n</token_budget>"
.to_string();
assert_eq!(token_budget_texts(&requests[0]), vec![full_context.clone()]);
assert_eq!(requests.len(), 2);
let initial_context = token_budget_contexts(&requests[0]);
assert_eq!(initial_context.len(), 1);
let reminder = "Your context window is nearly exhausted (only 1000 tokens remaining) and will be automatically reset for you soon. Once reset, message items in current context window will be cleared in the new window, but notes and history items will be persistent across windows.";
assert_eq!(
token_budget_texts(&requests[1]),
vec![full_context.clone(), threshold_25.clone()]
);
assert_eq!(
token_budget_texts(&requests[2]),
vec![full_context.clone(), threshold_25.clone()]
);
assert_eq!(
token_budget_texts(&requests[3]),
vec![
full_context.clone(),
threshold_25.clone(),
threshold_50.clone()
]
);
assert_eq!(
token_budget_texts(&requests[4]),
vec![full_context, threshold_25, threshold_50, threshold_75]
requests[1]
.message_input_texts("developer")
.into_iter()
.filter(|text| text == reminder)
.count(),
1
);
assert_eq!(token_budget_contexts(&requests[1]), initial_context);
Ok(())
}
@@ -240,18 +315,10 @@ async fn get_context_remaining_returns_token_budget_remaining_fragment() -> Resu
);
let thread_id = test.session_configured.thread_id;
let remaining_context =
"<token_budget>\nYou have 7000 tokens left in this context window.\n</token_budget>"
.to_string();
let token_budgets = token_budget_texts(&requests[1]);
assert_eq!(token_budgets.len(), 2);
assert_regex_match(
&format!(
r"^<token_budget>\nThread id {thread_id}\.\nCurrent context window id [0-9a-f-]{{36}}\.\nYou have 9500 tokens left in this context window\.\n</token_budget>$"
),
&token_budgets[0],
);
assert_eq!(token_budgets[1], remaining_context);
let remaining_context = "You have 7000 tokens left in this context window.".to_string();
let token_budgets = token_budget_contexts(&requests[1]);
assert_eq!(token_budgets.len(), 1);
token_budget_window_ids(&token_budgets[0], thread_id);
assert_eq!(
requests[2].function_call_output_content_and_success(call_id),
Some((Some(remaining_context), None))
@@ -308,14 +375,11 @@ async fn get_context_remaining_returns_unknown_when_window_is_unavailable() -> R
"get_context_remaining should be exposed when token budget is enabled"
);
assert_eq!(token_budget_texts(&requests[0]), Vec::<String>::new());
assert_eq!(token_budget_contexts(&requests[0]), Vec::<String>::new());
assert_eq!(
requests[1].function_call_output_content_and_success(call_id),
Some((
Some(
"<token_budget>\nYou have unknown tokens left in this context window.\n</token_budget>"
.to_string()
),
Some("You have unknown tokens left in this context window.".to_string()),
None,
))
);
@@ -371,30 +435,24 @@ async fn token_budget_context_uses_new_window_after_compaction() -> Result<()> {
assert_eq!(requests.len(), 3);
let thread_id = test.session_configured.thread_id;
let initial_token_budget = token_budget_texts(&requests[0]);
let initial_token_budget = token_budget_contexts(&requests[0]);
assert_eq!(initial_token_budget.len(), 1);
let initial_window_id = assert_regex_match(
&format!(
r"^<token_budget>\nThread id {thread_id}\.\nCurrent context window id ([0-9a-f-]{{36}})\.\nYou have {EFFECTIVE_CONTEXT_WINDOW} tokens left in this context window\.\n</token_budget>$"
),
&initial_token_budget[0],
)
.get(1)
.expect("window id capture")
.as_str()
.to_string();
let post_compaction_token_budget = token_budget_texts(&requests[2]);
let (initial_first_window_id, initial_previous_window_id, initial_window_id) =
token_budget_window_ids(&initial_token_budget[0], thread_id);
let post_compaction_token_budget = token_budget_contexts(&requests[2]);
assert_eq!(post_compaction_token_budget.len(), 1);
let post_compaction_window_id = assert_regex_match(
&format!(
r"^<token_budget>\nThread id {thread_id}\.\nCurrent context window id ([0-9a-f-]{{36}})\.\nYou have {EFFECTIVE_CONTEXT_WINDOW} tokens left in this context window\.\n</token_budget>$"
),
&post_compaction_token_budget[0],
)
.get(1)
.expect("window id capture")
.as_str()
.to_string();
let (
post_compaction_first_window_id,
post_compaction_previous_window_id,
post_compaction_window_id,
) = token_budget_window_ids(&post_compaction_token_budget[0], thread_id);
assert_eq!(initial_previous_window_id, None);
assert_eq!(initial_first_window_id, initial_window_id);
assert_eq!(post_compaction_first_window_id, initial_first_window_id);
assert_eq!(
post_compaction_previous_window_id.as_deref(),
Some(initial_window_id.as_str())
);
assert_ne!(post_compaction_window_id, initial_window_id);
Ok(())
@@ -456,31 +514,20 @@ async fn new_context_tool_starts_new_window_before_follow_up() -> Result<()> {
"new_context should be exposed when token budget is enabled"
);
let thread_id = test.session_configured.thread_id;
let initial_token_budget = token_budget_texts(&requests[0]);
let initial_token_budget = token_budget_contexts(&requests[0]);
assert_eq!(initial_token_budget.len(), 1);
let initial_window_id = assert_regex_match(
&format!(
r"^<token_budget>\nThread id {thread_id}\.\nCurrent context window id ([0-9a-f-]{{36}})\.\nYou have {EFFECTIVE_CONTEXT_WINDOW} tokens left in this context window\.\n</token_budget>$"
),
&initial_token_budget[0],
)
.get(1)
.expect("window id capture")
.as_str()
.to_string();
let new_window_token_budget = token_budget_texts(&requests[2]);
let (initial_first_window_id, _, initial_window_id) =
token_budget_window_ids(&initial_token_budget[0], thread_id);
let new_window_token_budget = token_budget_contexts(&requests[2]);
assert_eq!(new_window_token_budget.len(), 1);
let window_id = assert_regex_match(
&format!(
r"^<token_budget>\nThread id {thread_id}\.\nCurrent context window id ([0-9a-f-]{{36}})\.\nYou have {EFFECTIVE_CONTEXT_WINDOW} tokens left in this context window\.\n</token_budget>$"
),
&new_window_token_budget[0],
)
.get(1)
.expect("window id capture")
.as_str()
.to_string();
assert_ne!(window_id, initial_window_id);
let (new_first_window_id, new_previous_window_id, new_window_id) =
token_budget_window_ids(&new_window_token_budget[0], thread_id);
assert_eq!(new_first_window_id, initial_first_window_id);
assert_eq!(
new_previous_window_id.as_deref(),
Some(initial_window_id.as_str())
);
assert_ne!(new_window_id, initial_window_id);
assert!(
!requests[2].body_contains_text("request new context window"),
"new_context should drop the prior window history before continuing the turn"
@@ -496,7 +543,8 @@ async fn new_context_tool_starts_new_window_before_follow_up() -> Result<()> {
);
let snapshot = snapshot
.replace(&thread_id.to_string(), "<THREAD_ID>")
.replace(&window_id, "<UUID>");
.replace(&new_first_window_id, "<FIRST_WINDOW_ID>")
.replace(&new_window_id, "<WINDOW_ID>");
insta::assert_snapshot!(
"token_budget_new_context_window_tool_full_context",
snapshot
@@ -504,3 +552,51 @@ async fn new_context_tool_starts_new_window_before_follow_up() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn auto_compaction_feature_disabled_hides_new_context_tool() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let responses = mount_sse_sequence(
&server,
vec![sse(vec![
ev_response_created("resp-1"),
ev_completed("resp-1"),
])],
)
.await;
let test = test_codex()
.with_config(|config| {
config.model_context_window = Some(CONFIGURED_CONTEXT_WINDOW);
config
.features
.enable(Feature::TokenBudget)
.expect("test config should allow token budget");
config
.features
.disable(Feature::AutoCompaction)
.expect("test config should allow disabling auto-compaction");
})
.build(&server)
.await?;
test.submit_turn("preserve the current context window")
.await?;
let requests = responses.requests();
assert_eq!(requests.len(), 1);
let tool_names = tool_names(&requests[0]);
assert!(
tool_names
.iter()
.any(|name| name == "get_context_remaining"),
"token budget should continue to expose get_context_remaining"
);
assert!(
!tool_names.iter().any(|name| name == "new_context"),
"disabled auto-compaction should hide new_context"
);
Ok(())
}
+1 -1
View File
@@ -474,7 +474,7 @@ async fn mcp_image_output_preserves_image_and_no_text_summary() -> Result<()> {
let rmcp_test_server_bin = stdio_server_bin()?;
// 1x1 PNG data URL
let openai_png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMB/ee9bQAAAABJRU5ErkJggg==";
let openai_png = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
let mut builder = test_codex().with_config(move |config| {
let mut servers = config.mcp_servers.get().clone();
+4 -4
View File
@@ -229,7 +229,7 @@ async fn create_workspace_directory(
rel_path: impl AsRef<std::path::Path>,
) -> Result<std::path::PathBuf> {
let abs_path = test.config.cwd.join(rel_path.as_ref());
let abs_path_uri = PathUri::from_path(&abs_path)?;
let abs_path_uri = PathUri::from_host_native_path(&abs_path)?;
test.fs()
.create_directory(
&abs_path_uri,
@@ -437,7 +437,7 @@ async fn unified_exec_emits_exec_command_begin_event() -> Result<()> {
assert_command(&begin_event.command, "-lc", "/bin/echo hello unified exec");
assert_eq!(begin_event.cwd, PathUri::from_path(&cwd)?);
assert_eq!(begin_event.cwd, PathUri::from_host_native_path(&cwd)?);
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
@@ -508,7 +508,7 @@ async fn unified_exec_resolves_relative_workdir() -> Result<()> {
assert_eq!(
begin_event.cwd,
PathUri::from_path(&workdir)?,
PathUri::from_host_native_path(&workdir)?,
"exec_command cwd should resolve relative workdir against turn cwd",
);
@@ -570,7 +570,7 @@ async fn unified_exec_respects_workdir_override() -> Result<()> {
assert_eq!(
begin_event.cwd,
PathUri::from_path(&workdir)?,
PathUri::from_host_native_path(&workdir)?,
"exec_command cwd should reflect the requested workdir override"
);
+11 -113
View File
@@ -7,7 +7,6 @@ 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_features::Feature;
use codex_login::CodexAuth;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::models::PermissionProfile;
@@ -134,7 +133,7 @@ fn png_bytes(width: u32, height: u32, rgba: [u8; 4]) -> anyhow::Result<Vec<u8>>
async fn create_workspace_directory(test: &TestCodex, rel_path: &str) -> anyhow::Result<PathBuf> {
let abs_path = test.config.cwd.join(rel_path);
let abs_path_uri = PathUri::from_path(&abs_path)?;
let abs_path_uri = PathUri::from_host_native_path(&abs_path)?;
test.fs()
.create_directory(
&abs_path_uri,
@@ -152,7 +151,7 @@ async fn write_workspace_file(
) -> anyhow::Result<PathBuf> {
let abs_path = test.config.cwd.join(rel_path);
if let Some(parent) = abs_path.parent() {
let parent_uri = PathUri::from_path(&parent)?;
let parent_uri = PathUri::from_host_native_path(&parent)?;
test.fs()
.create_directory(
&parent_uri,
@@ -161,7 +160,7 @@ async fn write_workspace_file(
)
.await?;
}
let abs_path_uri = PathUri::from_path(&abs_path)?;
let abs_path_uri = PathUri::from_host_native_path(&abs_path)?;
test.fs()
.write_file(&abs_path_uri, contents, /*sandbox*/ None)
.await?;
@@ -181,15 +180,10 @@ async fn write_workspace_png(
async fn assert_user_turn_local_image_resizes_to(
original_dimensions: (u32, u32),
expected_dimensions: (u32, u32),
resize_policy: TestImageResizePolicy,
) -> anyhow::Result<()> {
let server = start_mock_server().await;
let mut builder = test_codex().with_config(move |config| {
if resize_policy == TestImageResizePolicy::AllImages {
let _ = config.features.enable(Feature::ResizeAllImages);
}
});
let mut builder = test_codex();
let test = builder.build_with_remote_env(&server).await?;
let TestCodex {
codex,
@@ -263,42 +257,25 @@ async fn assert_user_turn_local_image_resizes_to(
Ok(())
}
#[derive(Clone, Copy, Eq, PartialEq)]
enum TestImageResizePolicy {
Legacy,
AllImages,
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn user_turn_with_local_image_attaches_image() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
assert_user_turn_local_image_resizes_to((2304, 864), (2048, 768), TestImageResizePolicy::Legacy)
.await
assert_user_turn_local_image_resizes_to((2304, 864), (2048, 768)).await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn user_turn_with_vertical_local_image_resizes_to_square_bounds() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
assert_user_turn_local_image_resizes_to(
(1024, 4096),
(512, 2048),
TestImageResizePolicy::Legacy,
)
.await
assert_user_turn_local_image_resizes_to((1024, 4096), (512, 2048)).await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn resize_all_images_applies_patch_budget_to_local_user_image() -> anyhow::Result<()> {
async fn user_turn_local_image_applies_patch_budget() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
assert_user_turn_local_image_resizes_to(
(2048, 2048),
(1600, 1600),
TestImageResizePolicy::AllImages,
)
.await
assert_user_turn_local_image_resizes_to((2048, 2048), (1600, 1600)).await
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -612,7 +589,7 @@ async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<()
))
.abs();
let image_path = remote_cwd.join("remote.png");
let remote_cwd_uri = PathUri::from_path(&remote_cwd)?;
let remote_cwd_uri = PathUri::from_host_native_path(&remote_cwd)?;
test.fs()
.create_directory(
&remote_cwd_uri,
@@ -621,7 +598,7 @@ async fn view_image_routes_to_selected_remote_environment() -> anyhow::Result<()
)
.await?;
let png = png_bytes(/*width*/ 1, /*height*/ 1, [0, 255, 0, 255])?;
let image_path_uri = PathUri::from_path(&image_path)?;
let image_path_uri = PathUri::from_host_native_path(&image_path)?;
test.fs()
.write_file(&image_path_uri, png, /*sandbox*/ None)
.await?;
@@ -1209,11 +1186,10 @@ async fn view_image_tool_errors_when_path_is_directory() -> anyhow::Result<()> {
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn view_image_tool_errors_for_non_image_files() -> anyhow::Result<()> {
async fn view_image_tool_turns_invalid_image_into_placeholder() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mut builder = test_codex();
let test = builder.build_with_remote_env(&server).await?;
let TestCodex {
@@ -1222,84 +1198,6 @@ async fn view_image_tool_errors_for_non_image_files() -> anyhow::Result<()> {
..
} = &test;
let rel_path = "assets/example.json";
let abs_path =
write_workspace_file(&test, rel_path, br#"{ "message": "hello" }"#.to_vec()).await?;
let call_id = "view-image-non-image";
let arguments = serde_json::json!({ "path": rel_path }).to_string();
let first_response = sse(vec![
ev_response_created("resp-1"),
ev_function_call(call_id, "view_image", &arguments),
ev_completed("resp-1"),
]);
responses::mount_sse_once(&server, first_response).await;
let second_response = sse(vec![
ev_assistant_message("msg-1", "done"),
ev_completed("resp-2"),
]);
let mock = responses::mount_sse_once(&server, second_response).await;
let session_model = session_configured.model.clone();
codex
.submit(disabled_user_turn(
&test,
vec![UserInput::Text {
text: "please use the view_image tool to read the json file".into(),
text_elements: Vec::new(),
}],
session_model,
))
.await?;
wait_for_event_with_timeout(
codex,
|event| matches!(event, EventMsg::TurnComplete(_)),
VIEW_IMAGE_TURN_COMPLETE_TIMEOUT,
)
.await;
let request = mock.single_request();
assert!(
request.inputs_of_type("input_image").is_empty(),
"non-image file should not produce an input_image message"
);
let (error_text, success) = request
.function_call_output_content_and_success(call_id)
.expect("function_call_output should be present");
assert_eq!(success, None);
let error_text = error_text.expect("error text present");
let expected_error = format!(
"unable to process image at `{}`: unsupported image `application/json`",
abs_path.display()
);
assert!(
error_text.contains(&expected_error),
"error should describe unsupported file type: {error_text}"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn resize_all_images_turns_invalid_view_image_into_placeholder() -> anyhow::Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let mut builder = test_codex().with_config(|config| {
let _ = config.features.enable(Feature::ResizeAllImages);
});
let test = builder.build_with_remote_env(&server).await?;
let TestCodex {
codex,
session_configured,
..
} = &test;
let rel_path = "assets/invalid-image.json";
write_workspace_file(&test, rel_path, br#"{ "message": "hello" }"#.to_vec()).await?;
let call_id = "view-image-invalid-placeholder";