aKode fase 2c: eliminato il codice di invio dati (crate analytics, otel-trace-websocket, sentry, esportatori OTLP); /feedback salva solo in locale; chiavi legacy [analytics]/[otel] accettate e ignorate; test di analytics/OTLP/upload rimossi
Some checks failed
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (push) Has been cancelled
blocking-ci / Bazel (push) Has been cancelled
blocking-ci / Blob size policy (push) Has been cancelled
blocking-ci / cargo-deny (push) Has been cancelled
blocking-ci / Codespell (push) Has been cancelled
blocking-ci / repo-checks (push) Has been cancelled
postmerge-ci / rust-ci-full (push) Has been cancelled
postmerge-ci / v8-canary (push) Has been cancelled
postmerge-ci / Postmerge CI results (push) Has been cancelled

This commit is contained in:
Andrea
2026-11-09 18:45:41 +01:00
parent 981745ccc8
commit 60532b6337
509 changed files with 2043 additions and 46606 deletions

View File

@@ -2289,7 +2289,6 @@ async fn login_account_chatgpt_device_code_succeeds_and_notifies() -> Result<()>
},
)?;
write_models_cache(codex_home.path()).await?;
let collector = super::auth_storage_originator::configure_collector(codex_home.path()).await?;
mock_device_code_usercode(&mock_server, /*interval_seconds*/ 0).await;
mock_device_code_token_success(&mock_server).await;
@@ -2308,7 +2307,6 @@ async fn login_account_chatgpt_device_code_succeeds_and_notifies() -> Result<()>
.without_auto_env()
.with_env_overrides(&[
("OPENAI_API_KEY", None),
("OTEL_METRIC_EXPORT_INTERVAL", Some("200")),
(LOGIN_ISSUER_ENV_VAR, Some(issuer.as_str())),
])
.build()
@@ -2362,7 +2360,6 @@ async fn login_account_chatgpt_device_code_succeeds_and_notifies() -> Result<()>
codex_home.path().join("auth.json").exists(),
"auth.json should be created when device code login succeeds"
);
super::auth_storage_originator::assert_saved_originators(&collector, &["codex_vscode"]).await?;
Ok(())
}

View File

@@ -420,8 +420,7 @@ async fn enterprise_login_attempt_lifecycle() -> Result<()> {
.with_root_config(&format!(
r#"cli_auth_credentials_store = "file"
chatgpt_base_url = "{origin}/backend-api"
mcp_oauth_callback_port = {callback_port}
analytics = {{ enabled = false }}"#
mcp_oauth_callback_port = {callback_port}"#
))
.with_provider_config("requires_openai_auth = true")
.with_extra_config(&format!(
@@ -1678,8 +1677,7 @@ async fn enterprise_login_setup_is_cancelled_by_account_changes() -> Result<()>
.with_root_config(&format!(
r#"cli_auth_credentials_store = "file"
chatgpt_base_url = "{origin}/backend-api"
mcp_oauth_callback_port = {callback_port}
analytics = {{ enabled = false }}"#
mcp_oauth_callback_port = {callback_port}"#
))
.with_provider_config("requires_openai_auth = true")
.with_extra_config(&format!(

File diff suppressed because it is too large Load Diff

View File

@@ -1,252 +0,0 @@
//! Checks client attribution on exported storage metrics through the public RPC API.
use super::connection_handling_websocket::connect_websocket;
use super::connection_handling_websocket::read_response_for_id;
use super::connection_handling_websocket::send_initialize_request;
use super::connection_handling_websocket::send_request;
use super::connection_handling_websocket::spawn_websocket_server;
use anyhow::Context;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
use app_test_support::write_chatgpt_auth;
use app_test_support::write_models_cache;
use codex_app_server_protocol::ClientInfo;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::TurnCompletedNotification;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::UserInput;
use codex_login::AuthCredentialsStoreMode;
use codex_login::REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR;
use core_test_support::responses;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;
use std::time::Duration;
use tempfile::TempDir;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
pub(super) async fn configure_collector(codex_home: &Path) -> Result<MockServer> {
let collector = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/v1/metrics"))
.respond_with(ResponseTemplate::new(/*s*/ 200))
.mount(&collector)
.await;
let endpoint = format!("{}/v1/metrics", collector.uri());
let mut config = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(codex_home.join("config.toml"))?;
writeln!(
config,
"\n[analytics]\nenabled = true\n[otel.metrics_exporter.otlp-http]\nendpoint = {endpoint:?}\nprotocol = \"json\""
)?;
Ok(collector)
}
pub(super) async fn assert_saved_originators(
collector: &MockServer,
expected: &[&str],
) -> Result<()> {
let expected: BTreeMap<_, _> = expected
.iter()
.map(|value| (value.to_string(), 1_u64))
.collect();
let actual = tokio::time::timeout(Duration::from_secs(/*secs*/ 60), async {
loop {
let mut actual = BTreeMap::<String, u64>::new();
for request in collector.received_requests().await.unwrap_or_default() {
let body: Value = serde_json::from_slice(&request.body)?;
for resource in body["resourceMetrics"].as_array().into_iter().flatten() {
for scope in resource["scopeMetrics"].as_array().into_iter().flatten() {
for metric in scope["metrics"].as_array().into_iter().flatten() {
if metric["name"] != "codex.auth_storage.operation" {
continue;
}
for point in
metric["sum"]["dataPoints"].as_array().into_iter().flatten()
{
let tags: BTreeMap<_, _> = point["attributes"]
.as_array()
.into_iter()
.flatten()
.filter_map(|tag| {
Some((
tag["key"].as_str()?,
tag["value"]["stringValue"].as_str()?,
))
})
.collect();
if tags.get("credential_kind") == Some(&"codex")
&& tags.get("operation") == Some(&"save")
{
let count = point["asInt"]
.as_u64()
.or_else(|| point["asInt"].as_str()?.parse().ok())
.context("storage count must be an integer")?;
*actual
.entry(
tags.get("originator")
.unwrap_or(&"missing")
.to_string(),
)
.or_default() += count;
}
}
}
}
}
}
if actual.values().sum::<u64>() >= expected.len() as u64 {
break Ok::<_, anyhow::Error>(actual);
}
tokio::time::sleep(Duration::from_millis(/*millis*/ 25)).await;
}
})
.await??;
assert_eq!(actual, expected);
Ok(())
}
#[tokio::test]
async fn concurrent_connections_export_their_own_storage_originator() -> Result<()> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
"cli_auth_credentials_store = \"file\"\n",
)?;
let collector = configure_collector(codex_home.path()).await?;
let (_process, address) = spawn_websocket_server(codex_home.path()).await?;
let mut clients = Vec::new();
for name in ["Codex Desktop", "codex_vscode", "private-client-name"] {
let mut client = connect_websocket(address).await?;
send_initialize_request(&mut client, /*id*/ 1, name).await?;
read_response_for_id(&mut client, /*id*/ 1).await?;
clients.push(client);
}
// All clients initialize before any storage request; a process-global identity fails this test.
for client in &mut clients {
send_request(
client,
"account/login/start",
/*id*/ 2,
Some(json!({"type": "apiKey", "apiKey": "sk-test-key"})),
)
.await?;
}
for client in &mut clients {
let response = read_response_for_id(client, /*id*/ 2).await?;
assert_eq!(response.result, json!({"type": "apiKey"}));
}
assert_saved_originators(&collector, &["codex_desktop", "codex_vscode", "other"]).await
}
#[tokio::test]
async fn turn_token_refresh_exports_thread_storage_originator() -> Result<()> {
let codex_home = TempDir::new()?;
let backend = MockServer::start().await;
MockResponsesConfig::new(&backend.uri())
.with_root_config("cli_auth_credentials_store = \"file\"")
.with_provider_config("requires_openai_auth = true")
.write(codex_home.path())?;
write_models_cache(codex_home.path()).await?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("initial-access-token")
.account_id("account-123")
.chatgpt_user_id("user-123"),
AuthCredentialsStoreMode::File,
)?;
let collector = configure_collector(codex_home.path()).await?;
Mock::given(method("POST"))
.and(path("/oauth/token"))
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"access_token": "refreshed-access-token",
"refresh_token": "refreshed-refresh-token",
})))
.expect(/*r*/ 1)
.mount(&backend)
.await;
// Fresh credentials prevent startup refresh. The turn first reloads storage on 401,
// then refreshes and persists the tokens when the retry is also unauthorized.
let responses_mock = responses::mount_response_sequence(
&backend,
vec![
ResponseTemplate::new(/*s*/ 401),
ResponseTemplate::new(/*s*/ 401),
responses::sse_response(responses::sse(vec![
responses::ev_response_created("resp-turn"),
responses::ev_completed("resp-turn"),
])),
],
)
.await;
let refresh_url = format!("{}/oauth/token", backend.uri());
let mut server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.with_env_overrides(&[
("OPENAI_API_KEY", None),
(
REFRESH_TOKEN_URL_OVERRIDE_ENV_VAR,
Some(refresh_url.as_str()),
),
])
.build()
.await?;
server
.initialize_with_client_info(ClientInfo {
name: "codex_vscode".to_string(),
title: None,
version: "0.1.0".to_string(),
})
.await?;
let request = server
.send_thread_start_request_with_auto_env(ThreadStartParams::default())
.await?;
let thread: ThreadStartResponse = server.read_response(request).await?;
let request = server
.send_turn_start_request(TurnStartParams {
thread_id: thread.thread.id,
input: vec![UserInput::Text {
text: "Hello".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let _: TurnStartResponse = server.read_response(request).await?;
let notification = server
.read_stream_until_notification_message("turn/completed")
.await?;
let completed: TurnCompletedNotification =
serde_json::from_value(notification.params.context("turn/completed params")?)?;
assert_eq!(completed.turn.status, TurnStatus::Completed);
assert_eq!(
responses_mock
.requests()
.iter()
.map(|request| request.header("authorization"))
.collect::<Vec<_>>(),
vec![
Some("Bearer initial-access-token".to_string()),
Some("Bearer initial-access-token".to_string()),
Some("Bearer refreshed-access-token".to_string()),
]
);
assert_saved_originators(&collector, &["codex_vscode"]).await?;
backend.verify().await;
Ok(())
}

View File

@@ -30,10 +30,6 @@ use std::collections::HashMap;
use tempfile::TempDir;
use tokio::time::timeout;
use super::analytics::captured_analytics_events;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_analytics_event;
// Bazel CI can spend tens of seconds starting app-server subprocesses or
// processing turn RPCs under load.
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
@@ -341,7 +337,6 @@ async fn turn_start_sends_nested_subagent_lineage_after_cold_thread_resume_v2()
.with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri()))
.with_provider_config("supports_websockets = false")
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let root_thread_id = CoreThreadId::new();
let root_thread_id_str = root_thread_id.to_string();
@@ -419,32 +414,7 @@ async fn turn_start_sends_nested_subagent_lineage_after_cold_thread_resume_v2()
assert_eq!(metadata["turn_id"].as_str(), Some(turn.id.as_str()));
assert!(metadata.get("forked_from_thread_id").is_none());
let turn_event =
wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?;
let params = &turn_event["event_params"];
assert_eq!(
(
params["total_tool_call_count"].as_u64(),
params["web_search_count"].as_u64()
),
(Some(1), Some(1))
);
timeout(DEFAULT_READ_TIMEOUT, mcp.shutdown_gracefully()).await??;
let events = captured_analytics_events(&server).await;
let count = |event_type: &str| {
events
.iter()
.filter(|event| {
event["event_type"] == event_type
&& event["event_params"]["thread_id"] == thread.id
&& event["event_params"]["turn_id"] == turn.id
})
.count()
};
assert_eq!(
(count("codex_turn_event"), count("codex_web_search_event")),
(1, 1)
);
Ok(())
}
@@ -478,7 +448,6 @@ async fn turn_steer_updates_client_metadata_on_follow_up_responses_request_v2(
.with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri()))
.with_provider_config("supports_websockets = false")
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -602,15 +571,6 @@ async fn turn_steer_updates_client_metadata_on_follow_up_responses_request_v2(
first_metadata["misalignment_override"],
);
let event = wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?;
assert_eq!(
(
event["event_params"]["turn_trigger"].as_str(),
event["event_params"]["codex_turn_source"].as_str(),
),
(Some("user"), Some("steer-source"))
);
Ok(())
}

View File

@@ -44,10 +44,6 @@ use std::collections::BTreeMap;
use tempfile::TempDir;
use test_case::test_case;
use tokio::time::timeout;
use wiremock::ResponseTemplate;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_matching_analytics_event;
// macOS and Windows Bazel CI can spend tens of seconds starting app-server
// subprocesses or processing test RPCs under load.
@@ -274,96 +270,6 @@ async fn prediction_context_failure_does_not_compact(reset_context: bool) -> Res
Ok(())
}
#[test_case(CompactionRoute::Local, Some(300), 429, "usage_limit_reached"; "local five hour")]
#[test_case(CompactionRoute::Remote, Some(10_080), 429, "usage_limit_reached"; "remote weekly")]
#[test_case(CompactionRoute::Local, None, 429, "usage_limit_reached"; "missing window")]
#[test_case(CompactionRoute::Remote, Some(300), 400, "invalid_request"; "other error")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn compaction_error_window_reaches_analytics(
route: CompactionRoute,
window: Option<u16>,
status: u16,
expected_error: &str,
) -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let seed = responses::sse(vec![
responses::ev_assistant_message("seed", "FIRST_REPLY"),
responses::ev_completed_with_tokens("seed", /*total_tokens*/ 120),
]);
let mut error = json!({
"type": if status == 429 { "usage_limit_reached" } else { "invalid_request_error" },
"message": "request failed",
});
if let Some(window) = window {
error["limit_window_minutes"] = json!(window);
}
let _requests = responses::mount_response_sequence(
&server,
vec![
responses::sse_response(seed),
ResponseTemplate::new(status).set_body_json(json!({ "error": error })),
],
)
.await;
let codex_home = TempDir::new()?;
let mut config = compaction_config(&server.uri(), /*auto_compact_limit*/ 1_000_000)
.with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri()));
if let CompactionRoute::Remote = route {
config = config
.with_provider_name("OpenAI")
.with_provider_config("requires_openai_auth = true");
}
config.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.without_managed_config()
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
.await?;
let thread_id = start_thread(&mut mcp).await?;
send_turn_and_wait(&mut mcp, &thread_id, "seed history").await?;
let compact_id = mcp
.send_thread_compact_start_request(ThreadCompactStartParams {
thread_id: thread_id.clone(),
})
.await?;
let _: ThreadCompactStartResponse =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(compact_id)).await??;
let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_compaction_event"
&& event["event_params"]["thread_id"] == thread_id
})
.await?;
let params = &event["event_params"];
let implementation = match route {
CompactionRoute::Local => "responses",
CompactionRoute::Remote => "responses_compaction_v2",
};
let expected_window = if status == 429 { window } else { None };
assert_eq!(
json!([
params["implementation"],
params["phase"],
params["status"],
params["codex_error_kind"],
params["usage_limit_window_minutes"],
]),
json!([
implementation,
"standalone_turn",
"failed",
expected_error,
expected_window
])
);
Ok(())
}
#[test_case(CompactionRoute::Local; "local")]
#[test_case(CompactionRoute::Remote; "streamed remote")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]

View File

@@ -600,118 +600,14 @@ async fn config_read_disables_guardian_v2_when_managed_config_requires_guardian_
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn managed_otel_tracestate_merges_fields_and_protects_only_required_fields() -> Result<()> {
let codex_home = TempDir::new()?;
write_config(
&codex_home,
r#"[otel.tracestate.vendor]
tenant = "user"
region = "us"
"#,
)?;
std::fs::write(
codex_home.path().join("requirements.toml"),
"[otel.tracestate.vendor]\ntenant = \"enterprise\"\n",
)?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
.await?;
let read_id = app_server
.send_config_read_request(ConfigReadParams {
include_layers: false,
cwd: None,
})
.await?;
let response: ConfigReadResponse =
timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(read_id)).await??;
assert_eq!(
response.config.additional["otel"]["tracestate"],
json!({ "vendor": { "tenant": "enterprise", "region": "us" } }),
);
assert!(
!response
.origins
.contains_key("otel.tracestate.vendor.tenant")
);
assert!(
response
.origins
.contains_key("otel.tracestate.vendor.region")
);
let write_id = app_server
.send_config_value_write_request(ConfigValueWriteParams {
file_path: None,
key_path: "otel.tracestate.vendor.region".to_string(),
value: json!("eu"),
merge_strategy: MergeStrategy::Replace,
expected_version: None,
})
.await?;
let _: ConfigWriteResponse =
timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(write_id)).await??;
for key_path in [
"otel.tracestate.vendor.tenant",
"otel.tracestate.vendor",
"otel.tracestate",
] {
let write_id = app_server
.send_config_value_write_request(ConfigValueWriteParams {
file_path: None,
key_path: key_path.to_string(),
value: json!("user"),
merge_strategy: MergeStrategy::Replace,
expected_version: None,
})
.await?;
let error: JSONRPCError = timeout(
DEFAULT_READ_TIMEOUT,
app_server.read_stream_until_error_message(RequestId::Integer(write_id)),
)
.await??;
assert_eq!(
error
.error
.data
.as_ref()
.and_then(|data| data.get("config_write_error_code")),
Some(&json!("configRequirementReadonly")),
"{key_path}",
);
}
let read_id = app_server
.send_config_read_request(ConfigReadParams {
include_layers: false,
cwd: None,
})
.await?;
let response: ConfigReadResponse =
timeout(DEFAULT_READ_TIMEOUT, app_server.read_response(read_id)).await??;
assert_eq!(
response.config.additional["otel"]["tracestate"],
json!({ "vendor": { "tenant": "enterprise", "region": "eu" } }),
);
Ok(())
}
#[test_case::test_case("json", "none"; "json_and_disabled_metrics")]
#[test_case::test_case("binary", "statsig"; "binary_and_statsig_metrics")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn config_requirements_read_redacts_otel_exporter_headers(
protocol: &str,
metrics_exporter: &str,
) -> Result<()> {
async fn config_requirements_read_ignores_legacy_otel_exporters() -> Result<()> {
let codex_home = TempDir::new()?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
.await?;
// Read policy without starting exporters or opening the example TLS files.
// Legacy exporter keys still parse but are ignored and never echoed back.
std::fs::write(
codex_home.path().join("requirements.toml"),
r#"[otel]
@@ -721,13 +617,11 @@ log_sse_deltas = false
log_agent_responses = true
log_guardian_assessments = false
environment = "managed"
exporter = { otlp-http = { endpoint = "http://127.0.0.1:1/v1/logs", protocol = "$PROTOCOL", headers = { Authorization = "Bearer managed-token" }, tls = { ca-certificate = "ca.pem", client-certificate = "client.pem", client-private-key = "client-key.pem" } } }
exporter = { otlp-http = { endpoint = "http://127.0.0.1:1/v1/logs", protocol = "json", headers = { Authorization = "Bearer managed-token" }, tls = { ca-certificate = "ca.pem", client-certificate = "client.pem", client-private-key = "client-key.pem" } } }
trace_exporter = { otlp-grpc = { endpoint = "http://127.0.0.1:4317", headers = { "x-api-key" = "managed-grpc-secret" }, tls = { ca-certificate = "ca.pem" } } }
metrics_exporter = "$METRICS_EXPORTER"
metrics_exporter = "statsig"
span_attributes = { "service.name" = "managed-service" }
tracestate = { managed = { tenant = "enterprise" } }"#
.replace("$PROTOCOL", protocol)
.replace("$METRICS_EXPORTER", metrics_exporter),
tracestate = { managed = { tenant = "enterprise" } }"#,
)?;
let request_id = mcp.send_config_requirements_read_request().await?;
let response: serde_json::Value =
@@ -738,43 +632,12 @@ tracestate = { managed = { tenant = "enterprise" } }"#
"tool_result": { "max_bytes": 1024 },
"log_user_prompt": false,
"log_sse_deltas": false,
"log_agent_responses": true,
"log_guardian_assessments": false,
"environment": "managed",
"exporter": {
"otlp-http": {
"endpoint": "http://127.0.0.1:1/v1/logs",
"headers": { "Authorization": "[redacted]" },
"protocol": protocol,
"tls": {
"ca-certificate": codex_home.path().join("ca.pem"),
"client-certificate": codex_home.path().join("client.pem"),
"client-private-key": codex_home.path().join("client-key.pem"),
},
},
},
"trace_exporter": {
"otlp-grpc": {
"endpoint": "http://127.0.0.1:4317",
"headers": { "x-api-key": "[redacted]" },
"tls": {
"ca-certificate": codex_home.path().join("ca.pem"),
"client-certificate": null,
"client-private-key": null,
},
},
},
"metrics_exporter": metrics_exporter,
"span_attributes": { "service.name": "managed-service" },
"tracestate": { "managed": { "tenant": "enterprise" } },
})
);
// API clients must preserve certificate paths from servers on either OS.
let mut response = response;
response["requirements"]["otel"]["exporter"]["otlp-http"]["tls"]["ca-certificate"] =
json!(r"C:\certs\ca.pem");
response["requirements"]["otel"]["trace_exporter"]["otlp-grpc"]["tls"]["ca-certificate"] =
json!("/etc/certs/ca.pem");
let serialized = response.to_string();
for secret in ["managed-token", "managed-grpc-secret", "managed-service"] {
assert!(!serialized.contains(secret), "response leaked {secret}");
}
let typed: ConfigRequirementsReadResponse = serde_json::from_value(response.clone())?;
assert_eq!(
serde_json::to_value(
@@ -788,8 +651,7 @@ tracestate = { managed = { tenant = "enterprise" } }"#
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn config_read_redacts_otel_exporter_headers_from_effective_config_and_layers() -> Result<()>
{
async fn config_read_drops_legacy_otel_exporters_and_redacts_their_layer_headers() -> Result<()> {
let codex_home = TempDir::new()?;
write_config(
&codex_home,
@@ -816,11 +678,7 @@ metrics_exporter = { otlp-http = { endpoint = "http://127.0.0.1:1/v1/metrics", p
let response: ConfigReadResponse =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await??;
let serialized = serde_json::to_string(&response)?;
let effective_otel = response
.config
.additional
.get("otel")
.expect("effective OTEL config");
let effective_otel = response.config.additional.get("otel");
let layers = response.layers.as_ref().expect("included config layers");
let user_otel = layers
.iter()
@@ -846,7 +704,8 @@ metrics_exporter = { otlp-http = { endpoint = "http://127.0.0.1:1/v1/metrics", p
("metrics_exporter", "otlp-http", "metrics-secret"),
] {
let expected = json!({ "Authorization": "[redacted]" });
assert_eq!(effective_otel[field][transport]["headers"], expected);
// Exporters were removed, so the effective config no longer carries them.
assert_eq!(effective_otel.and_then(|otel| otel.get(field)), None);
assert_eq!(user_otel[field][transport]["headers"], expected);
assert!(!serialized.contains(secret), "response leaked {field}");
}

View File

@@ -579,8 +579,7 @@ pub(super) async fn spawn_websocket_server_with_args(
.stdout(Stdio::null())
.stderr(Stdio::piped())
.env("CODEX_HOME", codex_home)
.env("RUST_LOG", "warn")
.env("OTEL_METRIC_EXPORT_INTERVAL", "200");
.env("RUST_LOG", "warn");
let mut process = cmd
.kill_on_drop(true)

View File

@@ -1,202 +0,0 @@
//! Verify Core capture reaches the existing analytics endpoint on terminal turns.
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_matching_analytics_event;
use anyhow::Result;
use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::UserInput;
use codex_features::Feature;
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::BTreeMap;
use std::time::Duration;
use tempfile::TempDir;
use tokio::time::timeout;
use wiremock::Mock;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path_regex;
#[derive(Clone, Copy)]
enum Finish {
Complete,
Interrupt,
}
#[derive(Clone, Copy)]
enum Capture {
Default,
Enabled,
Disabled,
}
#[test_case::test_case(Finish::Complete, Capture::Default; "complete_default")]
#[test_case::test_case(Finish::Complete, Capture::Enabled; "complete_enabled")]
#[test_case::test_case(Finish::Complete, Capture::Disabled; "complete_disabled")]
#[test_case::test_case(Finish::Interrupt, Capture::Default; "interrupt_default")]
#[test_case::test_case(Finish::Interrupt, Capture::Enabled; "interrupt_enabled")]
#[test_case::test_case(Finish::Interrupt, Capture::Disabled; "interrupt_disabled")]
#[tokio::test]
async fn critical_path_reaches_turn_event(finish: Finish, capture: Capture) -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let body = responses::sse(vec![
responses::ev_response_created("response-1"),
responses::ev_assistant_message("answer", "Done"),
responses::ev_completed("response-1"),
]);
let mut response = ResponseTemplate::new(200).set_body_raw(body, "text/event-stream");
if matches!(finish, Finish::Interrupt) {
response = response.set_delay(Duration::from_secs(60));
}
Mock::given(method("POST"))
.and(path_regex(".*/responses$"))
.respond_with(response)
.mount(&server)
.await;
let codex_home = TempDir::new()?;
let mut features = BTreeMap::from([(Feature::RuntimeMetrics, true)]);
match capture {
Capture::Default => {}
Capture::Enabled => {
features.insert(Feature::CriticalPathTiming, true);
}
Capture::Disabled => {
features.insert(Feature::CriticalPathTiming, false);
}
}
MockResponsesConfig::new(&server.uri())
.with_root_config(&format!("chatgpt_base_url = {:?}", server.uri()))
.with_provider_config("supports_websockets = false")
.with_features(&features)
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut app = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_managed_config()
.build_initialized()
.await?;
let thread = app.start_thread(ThreadStartParams::default()).await?.thread;
let params = TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: "Hello".into(),
text_elements: Vec::new(),
}],
..Default::default()
};
let (turn_id, expected_status) = match finish {
Finish::Complete => {
let completed = app.start_turn_and_wait_for_completion(params).await?;
(completed.turn.id, "completed")
}
Finish::Interrupt => {
let started: TurnStartResponse = app
.request(|request_id| ClientRequest::TurnStart { request_id, params })
.await?;
// Wait for sampling to begin before interrupting, without a timing-dependent sleep.
timeout(Duration::from_secs(10), async {
loop {
if server
.received_requests()
.await
.unwrap_or_default()
.iter()
.any(|r| r.url.path().ends_with("/responses"))
{
break;
}
tokio::task::yield_now().await;
}
})
.await?;
app.interrupt_turn_and_wait_for_aborted(
thread.id.clone(),
started.turn.id.clone(),
Duration::from_secs(10),
)
.await?;
(started.turn.id, "interrupted")
}
};
let event = wait_for_matching_analytics_event(&server, Duration::from_secs(30), |event| {
event["event_type"] == "codex_turn_event" && event["event_params"]["turn_id"] == turn_id
})
.await?;
let p = &event["event_params"];
assert_eq!(
json!([p["thread_id"], p["status"]]),
json!([thread.id, expected_status])
);
let fields = [
"critical_path_duration_ms",
"critical_path_sampling_ms",
"critical_path_compaction_ms",
"critical_path_auto_review_ms",
"critical_path_user_wait_ms",
"critical_path_tools_ms",
"critical_path_overhead_ms",
"critical_path_unknown_ms",
];
if matches!(capture, Capture::Enabled) {
assert_eq!(p["critical_path_status"], "complete");
assert_eq!(
p.get("critical_path_auto_review_overhead_ms"),
Some(&json!(0))
);
let inference = p["critical_path_inference_ms"]
.as_u64()
.expect("inference duration");
let phases = p["critical_path_sampling_ms"]
.as_u64()
.expect("sampling duration")
+ p["critical_path_compaction_ms"]
.as_u64()
.expect("compaction duration");
assert!(phases <= inference && inference - phases <= 1);
assert_eq!(p[fields[0]], p["duration_ms"]);
let total = p[fields[0]]
.as_u64()
.expect("complete capture has a numeric total");
let sum: u64 = fields[1..]
.iter()
.map(|key| {
p[key]
.as_u64()
.expect("complete capture has numeric categories")
})
.sum();
assert!(sum <= total && total - sum <= 6);
assert_eq!(
json!([
p["critical_path_user_wait_ms"],
p["critical_path_tools_ms"],
p["critical_path_auto_review_ms"],
p["critical_path_unknown_ms"],
]),
json!([0, 0, 0, 0])
);
} else {
assert_eq!(p["critical_path_status"], "disabled");
assert_eq!(
p.get("critical_path_auto_review_overhead_ms"),
Some(&serde_json::Value::Null)
);
assert_eq!(
p.get("critical_path_inference_ms"),
Some(&serde_json::Value::Null)
);
assert_eq!(
fields.map(|key| p.get(key)),
[Some(&serde_json::Value::Null); 8]
);
}
Ok(())
}

View File

@@ -29,9 +29,6 @@ use serde_json::json;
use tempfile::TempDir;
use tokio::time::timeout;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_matching_analytics_event;
#[cfg(target_os = "macos")]
const READ_TIMEOUT: Duration = Duration::from_secs(60);
#[cfg(not(target_os = "macos"))]
@@ -113,17 +110,11 @@ async fn exercise_executor_skill(scenario: ExecutorSkillScenario) -> Result<()>
} else {
("never", "")
};
let analytics_config = if scenario == ExecutorSkillScenario::ExplicitOnly {
format!("chatgpt_base_url = \"{}\"", server.uri())
} else {
String::new()
};
std::fs::write(
codex_home.path().join("config.toml"),
format!(
r#"
model = "mock-model"
{analytics_config}
approval_policy = "{approval_policy}"
{sandbox_config}
model_provider = "mock_provider"
@@ -143,9 +134,6 @@ stream_max_retries = 0
server.uri()
),
)?;
if scenario == ExecutorSkillScenario::ExplicitOnly {
mount_analytics_capture(&server, codex_home.path()).await?;
}
let local_skill_dir = codex_home.path().join("skills/local-deploy");
std::fs::create_dir_all(&local_skill_dir)?;
std::fs::write(
@@ -471,18 +459,6 @@ stream_max_retries = 0
app_server.read_stream_until_notification_message("turn/completed"),
)
.await??;
if scenario == ExecutorSkillScenario::ExplicitOnly {
for invocation_type in ["explicit", "implicit"] {
let event = wait_for_matching_analytics_event(&server, READ_TIMEOUT, |event| {
event["event_type"] == "skill_invocation"
&& event["event_params"]["invoke_type"] == invocation_type
})
.await?;
assert_eq!(event["event_params"]["plugin_id"], authority_id);
assert_eq!(event["event_params"]["skill_scope"], "user");
}
}
let requests = response_mock.requests();
let request = &requests[0];
if scenario == ExecutorSkillScenario::VisibleWithBudgetWarning {

View File

@@ -6,7 +6,6 @@ use app_test_support::ChatGptAuthFixture;
use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
use app_test_support::create_mock_responses_server_repeating_assistant;
use app_test_support::start_analytics_events_server;
use app_test_support::write_chatgpt_auth;
#[cfg(unix)]
use codex_app_server_protocol::ConfigReadParams;
@@ -57,8 +56,6 @@ use tempfile::TempDir;
use tokio::io::AsyncWriteExt;
use tokio::time::timeout;
use super::analytics::wait_for_analytics_event;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
const SECONDARY_MIGRATION_SOURCE: &str = concat!("cur", "sor");
@@ -1325,18 +1322,10 @@ async fn external_agent_config_import_reports_failed_sync_import_in_completion()
)?;
std::fs::write(codex_home.path().join("config.toml"), "invalid = [")?;
let home_dir = codex_home.path().display().to_string();
let analytics_capture_file = codex_home.path().join("analytics-events.jsonl");
let analytics_capture_file = analytics_capture_file.display().to_string();
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[
("HOME", Some(home_dir.as_str())),
(
"CODEX_ANALYTICS_EVENTS_CAPTURE_FILE",
Some(analytics_capture_file.as_str()),
),
])
.with_env_overrides(&[("HOME", Some(home_dir.as_str()))])
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
@@ -1399,63 +1388,13 @@ async fn external_agent_config_import_reports_failed_sync_import_in_completion()
assert!(commands_result.successes.is_empty());
assert!(commands_result.failures.is_empty());
let events = timeout(DEFAULT_TIMEOUT, async {
loop {
let contents = match std::fs::read_to_string(&analytics_capture_file) {
Ok(contents) => contents,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
tokio::time::sleep(Duration::from_millis(25)).await;
continue;
}
Err(err) => return Err(err.into()),
};
let mut captured_events = Vec::new();
for line in contents.lines() {
let payload: serde_json::Value = serde_json::from_str(line)?;
let Some(events) = payload["events"].as_array() else {
continue;
};
captured_events.extend(events.iter().cloned());
}
if captured_events.iter().any(|event| {
event["event_type"] == "codex_onboarding_external_agent_import_complete"
&& event["event_params"]["type"] == "COMMANDS"
}) {
return Ok::<Vec<serde_json::Value>, anyhow::Error>(captured_events);
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await??;
let event = events
.iter()
.find(|event| {
event["event_type"] == "codex_onboarding_external_agent_import_failure"
&& event["event_params"]["type"] == "CONFIG"
})
.expect("config failure analytics event");
let event_params = &event["event_params"];
assert_eq!(event_params["import_id"], import_id);
assert_eq!(event_params["source"], "test_import");
assert_eq!(event_params["provider_id"], "test-provider-42");
assert_eq!(event_params["type"], "CONFIG");
assert_eq!(event_params["failure_stage"], "import_request_failed");
assert_eq!(event_params["error_type"], "invalid_existing_config");
assert!(event_params.get("raw_errors").is_none());
assert!(event_params.get("message").is_none());
assert!(!events.iter().any(|event| {
event["event_type"] == "codex_onboarding_external_agent_import_failure"
&& event["event_params"]["type"] == "COMMANDS"
}));
Ok(())
}
#[tokio::test]
async fn external_agent_config_import_completed_tracks_analytics_event() -> Result<()> {
let analytics_server = start_analytics_events_server().await?;
async fn external_agent_config_import_reports_missing_session_in_completion() -> Result<()> {
let codex_home = TempDir::new()?;
write_analytics_config(codex_home.path(), &analytics_server.uri())?;
std::fs::write(codex_home.path().join("config.toml"), "")?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
@@ -1518,46 +1457,13 @@ async fn external_agent_config_import_completed_tracks_analytics_event() -> Resu
Some("session_not_detected")
);
let event = wait_for_analytics_event(
&analytics_server,
DEFAULT_TIMEOUT,
"codex_onboarding_external_agent_import_complete",
)
.await?;
let event_params = &event["event_params"];
assert_eq!(event_params["import_id"], serde_json::json!(import_id));
assert_eq!(event_params["source"], "test_import");
assert_eq!(event_params["provider_id"], "test-provider-42");
assert_eq!(event_params["type"], "SESSIONS");
assert_eq!(event_params["success_count"], 0);
assert_eq!(event_params["failed_count"], 1);
assert!(event_params.get("raw_errors").is_none());
let event = wait_for_analytics_event(
&analytics_server,
DEFAULT_TIMEOUT,
"codex_onboarding_external_agent_import_failure",
)
.await?;
let event_params = &event["event_params"];
assert_eq!(event_params["import_id"], serde_json::json!(import_id));
assert_eq!(event_params["source"], "test_import");
assert_eq!(event_params["provider_id"], "test-provider-42");
assert_eq!(event_params["type"], "SESSIONS");
assert_eq!(event_params["failure_stage"], "session_missing");
assert_eq!(event_params["error_type"], "session_missing");
assert_eq!(event_params["sub_error_type"], "session_not_detected");
assert!(event_params.get("raw_errors").is_none());
assert!(event_params.get("message").is_none());
Ok(())
}
#[tokio::test]
async fn external_agent_config_import_reports_session_config_error_subtype() -> Result<()> {
let analytics_server = start_analytics_events_server().await?;
let codex_home = TempDir::new()?;
write_analytics_config(codex_home.path(), &analytics_server.uri())?;
std::fs::write(codex_home.path().join("config.toml"), "")?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
@@ -1636,33 +1542,13 @@ async fn external_agent_config_import_reports_session_config_error_subtype() ->
Some("failed_to_load_session_config_invalid_data")
);
let event = wait_for_analytics_event(
&analytics_server,
DEFAULT_TIMEOUT,
"codex_onboarding_external_agent_import_failure",
)
.await?;
let event_params = &event["event_params"];
assert_eq!(event_params["import_id"], serde_json::json!(import_id));
assert_eq!(event_params["source"], "test_import");
assert_eq!(event_params["provider_id"], "test-provider-42");
assert_eq!(event_params["type"], "SESSIONS");
assert_eq!(event_params["failure_stage"], "session_persist");
assert_eq!(
event_params["sub_error_type"],
"failed_to_load_session_config_invalid_data"
);
assert!(event_params.get("raw_errors").is_none());
assert!(event_params.get("message").is_none());
Ok(())
}
#[tokio::test]
async fn external_agent_config_import_reinstalls_plugins_from_known_marketplaces() -> Result<()> {
let codex_home = TempDir::new()?;
let analytics_server = start_analytics_events_server().await?;
write_analytics_config(codex_home.path(), &analytics_server.uri())?;
std::fs::write(codex_home.path().join("config.toml"), "")?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
@@ -1802,30 +1688,6 @@ async fn external_agent_config_import_reinstalls_plugins_from_known_marketplaces
"plugin `missing` was not found in marketplace `debug`"
);
let event = wait_for_analytics_event(
&analytics_server,
DEFAULT_TIMEOUT,
"codex_plugin_install_failed",
)
.await?;
let event_params = &event["event_params"];
assert_eq!(event_params["plugin_id"], "missing@debug");
assert_eq!(event_params["plugin_name"], "missing");
assert_eq!(event_params["marketplace_name"], "debug");
assert_eq!(event_params["source"], "external_agent_migration");
assert_eq!(event_params["error_type"], "plugin_not_found");
let event = wait_for_analytics_event(
&analytics_server,
DEFAULT_TIMEOUT,
"codex_onboarding_external_agent_import_failure",
)
.await?;
let event_params = &event["event_params"];
assert_eq!(event_params["type"], "PLUGINS");
assert_eq!(event_params["failure_stage"], "plugin_import");
assert_eq!(event_params["error_type"], "plugin_not_found");
let request_id = mcp
.send_plugin_list_request(PluginListParams {
cwds: None,
@@ -2753,10 +2615,3 @@ async fn external_agent_config_import_compacts_huge_session_before_first_follow_
assert!(second.contains("LOCAL_SUMMARY"));
Ok(())
}
fn write_analytics_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> {
std::fs::write(
codex_home.join("config.toml"),
format!("chatgpt_base_url = \"{base_url}\"\n"),
)
}

View File

@@ -5,106 +5,18 @@ use app_test_support::TestAppServer;
use codex_app_server_protocol::RequestId;
use pretty_assertions::assert_eq;
use serde_json::json;
use tokio::io::AsyncBufReadExt;
use tokio::io::AsyncWriteExt;
use tokio::io::BufReader;
use tokio::net::TcpListener;
use tokio::time::timeout;
#[tokio::test]
async fn feedback_upload_limits_concurrency_and_releases_failed_uploads() -> Result<()> {
let proxy = TcpListener::bind("127.0.0.1:0").await?;
let proxy_uri = format!("http://{}", proxy.local_addr()?);
let mut app_server = TestAppServer::builder()
.with_env_overrides(&[
("HTTPS_PROXY", Some(proxy_uri.as_str())),
("https_proxy", Some(proxy_uri.as_str())),
("NO_PROXY", Some("")),
("no_proxy", Some("")),
])
.build_initialized()
.await?;
let mut pending = Vec::new();
for _ in 0..3 {
let request_id = app_server
.send_raw_request(
"feedback/upload",
Some(json!({ "classification": "bug", "includeLogs": false })),
)
.await?;
let (stream, _) = timeout(Duration::from_secs(/*secs*/ 15), proxy.accept()).await??;
let mut stream = BufReader::new(stream);
let mut request = String::new();
timeout(
Duration::from_secs(/*secs*/ 15),
stream.read_line(&mut request),
)
.await??;
assert!(request.starts_with("CONNECT "));
pending.push((request_id, stream.into_inner()));
}
let excess_id = app_server
.send_raw_request(
"feedback/upload",
Some(json!({ "classification": "bug", "includeLogs": false })),
)
.await?;
let error = timeout(
Duration::from_secs(/*secs*/ 15),
app_server.read_stream_until_error_message(RequestId::Integer(excess_id)),
)
.await??;
assert_eq!(error.error.code, -32001);
let unavailable =
b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
for (request_id, mut stream) in pending {
stream.write_all(unavailable).await?;
stream.shutdown().await?;
let error = timeout(
Duration::from_secs(/*secs*/ 15),
app_server.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(error.error.code, -32603);
assert!(error.error.message.contains("failed to upload feedback"));
}
let request_id = app_server
.send_raw_request(
"feedback/upload",
Some(json!({ "classification": "bug", "includeLogs": false })),
)
.await?;
let (mut stream, _) = timeout(Duration::from_secs(/*secs*/ 15), proxy.accept()).await??;
stream.write_all(unavailable).await?;
stream.shutdown().await?;
let error = timeout(
Duration::from_secs(/*secs*/ 15),
app_server.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(error.error.code, -32603);
Ok(())
}
#[tokio::test]
async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures() -> Result<()> {
async fn feedback_save_recovers_persisted_evidence_and_reports_sqlite_failures() -> Result<()> {
use std::collections::HashSet;
use std::io::Read;
use std::sync::Arc;
use app_test_support::MockResponsesConfig;
use codex_app_server_protocol::ClientNotification;
use codex_protocol::ThreadId;
use tokio::io::AsyncReadExt;
use tokio_rustls::TlsAcceptor;
use tokio_rustls::rustls;
// Terminate HTTPS locally and capture real Sentry envelopes. Never forward uploads.
let home = tempfile::tempdir()?;
let daemon_logs = home.path().join("app-server-daemon");
std::fs::create_dir(&daemon_logs)?;
@@ -124,70 +36,6 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures
daemon_logs.join("daemon-updater.stderr.log"),
"current updater diagnostic",
)?;
let cert = rcgen::generate_simple_self_signed(vec!["o33249.ingest.us.sentry.io".to_string()])?;
let cert_path = home.path().join("feedback-ca.pem");
std::fs::write(&cert_path, cert.cert.pem())?;
let tls = rustls::ServerConfig::builder_with_provider(Arc::new(
rustls::crypto::aws_lc_rs::default_provider(),
))
.with_safe_default_protocol_versions()?
.with_no_client_auth()
.with_single_cert(
vec![cert.cert.der().clone()],
rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()).into(),
)?;
let acceptor = TlsAcceptor::from(Arc::new(tls));
let listener = TcpListener::bind("127.0.0.1:0").await?;
let proxy_uri = format!("http://{}", listener.local_addr()?);
let (uploads_tx, mut uploads_rx) = tokio::sync::mpsc::unbounded_channel();
let _proxy = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
while let Ok((stream, _)) = listener.accept().await {
let mut stream = BufReader::new(stream);
loop {
let mut line = String::new();
anyhow::ensure!(stream.read_line(&mut line).await? > 0, "missing CONNECT");
if line == "\r\n" {
break;
}
}
stream
.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
.await?;
let mut stream = BufReader::new(acceptor.accept(stream.into_inner()).await?);
let mut length = None;
loop {
let mut line = String::new();
anyhow::ensure!(
stream.read_line(&mut line).await? > 0,
"missing HTTP headers"
);
if line == "\r\n" {
break;
}
if let Some((name, value)) = line.split_once(':')
&& name.eq_ignore_ascii_case("content-length")
{
length = Some(value.trim().parse::<usize>()?);
}
}
let length = length.ok_or_else(|| anyhow::anyhow!("missing content length"))?;
anyhow::ensure!(length < 16 * 1024 * 1024, "unexpected envelope size");
let mut body = vec![0; length];
stream.read_exact(&mut body).await?;
if body.starts_with(&[0x1f, 0x8b]) {
let mut decoded = Vec::new();
flate2::read::GzDecoder::new(body.as_slice()).read_to_end(&mut decoded)?;
body = decoded;
}
uploads_tx.send(body)?;
stream
.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}")
.await?;
stream.flush().await?;
}
Ok::<(), anyhow::Error>(())
}));
let models = wiremock::MockServer::start().await;
MockResponsesConfig::new(&models.uri())
.with_root_config(&format!("log_dir = {:?}", home.path().join("log")))
@@ -252,15 +100,9 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures
// This new process can recover review context only from SQLite.
let mut app_server = TestAppServer::builder()
.with_codex_home(home.path())
.with_env_overrides(&[
("HTTPS_PROXY", Some(proxy_uri.as_str())),
("https_proxy", Some(proxy_uri.as_str())),
("NO_PROXY", Some("127.0.0.1,localhost")),
("no_proxy", Some("127.0.0.1,localhost")),
("SSL_CERT_FILE", cert_path.to_str()),
])
.build_initialized()
.await?;
let output = tempfile::tempdir()?;
let pool = sqlite.open_read_write_pool(&sqlite.logs_db_path()).await?;
// This old history exists only in SQLite, as if it had already left the memory ring.
sqlx::query("INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body, thread_id) VALUES (unixepoch(), 0, 'INFO', 'test', 'sqlite-only-history', ?)")
@@ -281,7 +123,7 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures
}
Phase::WithoutLogs | Phase::WriteFailure => {}
}
// Notifications emit an INFO log, ensuring feedback/upload has a batch to flush.
// Notifications emit an INFO log, ensuring feedback/save has a batch to flush.
app_server
.send_notification(ClientNotification::Initialized)
.await?;
@@ -299,11 +141,15 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures
message: "Codex couldn't save diagnostic logs to its local database. Use /feedback with logs included before closing Codex, or run `codex doctor` for diagnostics.".to_string(),
});
}
let saved = output.path().join(format!("{phase:?}.zip"));
let request = app_server
.send_raw_request(
"feedback/upload",
"feedback/save",
Some(json!({
"classification": "bug", "includeLogs": phase != Phase::WithoutLogs, "threadId": thread_id
"classification": "bug",
"includeLogs": phase != Phase::WithoutLogs,
"threadId": thread_id,
"savePath": saved,
})),
)
.await?;
@@ -313,43 +159,34 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures
)
.await??;
let mut attachments = std::collections::BTreeMap::new();
let mut uploaded_rollouts = HashSet::<ThreadId>::new();
while let Ok(envelope) = uploads_rx.try_recv() {
let mut bytes = envelope.as_slice();
// Skip the envelope header, then decode each length-delimited item.
let header_end = bytes.iter().position(|byte| *byte == b'\n').unwrap();
bytes = &bytes[header_end + 1..];
while !bytes.is_empty() {
let header_end = bytes.iter().position(|byte| *byte == b'\n').unwrap();
let header: serde_json::Value = serde_json::from_slice(&bytes[..header_end])?;
let length = header["length"].as_u64().unwrap() as usize;
bytes = &bytes[header_end + 1..];
if header["filename"] == "rollouts.tar.gz" {
let mut archive =
tar::Archive::new(flate2::read::GzDecoder::new(&bytes[..length]));
for entry in archive.entries()? {
uploaded_rollouts.insert(serde_json::from_reader(entry?)?);
}
} else if let Some(filename) = header["filename"].as_str() {
attachments.insert(
filename.to_string(),
String::from_utf8_lossy(&bytes[..length]).into_owned(),
);
}
bytes = &bytes[length..];
if bytes.starts_with(b"\n") {
bytes = &bytes[1..];
}
let mut saved_rollouts = HashSet::<ThreadId>::new();
let mut zip = zip::ZipArchive::new(std::fs::File::open(&saved)?)?;
for index in 0..zip.len() {
let mut entry = zip.by_index(index)?;
let Some(filename) = entry
.name()?
.strip_prefix("attachments/")
.and_then(|name| name.rsplit('/').next())
.map(str::to_string)
else {
continue;
};
let mut contents = Vec::new();
entry.read_to_end(&mut contents)?;
if filename.starts_with("rollout-") {
saved_rollouts.insert(serde_json::from_slice(&contents)?);
} else {
attachments.insert(filename, String::from_utf8_lossy(&contents).into_owned());
}
}
if phase == Phase::WithoutLogs {
assert!(uploaded_rollouts.is_empty());
assert!(saved_rollouts.is_empty());
assert!(!attachments.contains_key("auto-review-failures.jsonl"));
assert!(!attachments.contains_key("codex-logs.log"));
assert!(!attachments.contains_key("codex-logs-legacy.log"));
continue;
}
assert_eq!(uploaded_rollouts, HashSet::from([thread_id, attached_id]));
assert_eq!(saved_rollouts, HashSet::from([thread_id, attached_id]));
assert_eq!(
attachments.get("codex-logs-legacy.log"),
(phase == Phase::Corrupt)
@@ -393,7 +230,7 @@ async fn feedback_upload_recovers_persisted_evidence_and_reports_sqlite_failures
Ok(())
}
/// Disabling uploads still permits local ZIPs, with invalid paths and collisions leaving existing files intact.
/// Local ZIPs stay local even with feedback disabled, and invalid paths or collisions leave existing files intact.
#[tokio::test]
async fn feedback_save_is_local_and_never_overwrites() -> Result<()> {
let proxy = TcpListener::bind("127.0.0.1:0").await?;
@@ -408,17 +245,6 @@ async fn feedback_save_is_local_and_never_overwrites() -> Result<()> {
])
.build_initialized()
.await?;
let request = app_server
.send_raw_request("feedback/upload", Some(json!({ "classification": "bug" })))
.await?;
let error = app_server
.read_stream_until_error_message(RequestId::Integer(request))
.await?;
assert_eq!(
error.error.message,
"sending feedback is disabled by configuration"
);
let directory = tempfile::tempdir()?;
let saved = directory.path().join("local.zip");
std::fs::write(&saved, b"existing export")?;

View File

@@ -117,15 +117,13 @@ with urllib.request.urlopen(request, timeout=30) as response:
))
.join("\n");
std::fs::write(codex_home.path().join("requirements.toml"), hooks)?;
let analytics_server = responses::start_mock_server().await;
mount_analytics_capture(&analytics_server, codex_home.path()).await?;
MockResponsesConfig::new(&responses_url)
.with_model(MODEL)
.with_provider_config("supports_websockets = false")
.with_approval_policy("on-request")
.with_root_config(&format!("approvals_reviewer = \"auto_review\"\nchatgpt_base_url = \"{}\"", analytics_server.uri()))
.with_root_config("approvals_reviewer = \"auto_review\"")
.with_extra_config(&format!(
"[mcp_servers.{TEST_SERVER_NAME}]\nurl = \"{mcp_url}/mcp\"\ndefault_tools_approval_mode = \"prompt\"\n\n[analytics]\nenabled = true\n\n[features.guardianv2]\nenabled = true\nmax_action_tokens = 128\n\n[features.guardianv2.review_scope]\ncomputer_use_only = false"
"[mcp_servers.{TEST_SERVER_NAME}]\nurl = \"{mcp_url}/mcp\"\ndefault_tools_approval_mode = \"prompt\"\n\n[features.guardianv2]\nenabled = true\nmax_action_tokens = 128\n\n[features.guardianv2.review_scope]\ncomputer_use_only = false"
))
.enable_feature(Feature::GuardianApproval)
.write(codex_home.path())?;
@@ -140,7 +138,7 @@ with urllib.request.urlopen(request, timeout=30) as response:
state.allow_guardian_review.notify_one();
let id = app_server
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: USER_CONTEXT.to_owned(),
text_elements: Vec::new(),
@@ -156,24 +154,7 @@ with urllib.request.urlopen(request, timeout=30) as response:
wait_for_guardian_reviews(&state, 1 + index).await?;
// First establish a permissive score; after overflow, establish a new one.
state.allow_luna.notify_one();
timeout(TIMEOUT, async {
loop {
let events = captured_analytics_events(&analytics_server).await;
if events
.iter()
.filter(|event| {
event["event_type"] == "codex_guardian_v2_classification"
&& event["event_params"]["outcome"] == "success"
})
.count()
> index
{
break;
}
tokio::time::sleep(Duration::from_millis(/*millis*/ 25)).await;
}
})
.await?;
wait_for_classification_logs(&codex_home, &thread.id, index + 1).await?;
gate.notify_one();
}
let completed: TurnCompletedNotification =

View File

@@ -141,18 +141,13 @@ async fn model_guardian_policy_scores_code_mode_cells(
)
}
};
let analytics_server = responses::start_mock_server().await;
mount_analytics_capture(&analytics_server, codex_home.path()).await?;
MockResponsesConfig::new(&responses_url)
.with_model(MODEL)
.with_provider_config("supports_websockets = false")
.with_approval_policy("on-request")
.with_root_config(&format!(
"approvals_reviewer = \"auto_review\"\nchatgpt_base_url = \"{}\"",
analytics_server.uri(),
))
.with_root_config("approvals_reviewer = \"auto_review\"")
.with_extra_config(&format!(
"[mcp_servers.node_repl]\nurl = \"{mcp_url}/mcp\"\ndefault_tools_approval_mode = \"auto\"\n\n[analytics]\nenabled = true{legacy_config}"
"[mcp_servers.node_repl]\nurl = \"{mcp_url}/mcp\"\ndefault_tools_approval_mode = \"auto\"{legacy_config}"
))
.enable_feature(Feature::GuardianApproval)
.enable_feature(Feature::CodeModeOnly)
@@ -182,7 +177,7 @@ async fn model_guardian_policy_scores_code_mode_cells(
state.allow_guardian_review.notify_one();
let id = app_server
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: USER_CONTEXT.to_owned(),
text_elements: Vec::new(),
@@ -203,27 +198,7 @@ async fn model_guardian_policy_scores_code_mode_cells(
}
for completed_scores in 1..=scores_per_cell {
state.allow_luna.notify_one();
timeout(TIMEOUT, async {
loop {
let events = captured_analytics_events(&analytics_server).await;
if events
.iter()
.filter(|event| {
event["event_type"] == "codex_guardian_v2_classification"
&& matches!(
event["event_params"]["outcome"].as_str(),
Some("success" | "superseded")
)
})
.count()
>= completed_scores
{
break;
}
tokio::time::sleep(Duration::from_millis(/*millis*/ 25)).await;
}
})
.await?;
wait_for_classification_logs(&codex_home, &thread.id, completed_scores).await?;
}
continue_parent.notify_one();
let completed: TurnCompletedNotification =

View File

@@ -1,4 +1,3 @@
use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;
use std::sync::Arc;
@@ -67,9 +66,6 @@ use tokio::net::TcpListener;
use tokio::sync::Notify;
use tokio::time::timeout;
use super::analytics::captured_analytics_events;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_matching_analytics_event;
use super::mcp_tool::TEST_SERVER_NAME;
use super::mcp_tool::TEST_TOOL_NAME;
use super::mcp_tool::start_mcp_server;
@@ -190,10 +186,6 @@ struct MockResponsesState {
gate_each_guardian_review: bool,
gate_second_tool_on_classification: bool,
allow_second_tool: Notify,
classification_completed: Notify,
truncation_recorded: Notify,
context_metric_bounds: Mutex<BTreeMap<(String, String), Option<f64>>>,
context_metrics_recorded: Notify,
luna_score: f64,
invalid_classification: bool,
fail_after_classification: bool,
@@ -326,6 +318,52 @@ fn sync_review_fragments(request: &Value) -> Vec<&str> {
.collect()
}
async fn wait_for_luna_completions(state: &MockResponsesState, expected: usize) -> Result<()> {
timeout(TIMEOUT, async {
while state.luna_completions.load(Ordering::Relaxed) < expected {
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await?;
Ok(())
}
/// Waits until `expected` Guardian V2 classifications of `thread_id` have finished, using the
/// result or failure line each classification writes to the local feedback logs.
async fn wait_for_classification_logs(
codex_home: &TempDir,
thread_id: &str,
expected: usize,
) -> Result<()> {
let state_db = StateRuntime::init(
load_default_config_for_test(codex_home).await.sqlite,
"mock_provider".to_owned(),
)
.await?;
timeout(TIMEOUT, async {
loop {
let logs = String::from_utf8(
state_db
.query_feedback_logs_for_threads(&[thread_id])
.await?,
)?;
let finished = logs
.lines()
.filter(|line| {
line.contains("Guardian V2 classification result")
|| line.contains("Guardian V2 background scoring failed")
})
.count();
if finished >= expected {
return anyhow::Ok(());
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await??;
Ok(())
}
async fn wait_for_luna_request(state: &MockResponsesState, index: usize) -> Result<Value> {
Ok(timeout(TIMEOUT, async {
loop {
@@ -779,73 +817,6 @@ async fn guardian_v2_routes_scoped_tool_approvals(
let responses_url = format!("http://{}", listener.local_addr()?);
let router = Router::new()
.route("/v1/responses", get(luna_websocket).post(parent_response))
.route(
"/metrics",
post(
|State(state): State<Arc<MockResponsesState>>, body: String| async move {
if matches!(state.transcript_content, TranscriptContent::MixedEvidence) {
let payload: Value = serde_json::from_str(&body).expect("OTLP JSON");
for metric in payload["resourceMetrics"]
.as_array()
.into_iter()
.flatten()
.flat_map(|resource| {
resource["scopeMetrics"].as_array().into_iter().flatten()
})
.flat_map(|scope| scope["metrics"].as_array().into_iter().flatten())
.filter(|metric| {
matches!(
metric["name"].as_str(),
Some(
"codex.guardian.context.request_tokens"
| "codex.guardian.context.section_cost"
)
)
})
{
let name = metric["name"].as_str().expect("context metric name");
for point in metric["histogram"]["dataPoints"]
.as_array()
.into_iter()
.flatten()
{
let attributes =
point["attributes"].as_array().expect("metric attributes");
for target in ["sync", "async"] {
if attributes.iter().any(|attr| {
attr["key"] == "target"
&& attr["value"]["stringValue"] == target
}) {
let mut bounds = state
.context_metric_bounds
.lock()
.expect("context metric bounds");
bounds.insert(
(name.to_owned(), target.to_owned()),
point["explicitBounds"]
.as_array()
.and_then(|bounds| bounds.last())
.and_then(Value::as_f64),
);
if bounds.len() == 4 {
state.context_metrics_recorded.notify_one();
}
}
}
}
}
}
if body.contains("\"codex.guardian_v2.classification\"") {
state.classification_completed.notify_one();
}
if body.contains("codex.guardian_v2.classification.truncation")
&& body.contains("sync_review_action")
{
state.truncation_recorded.notify_one();
}
},
),
)
.with_state(Arc::clone(&responses_state));
let responses_server = tokio::spawn(async move {
let _ = axum::serve(listener, router).await;
@@ -853,8 +824,6 @@ async fn guardian_v2_routes_scoped_tool_approvals(
let (mcp_server_url, mcp_server_handle) = start_mcp_server(sensitive_action).await?;
let codex_home = TempDir::new()?;
let analytics_server = responses::start_mock_server().await;
mount_analytics_capture(&analytics_server, codex_home.path()).await?;
let mixed_evidence = matches!(transcript_content, TranscriptContent::MixedEvidence);
let root_skill = if matches!(lifecycle, ThreadLifecycle::RootTrustedSkill) || mixed_evidence {
let path = codex_home.path().join("skills/root-trusted/SKILL.md");
@@ -930,12 +899,9 @@ async fn guardian_v2_routes_scoped_tool_approvals(
.with_model(MODEL)
.with_provider_config("supports_websockets = false")
.with_approval_policy("on-request")
.with_root_config(&format!(
"{reviewer_config}\nchatgpt_base_url = \"{}\"",
analytics_server.uri(),
))
.with_root_config(reviewer_config)
.with_extra_config(&format!(
"[mcp_servers.{server_name}]\nurl = \"{mcp_server_url}/mcp\"\ndefault_tools_approval_mode = \"{tool_approval_mode}\"\n\n[analytics]\nenabled = true\n\n[otel]\nmetrics_exporter = {{ otlp-http = {{ endpoint = \"{responses_url}/metrics\", protocol = \"json\" }} }}\n\n[features.guardianv2]\nenabled = true{classifier_config}{guardian_scope_config}"
"[mcp_servers.{server_name}]\nurl = \"{mcp_server_url}/mcp\"\ndefault_tools_approval_mode = \"{tool_approval_mode}\"\n\n[features.guardianv2]\nenabled = true{classifier_config}{guardian_scope_config}"
))
.enable_feature(Feature::GuardianApproval);
if lifecycle.has_user_input() || lifecycle.has_root_user_input() {
@@ -1008,10 +974,7 @@ async fn guardian_v2_routes_scoped_tool_approvals(
.then(|| traces.path().to_str().expect("trace root path"));
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.with_env_overrides(&[
("OTEL_METRIC_EXPORT_INTERVAL", Some("25")),
("CODEX_ROLLOUT_TRACE_ROOT", trace_root),
])
.with_env_overrides(&[("CODEX_ROLLOUT_TRACE_ROOT", trace_root)])
.build_initialized_with_timeout(TIMEOUT)
.await?;
let thread = match lifecycle {
@@ -1244,7 +1207,13 @@ async fn guardian_v2_routes_scoped_tool_approvals(
.await??;
}
responses_state.allow_luna.notify_one();
timeout(TIMEOUT, responses_state.classification_completed.notified()).await?;
if late_root_restriction {
// A superseded classification leaves no observable trace, so only wait
// until the classifier response has been served.
wait_for_luna_completions(&responses_state, /*expected*/ 1).await?;
} else {
wait_for_classification_logs(&codex_home, &reviewed_thread_id, /*expected*/ 1).await?;
}
if late_root_restriction {
responses_state.allow_guardian_review.notify_one();
} else {
@@ -1700,26 +1669,6 @@ async fn guardian_v2_routes_scoped_tool_approvals(
assert!(text.contains("Planned action JSON:"));
}
}
if mixed_evidence {
timeout(TIMEOUT, responses_state.context_metrics_recorded.notified())
.await
.expect("sync and async request/section metrics should all be exported");
let bounds = responses_state
.context_metric_bounds
.lock()
.expect("context metric bounds");
for ((metric, target), bound) in bounds.iter() {
assert_eq!(
*bound,
Some(if metric == "codex.guardian.context.request_tokens" {
2_000_000.0
} else {
16_777_216.0
}),
"{metric} ({target}) must export its context metric buckets"
);
}
}
if lifecycle.has_user_answer() {
let reviews = responses_state
.guardian_requests
@@ -1793,7 +1742,7 @@ async fn guardian_v2_routes_scoped_tool_approvals(
"mock_provider".to_owned(),
)
.await?;
// Exercise the same log export used by feedback/upload, including async
// Exercise the same log export used by feedback/save, including async
// classifier events that cannot rely on inheriting a thread tracing span.
let logs = timeout(TIMEOUT, async {
loop {
@@ -1826,7 +1775,7 @@ async fn guardian_v2_routes_scoped_tool_approvals(
if matches!(lifecycle, ThreadLifecycle::RequiredModelSwitch) {
// Both MCP actions have low scores; the sandboxed exec must still receive full review.
timeout(TIMEOUT, responses_state.classification_completed.notified()).await?;
wait_for_classification_logs(&codex_home, &reviewed_thread_id, /*expected*/ 2).await?;
// Continue without new user input so authorization changes cannot invalidate the score.
// Only the required-model check should prevent cached approval of the sandboxed command.
let request_id = app_server
@@ -2051,26 +2000,10 @@ async fn guardian_v2_routes_scoped_tool_approvals(
responses_state.allow_luna.notify_one();
}
if matches!(review_outcome, ReviewOutcome::Deny) && !lifecycle.has_user_answer() {
timeout(TIMEOUT, responses_state.truncation_recorded.notified()).await?;
}
if matches!(lifecycle, ThreadLifecycle::New)
&& matches!(scope, GuardianToolScope::AllTools)
&& sensitive_action.is_none()
{
if classifier_in_scope {
wait_for_matching_analytics_event(&analytics_server, TIMEOUT, |event| {
event["event_type"] == "codex_guardian_v2_classification"
&& event["event_params"]["item_id"] == "guardian-action-0"
})
.await?;
}
let turn = wait_for_matching_analytics_event(&analytics_server, TIMEOUT, |event| {
event["event_type"] == "codex_turn_event"
&& event["event_params"]["thread_id"] == reviewed_thread_id
})
.await?;
timeout(TIMEOUT, app_server.shutdown_gracefully()).await??;
if matches!(review_outcome, ReviewOutcome::Deny) {
// Denied calls have no backend response, but their runtime result must
@@ -2135,58 +2068,6 @@ async fn guardian_v2_routes_scoped_tool_approvals(
None
),
);
let events = captured_analytics_events(&analytics_server).await;
let turn = &turn["event_params"];
assert_eq!(turn["guardian_v2_enabled"], classifier_in_scope);
let classification = events.iter().find(|event| {
event["event_type"] == "codex_guardian_v2_classification"
&& event["event_params"]["item_id"] == "guardian-action-0"
});
assert_eq!(classification.is_some(), classifier_in_scope);
if let Some(event) = classification {
assert_eq!(
json!([
event["event_params"]["outcome"],
event["event_params"]["risk_level"]
]),
match risk {
GuardianRisk::Low | GuardianRisk::LowWithStreamFailure =>
json!(["success", "low"]),
GuardianRisk::Threshold | GuardianRisk::High => json!(["success", "high"]),
GuardianRisk::InvalidResponse => json!(["failure", null]),
}
);
}
let approvals = events
.iter()
.filter(|event| event["event_type"] == "codex_guardian_v2_fast_decision")
.collect::<Vec<_>>();
assert_eq!(
approvals.len(),
usize::from(classifier_in_scope && matches!(risk, GuardianRisk::Low))
);
for event in classification.into_iter().chain(approvals) {
let params = &event["event_params"];
for key in [
"session_id",
"thread_id",
"turn_id",
"model",
"app_server_client",
"runtime",
"thread_source",
"subagent_source",
"parent_thread_id",
] {
assert_eq!(params[key], turn[key], "{key}");
}
if event["event_type"] == "codex_guardian_v2_fast_decision" {
assert_eq!(
json!([params["item_id"], params["decision"]]),
json!(["guardian-action-1", "approved"])
);
}
}
}
mcp_server_handle.abort();

View File

@@ -3,6 +3,7 @@ use std::time::Duration;
use anyhow::Result;
use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
use app_test_support::mount_chatgpt_account;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::UserInput;
@@ -21,11 +22,6 @@ use wiremock::matchers::body_partial_json;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_matching_analytics_event;
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(30);
const THREAD_HINT: &str =
"Recent notes (up to 5, most-recent first):\n- /root/notes/latest.md (2 lines, 14 UTF-8 bytes)";
const BRIDGE_HINT: &str = "unstructured notes/thread_hint fixture result";
@@ -138,7 +134,7 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
server.uri(),
))
.write(codex_home.path())?;
mount_analytics_capture(&backend, codex_home.path()).await?;
mount_chatgpt_account(&backend, codex_home.path()).await?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -231,27 +227,11 @@ async fn app_server_uses_configured_notes_backend_for_context_window_hints(
&& item["name"] == "thread_hint"
}));
if use_history_notes_extension {
let event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_thread_hint_status"
&& event["event_params"]["thread_id"] == thread.id
})
.await?;
assert_eq!(
event["event_params"]["status"],
if hint_status == 200 {
"succeeded"
} else {
"failed"
},
);
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result<()> {
async fn history_notes_and_async_message_control_tools_execute() -> Result<()> {
let encrypted_query = format!("enc_query_{}", "x".repeat(1_001));
let calls = [
("history", "list_windows", json!({})),
@@ -364,7 +344,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
"[features.token_budget]\nenabled = true\nuse_history_notes_extension = true",
)
.write(codex_home.path())?;
mount_analytics_capture(&backend, codex_home.path()).await?;
mount_chatgpt_account(&backend, codex_home.path()).await?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -376,7 +356,7 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
.start_thread(ThreadStartParams::default())
.await?
.thread;
let completed = app_server
app_server
.start_turn_and_wait_for_completion(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
@@ -400,45 +380,6 @@ async fn history_notes_and_async_message_emit_control_tool_analytics() -> Result
assert_eq!(tool["parameters"]["properties"][field]["encrypted"], true);
}
for (index, (namespace, tool, _)) in calls.iter().enumerate() {
let event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_control_tool_call_event"
&& event["event_params"]["item_id"] == format!("call-{index}")
})
.await?;
let params = &event["event_params"];
assert_eq!(
json!({
"tool": params["tool_name"],
"thread": params["thread_id"],
"turn": params["turn_id"],
"status": params["terminal_status"],
"origin": params["originating_response_id"],
"duration": params["execution_duration_ms"].is_u64(),
}),
json!({
"tool": if *namespace == "functions" { tool.to_string() } else { format!("{namespace}.{tool}") },
"thread": thread.id,
"turn": completed.turn.id,
"status": if index < 10 { "completed" } else { "failed" },
"origin": format!("resp-{index}"),
"duration": true,
})
);
assert!(!event.to_string().contains("PRIVATE_"));
}
let turn_event = wait_for_matching_analytics_event(&backend, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_turn_event"
&& event["event_params"]["turn_id"] == completed.turn.id
})
.await?;
assert_eq!(
json!({
"total": turn_event["event_params"]["total_tool_call_count"],
"dynamic": turn_event["event_params"]["dynamic_tool_call_count"],
}),
json!({"total": calls.len(), "dynamic": 0})
);
assert_eq!(
response_mock.requests()[10].function_call_output_text("call-9"),
Some(r#"{"accepted":true}"#.to_string())

View File

@@ -6,6 +6,7 @@ use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
use app_test_support::mount_chatgpt_account;
use app_test_support::write_chatgpt_auth;
use base64::Engine;
use codex_app_server_protocol::GeneratedImageRef;
@@ -43,9 +44,6 @@ use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_analytics_event;
const RESULT: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
// Two one-pixel frames, red then blue, with a 200 ms frame duration.
const ANIMATED_RESULT: &str = "R0lGODlhAQABAIEAAP8AAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQAFAAAACwAAAAAAQABAAAIBAABBAQAIfkEARQAAQAsAAAAAAEAAQCBAAD/AAAAAAAAAAAACAQAAQQEADs=";
@@ -132,7 +130,7 @@ async fn standalone_image_generation_returns_saved_path_hint_to_model(
let codex_home = TempDir::new()?;
create_config_toml(codex_home.path(), &server.uri(), ImagegenTestMode::Direct)?;
mount_analytics_capture(&server, codex_home.path()).await?;
mount_chatgpt_account(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -286,21 +284,6 @@ async fn standalone_image_generation_returns_saved_path_hint_to_model(
"standalone image generation should not emit the legacy developer-message hint"
);
let event = wait_for_analytics_event(
&server,
DEFAULT_READ_TIMEOUT,
"codex_image_generation_event",
)
.await?;
assert_eq!(
event["event_params"]["imagegen_request_id"],
json!("req-imagegen-123")
);
assert_eq!(
event["event_params"]["generation_id"],
json!("gen-image-123")
);
Ok(())
}
@@ -708,17 +691,6 @@ async fn standalone_image_generation_failure_emits_terminal_item(
)
);
let event = wait_for_analytics_event(
&server,
DEFAULT_READ_TIMEOUT,
"codex_image_generation_event",
)
.await?;
assert_eq!(
event["event_params"]["imagegen_request_id"],
json!("req-imagegen-failed-123")
);
Ok(())
}

View File

@@ -5,13 +5,10 @@ mod account_system_proxy;
mod account_gcp;
mod account_thread_usage;
mod agent_message_board;
mod analytics;
mod application_network;
#[path = "attached_thread_tests.rs"]
mod attached_thread;
mod attestation;
#[path = "auth_storage_originator_tests.rs"]
mod auth_storage_originator;
mod auto_env;
#[path = "bedrock_gov_cloud_tests.rs"]
mod bedrock_gov_cloud;
@@ -45,8 +42,6 @@ mod connection_handling_websocket;
mod connection_handling_websocket_compression;
#[cfg(unix)]
mod connection_handling_websocket_unix;
#[path = "critical_path_analytics_tests.rs"]
mod critical_path_analytics;
#[cfg(unix)]
mod curated_mcp_sync;
mod current_time;
@@ -106,7 +101,6 @@ mod model_provider_config_tests;
mod model_provider_enforcement;
mod model_provider_list_tests;
mod multi_agent_v2_developer_instructions;
mod otel;
mod output_schema;
mod permission_profile_list;
mod plan_item;
@@ -169,7 +163,6 @@ mod thread_timeline;
mod thread_unarchive;
mod thread_unload;
mod thread_unsubscribe;
mod turn_cost_otel;
mod turn_interrupt;
mod turn_settings_update;
mod turn_start;

View File

@@ -1,363 +0,0 @@
use anyhow::Context;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::ChatGptIdTokenClaims;
use app_test_support::TestAppServer;
use app_test_support::encode_id_token;
use app_test_support::write_chatgpt_auth;
use app_test_support::write_models_cache;
use codex_app_server_protocol::LoginAccountResponse;
use codex_app_server_protocol::ThreadStartParams;
use codex_config::types::AuthCredentialsStoreMode;
use pretty_assertions::assert_eq;
use std::path::Path;
use std::time::Duration;
use tempfile::TempDir;
use tokio::time::timeout;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
const TEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30);
const INITIAL_ACCOUNT_ID: &str = "123e4567-e89b-42d3-a456-426614174000";
const NEXT_ACCOUNT_ID: &str = "123e4567-e89b-42d3-a456-426614174001";
const INITIAL_EMAIL: &str = "initial-workspace@example.com";
const NEXT_EMAIL: &str = "next-account@example.com";
const PARENT_TRACE_ID: &str = "4bf92f3577b34da6a3ce929d0e0e4736";
const PARENT_TRACEPARENT: &str = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
enum TraceExporterSetting {
Disabled,
Collector,
}
#[tokio::test]
async fn account_switch_reloads_telemetry_collectors_and_preserves_trace_context() -> Result<()> {
let collector = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(200))
.mount(&collector)
.await;
let codex_home = TempDir::new()?;
let initial_endpoint = format!("{}/initial", collector.uri());
write_otel_config(
codex_home.path(),
&initial_endpoint,
TraceExporterSetting::Collector,
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("initial-access-token")
.account_id(INITIAL_ACCOUNT_ID)
.chatgpt_account_id(INITIAL_ACCOUNT_ID)
.chatgpt_user_id("initial-user")
.plan_type("pro")
.email(INITIAL_EMAIL),
AuthCredentialsStoreMode::File,
)?;
write_models_cache(codex_home.path()).await?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.with_env_overrides(&[("TRACEPARENT", Some(PARENT_TRACEPARENT))])
.with_json_logging("codex_app_server::otel_reloader=info")
.build_initialized_with_timeout(TEST_TIMEOUT)
.await?;
app_server
.start_thread(ThreadStartParams::default())
.await?;
let contains = |requests: &[wiremock::Request], path: &str, value: &str| {
requests.iter().any(|request| {
request.url.path() == path && String::from_utf8_lossy(&request.body).contains(value)
})
};
timeout(TEST_TIMEOUT, async {
let mut poll = tokio::time::interval(Duration::from_millis(/*millis*/ 25));
loop {
poll.tick().await;
let requests = collector.received_requests().await.unwrap_or_default();
if contains(&requests, "/initial/logs", INITIAL_EMAIL)
&& contains(&requests, "/initial/traces", PARENT_TRACE_ID)
{
break;
}
}
})
.await
.context("initial account telemetry must be exported before its permission is revoked")?;
let next_endpoint = format!("{}/next", collector.uri());
write_otel_config(
codex_home.path(),
&next_endpoint,
TraceExporterSetting::Collector,
)?;
let access_token = encode_id_token(
&ChatGptIdTokenClaims::new()
.email(NEXT_EMAIL)
.plan_type("pro")
.chatgpt_account_id(NEXT_ACCOUNT_ID)
.chatgpt_user_id("next-user"),
)?;
let request_id = app_server
.send_chatgpt_auth_tokens_login_request(
access_token,
NEXT_ACCOUNT_ID.to_string(),
Some("pro".to_string()),
)
.await?;
let response: LoginAccountResponse =
timeout(TEST_TIMEOUT, app_server.read_response(request_id)).await??;
assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {});
timeout(
TEST_TIMEOUT,
app_server.wait_for_json_log_event(
"codex.app_server.otel_reloaded",
Duration::from_secs(/*secs*/ 10),
),
)
.await??;
timeout(TEST_TIMEOUT, async {
let mut poll = tokio::time::interval(Duration::from_secs(/*secs*/ 1));
loop {
poll.tick().await;
app_server
.start_thread(ThreadStartParams::default())
.await?;
let requests = collector.received_requests().await.unwrap_or_default();
if contains(&requests, "/next/logs", NEXT_EMAIL) {
break Ok::<(), anyhow::Error>(());
}
}
})
.await
.context("new account telemetry must reach the replacement collector")??;
let status = timeout(TEST_TIMEOUT, app_server.shutdown_gracefully()).await??;
assert!(status.success(), "app-server did not shut down cleanly");
let requests = collector
.received_requests()
.await
.context("collector did not record requests")?;
for request in requests
.iter()
.filter(|request| request.url.path().ends_with("/logs"))
{
assert_eq!(
request
.headers
.get("x-collector-key")
.and_then(|value| value.to_str().ok()),
Some("test-collector-key")
);
}
let exported = |path: &str| {
requests
.iter()
.filter(|request| request.url.path() == path)
.map(|request| String::from_utf8_lossy(&request.body).into_owned())
.collect::<Vec<_>>()
.join("\n")
};
let initial_logs = exported("/initial/logs");
let initial_traces = exported("/initial/traces");
let next_logs = exported("/next/logs");
let next_traces = exported("/next/traces");
let next_metrics = exported("/next/metrics");
assert!(
initial_logs.contains(INITIAL_EMAIL),
"the initial account's logs were not exported: {initial_logs}"
);
assert!(
initial_traces.contains(PARENT_TRACE_ID),
"the initial account's trace context was not propagated: {initial_traces}"
);
assert!(
next_logs.contains(NEXT_EMAIL),
"the next account's logs did not reach its collector: {next_logs}"
);
assert!(
next_traces.contains(PARENT_TRACE_ID),
"the next account's trace context was not propagated: {next_traces}"
);
assert!(
next_metrics.contains("codex.thread.started"),
"the next account's metrics did not reach its collector: {next_metrics}"
);
assert!(
next_metrics.contains("is_worktree"),
"the thread-start worktree tag did not reach its collector: {next_metrics}"
);
Ok(())
}
#[tokio::test]
async fn account_switch_enables_trace_exporter_after_startup_without_tracing() -> Result<()> {
let collector = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(200))
.mount(&collector)
.await;
let codex_home = TempDir::new()?;
let initial_endpoint = format!("{}/initial", collector.uri());
write_otel_config(
codex_home.path(),
&initial_endpoint,
TraceExporterSetting::Disabled,
)?;
write_trace_requirements(
codex_home.path(),
&initial_endpoint,
TraceExporterSetting::Disabled,
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("initial-access-token")
.account_id(INITIAL_ACCOUNT_ID)
.chatgpt_account_id(INITIAL_ACCOUNT_ID)
.chatgpt_user_id("initial-user")
.plan_type("pro")
.email(INITIAL_EMAIL),
AuthCredentialsStoreMode::File,
)?;
write_models_cache(codex_home.path()).await?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.with_env_overrides(&[("TRACEPARENT", Some(PARENT_TRACEPARENT))])
.with_json_logging("codex_app_server::otel_reloader=info")
.build_initialized_with_timeout(TEST_TIMEOUT)
.await?;
app_server
.start_thread(ThreadStartParams::default())
.await?;
let next_endpoint = format!("{}/next", collector.uri());
write_trace_requirements(
codex_home.path(),
&next_endpoint,
TraceExporterSetting::Collector,
)?;
let access_token = encode_id_token(
&ChatGptIdTokenClaims::new()
.email(NEXT_EMAIL)
.plan_type("pro")
.chatgpt_account_id(NEXT_ACCOUNT_ID)
.chatgpt_user_id("next-user"),
)?;
let request_id = app_server
.send_chatgpt_auth_tokens_login_request(
access_token,
NEXT_ACCOUNT_ID.to_string(),
Some("pro".to_string()),
)
.await?;
let response: LoginAccountResponse =
timeout(TEST_TIMEOUT, app_server.read_response(request_id)).await??;
assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {});
timeout(
TEST_TIMEOUT,
app_server.wait_for_json_log_event(
"codex.app_server.otel_reloaded",
Duration::from_secs(/*secs*/ 10),
),
)
.await??;
app_server
.start_thread(ThreadStartParams::default())
.await?;
let status = timeout(TEST_TIMEOUT, app_server.shutdown_gracefully()).await??;
assert!(status.success(), "app-server did not shut down cleanly");
let requests = collector
.received_requests()
.await
.context("collector did not record requests")?;
let exported = |path: &str| {
requests
.iter()
.filter(|request| request.url.path() == path)
.map(|request| String::from_utf8_lossy(&request.body).into_owned())
.collect::<Vec<_>>()
.join("\n")
};
let initial_traces = exported("/initial/traces");
let next_traces = exported("/next/traces");
assert!(
initial_traces.is_empty(),
"traces were exported before tracing was configured: {initial_traces}"
);
assert!(
next_traces.contains(PARENT_TRACE_ID),
"the requirements-managed trace exporter did not start after account switch: {next_traces}"
);
Ok(())
}
fn write_otel_config(
codex_home: &Path,
collector_endpoint: &str,
trace_exporter_setting: TraceExporterSetting,
) -> Result<()> {
let trace_exporter = match trace_exporter_setting {
TraceExporterSetting::Disabled => String::new(),
TraceExporterSetting::Collector => format!(
r#"trace_exporter = {{ otlp-http = {{ endpoint = "{collector_endpoint}/traces", protocol = "json" }} }}"#
),
};
std::fs::write(
codex_home.join("config.toml"),
format!(
r#"model = "mock-model"
model_provider = "mock_provider"
[model_providers.mock_provider]
name = "Mock provider"
base_url = "http://127.0.0.1:1/v1"
wire_api = "responses"
[analytics]
enabled = false
[otel]
environment = "test"
exporter = {{ otlp-http = {{ endpoint = "{collector_endpoint}/logs", protocol = "json", headers = {{ x-collector-key = "test-collector-key" }} }} }}
{trace_exporter}
metrics_exporter = {{ otlp-http = {{ endpoint = "{collector_endpoint}/metrics", protocol = "json" }} }}
"#
),
)?;
Ok(())
}
fn write_trace_requirements(
codex_home: &Path,
collector_endpoint: &str,
trace_exporter_setting: TraceExporterSetting,
) -> Result<()> {
let trace_exporter = match trace_exporter_setting {
TraceExporterSetting::Disabled => "trace_exporter = \"none\"".to_string(),
TraceExporterSetting::Collector => format!(
r#"trace_exporter = {{ otlp-http = {{ endpoint = "{collector_endpoint}/traces", protocol = "json" }} }}"#
),
};
std::fs::write(
codex_home.join("requirements.toml"),
format!(
r#"[otel]
{trace_exporter}
"#
),
)?;
Ok(())
}

View File

@@ -9,9 +9,7 @@ use std::time::Duration;
use anyhow::Result;
use anyhow::bail;
use app_test_support::ChatGptAuthFixture;
use app_test_support::DEFAULT_CLIENT_NAME;
use app_test_support::TestAppServer;
use app_test_support::start_analytics_events_server;
use app_test_support::write_chatgpt_auth;
use axum::Json;
use axum::Router;
@@ -565,12 +563,11 @@ async fn plugin_install_rejects_invalid_remote_plugin_name() -> Result<()> {
}
#[tokio::test]
async fn plugin_install_tracks_analytics_when_remote_detail_fetch_fails() -> Result<()> {
async fn plugin_install_reports_remote_detail_fetch_failure() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
configure_remote_plugin_test(codex_home.path(), &server)?;
mount_empty_remote_installed_plugins(&server).await;
mount_backend_analytics_events(&server).await;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -587,27 +584,11 @@ async fn plugin_install_tracks_analytics_when_remote_detail_fetch_fails() -> Res
assert_eq!(err.error.code, -32600);
assert!(err.error.message.contains("failed with status 404"));
let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?;
let event_params = &payload["events"][0]["event_params"];
assert_eq!(
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], json!(null));
assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(event_params["plugin_name"], json!(null));
assert_eq!(event_params["marketplace_name"], json!(null));
assert_eq!(event_params["source"], "manual");
assert_eq!(
event_params["error_type"],
"remote_catalog_unexpected_status"
);
assert_eq!(event_params["sub_error_type"], "http_404");
Ok(())
}
#[tokio::test]
async fn plugin_install_tracks_analytics_when_remote_install_is_rate_limited() -> Result<()> {
async fn plugin_install_reports_rate_limited_remote_install() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
let bundle_url = mount_remote_plugin_bundle(
@@ -628,7 +609,6 @@ async fn plugin_install_tracks_analytics_when_remote_install_is_rate_limited() -
.respond_with(ResponseTemplate::new(/*status_code*/ 429).set_body_string("rate limited"))
.mount(&server)
.await;
mount_backend_analytics_events(&server).await;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -659,21 +639,6 @@ async fn plugin_install_tracks_analytics_when_remote_install_is_rate_limited() -
/*expected_count*/ 1,
)
.await?;
let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?;
let event_params = &payload["events"][0]["event_params"];
assert_eq!(
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], "linear@openai-curated-remote");
assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(event_params["marketplace_name"], "openai-curated-remote");
assert_eq!(event_params["source"], "manual");
assert_eq!(
event_params["error_type"],
"remote_catalog_unexpected_status"
);
assert_eq!(event_params["sub_error_type"], "http_429");
Ok(())
}
@@ -697,7 +662,6 @@ async fn plugin_install_rejects_remote_plugin_disabled_by_admin_before_download(
)
.await;
mount_empty_remote_installed_plugins(&server).await;
mount_backend_analytics_events(&server).await;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -734,16 +698,6 @@ async fn plugin_install_rejects_remote_plugin_disabled_by_admin_before_download(
.join("plugins/cache/openai-curated-remote/linear")
.exists()
);
let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?;
let event_params = &payload["events"][0]["event_params"];
assert_eq!(
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], "linear@openai-curated-remote");
assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(event_params["error_type"], "remote_plugin_not_available");
assert_eq!(event_params["sub_error_type"], "disabled_by_admin");
Ok(())
}
@@ -760,7 +714,6 @@ async fn plugin_install_rejects_remote_plugin_not_available() -> Result<()> {
)
.await;
mount_empty_remote_installed_plugins(&server).await;
mount_backend_analytics_events(&server).await;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -783,19 +736,6 @@ async fn plugin_install_rejects_remote_plugin_not_available() -> Result<()> {
/*expected_count*/ 0,
)
.await?;
let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?;
let event_params = &payload["events"][0]["event_params"];
assert_eq!(
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], "linear@openai-curated-remote");
assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(event_params["error_type"], "remote_plugin_not_available");
assert_eq!(
event_params["sub_error_type"],
"install_policy_not_available"
);
Ok(())
}
@@ -831,18 +771,8 @@ async fn plugin_install_returns_invalid_request_for_missing_marketplace_file() -
}
#[tokio::test]
async fn plugin_install_tracks_analytics_when_marketplace_file_cannot_be_read() -> Result<()> {
let analytics_server = start_analytics_events_server().await?;
async fn plugin_install_reports_unreadable_marketplace_file() -> Result<()> {
let codex_home = TempDir::new()?;
write_analytics_config(codex_home.path(), &analytics_server.uri())?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let marketplace_path = codex_home.path().join("marketplace-dir");
std::fs::create_dir_all(&marketplace_path)?;
@@ -872,20 +802,6 @@ async fn plugin_install_tracks_analytics_when_marketplace_file_cannot_be_read()
.contains("failed to read marketplace file")
);
let payload =
wait_for_plugin_analytics_payload(&analytics_server, "codex_plugin_install_failed").await?;
let event_params = &payload["events"][0]["event_params"];
assert_eq!(
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], json!(null));
assert_eq!(event_params["remote_plugin_id"], json!(null));
assert_eq!(event_params["error_type"], "marketplace_io");
assert_eq!(
event_params["sub_error_type"],
"failed_to_read_marketplace_file"
);
Ok(())
}
@@ -984,85 +900,8 @@ async fn plugin_install_returns_invalid_request_for_disallowed_product_plugin()
}
#[tokio::test]
async fn plugin_install_tracks_analytics_event() -> Result<()> {
let analytics_server = start_analytics_events_server().await?;
async fn plugin_install_rejects_missing_local_plugin_source() -> Result<()> {
let codex_home = TempDir::new()?;
write_analytics_config(codex_home.path(), &analytics_server.uri())?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let repo_root = TempDir::new()?;
write_plugin_marketplace(
repo_root.path(),
"debug",
"sample-plugin",
"./sample-plugin",
/*install_policy*/ None,
/*auth_policy*/ None,
)?;
write_plugin_source(repo_root.path(), "sample-plugin", &[])?;
let marketplace_path =
AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
let request_id = mcp
.send_plugin_install_request(PluginInstallParams {
marketplace_path: Some(marketplace_path),
remote_marketplace_name: None,
install_attempt_id: None,
plugin_name: "sample-plugin".to_string(),
})
.await?;
let response: PluginInstallResponse =
timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??;
assert_eq!(response.apps_needing_auth, Vec::<AppSummary>::new());
let payload =
wait_for_plugin_analytics_payload(&analytics_server, "codex_plugin_installed").await?;
assert_eq!(
payload,
json!({
"events": [{
"event_type": "codex_plugin_installed",
"event_params": {
"plugin_id": "sample-plugin@debug",
"remote_plugin_id": null,
"plugin_name": "sample-plugin",
"marketplace_name": "debug",
"has_skills": false,
"mcp_server_count": 0,
"connector_ids": [],
"product_client_id": DEFAULT_CLIENT_NAME,
}
}]
})
);
Ok(())
}
#[tokio::test]
async fn plugin_install_failure_tracks_analytics_event() -> Result<()> {
let analytics_server = start_analytics_events_server().await?;
let codex_home = TempDir::new()?;
write_analytics_config(codex_home.path(), &analytics_server.uri())?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let repo_root = TempDir::new()?;
write_plugin_marketplace(
@@ -1096,28 +935,11 @@ async fn plugin_install_failure_tracks_analytics_event() -> Result<()> {
.await??;
assert_eq!(err.error.code, -32600);
let payload =
wait_for_plugin_analytics_payload(&analytics_server, "codex_plugin_install_failed").await?;
let event_params = &payload["events"][0]["event_params"];
assert_eq!(
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], "sample-plugin@debug");
assert_eq!(event_params["remote_plugin_id"], json!(null));
assert_eq!(event_params["plugin_name"], "sample-plugin");
assert_eq!(event_params["marketplace_name"], "debug");
assert_eq!(event_params["has_skills"], json!(null));
assert_eq!(event_params["mcp_server_count"], json!(null));
assert_eq!(event_params["connector_ids"], json!(null));
assert_eq!(event_params["product_client_id"], DEFAULT_CLIENT_NAME);
assert_eq!(event_params["source"], "manual");
assert_eq!(event_params["error_type"], "store_invalid");
Ok(())
}
#[tokio::test]
async fn plugin_install_tracks_remote_plugin_analytics_event() -> Result<()> {
async fn plugin_install_forwards_install_attempt_id_to_remote_install() -> Result<()> {
let codex_home = TempDir::new()?;
let server = MockServer::start().await;
let bundle_url = mount_remote_plugin_bundle(
@@ -1130,7 +952,6 @@ async fn plugin_install_tracks_remote_plugin_analytics_event() -> Result<()> {
mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.2.3", Some(&bundle_url)).await;
mount_empty_remote_installed_plugins(&server).await;
mount_remote_plugin_install(&server, REMOTE_PLUGIN_ID).await;
mount_backend_analytics_events(&server).await;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -1154,25 +975,6 @@ async fn plugin_install_tracks_remote_plugin_analytics_event() -> Result<()> {
json!({"install_attempt_id": INSTALL_ATTEMPT_ID})
);
let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_installed").await?;
assert_eq!(
payload,
json!({
"events": [{
"event_type": "codex_plugin_installed",
"event_params": {
"plugin_id": "linear@openai-curated-remote",
"remote_plugin_id": REMOTE_PLUGIN_ID,
"plugin_name": "linear",
"marketplace_name": "openai-curated-remote",
"has_skills": true,
"mcp_server_count": 0,
"connector_ids": [],
"product_client_id": DEFAULT_CLIENT_NAME,
}
}]
})
);
Ok(())
}
@@ -1188,7 +990,6 @@ async fn plugin_install_preserves_status_when_remote_bundle_error_body_is_too_la
mount_remote_plugin_detail(&server, REMOTE_PLUGIN_ID, "1.2.3", Some(&bundle_url)).await;
mount_empty_remote_installed_plugins(&server).await;
mount_remote_plugin_install(&server, REMOTE_PLUGIN_ID).await;
mount_backend_analytics_events(&server).await;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -1234,18 +1035,6 @@ async fn plugin_install_preserves_status_when_remote_bundle_error_body_is_too_la
/*expected_count*/ 0,
)
.await?;
let payload = wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?;
let event_params = &payload["events"][0]["event_params"];
assert_eq!(
payload["events"][0]["event_type"],
"codex_plugin_install_failed"
);
assert_eq!(event_params["plugin_id"], "linear@openai-curated-remote");
assert_eq!(event_params["remote_plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(event_params["marketplace_name"], "openai-curated-remote");
assert_eq!(event_params["source"], "manual");
assert_eq!(event_params["error_type"], "remote_bundle_download_status");
assert_eq!(event_params["sub_error_type"], "http_5xx");
assert!(
!codex_home
.path()
@@ -2861,84 +2650,6 @@ connectors = true
)
}
fn write_analytics_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> {
std::fs::write(
codex_home.join("config.toml"),
format!("chatgpt_base_url = \"{base_url}\"\n"),
)
}
async fn mount_backend_analytics_events(server: &MockServer) {
Mock::given(method("POST"))
.and(path("/backend-api/codex/analytics-events/events"))
.respond_with(ResponseTemplate::new(200).set_body_string(r#"{"status":"ok"}"#))
.mount(server)
.await;
}
async fn wait_for_plugin_analytics_payload(
server: &MockServer,
event_type: &str,
) -> Result<serde_json::Value> {
timeout(DEFAULT_TIMEOUT, async {
loop {
let Some(requests) = server.received_requests().await else {
tokio::time::sleep(Duration::from_millis(25)).await;
continue;
};
for request in requests.iter().filter(|request| {
request.method == "POST"
&& request
.url
.path()
.ends_with("/codex/analytics-events/events")
}) {
let mut payload: serde_json::Value = serde_json::from_slice(&request.body)
.map_err(|err| anyhow::anyhow!("invalid analytics payload: {err}"))?;
let events = payload["events"]
.as_array_mut()
.ok_or_else(|| anyhow::anyhow!("analytics payload missing events array"))?;
events.retain(|event| event["event_type"] == event_type);
if !events.is_empty() {
return Ok(payload);
}
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await?
}
#[tokio::test]
async fn plugin_analytics_wait_ignores_unrelated_requests_and_batched_events() -> Result<()> {
let server = MockServer::start().await;
mount_backend_analytics_events(&server).await;
let client = HttpClientBuilder::new().build_direct()?;
let expected = json!({
"event_type": "codex_plugin_install_failed",
"event_params": {"plugin_id": "sample-plugin@debug"}
});
for events in [
json!([{"event_type": "codex_turn_event"}]),
json!([{"event_type": "codex_thread_initialized"}, expected.clone()]),
] {
client
.post(format!(
"{}/backend-api/codex/analytics-events/events",
server.uri()
))
.json(&json!({"events": events}))
.send()
.await?
.error_for_status()?;
}
assert_eq!(
wait_for_plugin_analytics_payload(&server, "codex_plugin_install_failed").await?,
json!({"events": [expected]})
);
Ok(())
}
async fn oauth_discovery_request_count(server: &MockServer) -> usize {
server
.received_requests()

View File

@@ -3,16 +3,13 @@ use std::time::Duration;
use anyhow::Result;
use anyhow::bail;
use app_test_support::ChatGptAuthFixture;
use app_test_support::DEFAULT_CLIENT_NAME;
use app_test_support::TestAppServer;
use app_test_support::start_analytics_events_server;
use app_test_support::write_chatgpt_auth;
use codex_app_server_protocol::PluginUninstallParams;
use codex_app_server_protocol::PluginUninstallResponse;
use codex_app_server_protocol::RequestId;
use codex_config::types::AuthCredentialsStoreMode;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use tokio::time::timeout;
use wiremock::Mock;
@@ -63,72 +60,6 @@ enabled = true
Ok(())
}
#[tokio::test]
async fn plugin_uninstall_tracks_analytics_event() -> Result<()> {
let analytics_server = start_analytics_events_server().await?;
let codex_home = TempDir::new()?;
write_installed_plugin(&codex_home, "debug", "sample-plugin")?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
"chatgpt_base_url = \"{}\"\n\n[features]\nplugins = true\n\n[plugins.\"sample-plugin@debug\"]\nenabled = true\n",
analytics_server.uri()
),
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
let response = uninstall_plugin(&mut mcp, "sample-plugin@debug").await?;
assert_eq!(response, PluginUninstallResponse {});
let payload = timeout(DEFAULT_TIMEOUT, async {
loop {
let Some(requests) = analytics_server.received_requests().await else {
tokio::time::sleep(Duration::from_millis(25)).await;
continue;
};
if let Some(request) = requests.iter().find(|request| {
request.method == "POST" && request.url.path() == "/codex/analytics-events/events"
}) {
break request.body.clone();
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await?;
let payload: serde_json::Value = serde_json::from_slice(&payload).expect("analytics payload");
assert_eq!(
payload,
json!({
"events": [{
"event_type": "codex_plugin_uninstalled",
"event_params": {
"plugin_id": "sample-plugin@debug",
"remote_plugin_id": null,
"plugin_name": "sample-plugin",
"marketplace_name": "debug",
"has_skills": false,
"mcp_server_count": 0,
"connector_ids": [],
"product_client_id": DEFAULT_CLIENT_NAME,
}
}]
})
);
Ok(())
}
#[tokio::test]
async fn plugin_uninstall_rejects_remote_plugin_when_plugins_are_disabled() -> Result<()> {
let codex_home = TempDir::new()?;
@@ -195,11 +126,6 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl
)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/backend-api/codex/analytics-events/events"))
.respond_with(ResponseTemplate::new(200).set_body_string(r#"{"status":"ok"}"#))
.mount(&server)
.await;
let remote_plugin_cache_root = codex_home
.path()
@@ -225,7 +151,7 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl
.await?;
// Simulate a background remote-cache refresh removing the local bundle
// before the uninstall request captures its telemetry metadata.
// before the uninstall request runs.
std::fs::remove_dir_all(remote_plugin_cache_root.join("1.0.0"))?;
let response = uninstall_plugin(&mut mcp, REMOTE_PLUGIN_ID).await?;
@@ -240,25 +166,6 @@ async fn plugin_uninstall_writes_remote_plugin_to_cloud_when_remote_plugin_enabl
.await?;
assert!(!remote_plugin_cache_root.exists());
assert!(!legacy_remote_plugin_cache_root.exists());
let payload = wait_for_plugin_analytics_payload(&server).await?;
assert_eq!(
payload,
json!({
"events": [{
"event_type": "codex_plugin_uninstalled",
"event_params": {
"plugin_id": "linear@openai-curated-remote",
"remote_plugin_id": REMOTE_PLUGIN_ID,
"plugin_name": "linear",
"marketplace_name": "openai-curated-remote",
"has_skills": true,
"mcp_server_count": 0,
"connector_ids": [],
"product_client_id": DEFAULT_CLIENT_NAME,
}
}]
})
);
Ok(())
}
@@ -663,29 +570,6 @@ async fn mount_remote_plugin_detail_with_name(
.await;
}
async fn wait_for_plugin_analytics_payload(server: &MockServer) -> Result<serde_json::Value> {
timeout(DEFAULT_TIMEOUT, async {
loop {
let Some(requests) = server.received_requests().await else {
tokio::time::sleep(Duration::from_millis(25)).await;
continue;
};
if let Some(request) = requests.iter().find(|request| {
request.method == "POST"
&& request
.url
.path()
.ends_with("/codex/analytics-events/events")
}) {
return serde_json::from_slice(&request.body)
.map_err(|err| anyhow::anyhow!("invalid analytics payload: {err}"));
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
})
.await?
}
async fn wait_for_remote_plugin_request_count(
server: &MockServer,
method_name: &str,

View File

@@ -6,6 +6,7 @@ use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::TestAppServer;
use app_test_support::create_final_assistant_message_sse_response;
use app_test_support::mount_chatgpt_account;
use app_test_support::to_response;
use app_test_support::write_chatgpt_auth;
use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url;
@@ -38,9 +39,6 @@ use tokio::process::Child;
use tokio::process::Command;
use tokio::time::timeout;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_matching_analytics_event;
const READ_TIMEOUT: Duration = Duration::from_secs(20);
const EXECUTOR_ID: &str = "executor-1";
const EXECUTOR_ENV_NAME: &str = "MCP_EXECUTOR_MARKER";
@@ -78,7 +76,7 @@ async fn selected_plugin_mcp_startup_respects_explicit_mentions(
let explicitly_mentioned = !matches!(mention, PluginMention::Unmentioned);
let responses_server = responses::start_mock_server().await;
let fixture = selected_capability_fixture(&responses_server.uri(), &responses_server.uri())?;
mount_analytics_capture(&responses_server, fixture.codex_home.path()).await?;
mount_chatgpt_account(&responses_server, fixture.codex_home.path()).await?;
let config_path = fixture.codex_home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?.replace(
"executor_capability_discovery = true",
@@ -146,7 +144,7 @@ async fn selected_plugin_mcp_startup_respects_explicit_mentions(
app_server.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let TurnStartResponse { turn } = to_response(response)?;
let _: TurnStartResponse = to_response(response)?;
wait_for_pid_file(&fixture.pid_file).await?;
if explicitly_mentioned {
// An explicit mention must outwait the optional one-second grace.
@@ -173,17 +171,6 @@ async fn selected_plugin_mcp_startup_respects_explicit_mentions(
explicitly_mentioned,
);
let event = wait_for_matching_analytics_event(&responses_server, READ_TIMEOUT, |event| {
event["event_type"] == "codex_turn_event"
&& event["event_params"]["thread_id"] == thread_id
&& event["event_params"]["turn_id"] == turn.id
})
.await?;
assert_eq!(
event["event_params"]["active_plugin_ids_at_turn_start"],
json!([PLUGIN_ID])
);
exec_server.kill().await?;
Ok(())
}

View File

@@ -18,151 +18,17 @@ use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::UserInput as V2UserInput;
use core_test_support::responses;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::time::Duration;
use tempfile::TempDir;
use test_case::test_case;
use tokio::time::timeout;
use super::analytics::captured_analytics_events;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_matching_analytics_event;
#[cfg(windows)]
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(25);
#[cfg(not(windows))]
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
const CURRENT_TIME_AT: i64 = 1_781_717_655;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn clock_tools_emit_control_tool_analytics() -> Result<()> {
let calls = [
("curr_time", json!({}), "completed"),
("sleep", json!({"duration_ms": 1}), "completed"),
(
"sleep",
json!({"duration_ms": "PRIVATE_INVALID_DURATION"}),
"failed",
),
("sleep", json!({"duration_ms": 43_200_000}), "interrupted"),
];
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
calls
.iter()
.enumerate()
.map(|(index, (tool, arguments, _))| {
let response_id = format!("resp-{index}");
responses::sse(vec![
responses::ev_response_created(&response_id),
responses::ev_function_call_with_namespace(
&format!("call-{index}"),
"clock",
tool,
&arguments.to_string(),
),
responses::ev_completed(&response_id),
])
})
.collect(),
)
.await;
let codex_home = TempDir::new()?;
MockResponsesConfig::new(&server.uri())
.with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri()))
.with_provider_config("supports_websockets = false")
.with_extra_config("[features.current_time_reminder]\nenabled = true\nsleep_tool = true")
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.without_managed_config()
.build_initialized()
.await?;
let thread = app_server
.start_thread(ThreadStartParams::default())
.await?
.thread;
let TurnStartResponse { turn } = app_server
.request(|request_id| ClientRequest::TurnStart {
request_id,
params: TurnStartParams {
thread_id: thread.id.clone(),
input: vec![V2UserInput::Text {
text: "Exercise clock tools".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
},
})
.await?;
wait_for_sleep_started(&mut app_server, "call-3").await?;
app_server
.interrupt_turn_and_wait_for_aborted(
thread.id.clone(),
turn.id.clone(),
DEFAULT_READ_TIMEOUT,
)
.await?;
let turn_event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_turn_event" && event["event_params"]["turn_id"] == turn.id
})
.await?;
timeout(DEFAULT_READ_TIMEOUT, app_server.shutdown_gracefully()).await??;
let events = captured_analytics_events(&server).await;
let mut control_events = events
.iter()
.filter(|event| event["event_type"] == "codex_control_tool_call_event")
.collect::<Vec<_>>();
control_events.sort_by_key(|event| event["event_params"]["item_id"].as_str());
assert_eq!(
control_events
.iter()
.map(|event| {
let params = &event["event_params"];
json!({
"tool": params["tool_name"],
"call": params["item_id"],
"thread": params["thread_id"],
"turn": params["turn_id"],
"status": params["terminal_status"],
"origin": params["originating_response_id"],
"duration": params["execution_duration_ms"].is_u64(),
})
})
.collect::<Vec<_>>(),
calls
.iter()
.enumerate()
.map(|(index, (tool, _, status))| json!({
"tool": format!("clock.{tool}"),
"call": format!("call-{index}"),
"thread": thread.id,
"turn": turn.id,
"status": status,
"origin": format!("resp-{index}"),
"duration": true,
}))
.collect::<Vec<_>>()
);
let control_json = serde_json::to_string(&control_events)?;
for private_content in ["PRIVATE_INVALID_DURATION", "It is ", "Sleep completed."] {
assert!(!control_json.contains(private_content));
}
assert_eq!(
json!({
"total": turn_event["event_params"]["total_tool_call_count"],
"dynamic": turn_event["event_params"]["dynamic_tool_call_count"],
}),
json!({"total": calls.len(), "dynamic": 0})
);
assert_eq!(response_mock.requests().len(), calls.len());
Ok(())
}
#[test_case(0; "initial read fails")]
#[test_case(1; "polling read fails")]
#[test_case(3; "successful reads")]

View File

@@ -39,15 +39,11 @@ use codex_state::StateRuntime;
use codex_utils_absolute_path::test_support::PathExt;
use core_test_support::responses;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::path::Path;
use tempfile::TempDir;
use tokio::time::timeout;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_matching_analytics_event;
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
fn body_contains(request: &wiremock::Request, text: &str) -> bool {
@@ -287,7 +283,6 @@ async fn thread_archive_without_turns(history_mode: ThreadHistoryMode) -> Result
MockResponsesConfig::new(&server.uri())
.with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri()))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -355,40 +350,6 @@ async fn thread_archive_without_turns(history_mode: ThreadHistoryMode) -> Result
assert_eq!(archived.turns, Vec::new());
assert_eq!(archived.status, ThreadStatus::NotLoaded);
let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_thread_archive_event"
&& event["event_params"]["thread_id"] == thread.id
})
.await?;
let occurred_at_ms = event["event_params"]["occurred_at_ms"]
.as_u64()
.expect("thread archive analytics must include its producer timestamp");
assert_eq!(
event,
json!({
"event_type": "codex_thread_archive_event",
"event_params": {
"thread_id": thread.id,
"action": "archived",
"occurred_at_ms": occurred_at_ms,
"app_server_client": {
"product_client_id": "codex_work_desktop",
"client_name": "codex_work_desktop",
"client_version": "0.1.0",
"rpc_transport": "stdio",
"experimental_api_enabled": true,
},
"runtime": {
"codex_rs_version": env!("CARGO_PKG_VERSION"),
"runtime_os": std::env::consts::OS,
"runtime_os_version": event["event_params"]["runtime"]["runtime_os_version"],
"runtime_arch": std::env::consts::ARCH,
},
"thread_source": "user",
},
})
);
// Verify file moved.
let archived_directory = codex_home.path().join(ARCHIVED_SESSIONS_SUBDIR);
// The archived file keeps the original filename (rollout-...-<id>.jsonl).
@@ -561,7 +522,6 @@ async fn thread_archive_succeeds_when_descendant_archive_fails() -> Result<()> {
MockResponsesConfig::new(&server.uri())
.with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri()))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let parent_id = create_fake_rollout(
codex_home.path(),
@@ -702,68 +662,13 @@ async fn thread_archive_succeeds_when_descendant_archive_fails() -> Result<()> {
.await??;
unarchive(&mut mcp, &parent_id).await?;
wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_thread_archive_event"
&& event["event_params"]["thread_id"] == grandchild_id
&& event["event_params"]["action"] == "unarchived"
})
.await?;
let requests = server
.received_requests()
.await
.ok_or_else(|| anyhow::anyhow!("wiremock did not record requests"))?;
let mut archive_events = Vec::new();
for request in requests {
if request.url.path() != "/codex/analytics-events/events" {
continue;
}
let payload: Value = serde_json::from_slice(&request.body)?;
let events = payload["events"]
.as_array()
.ok_or_else(|| anyhow::anyhow!("analytics payload missing events array"))?;
for event in events
.iter()
.filter(|event| event["event_type"] == "codex_thread_archive_event")
{
for (header, expected) in [
("authorization", "Bearer chatgpt-token"),
("chatgpt-account-id", "account-123"),
] {
assert_eq!(
request
.headers
.get(header)
.and_then(|value| value.to_str().ok()),
Some(expected)
);
}
archive_events.push(event.clone());
}
}
let expected = [
(parent_id.as_str(), "archived"),
(grandchild_id.as_str(), "archived"),
(parent_id.as_str(), "unarchived"),
(grandchild_id.as_str(), "unarchived"),
];
assert_eq!(archive_events.len(), expected.len());
for (event, (thread_id, action)) in archive_events.iter().zip(expected) {
let occurred_at_ms = event["event_params"]["occurred_at_ms"]
.as_u64()
.expect("thread archive analytics must include its producer timestamp");
assert_eq!(
event,
&json!({
"event_type": "codex_thread_archive_event",
"event_params": {
"thread_id": thread_id,
"action": action,
"occurred_at_ms": occurred_at_ms,
},
})
);
for thread_id in [&parent_id, &grandchild_id] {
let notification: ThreadUnarchivedNotification = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_notification("thread/unarchived"),
)
.await??;
assert_eq!(&notification.thread_id, thread_id);
}
Ok(())

View File

@@ -103,11 +103,6 @@ use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::analytics::assert_basic_thread_initialized_event;
use super::analytics::mount_analytics_capture;
use super::analytics::thread_initialized_event;
use super::analytics::wait_for_analytics_payload;
#[cfg(windows)]
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
#[cfg(not(windows))]
@@ -1453,63 +1448,6 @@ async fn thread_fork_can_exclude_turns_and_skip_restored_token_usage() -> Result
Ok(())
}
#[tokio::test]
async fn thread_fork_tracks_thread_initialized_analytics() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
MockResponsesConfig::new(&server.uri())
.with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri()))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let conversation_id = create_fake_rollout(
codex_home.path(),
"2025-01-05T12-00-00",
"2025-01-05T12:00:00Z",
"Saved user message",
Some("mock_provider"),
/*git_info*/ None,
)?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build_initialized()
.await?;
let fork_id = mcp
.send_thread_fork_request(ThreadForkParams {
thread_id: conversation_id,
thread_source: Some(ThreadSource::User),
..Default::default()
})
.await?;
let ThreadForkResponse { thread, .. } =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(fork_id)).await??;
let payload = wait_for_analytics_payload(&server, DEFAULT_READ_TIMEOUT).await?;
let event = thread_initialized_event(&payload)?;
assert_basic_thread_initialized_event(
event,
&thread.id,
&thread.session_id,
"codex",
"mock-model",
"forked",
"user",
);
assert_eq!(
event["event_params"]["forked_from_thread_id"],
thread
.forked_from_id
.as_deref()
.expect("forked thread has a source thread")
);
Ok(())
}
#[test_case(ThreadHistoryMode::Legacy; "legacy")]
#[test_case(ThreadHistoryMode::Paginated; "paginated")]
#[tokio::test]

View File

@@ -52,6 +52,7 @@ use codex_app_server_protocol::ThreadGoalGetParams;
use codex_app_server_protocol::ThreadGoalGetResponse;
use codex_app_server_protocol::ThreadGoalSetResponse;
use codex_app_server_protocol::ThreadGoalStatus;
use codex_app_server_protocol::ThreadGoalUpdatedNotification;
use codex_app_server_protocol::ThreadHistoryMode;
use codex_app_server_protocol::ThreadItemPayload;
use codex_app_server_protocol::ThreadListResponse;
@@ -66,7 +67,6 @@ use codex_app_server_protocol::ThreadResumeParams;
use codex_app_server_protocol::ThreadResumeResponse;
use codex_app_server_protocol::ThreadSettingsUpdateParams;
use codex_app_server_protocol::ThreadSettingsUpdateResponse;
use codex_app_server_protocol::ThreadSource;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::ThreadStatus;
@@ -151,13 +151,6 @@ use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::analytics::assert_basic_thread_initialized_event;
use super::analytics::mount_analytics_capture;
use super::analytics::thread_initialized_event;
use super::analytics::wait_for_analytics_payload;
use super::analytics::wait_for_goal_event;
use super::analytics::wait_for_matching_analytics_event;
#[path = "thread_resume_account_tests.rs"]
mod account_tests;
@@ -2637,166 +2630,6 @@ async fn goal_first_live_thread_appears_in_state_db_thread_list() -> Result<()>
Ok(())
}
#[tokio::test]
async fn thread_resume_tracks_thread_initialized_analytics() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
mock_responses_config(&server.uri())
.with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri()))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let conversation_id = create_fake_rollout(
codex_home.path(),
"2025-01-05T12-00-00",
"2025-01-05T12:00:00Z",
"Saved user message",
Some("mock_provider"),
/*git_info*/ None,
)?;
set_session_meta_on_fake_rollout(
codex_home.path(),
"2025-01-05T12-00-00",
&conversation_id,
"user",
"codex_work_desktop",
)?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_managed_config()
.build_initialized()
.await?;
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id: conversation_id,
..Default::default()
})
.await?;
let ThreadResumeResponse { thread, .. } =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??;
assert!(
!thread.session_id.is_empty(),
"session id should not be empty"
);
assert_eq!(thread.thread_source, Some(ThreadSource::User));
let payload = wait_for_analytics_payload(&server, DEFAULT_READ_TIMEOUT).await?;
let event = thread_initialized_event(&payload)?;
assert_basic_thread_initialized_event(
event,
&thread.id,
&thread.session_id,
"codex_work_desktop",
"gpt-5.4",
"resumed",
"user",
);
assert_eq!(event["event_params"]["thread_source"], "user");
Ok(())
}
#[tokio::test]
async fn thread_resume_running_thread_tracks_thread_originator_in_analytics() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
mock_responses_config(&server.uri())
.with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri()))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_managed_config()
.build_initialized()
.await?;
let start_id = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
thread_source: Some(ThreadSource::User),
service_name: Some("codex_work_desktop".to_string()),
..Default::default()
})
.await?;
let ThreadStartResponse { thread, .. } =
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(start_id)).await??;
let turn_id = mcp
.send_turn_start_request(TurnStartParams {
thread_id: thread.id.clone(),
client_user_message_id: None,
input: vec![UserInput::Text {
text: "materialize rollout".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(turn_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
let resume_id = mcp
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread.id.clone(),
exclude_turns: true,
..Default::default()
})
.await?;
let ThreadResumeResponse {
thread: resumed, ..
} = timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(resume_id)).await??;
let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_thread_initialized"
&& event["event_params"]["thread_id"] == resumed.id
&& event["event_params"]["initialization_mode"] == "resumed"
})
.await?;
assert_basic_thread_initialized_event(
&event,
&resumed.id,
&resumed.session_id,
"codex_work_desktop",
"mock-model",
"resumed",
"user",
);
Ok(())
}
fn set_session_meta_on_fake_rollout(
codex_home: &std::path::Path,
filename_ts: &str,
thread_id: &str,
thread_source: &str,
originator: &str,
) -> Result<()> {
let path = rollout_path(codex_home, filename_ts, thread_id);
let contents = std::fs::read_to_string(&path)?;
let mut lines = contents.lines();
let session_meta = lines
.next()
.ok_or_else(|| anyhow::anyhow!("fake rollout missing session meta"))?;
let mut session_meta: serde_json::Value = serde_json::from_str(session_meta)?;
session_meta["payload"]["thread_source"] = serde_json::json!(thread_source);
session_meta["payload"]["originator"] = serde_json::json!(originator);
let remaining = lines.collect::<Vec<_>>().join("\n");
std::fs::write(&path, format!("{session_meta}\n{remaining}\n"))?;
Ok(())
}
#[tokio::test]
async fn thread_resume_returns_rollout_history() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
@@ -4016,7 +3849,7 @@ fn ungated_goal_response(body: String) -> Vec<StreamingSseChunk> {
}
#[tokio::test]
async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Result<()> {
async fn thread_goal_lifecycle_accounts_usage_and_clear_deletes_goal() -> Result<()> {
let server = create_mock_responses_server_sequence_unchecked(vec![
responses::sse(vec![
responses::ev_response_created("materialize-thread"),
@@ -4031,9 +3864,7 @@ async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Resul
let codex_home = TempDir::new()?;
mock_responses_config(&server.uri())
.enable_feature(Feature::Goals)
.with_root_config(&format!(r#"chatgpt_base_url = "{}""#, server.uri()))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -4090,36 +3921,19 @@ async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Resul
)
.await??;
let created = wait_for_goal_event(&server, DEFAULT_READ_TIMEOUT, "created", "active").await?;
let persisted_goal_id = created["event_params"]["goal_id"]
.as_str()
.expect("created goal id");
assert_eq!(created["event_params"]["thread_id"], thread.id);
assert_eq!(created["event_params"]["turn_id"], serde_json::Value::Null);
assert_eq!(created["event_params"]["has_token_budget"], true);
assert!(created["event_params"]["session_id"].is_string());
assert!(created["event_params"]["app_server_client"].is_object());
assert!(created["event_params"]["runtime"].is_object());
assert!(created["event_params"].get("objective").is_none());
assert!(created["event_params"].get("token_budget").is_none());
let usage = wait_for_goal_event(
&server,
DEFAULT_READ_TIMEOUT,
"usage_accounted",
"budget_limited",
)
.await?;
let causal_turn_id = usage["event_params"]["turn_id"]
.as_str()
.expect("accounted usage turn id");
assert_eq!(usage["event_params"]["goal_id"], persisted_goal_id);
assert_eq!(usage["event_params"]["cumulative_tokens_accounted"], 200);
assert!(
usage["event_params"]["cumulative_time_accounted_seconds"]
.as_i64()
.is_some()
);
// The continuation turn spends the whole budget.
let budget_limited = timeout(DEFAULT_READ_TIMEOUT, async {
loop {
let notification: ThreadGoalUpdatedNotification =
mcp.read_notification("thread/goal/updated").await?;
if notification.goal.status == ThreadGoalStatus::BudgetLimited {
return Ok::<_, anyhow::Error>(notification);
}
}
})
.await??;
assert_eq!(budget_limited.thread_id, thread.id);
assert_eq!(budget_limited.goal.tokens_used, 200);
let requests = server
.received_requests()
@@ -4138,35 +3952,10 @@ async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Resul
let metadata: serde_json::Value = serde_json::from_str(metadata_header)?;
assert_eq!(metadata["turn_trigger"].as_str(), Some("goal"));
let status = wait_for_goal_event(
&server,
DEFAULT_READ_TIMEOUT,
"status_changed",
"budget_limited",
)
.await?;
assert_eq!(status["event_params"]["goal_id"], persisted_goal_id);
assert_eq!(status["event_params"]["turn_id"], causal_turn_id);
assert_eq!(
status["event_params"]["cumulative_tokens_accounted"],
serde_json::Value::Null
);
assert_eq!(
status["event_params"]["cumulative_time_accounted_seconds"],
serde_json::Value::Null
);
let requests = server.received_requests().await.expect("wiremock requests");
let goal_request = requests
.iter()
.filter(|request| request.url.path().ends_with("/responses"))
.nth(1)
.expect("externally created goal continuation request");
let goal_request_body = goal_request.body_json::<serde_json::Value>()?;
assert_eq!(
goal_request_body["client_metadata"]["turn_id"],
causal_turn_id
);
let goal_request_body = response_requests[1].body_json::<serde_json::Value>()?;
let causal_turn_id = goal_request_body["client_metadata"]["turn_id"]
.as_str()
.expect("goal continuation turn id");
responses::assert_root_turn(&goal_request_body, Some(causal_turn_id))?;
responses::assert_parent_turn(&goal_request_body, /*expected*/ None)?;
@@ -4188,11 +3977,6 @@ async fn thread_goal_lifecycle_emits_analytics_and_clear_deletes_goal() -> Resul
)
.await??;
let cleared =
wait_for_goal_event(&server, DEFAULT_READ_TIMEOUT, "cleared", "budget_limited").await?;
assert_eq!(cleared["event_params"]["goal_id"], persisted_goal_id);
assert_eq!(cleared["event_params"]["turn_id"], serde_json::Value::Null);
let get_id = mcp
.send_raw_request(
"thread/goal/get",

View File

@@ -62,11 +62,6 @@ use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::analytics::assert_basic_thread_initialized_event;
use super::analytics::mount_analytics_capture;
use super::analytics::thread_initialized_event;
use super::analytics::wait_for_analytics_payload;
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
const INVALID_REQUEST_ERROR_CODE: i64 = -32600;
const EXEC_POLICY_PARSE_WARNING_SUMMARY: &str = "Error parsing rules; custom rules not applied.";
@@ -955,44 +950,6 @@ fn normalize_path_for_comparison(path: impl AsRef<Path>) -> PathBuf {
path.as_ref().to_path_buf()
}
#[test_case("codex_work_desktop")]
#[tokio::test]
async fn thread_start_tracks_thread_initialized_analytics(originator: &str) -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;
let codex_home = TempDir::new()?;
create_config_toml_with_chatgpt_base_url(codex_home.path(), &server.uri(), &server.uri())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_managed_config()
.build_initialized()
.await?;
let ThreadStartResponse { thread, .. } = mcp
.start_thread(ThreadStartParams {
thread_source: Some(ThreadSource::User),
service_name: Some(originator.to_string()),
..Default::default()
})
.await?;
let payload = wait_for_analytics_payload(&server, DEFAULT_READ_TIMEOUT).await?;
assert_eq!(payload["events"].as_array().expect("events array").len(), 1);
let event = thread_initialized_event(&payload)?;
assert_basic_thread_initialized_event(
event,
&thread.id,
&thread.session_id,
originator,
"mock-model",
"new",
"user",
);
Ok(())
}
#[tokio::test]
async fn thread_start_respects_project_config_from_cwd() -> Result<()> {
let server = create_mock_responses_server_repeating_assistant("Done").await;

View File

@@ -1,324 +0,0 @@
//! Exercises the best-effort SiWC cost happy path through real app-server startup and OTLP.
//! The public in-process transport permits advancing the production timer without test-only hooks.
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::write_chatgpt_auth;
use app_test_support::write_models_cache;
use codex_app_server::in_process;
use codex_app_server::in_process::InProcessServerEvent;
use codex_app_server::in_process::InProcessStartArgs;
use codex_app_server_protocol::ClientInfo;
use codex_app_server_protocol::ClientRequest;
use codex_app_server_protocol::InitializeCapabilities;
use codex_app_server_protocol::InitializeParams;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::TurnEnvironmentParams;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::UserInput;
use codex_arg0::Arg0DispatchPaths;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::NoopThreadConfigLoader;
use codex_core::config::ConfigBuilder;
use codex_exec_server::EnvironmentManager;
use codex_feedback::CodexFeedback;
use codex_login::AuthCredentialsStoreMode;
use codex_protocol::protocol::SessionSource;
use core_test_support::responses;
use core_test_support::test_codex::test_env;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;
use tempfile::TempDir;
use tokio::time::timeout;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
const COST_PATH: &str = "/api/codex/usage/thread-estimates/query";
#[tokio::test]
async fn chatgpt_turn_cost_reaches_otlp_on_success() -> Result<()> {
let server = MockServer::start().await;
let collector = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/metrics"))
.respond_with(ResponseTemplate::new(200))
.mount(&collector)
.await;
Mock::given(method("POST")).and(path(COST_PATH))
.and(header("authorization", "Bearer siwc-token"))
.and(header("chatgpt-account-id", "workspace-a"))
.respond_with(move |request: &wiremock::Request| {
let body: Value = serde_json::from_slice(&request.body).expect("cost request");
assert_eq!(body["include_settled_response_ids"], true);
let threads: Vec<_> = body["threads"].as_array().expect("threads").iter().map(|thread| {
let turns: Vec<_> = thread["turn_ids"].as_array().expect("turns").iter().map(|turn_id| json!({
"turn_id": turn_id, "model": "mock-model", "estimated_usage_usd_micros": 1250001,
"settled_response_ids": ["resp-cost"]
})).collect();
json!({"thread_id": thread["thread_id"], "turns": turns})
}).collect();
ResponseTemplate::new(200).set_body_json(json!({"threads": threads}))
}).mount(&server).await;
let model = responses::mount_sse_once(
&server,
responses::sse(vec![
responses::ev_response_created("resp-cost"),
responses::ev_assistant_message("msg-cost", "Done"),
responses::ev_completed("resp-cost"),
]),
)
.await;
let home = TempDir::new()?;
std::fs::write(
home.path().join("config.toml"),
format!(
r#"
model = "mock-model"
model_provider = "openai"
openai_base_url = "{}/v1"
chatgpt_base_url = "{}"
approval_policy = "never"
[features]
responses_websockets = false
responses_websockets_v2 = false
runtime_metrics = true
[analytics]
enabled = true
[otel]
exporter = "none"
metrics_exporter = {{ otlp-http = {{ endpoint = "{}/metrics", protocol = "json" }} }}
"#,
server.uri(),
server.uri(),
collector.uri()
),
)?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new("siwc-token")
.account_id("workspace-a")
.chatgpt_account_id("workspace-a")
.chatgpt_user_id("user-a"),
AuthCredentialsStoreMode::File,
)?;
write_models_cache(home.path()).await?;
let loader_overrides = LoaderOverrides::without_managed_config_for_tests();
let config = Arc::new(
ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.loader_overrides(loader_overrides.clone())
.build()
.await?,
);
let provider = codex_core::otel_init::build_provider(
&config,
"test",
Some("codex-app-server"),
/*default_analytics_enabled*/ false,
)
.map_err(|error| anyhow::anyhow!(error.to_string()))?
.expect("OTLP enabled");
let metrics = provider.metrics.clone().expect("metrics exporter");
let env = test_env().await?;
let environment_manager = if let Some(url) = env.exec_server_url() {
EnvironmentManager::create_for_tests(
Some(url.to_string()),
/*local_runtime_paths*/ None,
)
.await
} else {
EnvironmentManager::default_for_tests()
};
let mut client = in_process::start(InProcessStartArgs {
arg0_paths: Arg0DispatchPaths::default(),
config,
cli_overrides: Vec::new(),
loader_overrides,
strict_config: false,
cloud_config_bundle: CloudConfigBundleLoader::default(),
embedded_network_policy: Default::default(),
thread_config_loader: Arc::new(NoopThreadConfigLoader),
feedback: CodexFeedback::new(),
log_db: None,
state_db: None,
environment_manager: Arc::new(environment_manager),
config_warnings: Vec::new(),
session_source: SessionSource::Cli,
enable_codex_api_key_env: false,
initialize: InitializeParams {
client_info: ClientInfo {
name: "codex-app-server-tests".to_string(),
title: None,
version: "test".to_string(),
},
capabilities: Some(InitializeCapabilities {
experimental_api: true,
..Default::default()
}),
},
channel_capacity: in_process::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
})
.await?;
wait_for_cost_queries(&server, /*count*/ 1).await;
let response = client
.request(ClientRequest::ThreadStart {
request_id: RequestId::Integer(1),
params: ThreadStartParams {
environments: Some(vec![TurnEnvironmentParams {
environment_id: env.selection().environment_id.clone(),
cwd: env.selection().cwd.clone().into(),
runtime_workspace_roots: None,
}]),
..Default::default()
},
})
.await?
.expect("thread/start");
let ThreadStartResponse { thread, .. } = serde_json::from_value(response)?;
let response = client
.request(ClientRequest::TurnStart {
request_id: RequestId::Integer(2),
params: TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: "Hello".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
},
})
.await?
.expect("turn/start");
let TurnStartResponse { turn } = serde_json::from_value(response)?;
timeout(Duration::from_secs(/*secs*/ 30), async {
while let Some(event) = client.next_event().await {
if let InProcessServerEvent::ServerNotification(event) = event
&& let ServerNotification::TurnCompleted(event) = *event
{
assert!(
event.turn.error.is_none(),
"turn failed: {:?}",
event.turn.error
);
break;
}
}
})
.await?;
assert_eq!(
model.single_request().header("authorization").as_deref(),
Some("Bearer siwc-token")
);
tokio::time::pause();
tokio::time::advance(Duration::from_secs(/*secs*/ 301)).await;
tokio::time::resume();
wait_for_cost_queries(&server, /*count*/ 2).await;
// Synchronize with actual recording, not just the backend receiving a request.
timeout(Duration::from_secs(/*secs*/ 10), async {
loop {
if metrics
.snapshot()
.expect("snapshot")
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
.any(|metric| metric.name() == "codex.turn.cost_microusd")
{
break;
}
tokio::task::yield_now().await;
}
})
.await?;
tokio::time::pause();
tokio::time::advance(Duration::from_secs(/*secs*/ 301)).await;
tokio::time::resume();
client.shutdown().await?;
tokio::task::spawn_blocking(move || provider.shutdown()).await?;
let mut points = Vec::new();
for request in collector.received_requests().await.expect("OTLP requests") {
let body: Value = serde_json::from_slice(&request.body)?;
for resource in body["resourceMetrics"]
.as_array()
.expect("resource metrics")
{
for scope in resource["scopeMetrics"].as_array().expect("scope metrics") {
for metric in scope["metrics"].as_array().expect("metrics") {
if metric["name"] == "codex.turn.cost_microusd" {
points.extend(
metric["sum"]["dataPoints"]
.as_array()
.expect("cost points")
.clone(),
);
}
}
}
}
}
assert_eq!(points.len(), 1);
assert_eq!(points[0]["asInt"], json!(1250001));
let attrs: std::collections::BTreeMap<_, _> = points[0]["attributes"]
.as_array()
.expect("attributes")
.iter()
.map(|attr| {
(
attr["key"].as_str().expect("key"),
attr["value"]["stringValue"].as_str().expect("value"),
)
})
.collect();
assert_eq!(attrs["turn.id"], turn.id);
assert_eq!(attrs["conversation.id"], thread.id);
assert_eq!(attrs["auth_mode"], "Chatgpt");
let requests = server
.received_requests()
.await
.expect("settlement requests");
let cost_requests: Vec<_> = requests
.iter()
.filter(|request| request.url.path() == COST_PATH)
.collect();
assert_eq!(cost_requests.len(), 2);
assert_eq!(
serde_json::from_slice::<Value>(&cost_requests[1].body)?,
json!({
"threads": [{"thread_id": thread.id, "turn_ids": [turn.id]}], "include_settled_response_ids": true
})
);
server.verify().await;
Ok(())
}
async fn wait_for_cost_queries(server: &MockServer, count: usize) {
timeout(Duration::from_secs(/*secs*/ 15), async {
loop {
if server
.received_requests()
.await
.expect("requests")
.iter()
.filter(|request| request.url.path() == COST_PATH)
.count()
>= count
{
break;
}
tokio::task::yield_now().await;
}
})
.await
.expect("cost query");
}

View File

@@ -11,7 +11,6 @@ use app_test_support::create_final_assistant_message_sse_response;
use app_test_support::create_mock_responses_server_repeating_assistant;
use app_test_support::create_mock_responses_server_sequence;
use app_test_support::create_mock_responses_server_sequence_unchecked;
use app_test_support::create_request_user_input_sse_response;
use app_test_support::format_with_current_shell_display;
use app_test_support::write_chatgpt_auth;
use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url;
@@ -116,10 +115,6 @@ use wiremock::matchers::body_partial_json;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_analytics_event;
use super::analytics::wait_for_matching_analytics_event;
#[cfg(windows)]
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
#[cfg(not(windows))]
@@ -357,13 +352,8 @@ async fn turn_start_omits_notification_media_without_changing_model_input() -> R
Ok(())
}
#[test_case(None; "analytics_unset")]
#[test_case(Some(true); "analytics_enabled")]
#[test_case(Some(false); "analytics_disabled")]
#[tokio::test]
async fn tool_call_metadata_stays_out_of_raw_response_item_notifications(
analytics_enabled: Option<bool>,
) -> Result<()> {
async fn tool_call_metadata_stays_out_of_raw_response_item_notifications() -> Result<()> {
skip_if_no_network!(Ok(()));
let arguments = json!({"query": "redaction"});
@@ -409,7 +399,7 @@ async fn tool_call_metadata_stays_out_of_raw_response_item_notifications(
.mount(&server)
.await;
let codex_home = TempDir::new()?;
let mut config = MockResponsesConfig::new(&server.uri())
MockResponsesConfig::new(&server.uri())
.with_provider_name("OpenAI")
.with_provider_config("supports_websockets = false")
.with_root_config(&format!(
@@ -417,11 +407,8 @@ async fn tool_call_metadata_stays_out_of_raw_response_item_notifications(
apps.chatgpt_base_url
))
.enable_feature(Feature::Apps)
.enable_feature(Feature::ExecutedToolCallMetadata);
if let Some(enabled) = analytics_enabled {
config = config.with_extra_config(&format!("[analytics]\nenabled = {enabled}"));
}
config.write(codex_home.path())?;
.enable_feature(Feature::ExecutedToolCallMetadata)
.write(codex_home.path())?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-test-token")
@@ -537,11 +524,11 @@ async fn tool_call_metadata_stays_out_of_raw_response_item_notifications(
.find(|item| item["type"] == "function_call_output" && item["call_id"] == "mcp-call")
.context("persisted MCP output")?;
assert_eq!(captured["output"], raw_output["output"]);
// The custom inference endpoint omits raw metadata, so verify capture in the rollout.
// Raw MCP result metadata is never recorded, not even in the local rollout.
assert_eq!(
captured["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0]
.get("tool_result_metadata"),
(analytics_enabled != Some(false)).then_some(&result_metadata),
None,
);
Ok(())
}
@@ -555,7 +542,6 @@ async fn turn_start_with_empty_input_runs_model_request() -> Result<()> {
MockResponsesConfig::new(&server.uri())
.with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri()))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -610,15 +596,6 @@ async fn turn_start_with_empty_input_runs_model_request() -> Result<()> {
[codex_app_server_protocol::ThreadItem { payload: ThreadItemPayload::AgentMessage { text, .. }, .. }] if text == "Done"
));
let event = wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?;
assert_eq!(
(
event["event_params"]["turn_id"].as_str(),
event["event_params"]["root_turn_id"].as_str(),
),
(Some(turn.id.as_str()), Some(turn.id.as_str()))
);
let requests = server
.received_requests()
.await
@@ -1497,7 +1474,7 @@ async fn thread_start_omits_empty_instruction_overrides_from_model_request() ->
}
#[tokio::test]
async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> {
async fn turn_start_forwards_trigger_and_source_after_retry() -> Result<()> {
let server = responses::start_mock_server().await;
let response_mock = responses::mount_response_sequence(
&server,
@@ -1523,7 +1500,6 @@ async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> {
let config = std::fs::read_to_string(&config_path)?
.replace("stream_max_retries = 0", "stream_max_retries = 1");
std::fs::write(config_path, config)?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -1540,7 +1516,7 @@ async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> {
})
.await?;
let TurnStartResponse { turn } = mcp
let _: TurnStartResponse = mcp
.request(|request_id| ClientRequest::TurnStart {
request_id,
params: TurnStartParams {
@@ -1568,11 +1544,6 @@ async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> {
)
.await??;
let event = wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?;
assert_eq!(event["event_params"]["thread_id"], thread.id);
assert_eq!(event["event_params"]["session_id"], thread.session_id);
assert_eq!(event["event_params"]["turn_id"], turn.id);
assert_eq!(event["event_params"]["root_turn_id"], turn.id);
let request = response_mock.requests()[0].body_json();
let request_metadata: Value = serde_json::from_str(
request["client_metadata"]["x-codex-turn-metadata"]
@@ -1581,82 +1552,14 @@ async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> {
)?;
assert_eq!(
json!({
"eventTrigger": event["event_params"]["turn_trigger"],
"eventSource": event["event_params"]["codex_turn_source"],
"requestTrigger": request_metadata["turn_trigger"],
"requestSource": request_metadata["source"],
}),
json!({
"eventTrigger": "user",
"eventSource": "composer",
"requestTrigger": "user",
"requestSource": "composer",
})
);
assert_eq!(
event["event_params"]["app_server_client"]["product_client_id"],
"codex_work_desktop"
);
assert_eq!(event["event_params"]["model"], "mock-model");
assert_eq!(event["event_params"]["model_provider"], "mock_provider");
assert_eq!(event["event_params"]["sandbox_policy"], "read_only");
assert_eq!(event["event_params"]["workspace_kind"], "projectless");
assert_eq!(event["event_params"]["ephemeral"], false);
assert_eq!(event["event_params"]["thread_source"], "user");
assert_eq!(event["event_params"]["initialization_mode"], "new");
assert_eq!(
event["event_params"]["subagent_source"],
serde_json::Value::Null
);
assert_eq!(
event["event_params"]["parent_thread_id"],
serde_json::Value::Null
);
assert_eq!(event["event_params"]["num_input_images"], 1);
assert_eq!(
event["event_params"]["image_preparations"],
json!([{
"message_role": "user",
"item_id": null,
"effective_detail": "high",
"source_width": 1,
"source_height": 1,
"prepared_width": 1,
"prepared_height": 1,
}])
);
assert_eq!(event["event_params"]["status"], "completed");
assert!(event["event_params"]["started_at"].as_u64().is_some());
assert!(event["event_params"]["completed_at"].as_u64().is_some());
assert!(event["event_params"]["duration_ms"].as_u64().is_some());
assert_eq!(event["event_params"]["input_tokens"], 0);
assert_eq!(event["event_params"]["cached_input_tokens"], 0);
assert_eq!(event["event_params"]["output_tokens"], 0);
assert_eq!(event["event_params"]["reasoning_output_tokens"], 0);
assert_eq!(event["event_params"]["total_tokens"], 0);
let params = &event["event_params"];
let timings_are_numbers = [
"before_first_sampling_ms",
"sampling_ms",
"between_sampling_overhead_ms",
"tool_blocking_ms",
"after_last_sampling_ms",
]
.into_iter()
.all(|field| params[field].as_u64().is_some());
assert_eq!(
json!({
"timingsAreNumbers": timings_are_numbers,
"toolBlockingMs": params["tool_blocking_ms"],
"samplingRequestCount": params["sampling_request_count"],
"samplingRetryCount": params["sampling_retry_count"],
"responseRequestCount": response_mock.requests().len(),
}),
json!({
"timingsAreNumbers": true,
"toolBlockingMs": 0,
"samplingRequestCount": 2,
"samplingRetryCount": 1,
"requestTrigger": "user",
"requestSource": "composer",
// The first sampling request fails with a retryable error.
"responseRequestCount": 2,
})
);
@@ -1664,296 +1567,6 @@ async fn turn_start_tracks_thread_originator_in_analytics() -> Result<()> {
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn code_mode_exec_emits_correlated_production_analytics() -> Result<()> {
let server = responses::start_mock_server().await;
let _responses = responses::mount_sse_sequence(
&server,
vec![
responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_custom_tool_call("exec-1", "exec", "text('analytics');"),
responses::ev_completed("resp-1"),
]),
responses::sse(vec![responses::ev_completed("resp-2")]),
],
)
.await;
let codex_home = TempDir::new()?;
MockResponsesConfig::new(&server.uri())
.enable_feature(Feature::CodeModeOnly)
.with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri()))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_managed_config()
.build_initialized()
.await?;
let params = ThreadStartParams::default();
let thread = app_server.start_thread(params).await?;
let turn = app_server
.start_turn_and_wait_for_completion(TurnStartParams {
thread_id: thread.thread.id,
input: vec![V2UserInput::Text {
text: "run exec".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let event = wait_for_analytics_event(
&server,
DEFAULT_READ_TIMEOUT,
"codex_dynamic_tool_call_event",
)
.await?;
assert_eq!(
json!({
"turnId": event["event_params"]["turn_id"],
"rootTurnId": event["event_params"]["root_turn_id"],
"tool": event["event_params"]["tool_name"],
"origin": event["event_params"]["originating_response_id"],
"subsequent": event["event_params"]["subsequent_response_id"],
"hasCell": event["event_params"]["cell_id"].as_str().is_some(),
}),
json!({
"turnId": turn.turn.id,
"rootTurnId": turn.turn.id,
"tool": "exec",
"origin": "resp-1",
"subsequent": "resp-2",
"hasCell": true,
})
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn turn_profile_tracks_blocking_tool_and_follow_up_sampling() -> Result<()> {
let control_tools = [
("call1", "request_user_input", json!({})),
(
"plan-call",
"update_plan",
json!({"plan": [{"step": "PRIVATE_PLAN", "status": "in_progress"}]}),
),
(
"image-call",
"view_image",
json!({"path": "PRIVATE_IMAGE_PATH.png"}),
),
("get-goal-call", "get_goal", json!({})),
(
"create-goal-call",
"create_goal",
json!({"objective": "PRIVATE_GOAL"}),
),
(
"update-goal-call",
"update_goal",
json!({"status": "complete"}),
),
];
let mut responses = vec![
create_request_user_input_sse_response("call1")?,
create_final_assistant_message_sse_response("Done")?,
];
responses.extend(control_tools.iter().skip(1).map(|(call_id, tool, args)| {
let response_id = format!("resp-{call_id}");
responses::sse(vec![
responses::ev_response_created(&response_id),
responses::ev_function_call(call_id, tool, &args.to_string()),
responses::ev_completed(&response_id),
])
}));
responses.push(create_final_assistant_message_sse_response("Done")?);
let server = create_mock_responses_server_sequence(responses).await;
let codex_home = TempDir::new()?;
MockResponsesConfig::new(&server.uri())
.enable_feature(Feature::Goals)
.with_root_config(&format!(
"chatgpt_base_url = \"{}\"\ntools.update_plan.enabled = true",
server.uri()
))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_managed_config()
.build_initialized()
.await?;
let ThreadStartResponse { thread, .. } = mcp
.start_thread(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
.await?;
let TurnStartResponse { turn: first_turn } = mcp
.request(|request_id| ClientRequest::TurnStart {
request_id,
params: TurnStartParams {
thread_id: thread.id.clone(),
client_user_message_id: None,
input: vec![V2UserInput::Text {
text: "ask something".to_string(),
text_elements: Vec::new(),
}],
collaboration_mode: Some(CollaborationMode {
mode: ModeKind::Plan,
settings: Settings {
model: "mock-model".to_string(),
reasoning_effort: Some(ReasoningEffort::Medium),
developer_instructions: None,
},
}),
..Default::default()
},
})
.await?;
let server_req = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_request_message(),
)
.await??;
let ServerRequest::ToolRequestUserInput { request_id, .. } = server_req else {
panic!("expected ToolRequestUserInput request, got: {server_req:?}");
};
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
mcp.send_response(
request_id,
json!({
"answers": {
"confirm_path": { "answers": ["yes"] }
}
}),
)
.await?;
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
)
.await??;
let event = wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_event").await?;
let params = &event["event_params"];
assert_eq!(
json!({
"turnId": params["turn_id"],
"rootTurnId": params["root_turn_id"],
"toolBlockingIsPositive": params["tool_blocking_ms"]
.as_u64()
.is_some_and(|duration| duration > 0),
"samplingRequestCount": params["sampling_request_count"],
"samplingRetryCount": params["sampling_retry_count"],
"totalToolCalls": params["total_tool_call_count"],
"dynamicToolCalls": params["dynamic_tool_call_count"],
"status": params["status"],
}),
json!({
"turnId": first_turn.id,
"rootTurnId": first_turn.id,
"toolBlockingIsPositive": true,
"samplingRequestCount": 2,
"samplingRetryCount": 0,
"totalToolCalls": 1,
"dynamicToolCalls": 0,
"status": "completed",
})
);
let second_turn = mcp
.start_turn_and_wait_for_completion(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![V2UserInput::Text {
text: "run the other control tools".to_string(),
text_elements: Vec::new(),
}],
collaboration_mode: Some(CollaborationMode {
mode: ModeKind::Default,
settings: Settings {
model: "mock-model".to_string(),
reasoning_effort: Some(ReasoningEffort::Medium),
developer_instructions: None,
},
}),
..Default::default()
})
.await?;
for (call_id, tool_name, _) in control_tools {
let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_control_tool_call_event"
&& event["event_params"]["item_id"] == call_id
})
.await?;
let success = tool_name != "view_image";
let turn_id = if call_id == "call1" {
&first_turn.id
} else {
&second_turn.turn.id
};
assert_eq!(
json!({
"turnId": event["event_params"]["turn_id"],
"rootTurnId": event["event_params"]["root_turn_id"],
"tool": event["event_params"]["tool_name"],
"success": event["event_params"]["success"],
"status": event["event_params"]["terminal_status"],
"hasOrigin": event["event_params"]["originating_response_id"]
.as_str()
.is_some(),
}),
json!({
"turnId": turn_id,
"rootTurnId": turn_id,
"tool": tool_name,
"success": success,
"status": if success { "completed" } else { "failed" },
"hasOrigin": true,
})
);
let serialized = event.to_string();
assert!(
![
"PRIVATE_PLAN",
"PRIVATE_IMAGE_PATH",
"PRIVATE_GOAL",
"Proceed with the plan?"
]
.iter()
.any(|private_input| serialized.contains(private_input)),
"tool-call analytics must not contain private tool arguments: {serialized}"
);
}
let second_turn_event =
wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_turn_event"
&& event["event_params"]["turn_id"] == second_turn.turn.id
})
.await?;
assert_eq!(
json!({
"rootTurnId": second_turn_event["event_params"]["root_turn_id"],
"total": second_turn_event["event_params"]["total_tool_call_count"],
"dynamic": second_turn_event["event_params"]["dynamic_tool_call_count"],
}),
json!({"rootTurnId": second_turn.turn.id, "total": 5, "dynamic": 0})
);
Ok(())
}
#[tokio::test]
async fn turn_start_accepts_text_at_limit_with_mention_item() -> Result<()> {
let responses = vec![create_final_assistant_message_sse_response("Done")?];
@@ -4426,7 +4039,6 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<()
server.uri()
))
.write(codex_home.path())?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -4545,42 +4157,22 @@ async fn turn_start_emits_spawn_agent_item_with_model_metadata_v2() -> Result<()
assert_eq!(turn_completed.thread_id, thread.id);
assert_eq!(turn_completed.turn.id, turn.turn.id);
let child_turn_event =
wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_turn_event"
&& event["event_params"]["thread_id"] == receiver_thread_id
})
.await?;
let child_tool_event =
wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_control_tool_call_event"
&& event["event_params"]["item_id"] == CHILD_PLAN_CALL_ID
})
.await?;
let child_request = child_turn
.requests()
.into_iter()
.find(|request| request.body_json()["client_metadata"]["thread_id"] == receiver_thread_id)
.context("child should issue a model request")?
.body_json();
let child_request = timeout(DEFAULT_READ_TIMEOUT, async {
loop {
if let Some(request) = child_turn.requests().into_iter().find(|request| {
request.body_json()["client_metadata"]["thread_id"] == receiver_thread_id
}) {
return request.body_json();
}
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
}
})
.await?;
let child_turn_id = child_request["client_metadata"]["turn_id"]
.as_str()
.context("child request should have a turn id")?;
assert_ne!(child_turn_id, turn.turn.id);
for event in [child_turn_event, child_tool_event] {
assert_eq!(
json!({
"thread_id": event["event_params"]["thread_id"],
"turn_id": event["event_params"]["turn_id"],
"root_turn_id": event["event_params"]["root_turn_id"],
}),
json!({
"thread_id": receiver_thread_id,
"turn_id": child_turn_id,
"root_turn_id": turn.turn.id,
})
);
}
responses::assert_root_turn(&child_request, Some(turn.turn.id.as_str()))?;
// Reuse this live spawn setup to cover thread/delete's ThreadManager descendant path.
let _: ThreadDeleteResponse = mcp
@@ -4668,7 +4260,6 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected(
.with_root_config(&format!("chatgpt_base_url = \"{}\"", server.uri()))
.write(codex_home.path())?;
write_models_cache(codex_home.path()).await?;
mount_analytics_capture(&server, codex_home.path()).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
@@ -4942,63 +4533,6 @@ async fn direct_input_to_multi_agent_v2_subagent_is_rejected(
);
}
let event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_collab_agent_tool_call_event"
&& event["event_params"]["item_id"] == SPAWN_CALL_ID
})
.await?;
assert_eq!(
json!({
"tool_name": event["event_params"]["tool_name"],
"sender_thread_id": event["event_params"]["sender_thread_id"],
"receiver_thread_ids": event["event_params"]["receiver_thread_ids"],
"agent_state_count": event["event_params"]["agent_state_count"],
"terminal_status": event["event_params"]["terminal_status"],
}),
json!({
"tool_name": "spawn_agent",
"sender_thread_id": thread.id,
"receiver_thread_ids": [child_thread_id],
"agent_state_count": 1,
"terminal_status": "completed",
})
);
let duration_ms = event["event_params"]["duration_ms"]
.as_u64()
.context("successful spawn should report its execution duration")?;
assert_eq!(event["event_params"]["execution_duration_ms"], duration_ms);
assert!(!event.to_string().contains(CHILD_PROMPT));
let failed_event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_collab_agent_tool_call_event"
&& event["event_params"]["item_id"] == FAILED_SPAWN_CALL_ID
})
.await?;
assert_eq!(
json!({
"tool_name": failed_event["event_params"]["tool_name"],
"receiver_thread_count": failed_event["event_params"]["receiver_thread_count"],
"receiver_thread_ids": failed_event["event_params"]["receiver_thread_ids"],
"terminal_status": failed_event["event_params"]["terminal_status"],
"failure_kind": failed_event["event_params"]["failure_kind"],
}),
json!({
"tool_name": "spawn_agent",
"receiver_thread_count": 0,
"receiver_thread_ids": [],
"terminal_status": "failed",
"failure_kind": "tool_error",
})
);
assert!(!failed_event.to_string().contains(CHILD_PROMPT));
let turn_event = wait_for_matching_analytics_event(&server, DEFAULT_READ_TIMEOUT, |event| {
event["event_type"] == "codex_turn_event" && event["event_params"]["thread_id"] == thread.id
})
.await?;
assert_eq!(turn_event["event_params"]["subagent_tool_call_count"], 2);
assert_eq!(turn_event["event_params"]["total_tool_call_count"], 2);
Ok(())
}

View File

@@ -6,6 +6,7 @@ use app_test_support::TestAppServer;
use app_test_support::create_command_execution_sse_response;
use app_test_support::create_mock_responses_server_sequence;
use app_test_support::create_mock_responses_server_sequence_unchecked;
use app_test_support::mount_chatgpt_account;
use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url;
use codex_app_server::INPUT_TOO_LARGE_ERROR_CODE;
use codex_app_server::INVALID_PARAMS_ERROR_CODE;
@@ -32,9 +33,6 @@ use std::collections::HashMap;
use tempfile::TempDir;
use tokio::time::timeout;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_analytics_event;
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
#[tokio::test]
@@ -49,7 +47,7 @@ async fn turn_steer_requires_active_turn() -> Result<()> {
&server.uri(),
&server.uri(),
)?;
mount_analytics_capture(&server, &codex_home).await?;
mount_chatgpt_account(&server, &codex_home).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
@@ -85,21 +83,6 @@ async fn turn_steer_requires_active_turn() -> Result<()> {
.await??;
assert_eq!(steer_err.error.code, -32600);
let event =
wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_steer_event").await?;
assert_eq!(event["event_params"]["thread_id"], thread.id);
assert_eq!(event["event_params"]["result"], "rejected");
assert_eq!(event["event_params"]["num_input_images"], 0);
assert_eq!(
event["event_params"]["expected_turn_id"],
"turn-does-not-exist"
);
assert_eq!(
event["event_params"]["accepted_turn_id"],
serde_json::Value::Null
);
assert_eq!(event["event_params"]["rejection_reason"], "no_active_turn");
let malformed_request = mcp
.send_turn_steer_request(TurnSteerParams {
thread_id: thread.id,
@@ -175,7 +158,7 @@ async fn turn_steer_rejects_oversized_text_input() -> Result<()> {
&server.uri(),
&server.uri(),
)?;
mount_analytics_capture(&server, &codex_home).await?;
mount_chatgpt_account(&server, &codex_home).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
@@ -292,7 +275,7 @@ async fn turn_steer_returns_active_turn_id(tool_outputs: bool) -> Result<()> {
&server.uri(),
&server.uri(),
)?;
mount_analytics_capture(&server, &codex_home).await?;
mount_chatgpt_account(&server, &codex_home).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
@@ -387,19 +370,6 @@ async fn turn_steer_returns_active_turn_id(tool_outputs: bool) -> Result<()> {
})
.await??;
let event =
wait_for_analytics_event(&server, DEFAULT_READ_TIMEOUT, "codex_turn_steer_event").await?;
assert_eq!(event["event_params"]["thread_id"], thread.id);
assert_eq!(event["event_params"]["session_id"], thread.session_id);
assert_eq!(event["event_params"]["result"], "accepted");
assert_eq!(event["event_params"]["num_input_images"], 0);
assert_eq!(event["event_params"]["expected_turn_id"], turn.id);
assert_eq!(event["event_params"]["accepted_turn_id"], turn.id);
assert_eq!(
event["event_params"]["rejection_reason"],
serde_json::Value::Null
);
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_notification_message("turn/completed"),
@@ -476,7 +446,7 @@ async fn turn_steer_rejects_context_only_input_without_merging_context() -> Resu
&server.uri(),
&server.uri(),
)?;
mount_analytics_capture(&server, &codex_home).await?;
mount_chatgpt_account(&server, &codex_home).await?;
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)