mirror of
https://github.com/openai/codex.git
synced 2026-11-30 00:10:49 +00:00
Merge branch 'abhinav/hooks-updated-input' into abhinav/hooks-updated-input-permission-request
This commit is contained in:
@@ -7,4 +7,7 @@ codex_rust_crate(
|
||||
lib_data_extra = [
|
||||
"//codex-rs/core:model_availability_nux_fixtures",
|
||||
],
|
||||
deps_extra = [
|
||||
"@crates//:similar",
|
||||
],
|
||||
)
|
||||
|
||||
@@ -33,6 +33,7 @@ opentelemetry = { workspace = true }
|
||||
opentelemetry_sdk = { workspace = true }
|
||||
regex-lite = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
similar = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
tokio = { workspace = true, features = ["net", "time"] }
|
||||
tokio-tungstenite = { workspace = true }
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use regex_lite::Regex;
|
||||
use serde_json::Value;
|
||||
use similar::ChangeTag;
|
||||
use similar::TextDiff;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::responses::ResponsesRequest;
|
||||
@@ -242,6 +244,102 @@ pub fn format_labeled_items_snapshot(
|
||||
format!("Scenario: {scenario}\n\n{sections}")
|
||||
}
|
||||
|
||||
/// Render changed JSON lines between two captured `/responses` request bodies.
|
||||
///
|
||||
/// Request-parity tests use this to compare the entire JSON payload while showing only fields that
|
||||
/// changed, with the same redactions as the other context snapshots.
|
||||
pub fn format_request_body_diff_snapshot(
|
||||
scenario: &str,
|
||||
before_title: &str,
|
||||
before_request: &ResponsesRequest,
|
||||
after_title: &str,
|
||||
after_request: &ResponsesRequest,
|
||||
options: &ContextSnapshotOptions,
|
||||
) -> String {
|
||||
let before = format_request_body_snapshot(before_request, options);
|
||||
let after = format_request_body_snapshot(after_request, options);
|
||||
let diff = format_changed_lines_diff(before_title, &before, after_title, &after);
|
||||
format!("Scenario: {scenario}\n\n{diff}")
|
||||
}
|
||||
|
||||
fn format_request_body_snapshot(
|
||||
request: &ResponsesRequest,
|
||||
options: &ContextSnapshotOptions,
|
||||
) -> String {
|
||||
let mut body = request.body_json();
|
||||
canonicalize_json_snapshot_value(&mut body, options);
|
||||
serde_json::to_string_pretty(&body).expect("request body should serialize")
|
||||
}
|
||||
|
||||
fn canonicalize_json_snapshot_value(value: &mut Value, options: &ContextSnapshotOptions) {
|
||||
match value {
|
||||
Value::Array(values) => {
|
||||
for value in values {
|
||||
canonicalize_json_snapshot_value(value, options);
|
||||
}
|
||||
}
|
||||
Value::Object(map) => {
|
||||
// Keep request-body snapshots stable when serde_json preserves insertion order.
|
||||
let mut entries = std::mem::take(map).into_iter().collect::<Vec<_>>();
|
||||
entries.sort_by(|(left_key, _), (right_key, _)| left_key.cmp(right_key));
|
||||
for (key, mut value) in entries {
|
||||
canonicalize_json_snapshot_value(&mut value, options);
|
||||
map.insert(key, value);
|
||||
}
|
||||
}
|
||||
Value::String(text) => {
|
||||
*text = format_snapshot_json_string(text, options);
|
||||
}
|
||||
Value::Null | Value::Bool(_) | Value::Number(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn format_snapshot_json_string(text: &str, options: &ContextSnapshotOptions) -> String {
|
||||
let normalized = match options.render_mode {
|
||||
ContextSnapshotRenderMode::RedactedText
|
||||
| ContextSnapshotRenderMode::KindWithTextPrefix { .. } => normalize_snapshot_uuids(
|
||||
&normalize_snapshot_line_endings(&canonicalize_snapshot_text(text)),
|
||||
),
|
||||
ContextSnapshotRenderMode::FullText => normalize_snapshot_line_endings(text),
|
||||
ContextSnapshotRenderMode::KindOnly => unreachable!(),
|
||||
};
|
||||
match options.render_mode {
|
||||
ContextSnapshotRenderMode::KindWithTextPrefix { max_chars }
|
||||
if normalized.chars().count() > max_chars =>
|
||||
{
|
||||
let prefix = normalized.chars().take(max_chars).collect::<String>();
|
||||
format!("{prefix}...")
|
||||
}
|
||||
ContextSnapshotRenderMode::RedactedText
|
||||
| ContextSnapshotRenderMode::FullText
|
||||
| ContextSnapshotRenderMode::KindWithTextPrefix { .. } => normalized,
|
||||
ContextSnapshotRenderMode::KindOnly => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_changed_lines_diff(
|
||||
before_title: &str,
|
||||
before: &str,
|
||||
after_title: &str,
|
||||
after: &str,
|
||||
) -> String {
|
||||
let mut diff = format!("--- {before_title}\n+++ {after_title}\n");
|
||||
for change in TextDiff::from_lines(before, after).iter_all_changes() {
|
||||
match change.tag() {
|
||||
ChangeTag::Equal => {}
|
||||
ChangeTag::Delete => {
|
||||
diff.push('-');
|
||||
diff.push_str(change.value());
|
||||
}
|
||||
ChangeTag::Insert => {
|
||||
diff.push('+');
|
||||
diff.push_str(change.value());
|
||||
}
|
||||
}
|
||||
}
|
||||
diff
|
||||
}
|
||||
|
||||
fn format_snapshot_text(text: &str, options: &ContextSnapshotOptions) -> String {
|
||||
match options.render_mode {
|
||||
ContextSnapshotRenderMode::RedactedText => {
|
||||
@@ -342,6 +440,17 @@ fn normalize_dynamic_snapshot_paths(text: &str) -> String {
|
||||
.into_owned()
|
||||
}
|
||||
|
||||
fn normalize_snapshot_uuids(text: &str) -> String {
|
||||
static UUID_RE: OnceLock<Regex> = OnceLock::new();
|
||||
let uuid_re = UUID_RE.get_or_init(|| {
|
||||
Regex::new(
|
||||
r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b",
|
||||
)
|
||||
.expect("uuid regex should compile")
|
||||
});
|
||||
uuid_re.replace_all(text, "<UUID>").into_owned()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ContextSnapshotOptions;
|
||||
|
||||
@@ -18,6 +18,7 @@ use codex_core::ThreadManager;
|
||||
use codex_core::agent_graph_store_from_state_db;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::init_state_db_from_config;
|
||||
use codex_core::resolve_installation_id;
|
||||
use codex_core::shell::Shell;
|
||||
use codex_core::shell::get_shell_by_model_provided_path;
|
||||
use codex_core::thread_store_from_config;
|
||||
@@ -431,6 +432,7 @@ impl TestCodexBuilder {
|
||||
.expect("test codex requires state db");
|
||||
let thread_store = thread_store_from_config(&config, state_db.clone());
|
||||
let agent_graph_store = agent_graph_store_from_state_db(state_db.clone());
|
||||
let installation_id = resolve_installation_id(&config.codex_home).await?;
|
||||
ThreadManager::new(
|
||||
&config,
|
||||
codex_core::test_support::auth_manager_from_auth(auth.clone()),
|
||||
@@ -440,6 +442,7 @@ impl TestCodexBuilder {
|
||||
state_db,
|
||||
thread_store,
|
||||
agent_graph_store,
|
||||
installation_id,
|
||||
)
|
||||
} else {
|
||||
codex_core::test_support::thread_manager_with_models_provider_and_home(
|
||||
@@ -651,7 +654,7 @@ impl TestCodex {
|
||||
prompt,
|
||||
AskForApproval::Never,
|
||||
PermissionProfile::Disabled,
|
||||
Some(service_tier),
|
||||
Some(service_tier.map(|service_tier| service_tier.request_value().to_string())),
|
||||
/*environments*/ None,
|
||||
)
|
||||
.await
|
||||
@@ -713,7 +716,7 @@ impl TestCodex {
|
||||
prompt: &str,
|
||||
approval_policy: AskForApproval,
|
||||
permission_profile: PermissionProfile,
|
||||
service_tier: Option<Option<ServiceTier>>,
|
||||
service_tier: Option<Option<String>>,
|
||||
environments: Option<Vec<TurnEnvironmentSelection>>,
|
||||
) -> Result<()> {
|
||||
self.submit_turn_with_context(
|
||||
@@ -731,7 +734,7 @@ impl TestCodex {
|
||||
prompt: &str,
|
||||
approval_policy: AskForApproval,
|
||||
permission_profile: PermissionProfile,
|
||||
service_tier: Option<Option<ServiceTier>>,
|
||||
service_tier: Option<Option<String>>,
|
||||
environments: Option<Vec<TurnEnvironmentSelection>>,
|
||||
) -> Result<()> {
|
||||
let (sandbox_policy, permission_profile) =
|
||||
|
||||
@@ -80,13 +80,13 @@ async fn responses_stream_includes_subagent_header_on_review() {
|
||||
config.model = Some(model.clone());
|
||||
let config = Arc::new(config);
|
||||
|
||||
let conversation_id = ThreadId::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let auth_mode = TelemetryAuthMode::Chatgpt;
|
||||
let session_source = SessionSource::SubAgent(SubAgentSource::Review);
|
||||
let model_info =
|
||||
codex_core::test_support::construct_model_info_offline(model.as_str(), &config);
|
||||
let session_telemetry = SessionTelemetry::new(
|
||||
conversation_id,
|
||||
thread_id,
|
||||
model.as_str(),
|
||||
model_info.slug.as_str(),
|
||||
/*account_id*/ None,
|
||||
@@ -100,7 +100,8 @@ async fn responses_stream_includes_subagent_header_on_review() {
|
||||
|
||||
let client = ModelClient::new(
|
||||
/*auth_manager*/ None,
|
||||
conversation_id,
|
||||
thread_id.into(),
|
||||
thread_id,
|
||||
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
|
||||
provider.clone(),
|
||||
session_source,
|
||||
@@ -141,7 +142,7 @@ async fn responses_stream_includes_subagent_header_on_review() {
|
||||
}
|
||||
|
||||
let request = request_recorder.single_request();
|
||||
let expected_window_id = format!("{conversation_id}:0");
|
||||
let expected_window_id = format!("{thread_id}:0");
|
||||
assert_eq!(
|
||||
request.header("x-openai-subagent").as_deref(),
|
||||
Some("review")
|
||||
@@ -205,14 +206,14 @@ async fn responses_stream_includes_subagent_header_on_other() {
|
||||
config.model = Some(model.clone());
|
||||
let config = Arc::new(config);
|
||||
|
||||
let conversation_id = ThreadId::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let auth_mode = TelemetryAuthMode::Chatgpt;
|
||||
let session_source = SessionSource::SubAgent(SubAgentSource::Other("my-task".to_string()));
|
||||
let model_info =
|
||||
codex_core::test_support::construct_model_info_offline(model.as_str(), &config);
|
||||
|
||||
let session_telemetry = SessionTelemetry::new(
|
||||
conversation_id,
|
||||
thread_id,
|
||||
model.as_str(),
|
||||
model_info.slug.as_str(),
|
||||
/*account_id*/ None,
|
||||
@@ -226,7 +227,8 @@ async fn responses_stream_includes_subagent_header_on_other() {
|
||||
|
||||
let client = ModelClient::new(
|
||||
/*auth_manager*/ None,
|
||||
conversation_id,
|
||||
thread_id.into(),
|
||||
thread_id,
|
||||
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
|
||||
provider.clone(),
|
||||
session_source,
|
||||
@@ -317,7 +319,7 @@ async fn responses_respects_model_info_overrides_from_config() {
|
||||
let model = config.model.clone().expect("model configured");
|
||||
let config = Arc::new(config);
|
||||
|
||||
let conversation_id = ThreadId::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let auth_mode =
|
||||
codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("Test API Key"))
|
||||
.auth_mode()
|
||||
@@ -327,7 +329,7 @@ async fn responses_respects_model_info_overrides_from_config() {
|
||||
let model_info =
|
||||
codex_core::test_support::construct_model_info_offline(model.as_str(), &config);
|
||||
let session_telemetry = SessionTelemetry::new(
|
||||
conversation_id,
|
||||
thread_id,
|
||||
model.as_str(),
|
||||
model_info.slug.as_str(),
|
||||
/*account_id*/ None,
|
||||
@@ -341,7 +343,8 @@ async fn responses_respects_model_info_overrides_from_config() {
|
||||
|
||||
let client = ModelClient::new(
|
||||
/*auth_manager*/ None,
|
||||
conversation_id,
|
||||
thread_id.into(),
|
||||
thread_id,
|
||||
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
|
||||
provider.clone(),
|
||||
session_source,
|
||||
|
||||
@@ -313,7 +313,7 @@ async fn websocket_v2_first_turn_drops_fast_tier_after_startup_prewarm() -> Resu
|
||||
.features
|
||||
.enable(Feature::ResponsesWebsocketsV2)
|
||||
.expect("test config should allow feature update");
|
||||
config.service_tier = Some(ServiceTier::Fast);
|
||||
config.service_tier = Some(ServiceTier::Fast.request_value().to_string());
|
||||
});
|
||||
let test = builder.build_with_websocket_server(&server).await?;
|
||||
|
||||
|
||||
@@ -807,7 +807,7 @@ async fn wait_for_spawned_thread(test: &TestCodex) -> Result<Arc<CodexThread>> {
|
||||
let ids = test.thread_manager.list_thread_ids().await;
|
||||
if let Some(thread_id) = ids
|
||||
.iter()
|
||||
.find(|id| **id != test.session_configured.session_id)
|
||||
.find(|id| **id != test.session_configured.thread_id)
|
||||
{
|
||||
return test
|
||||
.thread_manager
|
||||
|
||||
@@ -7,6 +7,7 @@ use codex_core::ResponseEvent;
|
||||
use codex_core::ThreadManager;
|
||||
use codex_core::agent_graph_store_from_state_db;
|
||||
use codex_core::init_state_db_from_config;
|
||||
use codex_core::resolve_installation_id;
|
||||
use codex_core::thread_store_from_config;
|
||||
use codex_features::Feature;
|
||||
use codex_login::AuthManager;
|
||||
@@ -726,7 +727,7 @@ async fn resume_replays_image_tool_outputs_with_detail() {
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn includes_conversation_id_and_model_headers_in_request() {
|
||||
async fn includes_session_id_thread_id_and_model_headers_in_request() {
|
||||
skip_if_no_network!();
|
||||
|
||||
// Mock server
|
||||
@@ -744,7 +745,8 @@ async fn includes_conversation_id_and_model_headers_in_request() {
|
||||
.await
|
||||
.expect("create new conversation");
|
||||
let codex = test.codex.clone();
|
||||
let session_id = test.session_configured.session_id;
|
||||
let expected_session_id = test.session_configured.session_id;
|
||||
let expected_thread_id = test.session_configured.thread_id;
|
||||
|
||||
codex
|
||||
.submit(Op::UserInput {
|
||||
@@ -764,6 +766,7 @@ async fn includes_conversation_id_and_model_headers_in_request() {
|
||||
let request = resp_mock.single_request();
|
||||
assert_eq!(request.path(), "/v1/responses");
|
||||
let request_session_id = request.header("session_id").expect("session_id header");
|
||||
let request_thread_id = request.header("thread_id").expect("thread_id header");
|
||||
let request_authorization = request
|
||||
.header("authorization")
|
||||
.expect("authorization header");
|
||||
@@ -772,10 +775,16 @@ async fn includes_conversation_id_and_model_headers_in_request() {
|
||||
let installation_id =
|
||||
std::fs::read_to_string(test.codex_home_path().join(INSTALLATION_ID_FILENAME))
|
||||
.expect("read installation id");
|
||||
let thread_id_string = expected_thread_id.to_string();
|
||||
|
||||
assert_eq!(request_session_id, session_id.to_string());
|
||||
assert_eq!(request_session_id, expected_session_id.to_string());
|
||||
assert_eq!(request_thread_id, thread_id_string.as_str());
|
||||
assert_eq!(request_originator, originator().value);
|
||||
assert_eq!(request_authorization, "Bearer Test API Key");
|
||||
assert_eq!(
|
||||
request_body["prompt_cache_key"].as_str(),
|
||||
Some(thread_id_string.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
request_body["client_metadata"]["x-codex-installation-id"].as_str(),
|
||||
Some(installation_id.as_str())
|
||||
@@ -867,9 +876,9 @@ async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuth
|
||||
let config = Arc::new(config);
|
||||
let model_info =
|
||||
codex_core::test_support::construct_model_info_offline(model.as_str(), &config);
|
||||
let conversation_id = ThreadId::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let session_telemetry = SessionTelemetry::new(
|
||||
conversation_id,
|
||||
thread_id,
|
||||
model.as_str(),
|
||||
model_info.slug.as_str(),
|
||||
/*account_id*/ None,
|
||||
@@ -884,7 +893,8 @@ async fn send_provider_auth_request(server: &MockServer, auth: ModelProviderAuth
|
||||
Some(AuthManager::from_auth_for_testing(CodexAuth::from_api_key(
|
||||
"unused-api-key",
|
||||
))),
|
||||
conversation_id,
|
||||
thread_id.into(),
|
||||
thread_id,
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
provider,
|
||||
SessionSource::Exec,
|
||||
@@ -1000,7 +1010,8 @@ async fn chatgpt_auth_sends_correct_request() {
|
||||
.await
|
||||
.expect("create new conversation");
|
||||
let codex = test.codex.clone();
|
||||
let thread_id = test.session_configured.session_id;
|
||||
let expected_session_id = test.session_configured.session_id;
|
||||
let expected_thread_id = test.session_configured.thread_id;
|
||||
|
||||
codex
|
||||
.submit(Op::UserInput {
|
||||
@@ -1028,11 +1039,13 @@ async fn chatgpt_auth_sends_correct_request() {
|
||||
.expect("chatgpt-account-id header");
|
||||
let request_body = request.body_json();
|
||||
|
||||
let session_id = request.header("session_id").expect("session_id header");
|
||||
let request_session_id = request.header("session_id").expect("session_id header");
|
||||
let request_thread_id = request.header("thread_id").expect("thread_id header");
|
||||
let installation_id =
|
||||
std::fs::read_to_string(test.codex_home_path().join(INSTALLATION_ID_FILENAME))
|
||||
.expect("read installation id");
|
||||
assert_eq!(session_id, thread_id.to_string());
|
||||
assert_eq!(request_session_id, expected_session_id.to_string());
|
||||
assert_eq!(request_thread_id, expected_thread_id.to_string());
|
||||
|
||||
assert_eq!(request_originator, originator().value);
|
||||
assert_eq!(request_authorization, "Bearer Access Token");
|
||||
@@ -1108,6 +1121,9 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() {
|
||||
.expect("client test requires state db");
|
||||
let thread_store = thread_store_from_config(&config, state_db.clone());
|
||||
let agent_graph_store = agent_graph_store_from_state_db(state_db.clone());
|
||||
let installation_id = resolve_installation_id(&config.codex_home)
|
||||
.await
|
||||
.expect("resolve installation id");
|
||||
let thread_manager = ThreadManager::new(
|
||||
&config,
|
||||
auth_manager,
|
||||
@@ -1117,6 +1133,7 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() {
|
||||
state_db,
|
||||
thread_store,
|
||||
agent_graph_store,
|
||||
installation_id,
|
||||
);
|
||||
let NewThread { thread: codex, .. } = thread_manager
|
||||
.start_thread(config.clone())
|
||||
@@ -2277,11 +2294,11 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
|
||||
let config = Arc::new(config);
|
||||
let model_info =
|
||||
codex_core::test_support::construct_model_info_offline(model.as_str(), &config);
|
||||
let conversation_id = ThreadId::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let auth_manager =
|
||||
codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("Test API Key"));
|
||||
let session_telemetry = SessionTelemetry::new(
|
||||
conversation_id,
|
||||
thread_id,
|
||||
model.as_str(),
|
||||
model_info.slug.as_str(),
|
||||
/*account_id*/ None,
|
||||
@@ -2295,7 +2312,8 @@ async fn azure_responses_request_includes_store_and_reasoning_ids() {
|
||||
|
||||
let client = ModelClient::new(
|
||||
/*auth_manager*/ None,
|
||||
conversation_id,
|
||||
thread_id.into(),
|
||||
thread_id,
|
||||
/*installation_id*/ "11111111-1111-4111-8111-111111111111".to_string(),
|
||||
provider.clone(),
|
||||
SessionSource::Exec,
|
||||
|
||||
@@ -15,6 +15,7 @@ use codex_otel::MetricsConfig;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_otel::TelemetryAuthMode;
|
||||
use codex_otel::current_span_w3c_trace_context;
|
||||
use codex_protocol::SessionId;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::account::PlanType;
|
||||
use codex_protocol::config_types::ReasoningSummary;
|
||||
@@ -87,7 +88,8 @@ fn assert_request_trace_matches(body: &serde_json::Value, expected_trace: &W3cTr
|
||||
struct WebsocketTestHarness {
|
||||
_codex_home: TempDir,
|
||||
client: ModelClient,
|
||||
conversation_id: ThreadId,
|
||||
session_id: SessionId,
|
||||
thread_id: ThreadId,
|
||||
model_info: ModelInfo,
|
||||
effort: Option<ReasoningEffortConfig>,
|
||||
summary: ReasoningSummary,
|
||||
@@ -125,7 +127,15 @@ async fn responses_websocket_streams_request() {
|
||||
);
|
||||
assert_eq!(
|
||||
handshake.header(X_CLIENT_REQUEST_ID_HEADER),
|
||||
Some(harness.conversation_id.to_string())
|
||||
Some(harness.thread_id.to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
handshake.header("session_id"),
|
||||
Some(harness.session_id.to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
handshake.header("thread_id"),
|
||||
Some(harness.thread_id.to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
handshake.header(USER_AGENT_HEADER),
|
||||
@@ -161,6 +171,93 @@ async fn responses_websocket_streams_without_feature_flag_when_provider_supports
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn responses_websocket_sends_response_processed_when_feature_enabled() {
|
||||
skip_if_no_network!();
|
||||
|
||||
let server = start_websocket_server(vec![vec![
|
||||
vec![
|
||||
ev_response_created("resp-prewarm"),
|
||||
ev_completed("resp-prewarm"),
|
||||
],
|
||||
vec![
|
||||
ev_response_created("resp-1"),
|
||||
ev_assistant_message("msg-1", "hi"),
|
||||
ev_completed("resp-1"),
|
||||
],
|
||||
vec![],
|
||||
]])
|
||||
.await;
|
||||
|
||||
let mut builder = test_codex().with_config(|config| {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::ResponsesWebsocketResponseProcessed)
|
||||
.expect("test config should allow feature update");
|
||||
});
|
||||
let test = builder
|
||||
.build_with_websocket_server(&server)
|
||||
.await
|
||||
.expect("build websocket codex");
|
||||
|
||||
test.submit_turn("hello")
|
||||
.await
|
||||
.expect("submission should send response.processed after processing");
|
||||
|
||||
let processed = server
|
||||
.wait_for_request(/*connection_index*/ 0, /*request_index*/ 2)
|
||||
.await;
|
||||
assert_eq!(
|
||||
processed.body_json(),
|
||||
json!({
|
||||
"type": "response.processed",
|
||||
"response_id": "resp-1",
|
||||
})
|
||||
);
|
||||
|
||||
let connection = server.single_connection();
|
||||
assert_eq!(connection.len(), 3);
|
||||
assert_eq!(
|
||||
connection[1].body_json()["type"].as_str(),
|
||||
Some("response.create")
|
||||
);
|
||||
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn responses_websocket_omits_response_processed_without_feature() {
|
||||
skip_if_no_network!();
|
||||
|
||||
let server = start_websocket_server(vec![vec![
|
||||
vec![
|
||||
ev_response_created("resp-prewarm"),
|
||||
ev_completed("resp-prewarm"),
|
||||
],
|
||||
vec![
|
||||
ev_response_created("resp-1"),
|
||||
ev_assistant_message("msg-1", "hi"),
|
||||
ev_completed("resp-1"),
|
||||
],
|
||||
vec![],
|
||||
]])
|
||||
.await;
|
||||
let mut builder = test_codex();
|
||||
let test = builder
|
||||
.build_with_websocket_server(&server)
|
||||
.await
|
||||
.expect("build websocket codex");
|
||||
|
||||
test.submit_turn("hello")
|
||||
.await
|
||||
.expect("submission should complete without response.processed");
|
||||
|
||||
let connection = server.single_connection();
|
||||
assert_eq!(connection.len(), 2);
|
||||
|
||||
server.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn responses_websocket_reuses_connection_with_per_turn_trace_payloads() {
|
||||
skip_if_no_network!();
|
||||
@@ -1827,7 +1924,8 @@ async fn websocket_harness_with_provider_options(
|
||||
}
|
||||
let config = Arc::new(config);
|
||||
let model_info = codex_core::test_support::construct_model_info_offline(MODEL, &config);
|
||||
let conversation_id = ThreadId::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let session_id = SessionId::new();
|
||||
let auth_manager =
|
||||
codex_core::test_support::auth_manager_from_auth(CodexAuth::from_api_key("Test API Key"));
|
||||
let exporter = InMemoryMetricExporter::default();
|
||||
@@ -1837,7 +1935,7 @@ async fn websocket_harness_with_provider_options(
|
||||
)
|
||||
.expect("in-memory metrics client");
|
||||
let session_telemetry = SessionTelemetry::new(
|
||||
conversation_id,
|
||||
thread_id,
|
||||
MODEL,
|
||||
model_info.slug.as_str(),
|
||||
/*account_id*/ None,
|
||||
@@ -1853,7 +1951,8 @@ async fn websocket_harness_with_provider_options(
|
||||
let summary = ReasoningSummary::Auto;
|
||||
let client = ModelClient::new(
|
||||
/*auth_manager*/ None,
|
||||
conversation_id,
|
||||
session_id,
|
||||
thread_id,
|
||||
/*installation_id*/ TEST_INSTALLATION_ID.to_string(),
|
||||
provider.clone(),
|
||||
SessionSource::Exec,
|
||||
@@ -1866,7 +1965,8 @@ async fn websocket_harness_with_provider_options(
|
||||
WebsocketTestHarness {
|
||||
_codex_home: codex_home,
|
||||
client,
|
||||
conversation_id,
|
||||
session_id,
|
||||
thread_id,
|
||||
model_info,
|
||||
effort,
|
||||
summary,
|
||||
@@ -1935,7 +2035,7 @@ async fn stream_until_complete_with_request_metadata(
|
||||
&harness.session_telemetry,
|
||||
harness.effort,
|
||||
harness.summary,
|
||||
service_tier,
|
||||
service_tier.map(|service_tier| service_tier.request_value().to_string()),
|
||||
turn_metadata_header,
|
||||
&codex_rollout_trace::InferenceTraceContext::disabled(),
|
||||
)
|
||||
|
||||
@@ -7,6 +7,7 @@ use anyhow::Result;
|
||||
use codex_core::compact::SUMMARY_PREFIX;
|
||||
use codex_features::Feature;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_protocol::config_types::ServiceTier;
|
||||
use codex_protocol::dynamic_tools::DynamicToolSpec;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::models::ContentItem;
|
||||
@@ -105,6 +106,23 @@ fn contains_defer_loading(value: &Value) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn canonical_json(value: &Value) -> Value {
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
let mut entries = map.iter().collect::<Vec<_>>();
|
||||
entries.sort_by(|(left_key, _), (right_key, _)| left_key.cmp(right_key));
|
||||
Value::Object(
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|(key, value)| (key.clone(), canonical_json(value)))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
Value::Array(values) => Value::Array(values.iter().map(canonical_json).collect()),
|
||||
Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => value.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
const PRETURN_CONTEXT_DIFF_CWD: &str = "/tmp/PRETURN_CONTEXT_DIFF_CWD";
|
||||
const DUMMY_FUNCTION_NAME: &str = "test_tool";
|
||||
const REMOTE_COMPACT_TURN_COMPLETE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
@@ -273,6 +291,7 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> {
|
||||
.await?;
|
||||
let codex = harness.test().codex.clone();
|
||||
let session_id = harness.test().session_configured.session_id.to_string();
|
||||
let thread_id = harness.test().session_configured.thread_id.to_string();
|
||||
|
||||
let responses_mock = responses::mount_sse_sequence(
|
||||
harness.server(),
|
||||
@@ -341,6 +360,10 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> {
|
||||
compact_request.header("session_id").as_deref(),
|
||||
Some(session_id.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
compact_request.header("thread_id").as_deref(),
|
||||
Some(thread_id.as_str())
|
||||
);
|
||||
let compact_body = compact_request.body_json();
|
||||
assert_eq!(
|
||||
compact_body.get("model").and_then(|v| v.as_str()),
|
||||
@@ -412,6 +435,267 @@ async fn remote_compact_replaces_history_for_followups() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn assert_remote_manual_compact_request_parity(
|
||||
auth: CodexAuth,
|
||||
configured_service_tier: Option<ServiceTier>,
|
||||
expected_service_tier: Option<&str>,
|
||||
snapshot_name: &str,
|
||||
scenario: &str,
|
||||
) -> Result<()> {
|
||||
let mut builder = test_codex().with_auth(auth);
|
||||
if let Some(service_tier) = configured_service_tier {
|
||||
builder = builder.with_config(move |config| {
|
||||
config.service_tier = Some(service_tier.request_value().to_string());
|
||||
});
|
||||
}
|
||||
let harness = TestCodexHarness::with_builder(builder).await?;
|
||||
let codex = harness.test().codex.clone();
|
||||
let image_url =
|
||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGNgYAAAAAMAASsJTYQAAAAASUVORK5CYII="
|
||||
.to_string();
|
||||
|
||||
let responses_mock = responses::mount_sse_sequence(
|
||||
harness.server(),
|
||||
vec![
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("turn-one-assistant", "TURN_ONE_ASSISTANT"),
|
||||
responses::ev_completed("turn-one-response"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_reasoning_item(
|
||||
"turn-two-reasoning",
|
||||
&["TURN_TWO_REASONING"],
|
||||
&["turn two raw content"],
|
||||
),
|
||||
responses::ev_assistant_message("turn-two-assistant", "TURN_TWO_ASSISTANT"),
|
||||
responses::ev_completed("turn-two-response"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_function_call("turn-three-call", DUMMY_FUNCTION_NAME, "{}"),
|
||||
responses::ev_completed("turn-three-call-response"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("turn-three-assistant", "TURN_THREE_ASSISTANT"),
|
||||
responses::ev_completed("turn-three-final-response"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_local_shell_call(
|
||||
"turn-four-local-shell",
|
||||
"completed",
|
||||
vec!["/bin/echo", "TURN_FOUR_LOCAL_SHELL"],
|
||||
),
|
||||
responses::ev_completed("turn-four-local-shell-response"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("turn-four-assistant", "TURN_FOUR_ASSISTANT"),
|
||||
responses::ev_completed("turn-four-final-response"),
|
||||
]),
|
||||
responses::sse(vec![
|
||||
responses::ev_reasoning_item(
|
||||
"turn-five-reasoning",
|
||||
&["TURN_FIVE_REASONING"],
|
||||
&["turn five raw content"],
|
||||
),
|
||||
responses::ev_assistant_message("turn-five-assistant", "TURN_FIVE_ASSISTANT"),
|
||||
responses::ev_completed("turn-five-response"),
|
||||
]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let compact_mock = responses::mount_compact_user_history_with_summary_once(
|
||||
harness.server(),
|
||||
"REMOTE_CACHE_TIER_SUMMARY",
|
||||
)
|
||||
.await;
|
||||
|
||||
codex
|
||||
.submit(Op::UserInput {
|
||||
environments: None,
|
||||
items: vec![UserInput::Text {
|
||||
text: "TURN_ONE_USER".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
final_output_json_schema: None,
|
||||
responsesapi_client_metadata: None,
|
||||
})
|
||||
.await?;
|
||||
wait_for_turn_complete(&codex).await;
|
||||
|
||||
codex
|
||||
.submit(Op::UserInput {
|
||||
environments: None,
|
||||
items: vec![
|
||||
UserInput::Text {
|
||||
text: "TURN_TWO_PREFIX".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
},
|
||||
UserInput::Text {
|
||||
text: "TURN_TWO_SUFFIX".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
},
|
||||
],
|
||||
final_output_json_schema: None,
|
||||
responsesapi_client_metadata: None,
|
||||
})
|
||||
.await?;
|
||||
wait_for_turn_complete(&codex).await;
|
||||
|
||||
codex
|
||||
.submit(Op::UserInput {
|
||||
environments: None,
|
||||
items: vec![UserInput::Text {
|
||||
text: "TURN_THREE_TOOL_USER".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
final_output_json_schema: None,
|
||||
responsesapi_client_metadata: None,
|
||||
})
|
||||
.await?;
|
||||
wait_for_turn_complete(&codex).await;
|
||||
|
||||
codex
|
||||
.submit(Op::UserInput {
|
||||
environments: None,
|
||||
items: vec![
|
||||
UserInput::Image { image_url },
|
||||
UserInput::Text {
|
||||
text: "TURN_FOUR_IMAGE_USER".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
},
|
||||
],
|
||||
final_output_json_schema: None,
|
||||
responsesapi_client_metadata: None,
|
||||
})
|
||||
.await?;
|
||||
wait_for_turn_complete(&codex).await;
|
||||
|
||||
codex
|
||||
.submit(Op::UserInput {
|
||||
environments: None,
|
||||
items: vec![UserInput::Text {
|
||||
text: "TURN_FIVE_USER".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
final_output_json_schema: None,
|
||||
responsesapi_client_metadata: None,
|
||||
})
|
||||
.await?;
|
||||
wait_for_turn_complete(&codex).await;
|
||||
|
||||
codex.submit(Op::Compact).await?;
|
||||
wait_for_turn_complete(&codex).await;
|
||||
|
||||
let response_requests = responses_mock.requests();
|
||||
assert_eq!(
|
||||
response_requests.len(),
|
||||
7,
|
||||
"expected five turns with one unsupported tool continuation and one local shell continuation"
|
||||
);
|
||||
assert_eq!(
|
||||
compact_mock.requests().len(),
|
||||
1,
|
||||
"expected exactly one remote compact request"
|
||||
);
|
||||
let normal_request = response_requests
|
||||
.last()
|
||||
.cloned()
|
||||
.expect("last turn request missing");
|
||||
let compact_request = compact_mock.single_request();
|
||||
let normal_body = normal_request.body_json();
|
||||
let compact_body = compact_request.body_json();
|
||||
|
||||
let mut expected_compact_body_without_input = normal_body.clone();
|
||||
let expected_compact_object = expected_compact_body_without_input
|
||||
.as_object_mut()
|
||||
.expect("responses request body should be an object");
|
||||
for field in [
|
||||
"input",
|
||||
"client_metadata",
|
||||
"include",
|
||||
"store",
|
||||
"stream",
|
||||
"tool_choice",
|
||||
] {
|
||||
expected_compact_object.remove(field);
|
||||
}
|
||||
if expected_service_tier.is_none() {
|
||||
expected_compact_object.remove("service_tier");
|
||||
}
|
||||
let mut compact_body_without_input = compact_body.clone();
|
||||
compact_body_without_input
|
||||
.as_object_mut()
|
||||
.expect("compact request body should be an object")
|
||||
.remove("input");
|
||||
let canonical_compact_body_without_input = canonical_json(&compact_body_without_input);
|
||||
let canonical_expected_compact_body_without_input =
|
||||
canonical_json(&expected_compact_body_without_input);
|
||||
|
||||
assert_eq!(
|
||||
json!({
|
||||
"compact_body_without_input": canonical_compact_body_without_input,
|
||||
"expected_compact_body_without_input": canonical_expected_compact_body_without_input,
|
||||
"prompt_cache_key_matches_responses": compact_body["prompt_cache_key"] == normal_body["prompt_cache_key"],
|
||||
"prompt_cache_key_present": compact_body["prompt_cache_key"].is_string(),
|
||||
"service_tier": compact_body.get("service_tier").and_then(Value::as_str),
|
||||
}),
|
||||
json!({
|
||||
"compact_body_without_input": canonical_expected_compact_body_without_input,
|
||||
"expected_compact_body_without_input": canonical_expected_compact_body_without_input,
|
||||
"prompt_cache_key_matches_responses": true,
|
||||
"prompt_cache_key_present": true,
|
||||
"service_tier": expected_service_tier,
|
||||
}),
|
||||
"compact requests should carry the same shared request fields as /responses"
|
||||
);
|
||||
|
||||
insta::assert_snapshot!(
|
||||
snapshot_name,
|
||||
context_snapshot::format_request_body_diff_snapshot(
|
||||
scenario,
|
||||
"Last Normal /responses Request",
|
||||
&normal_request,
|
||||
"Remote /responses/compact Request",
|
||||
&compact_request,
|
||||
&ContextSnapshotOptions::default(),
|
||||
)
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn remote_manual_compact_api_auth_reuses_prompt_cache_key() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
assert_remote_manual_compact_request_parity(
|
||||
CodexAuth::from_api_key("dummy"),
|
||||
Some(ServiceTier::Fast),
|
||||
Some("priority"),
|
||||
"remote_manual_compact_api_auth_prompt_cache_key_request_diff",
|
||||
"After five varied API-key-auth turns, remote manual compaction reuses the normal responses service_tier and prompt_cache_key while omitting responses-only fields.",
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn remote_manual_compact_chatgpt_auth_reuses_service_tier_and_prompt_cache_key() -> Result<()>
|
||||
{
|
||||
skip_if_no_network!(Ok(()));
|
||||
|
||||
assert_remote_manual_compact_request_parity(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
Some(ServiceTier::Fast),
|
||||
Some("priority"),
|
||||
"remote_manual_compact_chatgpt_auth_service_tier_prompt_cache_key_request_diff",
|
||||
"After five varied ChatGPT-auth turns, remote manual compaction reuses the normal responses service_tier and prompt_cache_key while omitting responses-only fields.",
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn remote_compact_v2_reuses_context_compaction_for_followups() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
@@ -713,6 +997,7 @@ async fn remote_compact_runs_automatically() -> Result<()> {
|
||||
.await?;
|
||||
let codex = harness.test().codex.clone();
|
||||
let session_id = harness.test().session_configured.session_id.to_string();
|
||||
let thread_id = harness.test().session_configured.thread_id.to_string();
|
||||
|
||||
mount_sse_once(
|
||||
harness.server(),
|
||||
@@ -764,6 +1049,10 @@ async fn remote_compact_runs_automatically() -> Result<()> {
|
||||
.as_deref(),
|
||||
Some(session_id.as_str())
|
||||
);
|
||||
assert_eq!(
|
||||
compact_mock.single_request().header("thread_id").as_deref(),
|
||||
Some(thread_id.as_str())
|
||||
);
|
||||
let follow_up_request = responses_mock.single_request();
|
||||
let follow_up_body = follow_up_request.body_json().to_string();
|
||||
assert!(follow_up_body.contains("REMOTE_COMPACTED_SUMMARY"));
|
||||
|
||||
@@ -195,7 +195,7 @@ async fn fork_thread_from_history_does_not_require_source_rollout_path() {
|
||||
ForkSnapshot::Interrupted,
|
||||
test.config.clone(),
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
conversation_id: test.session_configured.session_id,
|
||||
conversation_id: test.session_configured.thread_id,
|
||||
history: source_items.clone(),
|
||||
rollout_path: None,
|
||||
}),
|
||||
|
||||
@@ -358,7 +358,7 @@ async fn image_generation_call_event_is_emitted() -> anyhow::Result<()> {
|
||||
let call_id = "ig_image_saved_to_temp_dir_default";
|
||||
let expected_saved_path = image_generation_artifact_path(
|
||||
config.codex_home.as_path(),
|
||||
&session_configured.session_id.to_string(),
|
||||
&session_configured.thread_id.to_string(),
|
||||
call_id,
|
||||
);
|
||||
let _ = std::fs::remove_file(&expected_saved_path);
|
||||
@@ -444,7 +444,7 @@ async fn image_generation_call_event_is_emitted_when_image_save_fails() -> anyho
|
||||
} = test_codex().build(&server).await?;
|
||||
let expected_saved_path = image_generation_artifact_path(
|
||||
config.codex_home.as_path(),
|
||||
&session_configured.session_id.to_string(),
|
||||
&session_configured.thread_id.to_string(),
|
||||
"ig_invalid",
|
||||
);
|
||||
let _ = std::fs::remove_file(&expected_saved_path);
|
||||
@@ -547,8 +547,8 @@ async fn agent_message_content_delta_has_item_metadata() -> anyhow::Result<()> {
|
||||
})
|
||||
.await;
|
||||
|
||||
let session_id = session_configured.session_id.to_string();
|
||||
assert_eq!(delta_event.thread_id, session_id);
|
||||
let thread_id = session_configured.thread_id.to_string();
|
||||
assert_eq!(delta_event.thread_id, thread_id);
|
||||
assert_eq!(delta_event.turn_id, started_turn_id);
|
||||
assert_eq!(delta_event.item_id, started_item.id);
|
||||
assert_eq!(delta_event.delta, "streamed response");
|
||||
@@ -614,7 +614,7 @@ async fn plan_mode_emits_plan_item_from_proposed_plan_block() -> anyhow::Result<
|
||||
|
||||
assert_eq!(
|
||||
plan_delta.thread_id,
|
||||
session_configured.session_id.to_string()
|
||||
session_configured.thread_id.to_string()
|
||||
);
|
||||
assert_eq!(plan_delta.delta, "- Step 1\n- Step 2\n");
|
||||
assert_eq!(plan_completed.text, "- Step 1\n- Step 2\n");
|
||||
|
||||
@@ -487,7 +487,7 @@ async fn generated_image_is_replayed_for_image_capable_models() -> Result<()> {
|
||||
let test = builder.build(&server).await?;
|
||||
let saved_path = image_generation_artifact_path(
|
||||
test.codex_home_path(),
|
||||
&test.session_configured.session_id.to_string(),
|
||||
&test.session_configured.thread_id.to_string(),
|
||||
"ig_123",
|
||||
);
|
||||
let _ = std::fs::remove_file(&saved_path);
|
||||
@@ -601,7 +601,7 @@ async fn model_change_from_generated_image_to_text_preserves_prior_generated_ima
|
||||
let test = builder.build(&server).await?;
|
||||
let saved_path = image_generation_artifact_path(
|
||||
test.codex_home_path(),
|
||||
&test.session_configured.session_id.to_string(),
|
||||
&test.session_configured.thread_id.to_string(),
|
||||
"ig_123",
|
||||
);
|
||||
let _ = std::fs::remove_file(&saved_path);
|
||||
@@ -717,7 +717,7 @@ async fn thread_rollback_after_generated_image_drops_entire_image_turn_history()
|
||||
let test = builder.build(&server).await?;
|
||||
let saved_path = image_generation_artifact_path(
|
||||
test.codex_home_path(),
|
||||
&test.session_configured.session_id.to_string(),
|
||||
&test.session_configured.thread_id.to_string(),
|
||||
"ig_rollback",
|
||||
);
|
||||
let _ = std::fs::remove_file(&saved_path);
|
||||
|
||||
@@ -164,11 +164,11 @@ async fn submit_queue_only_agent_mail(codex: &CodexThread, text: &str) {
|
||||
.await
|
||||
.unwrap_or_else(|err| panic!("submit queue-only agent mail: {err}"));
|
||||
codex
|
||||
.submit(Op::ListMcpTools)
|
||||
.submit(Op::RealtimeConversationListVoices)
|
||||
.await
|
||||
.unwrap_or_else(|err| panic!("submit list-mcp-tools barrier: {err}"));
|
||||
.unwrap_or_else(|err| panic!("submit list-voices barrier: {err}"));
|
||||
wait_for_event(codex, |event| {
|
||||
matches!(event, EventMsg::McpListToolsResponse(_))
|
||||
matches!(event, EventMsg::RealtimeConversationListVoicesResponse(_))
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
@@ -74,6 +74,7 @@ fn write_plugin_mcp_plugin(home: &TempDir, command: &str) {
|
||||
"mcpServers": {{
|
||||
"sample": {{
|
||||
"command": "{command}",
|
||||
"cwd": ".",
|
||||
"startup_timeout_sec": 60.0
|
||||
}}
|
||||
}}
|
||||
@@ -98,20 +99,6 @@ fn write_plugin_app_plugin(home: &TempDir) {
|
||||
.expect("write plugin app config");
|
||||
}
|
||||
|
||||
async fn build_plugin_test_codex(
|
||||
server: &MockServer,
|
||||
codex_home: Arc<TempDir>,
|
||||
) -> Result<Arc<codex_core::CodexThread>> {
|
||||
let mut builder = test_codex()
|
||||
.with_home(codex_home)
|
||||
.with_auth(CodexAuth::from_api_key("Test API Key"));
|
||||
Ok(builder
|
||||
.build(server)
|
||||
.await
|
||||
.expect("create new conversation")
|
||||
.codex)
|
||||
}
|
||||
|
||||
async fn build_analytics_plugin_test_codex(
|
||||
server: &MockServer,
|
||||
codex_home: Arc<TempDir>,
|
||||
@@ -447,34 +434,3 @@ async fn explicit_plugin_mentions_track_plugin_used_analytics() -> Result<()> {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
|
||||
async fn plugin_mcp_tools_are_listed() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
let server = start_mock_server().await;
|
||||
let codex_home = Arc::new(TempDir::new()?);
|
||||
let rmcp_test_server_bin = stdio_server_bin()?;
|
||||
write_plugin_mcp_plugin(codex_home.as_ref(), &rmcp_test_server_bin);
|
||||
let codex = build_plugin_test_codex(&server, codex_home).await?;
|
||||
wait_for_sample_mcp_ready(&codex).await?;
|
||||
|
||||
codex.submit(Op::ListMcpTools).await?;
|
||||
let list_event = wait_for_event_with_timeout(
|
||||
&codex,
|
||||
|ev| matches!(ev, EventMsg::McpListToolsResponse(_)),
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await;
|
||||
let EventMsg::McpListToolsResponse(tool_list) = list_event else {
|
||||
unreachable!("event guard guarantees McpListToolsResponse");
|
||||
};
|
||||
let mut available_tools: Vec<&str> = tool_list.tools.keys().map(String::as_str).collect();
|
||||
available_tools.sort_unstable();
|
||||
assert!(
|
||||
tool_list.tools.contains_key("mcp__sample__echo")
|
||||
&& tool_list.tools.contains_key("mcp__sample__image"),
|
||||
"expected plugin MCP tools to be listed; discovered tools: {available_tools:?}"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -242,31 +242,42 @@ fn copy_binary_to_remote_env(
|
||||
Ok(remote_path)
|
||||
}
|
||||
|
||||
async fn wait_for_mcp_tool(fixture: &TestCodex, tool_name: &str) -> anyhow::Result<()> {
|
||||
let tools_ready_deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
fixture.codex.submit(Op::ListMcpTools).await?;
|
||||
let list_event = wait_for_event_with_timeout(
|
||||
&fixture.codex,
|
||||
|ev| matches!(ev, EventMsg::McpListToolsResponse(_)),
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await;
|
||||
let EventMsg::McpListToolsResponse(tool_list) = list_event else {
|
||||
unreachable!("event guard guarantees McpListToolsResponse");
|
||||
};
|
||||
if tool_list.tools.contains_key(tool_name) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let available_tools: Vec<&str> = tool_list.tools.keys().map(String::as_str).collect();
|
||||
if Instant::now() >= tools_ready_deadline {
|
||||
panic!(
|
||||
"timed out waiting for MCP tool {tool_name} to become available; discovered tools: {available_tools:?}"
|
||||
);
|
||||
}
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
async fn wait_for_mcp_server(fixture: &TestCodex, server_name: &str) -> anyhow::Result<()> {
|
||||
let startup_event = wait_for_event_with_timeout(
|
||||
&fixture.codex,
|
||||
|ev| match ev {
|
||||
EventMsg::McpStartupComplete(summary) => {
|
||||
summary.ready.iter().any(|server| server == server_name)
|
||||
|| summary
|
||||
.failed
|
||||
.iter()
|
||||
.any(|failure| failure.server == server_name)
|
||||
|| summary.cancelled.iter().any(|server| server == server_name)
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
Duration::from_secs(70),
|
||||
)
|
||||
.await;
|
||||
let EventMsg::McpStartupComplete(summary) = startup_event else {
|
||||
unreachable!("event guard guarantees McpStartupComplete");
|
||||
};
|
||||
if let Some(failure) = summary
|
||||
.failed
|
||||
.iter()
|
||||
.find(|failure| failure.server == server_name)
|
||||
{
|
||||
let error = &failure.error;
|
||||
anyhow::bail!("MCP server {server_name} failed to start: {error}");
|
||||
}
|
||||
if summary.cancelled.iter().any(|server| server == server_name) {
|
||||
anyhow::bail!("MCP server {server_name} startup was cancelled");
|
||||
}
|
||||
ensure!(
|
||||
summary.ready.iter().any(|server| server == server_name),
|
||||
"expected MCP server {server_name} to be ready; startup summary: {summary:?}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -731,7 +742,6 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta() -> anyhow::Result<()>
|
||||
let call_id = "sandbox-meta-call";
|
||||
let server_name = "rmcp";
|
||||
let namespace = format!("mcp__{server_name}__");
|
||||
let tool_name = format!("{namespace}sandbox_meta");
|
||||
|
||||
let call_mock = mount_sse_once(
|
||||
&server,
|
||||
@@ -767,30 +777,7 @@ async fn stdio_mcp_tool_call_includes_sandbox_state_meta() -> anyhow::Result<()>
|
||||
.build_remote_aware(&server)
|
||||
.await?;
|
||||
|
||||
let tools_ready_deadline = Instant::now() + Duration::from_secs(30);
|
||||
loop {
|
||||
fixture.codex.submit(Op::ListMcpTools).await?;
|
||||
let list_event = wait_for_event_with_timeout(
|
||||
&fixture.codex,
|
||||
|ev| matches!(ev, EventMsg::McpListToolsResponse(_)),
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await;
|
||||
let EventMsg::McpListToolsResponse(tool_list) = list_event else {
|
||||
unreachable!("event guard guarantees McpListToolsResponse");
|
||||
};
|
||||
if tool_list.tools.contains_key(&tool_name) {
|
||||
break;
|
||||
}
|
||||
|
||||
let available_tools: Vec<&str> = tool_list.tools.keys().map(String::as_str).collect();
|
||||
if Instant::now() >= tools_ready_deadline {
|
||||
panic!(
|
||||
"timed out waiting for MCP tool {tool_name} to become available; discovered tools: {available_tools:?}"
|
||||
);
|
||||
}
|
||||
sleep(Duration::from_millis(200)).await;
|
||||
}
|
||||
wait_for_mcp_server(&fixture, server_name).await?;
|
||||
|
||||
fixture
|
||||
.submit_turn_with_permission_profile(
|
||||
@@ -1039,7 +1026,6 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> {
|
||||
|
||||
let call_id = "img-1";
|
||||
let server_name = "rmcp";
|
||||
let tool_name = format!("mcp__{server_name}__image");
|
||||
let namespace = format!("mcp__{server_name}__");
|
||||
|
||||
// First stream: model decides to call the image tool.
|
||||
@@ -1086,7 +1072,7 @@ async fn stdio_image_responses_round_trip() -> anyhow::Result<()> {
|
||||
})
|
||||
.build_remote_aware(&server)
|
||||
.await?;
|
||||
wait_for_mcp_tool(&fixture, &tool_name).await?;
|
||||
wait_for_mcp_server(&fixture, server_name).await?;
|
||||
|
||||
fixture
|
||||
.codex
|
||||
@@ -1176,7 +1162,6 @@ async fn stdio_image_responses_preserve_original_detail_metadata() -> anyhow::Re
|
||||
|
||||
let call_id = "img-original-detail-1";
|
||||
let server_name = "rmcp";
|
||||
let tool_name = format!("mcp__{server_name}__image_scenario");
|
||||
let namespace = format!("mcp__{server_name}__");
|
||||
|
||||
mount_sse_once(
|
||||
@@ -1219,7 +1204,7 @@ async fn stdio_image_responses_preserve_original_detail_metadata() -> anyhow::Re
|
||||
})
|
||||
.build_remote_aware(&server)
|
||||
.await?;
|
||||
wait_for_mcp_tool(&fixture, &tool_name).await?;
|
||||
wait_for_mcp_server(&fixture, server_name).await?;
|
||||
|
||||
fixture
|
||||
.codex
|
||||
@@ -1955,7 +1940,6 @@ async fn streamable_http_with_oauth_round_trip_impl() -> anyhow::Result<()> {
|
||||
|
||||
let call_id = "call-789";
|
||||
let server_name = "rmcp_http_oauth";
|
||||
let tool_name = format!("mcp__{server_name}__echo");
|
||||
let namespace = format!("mcp__{server_name}__");
|
||||
|
||||
mount_sse_once(
|
||||
@@ -2036,9 +2020,9 @@ async fn streamable_http_with_oauth_round_trip_impl() -> anyhow::Result<()> {
|
||||
})
|
||||
.build_remote_aware(&server)
|
||||
.await?;
|
||||
// Phase 5: wait for MCP discovery to publish the expected tool before the
|
||||
// turn is submitted, which keeps failures tied to server startup/discovery.
|
||||
wait_for_mcp_tool(&fixture, &tool_name).await?;
|
||||
// Phase 5: wait for MCP startup before the turn is submitted, which keeps
|
||||
// failures tied to server startup/discovery.
|
||||
wait_for_mcp_server(&fixture, server_name).await?;
|
||||
|
||||
// Phase 6: submit the user turn that should invoke the OAuth-backed tool.
|
||||
fixture
|
||||
|
||||
@@ -598,6 +598,10 @@ async fn tool_search_returns_deferred_tools_without_follow_up_tool_injection() -
|
||||
apps_tool_call.pointer("/params/_meta/x-codex-turn-metadata/session_id"),
|
||||
Some(&json!(test.session_configured.session_id.to_string()))
|
||||
);
|
||||
assert_eq!(
|
||||
apps_tool_call.pointer("/params/_meta/x-codex-turn-metadata/thread_id"),
|
||||
Some(&json!(test.session_configured.thread_id.to_string()))
|
||||
);
|
||||
assert!(
|
||||
apps_tool_call
|
||||
.pointer("/params/_meta/x-codex-turn-metadata/turn_id")
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
---
|
||||
source: core/tests/suite/compact_remote.rs
|
||||
expression: "context_snapshot::format_request_body_diff_snapshot(scenario,\n\"Last Normal /responses Request\", &normal_request,\n\"Remote /responses/compact Request\", &compact_request,\n&ContextSnapshotOptions::default(),)"
|
||||
---
|
||||
Scenario: After five varied API-key-auth turns, remote manual compaction reuses the normal responses service_tier and prompt_cache_key while omitting responses-only fields.
|
||||
|
||||
--- Last Normal /responses Request
|
||||
+++ Remote /responses/compact Request
|
||||
- "client_metadata": {
|
||||
- "x-codex-installation-id": "<UUID>"
|
||||
- },
|
||||
- "include": [
|
||||
- "reasoning.encrypted_content"
|
||||
- ],
|
||||
+ },
|
||||
+ {
|
||||
+ "content": [
|
||||
+ {
|
||||
+ "text": "turn five raw content",
|
||||
+ "type": "reasoning_text"
|
||||
+ }
|
||||
+ ],
|
||||
+ "encrypted_content": "YmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYnR1cm4gZml2ZSByYXcgY29udGVudA==",
|
||||
+ "summary": [
|
||||
+ {
|
||||
+ "text": "TURN_FIVE_REASONING",
|
||||
+ "type": "summary_text"
|
||||
+ }
|
||||
+ ],
|
||||
+ "type": "reasoning"
|
||||
+ },
|
||||
+ {
|
||||
+ "content": [
|
||||
+ {
|
||||
+ "text": "TURN_FIVE_ASSISTANT",
|
||||
+ "type": "output_text"
|
||||
+ }
|
||||
+ ],
|
||||
+ "role": "assistant",
|
||||
+ "type": "message"
|
||||
- "store": false,
|
||||
- "stream": true,
|
||||
- "tool_choice": "auto",
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
---
|
||||
source: core/tests/suite/compact_remote.rs
|
||||
expression: "context_snapshot::format_request_body_diff_snapshot(scenario,\n\"Last Normal /responses Request\", &normal_request,\n\"Remote /responses/compact Request\", &compact_request,\n&ContextSnapshotOptions::default(),)"
|
||||
---
|
||||
Scenario: After five varied ChatGPT-auth turns, remote manual compaction reuses the normal responses service_tier and prompt_cache_key while omitting responses-only fields.
|
||||
|
||||
--- Last Normal /responses Request
|
||||
+++ Remote /responses/compact Request
|
||||
- "client_metadata": {
|
||||
- "x-codex-installation-id": "<UUID>"
|
||||
- },
|
||||
- "include": [
|
||||
- "reasoning.encrypted_content"
|
||||
- ],
|
||||
+ },
|
||||
+ {
|
||||
+ "content": [
|
||||
+ {
|
||||
+ "text": "turn five raw content",
|
||||
+ "type": "reasoning_text"
|
||||
+ }
|
||||
+ ],
|
||||
+ "encrypted_content": "YmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYmJiYnR1cm4gZml2ZSByYXcgY29udGVudA==",
|
||||
+ "summary": [
|
||||
+ {
|
||||
+ "text": "TURN_FIVE_REASONING",
|
||||
+ "type": "summary_text"
|
||||
+ }
|
||||
+ ],
|
||||
+ "type": "reasoning"
|
||||
+ },
|
||||
+ {
|
||||
+ "content": [
|
||||
+ {
|
||||
+ "text": "TURN_FIVE_ASSISTANT",
|
||||
+ "type": "output_text"
|
||||
+ }
|
||||
+ ],
|
||||
+ "role": "assistant",
|
||||
+ "type": "message"
|
||||
- "store": false,
|
||||
- "stream": true,
|
||||
- "tool_choice": "auto",
|
||||
@@ -48,7 +48,7 @@ async fn new_thread_is_recorded_in_state_db() -> Result<()> {
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
|
||||
let thread_id = test.session_configured.session_id;
|
||||
let thread_id = test.session_configured.thread_id;
|
||||
let rollout_path = test.codex.rollout_path().expect("rollout path");
|
||||
let db_path = codex_state::state_db_path(test.config.sqlite_home.as_path());
|
||||
|
||||
@@ -262,7 +262,7 @@ async fn user_messages_persist_in_state_db() -> Result<()> {
|
||||
test.submit_turn("another message").await?;
|
||||
|
||||
let db = test.codex.state_db().expect("state db enabled");
|
||||
let thread_id = test.session_configured.session_id;
|
||||
let thread_id = test.session_configured.thread_id;
|
||||
|
||||
let mut metadata = None;
|
||||
for _ in 0..100 {
|
||||
@@ -305,7 +305,7 @@ async fn web_search_marks_thread_memory_mode_polluted_when_configured() -> Resul
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
let db = test.codex.state_db().expect("state db enabled");
|
||||
let thread_id = test.session_configured.session_id;
|
||||
let thread_id = test.session_configured.thread_id;
|
||||
|
||||
test.submit_turn("search the web").await?;
|
||||
|
||||
@@ -397,7 +397,7 @@ async fn mcp_call_marks_thread_memory_mode_polluted_when_configured() -> Result<
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
let db = test.codex.state_db().expect("state db enabled");
|
||||
let thread_id = test.session_configured.session_id;
|
||||
let thread_id = test.session_configured.thread_id;
|
||||
let cwd = test.cwd_path().to_path_buf();
|
||||
let (sandbox_policy, permission_profile) =
|
||||
turn_permission_fields(PermissionProfile::read_only(), cwd.as_path());
|
||||
@@ -478,7 +478,7 @@ async fn tool_call_logs_include_thread_id() -> Result<()> {
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
let db = test.codex.state_db().expect("state db enabled");
|
||||
let expected_thread_id = test.session_configured.session_id.to_string();
|
||||
let expected_thread_id = test.session_configured.thread_id.to_string();
|
||||
|
||||
test.submit_turn("run a shell command").await?;
|
||||
|
||||
|
||||
@@ -116,7 +116,7 @@ async fn wait_for_spawned_thread_id(test: &TestCodex) -> Result<String> {
|
||||
let ids = test.thread_manager.list_thread_ids().await;
|
||||
if let Some(spawned_id) = ids
|
||||
.iter()
|
||||
.find(|id| **id != test.session_configured.session_id)
|
||||
.find(|id| **id != test.session_configured.thread_id)
|
||||
{
|
||||
return Ok(spawned_id.to_string());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user