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

@@ -240,12 +240,6 @@ async fn child_turn_start_preserves_root_attribution() -> Result<()> {
let test = test_codex()
.with_model("gpt-5.6-sol")
.with_config(|config| {
config.otel.log_agent_responses = true;
config.otel.exporter = codex_config::types::OtelExporterKind::OtlpGrpc {
endpoint: "http://127.0.0.1:1".into(),
headers: Default::default(),
tls: None,
};
config.features.enable(Feature::Collab).unwrap();
config.features.enable(Feature::MultiAgentV2).unwrap();
})
@@ -288,40 +282,6 @@ async fn child_turn_start_preserves_root_attribution() -> Result<()> {
.iter()
.all(|(_, event)| { event.root_turn_id.as_ref() == Some(root_turn_id) })
);
logs_assert(|lines: &[&str]| {
let logs: Vec<_> = lines
.iter()
.filter(|line| line.contains("codex.agent_response"))
.collect();
assert_eq!(logs.len(), 2);
for (id, turn) in &starts {
let line = logs
.iter()
.find(|line| line.contains(&format!(" conversation.id={id}")))
.expect("response log");
let (agent, item, text) = if *id == test.session_configured.thread_id {
("main", "msg-first-call", "collaboration completed")
} else {
assert!(line.contains(&format!(
" parent.conversation.id=\"{}\"",
test.session_configured.thread_id
)));
assert!(line.contains(&format!(" parent.turn.id={root_turn_id:?}")));
assert!(line.contains(" initiating.agent.path=\"/root\""));
("subagent", "msg-worker-first-call", "worker completed")
};
for field in [
format!(" agent.type={agent:?}"),
format!(" turn.id={:?}", turn.turn_id),
format!(" root.turn.id={root_turn_id:?}"),
format!(" item.id={item:?}"),
format!(" response={text:?}"),
] {
assert!(line.contains(&field), "missing {field}: {line}");
}
}
Ok(())
});
Ok(())
}

View File

@@ -611,7 +611,6 @@ async fn websocket_first_turn_uses_startup_prewarm_and_create(
.with_model("gpt-5.2")
.with_config(move |config| {
config.update_plan_enabled = update_plan_enabled;
config.analytics_enabled = Some(false);
if incremental_tools {
config
.features
@@ -663,7 +662,7 @@ async fn websocket_first_turn_uses_startup_prewarm_and_create(
.expect("warmup turn metadata"),
)?;
assert_eq!(warmup_metadata["request_kind"].as_str(), Some("prewarm"));
assert_eq!(warmup_metadata["analytics_enabled"].as_bool(), Some(false));
assert!(warmup_metadata.get("analytics_enabled").is_none());
assert_eq!(
warmup_metadata["window_id"].as_str(),
warmup["client_metadata"]["x-codex-window-id"].as_str()
@@ -682,7 +681,7 @@ async fn websocket_first_turn_uses_startup_prewarm_and_create(
.expect("turn metadata"),
)?;
assert_eq!(turn_metadata["request_kind"].as_str(), Some("turn"));
assert_eq!(turn_metadata["analytics_enabled"].as_bool(), Some(false));
assert!(turn_metadata.get("analytics_enabled").is_none());
assert_eq!(warmup_metadata["window_number"].as_u64(), Some(0));
assert_eq!(
warmup_metadata["window_number"],

View File

@@ -1,7 +1,6 @@
//! Verifies connector-scoped exposure, server restrictions, and MCP dispatch.
use codex_core::config::Config;
use core_test_support::apps_test_server::mock_apps_mcp_server_config;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::ExtensionRegistryBuilder;
use codex_extension_api::McpServerContribution;
@@ -11,6 +10,7 @@ use codex_features::Feature;
use codex_protocol::config_types::ToolExposureSurface;
use codex_protocol::openai_models::ToolMode;
use core_test_support::apps_test_server::AppsTestServer;
use core_test_support::apps_test_server::mock_apps_mcp_server_config;
use core_test_support::apps_test_server::search_capable_apps_builder;
use core_test_support::responses;
use pretty_assertions::assert_eq;
@@ -189,7 +189,6 @@ pub(super) async fn connector_exposure_requests(
if case.direct_only {
config.code_mode.direct_only_tool_namespaces = vec![namespace.to_string()];
}
config.analytics_enabled = Some(false);
config
.features
.enable(Feature::CodeModeHost)

View File

@@ -67,7 +67,6 @@ enabled = false
.features
.enable(Feature::CodeModeOnlyStrictThirdPartyTools)
.expect("strict third-party tools");
config.analytics_enabled = Some(false);
});
let test = builder.build_with_auto_env(&server).await?;
test.submit_turn("Look up my calendar.").await?;

View File

@@ -2090,7 +2090,6 @@ async fn prefers_apikey_when_config_prefers_apikey_even_with_chatgpt_tokens() {
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
empty_extension_registry(),
Arc::new(codex_core::test_support::EmptyUserInstructionsProvider),
/*analytics_events_client*/ None,
codex_core::passthrough_image_store(),
ThreadStoreBuilder::from_config(&config, /*state_db*/ None).build(),
/*agent_graph_store*/ None,

View File

@@ -11,7 +11,6 @@ use anyhow::Context;
use anyhow::Result;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use codex_analytics::AnalyticsEventsClient;
use codex_config::types::McpServerConfig;
use codex_config::types::McpServerTransportConfig;
use codex_core::StartThreadOptions;
@@ -38,7 +37,6 @@ use codex_http_client::DestinationPolicy;
use codex_http_client::NetworkPolicyController;
use codex_login::CodexAuth;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use core_test_support::apps_test_server::mock_apps_mcp_server_config;
use codex_models_manager::bundled_models_response;
use codex_protocol::config_types::ApprovalsReviewer;
use codex_protocol::config_types::CollaborationMode;
@@ -82,6 +80,7 @@ use codex_web_search_extension::install as install_web_search_extension;
use core_test_support::apps_test_server::AppsTestServer;
use core_test_support::apps_test_server::AppsTestToolLoading;
use core_test_support::apps_test_server::DIRECT_CALENDAR_APP_ONLY_TOOL;
use core_test_support::apps_test_server::mock_apps_mcp_server_config;
use core_test_support::apps_test_server::recorded_apps_tool_calls;
use core_test_support::apps_test_server::search_capable_apps_builder;
use core_test_support::assert_regex_match;
@@ -2191,399 +2190,18 @@ fn assert_result_metadata_call(
assert!(metadata.get("tool_result_metadata").is_none());
}
enum ResultMetadataAnalytics {
Config(Option<bool>),
HostDisabled(Option<bool>),
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn direct_result_metadata_retained_budget_preserves_resource_access() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let arguments = serde_json::json!({ "search": "retained-budget" });
let resource_access = serde_json::json!({
"schema_version": 1,
"resource_coverage": "complete",
"resources": [],
});
let resource_only = serde_json::json!({ "openai/resource_access": resource_access });
let result_metadata = serde_json::json!({
"payload": "x".repeat(31 * 1024),
"openai/resource_access": resource_access,
});
let metadata_bytes = serde_json::to_vec(&result_metadata)?.len();
assert!(metadata_bytes * 32 < 1024 * 1024);
assert!(metadata_bytes * 33 > 1024 * 1024);
let apps_server = mount_result_metadata_app(
&server,
Some(result_metadata.clone()),
/*is_error*/ false,
)
.await?;
let mut builder =
result_metadata_apps_builder(apps_server.chatgpt_base_url, "user@example.com").with_config(
|config| {
config.features.disable(Feature::CodeModeOnly).unwrap();
config.features.disable(Feature::CodeMode).unwrap();
},
);
let test = builder.build_with_auto_env(&server).await?;
let call_ids = (0..33)
.map(|index| format!("call-{index}"))
.collect::<Vec<_>>();
let mut events = call_ids[..32]
.iter()
.map(|call_id| {
responses::ev_function_call_with_namespace(
call_id,
"mcp__codex_apps__messagesearch",
RESULT_METADATA_TOOL,
&arguments.to_string(),
)
})
.collect::<Vec<_>>();
events.push(ev_completed("resp-1"));
let initial = responses::mount_sse_once(&server, sse(events)).await;
// Cross the retained-history limit after the first batch has finished, regardless of order.
let overflow = responses::mount_sse_once(
&server,
sse(vec![
responses::ev_function_call_with_namespace(
&call_ids[32],
"mcp__codex_apps__messagesearch",
RESULT_METADATA_TOOL,
&arguments.to_string(),
),
ev_completed("resp-2"),
]),
)
.await;
let completion = responses::mount_sse_once(&server, sse(vec![ev_completed("resp-3")])).await;
test.submit_turn("Search the connected app 33 times")
.await?;
let initial = initial.single_request();
assert!(initial.has_message_with_input_texts("user", |texts| {
texts == ["Search the connected app 33 times"]
}));
assert!(
!tool_names(&initial.body_json())
.iter()
.any(|name| name == "exec")
);
for (request, expected_calls) in [
(overflow.single_request(), &call_ids[..32]),
(completion.single_request(), &call_ids[..]),
] {
for call_id in expected_calls {
let output = request.function_call_output(call_id);
assert_eq!(
&output["output"].as_array().expect("direct output content")[1..],
&[serde_json::json!({
"type": "input_text",
"text": RESULT_METADATA_PRIVATE_RESULT,
})],
);
}
}
let calls = recorded_apps_tool_calls(&server).await;
assert_eq!(calls.len(), call_ids.len());
for call in calls {
assert_eq!(call["params"]["name"], RESULT_METADATA_TOOL);
assert_eq!(call["params"]["arguments"], arguments);
}
// Inspect retained history directly to isolate the Direct admission budget.
let history = test.codex.conversation_history_snapshot().await;
assert!(
history
.items()
.map(codex_protocol::models::executed_tool_call_metadata_bytes)
.sum::<usize>()
<= 1024 * 1024
);
let outputs = history
.items()
.filter(|item| matches!(item, ResponseItem::FunctionCallOutput { .. }))
.collect::<Vec<_>>();
assert_eq!(outputs.len(), call_ids.len());
for (index, call_id) in call_ids.iter().enumerate() {
let item = outputs
.iter()
.find(|item| matches!(item, ResponseItem::FunctionCallOutput { call_id: Some(id), .. } if id == call_id))
.expect("retained Direct output");
if let ResponseItem::FunctionCallOutput { output, .. } = item {
assert_eq!(output.success, Some(true));
}
let output = serde_json::to_value(item)?;
let metadata = &output["internal_chat_message_metadata_passthrough"];
assert_eq!(metadata["tool_calls_complete"], true);
let calls = metadata["executed_tool_calls"].as_array().unwrap();
assert_eq!(calls.len(), 1);
assert!(
calls[0]["name"]
.as_str()
.unwrap()
.ends_with(RESULT_METADATA_TOOL)
);
assert_eq!(calls[0]["arguments"], arguments);
assert_eq!(
calls[0]["tool_result_metadata"],
if index < 32 {
&result_metadata
} else {
&resource_only
}
.clone(),
);
}
test.codex.shutdown_and_wait().await?;
Ok(())
}
#[test_case(ToolMode::Direct; "direct")]
#[test_case(ToolMode::CodeModeOnly; "code_mode")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn result_metadata_preserves_results_within_request_budget(
tool_mode: ToolMode,
) -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let arguments = [
serde_json::json!({ "search": "large" }),
serde_json::json!({ "search": "medium-1" }),
serde_json::json!({ "search": "medium-2" }),
serde_json::json!({ "search": "medium-3" }),
serde_json::json!({ "search": "medium-4" }),
serde_json::json!({ "search": "medium-5" }),
serde_json::json!({ "search": "oversized" }),
serde_json::json!({ "search": "small" }),
];
let resource_access = serde_json::json!({
"schema_version": 1,
"resource_coverage": "complete",
"resources": [],
});
let result_metadata = [
serde_json::json!({
"payload": "l".repeat(31 * 1024),
"openai/resource_access": resource_access,
}),
serde_json::json!({ "payload": "m".repeat(450 * 1024) }),
serde_json::json!({ "payload": "m".repeat(450 * 1024) }),
serde_json::json!({ "payload": "m".repeat(450 * 1024) }),
serde_json::json!({ "payload": "m".repeat(450 * 1024) }),
serde_json::json!({ "payload": "m".repeat(450 * 1024) }),
serde_json::json!({
"payload": "o".repeat(40 * 1024),
"openai/resource_access": {
"schema_version": 1,
"resource_coverage": "complete",
"resources": ["r".repeat(40 * 1024)],
},
}),
serde_json::json!({ "status": "ok" }),
];
let metadata_sizes = result_metadata
.iter()
.map(|metadata| serde_json::to_vec(metadata).unwrap().len())
.collect::<Vec<_>>();
assert!(metadata_sizes.iter().sum::<usize>() > 2 * 1024 * 1024);
assert!(metadata_sizes.iter().sum::<usize>() < 15 * 1024 * 1024);
assert!(serde_json::to_vec(&result_metadata[6]["openai/resource_access"])?.len() > 32 * 1024);
for (arguments, metadata) in arguments.iter().zip(&result_metadata) {
let result = serde_json::json!({
"content": [{ "type": "text", "text": RESULT_METADATA_PRIVATE_RESULT }],
"isError": false,
"_meta": metadata,
});
Mock::given(method("POST"))
.and(path("/api/codex/ps/mcp"))
.and(body_partial_json(serde_json::json!({
"method": "tools/call",
"params": { "arguments": arguments },
})))
.respond_with(move |request: &Request| {
let request: Value = serde_json::from_slice(&request.body).unwrap();
ResponseTemplate::new(200).set_body_json(serde_json::json!({
"jsonrpc": "2.0",
"id": request["id"],
"result": result,
}))
})
.with_priority(/*p*/ 1)
.mount(&server)
.await;
}
// Exact argument matches take precedence over the shared fallback mounted afterward.
let apps_server = mount_result_metadata_app(
&server, /*result_metadata*/ None, /*is_error*/ false,
)
.await?;
let direct = tool_mode == ToolMode::Direct;
let mut builder =
result_metadata_apps_builder(apps_server.chatgpt_base_url, "user@example.com").with_config(
move |config| {
if direct {
config.features.disable(Feature::CodeModeOnly).unwrap();
config.features.disable(Feature::CodeMode).unwrap();
}
},
);
let test = builder.build_with_auto_env(&server).await?;
let call_ids = [
"call-1", "call-2", "call-3", "call-4", "call-5", "call-6", "call-7", "call-8",
];
let mut events = if direct {
arguments
.iter()
.zip(call_ids)
.map(|(arguments, call_id)| {
responses::ev_function_call_with_namespace(
call_id,
"mcp__codex_apps__messagesearch",
RESULT_METADATA_TOOL,
&arguments.to_string(),
)
})
.collect::<Vec<_>>()
} else {
let arguments = serde_json::to_string(&arguments)?;
let code = format!(
"const tool = ALL_TOOLS.find(({{ name }}) => name.endsWith(\"{RESULT_METADATA_TOOL}\")); \
const results = []; \
for (const args of {arguments}) {{ \
const result = await tools[tool.name](args); \
results.push({{ content: result.content, isError: Boolean(result.isError), \
hasMeta: Object.hasOwn(result, \"_meta\") }}); \
}} \
text(JSON.stringify(results));"
);
vec![ev_custom_tool_call("call-1", "exec", &code)]
};
events.push(ev_completed("resp-1"));
let initial = responses::mount_sse_once(&server, sse(events)).await;
let follow_up = responses::mount_sse_once(&server, sse(vec![ev_completed("resp-2")])).await;
test.submit_turn("Search the connected app eight times")
.await?;
let initial = initial.single_request();
assert!(initial.has_message_with_input_texts("user", |texts| {
texts == ["Search the connected app eight times"]
}));
assert_eq!(
tool_names(&initial.body_json())
.iter()
.any(|name| name == "exec"),
!direct,
);
let request = follow_up.single_request();
let mut actual_arguments = recorded_apps_tool_calls(&server)
.await
.into_iter()
.map(|call| {
assert_eq!(call["params"]["name"], RESULT_METADATA_TOOL);
call["params"]["arguments"].clone()
})
.collect::<Vec<_>>();
actual_arguments.sort_by_key(Value::to_string);
assert_eq!(actual_arguments, arguments);
if direct {
for call_id in call_ids {
let output = request.function_call_output(call_id);
assert_eq!(
&output["output"].as_array().expect("direct output content")[1..],
&[serde_json::json!({
"type": "input_text",
"text": RESULT_METADATA_PRIVATE_RESULT,
})],
);
assert!(!output["output"].to_string().contains("payload"));
}
} else {
let (body, success) = custom_tool_output_body_and_success(&request, "call-1");
assert_ne!(success, Some(false), "Code Mode failed: {body}");
assert_eq!(
serde_json::from_str::<Value>(&body)?,
serde_json::json!(vec![
serde_json::json!({
"content": [{ "type": "text", "text": RESULT_METADATA_PRIVATE_RESULT }],
"isError": false,
"hasMeta": false,
});
arguments.len()
]),
);
}
let captured = codex_core::test_support::history_with_tool_call_metadata(&test.codex).await;
if direct {
for item in &captured {
if let ResponseItem::FunctionCallOutput { output, .. } = item {
assert_eq!(output.success, Some(true));
}
}
}
assert!(
captured
.iter()
.map(codex_protocol::models::executed_tool_call_metadata_bytes)
.sum::<usize>()
> 2 * 1024 * 1024
);
let captured = serde_json::to_value(captured)?;
for (input, expected_metadata) in [
// Ungranted custom inference endpoints strip raw metadata, including omission markers.
(request.input(), None),
(
captured.as_array().unwrap().clone(),
Some(result_metadata.clone()),
),
] {
let mut calls = Vec::new();
for output in &input {
let metadata = &output["internal_chat_message_metadata_passthrough"];
if let Some(recorded) = metadata["executed_tool_calls"].as_array() {
assert_eq!(metadata["tool_calls_complete"], true);
calls.extend(recorded.iter().cloned());
}
}
assert_eq!(calls.len(), arguments.len());
let expected_calls = arguments
.iter()
.enumerate()
.map(|(index, arguments)| {
let name = calls[index]["name"].as_str().unwrap();
assert!(name.ends_with(RESULT_METADATA_TOOL));
let mut call = serde_json::json!({ "name": name, "arguments": arguments });
if let Some(metadata) = &expected_metadata {
call["tool_result_metadata"] = metadata[index].clone();
}
call
})
.collect::<Vec<_>>();
assert_eq!(calls, expected_calls);
}
test.codex.shutdown_and_wait().await?;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "copies_full_metadata_without_rules")]
#[test_case(true, true, true, true, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "accepted_error_keeps_metadata")]
#[test_case(true, true, false, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "missing_metadata_stays_absent")]
#[test_case(false, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "feature_off_does_not_record")]
#[test_case(true, false, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "extension_owned_apps_do_not_record")]
#[test_case(true, true, true, false, "employee@openai.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(None); "employee_keeps_metadata")]
#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(None); "direct_keeps_metadata")]
#[test_case(true, true, true, true, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(None); "direct_accepted_error_keeps_metadata")]
#[test_case(true, true, false, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(None); "direct_missing_metadata_stays_absent")]
#[test_case(false, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(None); "direct_feature_off_does_not_record")]
#[test_case(true, false, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(None); "direct_extension_owned_apps_do_not_record")]
#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(Some(true)); "analytics_enabled_keeps_metadata")]
#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::Config(Some(false)); "analytics_disabled_omits_metadata")]
#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(Some(true)); "direct_analytics_enabled_keeps_metadata")]
#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::Config(Some(false)); "direct_analytics_disabled_omits_metadata")]
#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::HostDisabled(None); "host_analytics_disabled_with_config_unset_omits_metadata")]
#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly, ResultMetadataAnalytics::HostDisabled(Some(true)); "host_analytics_disabled_with_config_enabled_omits_metadata")]
#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::HostDisabled(None); "direct_host_analytics_disabled_with_config_unset_omits_metadata")]
#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct, ResultMetadataAnalytics::HostDisabled(Some(true)); "direct_host_analytics_disabled_with_config_enabled_omits_metadata")]
#[test_case(true, true, true, false, "user@example.com", ToolMode::CodeModeOnly; "copies_full_metadata_without_rules")]
#[test_case(true, true, true, true, "user@example.com", ToolMode::CodeModeOnly; "accepted_error_keeps_metadata")]
#[test_case(true, true, false, false, "user@example.com", ToolMode::CodeModeOnly; "missing_metadata_stays_absent")]
#[test_case(false, true, true, false, "user@example.com", ToolMode::CodeModeOnly; "feature_off_does_not_record")]
#[test_case(true, false, true, false, "user@example.com", ToolMode::CodeModeOnly; "extension_owned_apps_do_not_record")]
#[test_case(true, true, true, false, "employee@openai.com", ToolMode::CodeModeOnly; "employee_keeps_metadata")]
#[test_case(true, true, true, false, "user@example.com", ToolMode::Direct; "direct_keeps_metadata")]
#[test_case(true, true, true, true, "user@example.com", ToolMode::Direct; "direct_accepted_error_keeps_metadata")]
#[test_case(true, true, false, false, "user@example.com", ToolMode::Direct; "direct_missing_metadata_stays_absent")]
#[test_case(false, true, true, false, "user@example.com", ToolMode::Direct; "direct_feature_off_does_not_record")]
#[test_case(true, false, true, false, "user@example.com", ToolMode::Direct; "direct_extension_owned_apps_do_not_record")]
async fn result_metadata_follows_call_binding(
metadata_enabled: bool,
host_owned: bool,
@@ -2591,14 +2209,8 @@ async fn result_metadata_follows_call_binding(
is_error: bool,
account_email: &str,
tool_mode: ToolMode,
analytics: ResultMetadataAnalytics,
) -> Result<()> {
skip_if_no_network!(Ok(()));
let (analytics_enabled, host_disables_analytics) = match analytics {
ResultMetadataAnalytics::Config(enabled) => (enabled, false),
ResultMetadataAnalytics::HostDisabled(enabled) => (enabled, true),
};
let effective_analytics_enabled = analytics_enabled != Some(false) && !host_disables_analytics;
let direct = matches!(tool_mode, ToolMode::Direct);
let server = responses::start_mock_server().await;
let result_metadata = has_metadata.then(|| {
@@ -2619,7 +2231,6 @@ async fn result_metadata_follows_call_binding(
let mut builder =
result_metadata_apps_builder(apps_server.chatgpt_base_url.clone(), account_email)
.with_config(move |config| {
config.analytics_enabled = analytics_enabled;
if direct {
config.features.disable(Feature::CodeModeOnly).unwrap();
config.features.disable(Feature::CodeMode).unwrap();
@@ -2631,9 +2242,6 @@ async fn result_metadata_follows_call_binding(
.unwrap();
}
});
if host_disables_analytics {
builder = builder.with_analytics_events_client(AnalyticsEventsClient::disabled());
}
if !host_owned {
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
extensions.mcp_server_contributor(Arc::new(ResultMetadataTestControl {
@@ -2672,7 +2280,6 @@ async fn result_metadata_follows_call_binding(
);
run_code_mode_turn_with_builder(&server, "Search a connected app", &code, builder).await?
};
assert_eq!(test.codex.analytics_enabled(), effective_analytics_enabled);
let request = follow_up.single_request();
assert_eq!(recorded_apps_tool_calls(&server).await.len(), 1);
let output = if direct {
@@ -2728,10 +2335,8 @@ async fn result_metadata_follows_call_binding(
.iter()
.find(|item| item["type"] == output["type"] && item["call_id"] == "call-1")
.expect("captured tool output");
let expected_metadata = (host_owned && effective_analytics_enabled)
.then_some(result_metadata)
.flatten();
assert_result_metadata_call(captured_output, &arguments, expected_metadata);
// Raw MCP result metadata is never captured: usage-data reporting was removed.
assert_result_metadata_call(captured_output, &arguments, /*expected_metadata*/ None);
assert_eq!(
output["internal_chat_message_metadata_passthrough"]["tool_calls_complete"],
true
@@ -2746,261 +2351,6 @@ async fn result_metadata_follows_call_binding(
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn code_mode_result_metadata_follows_runtime_recording_enablement() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let result_metadata = serde_json::json!({ "provider": { "id": "refresh" } });
let apps_server = mount_result_metadata_app(
&server,
Some(result_metadata.clone()),
/*is_error*/ false,
)
.await?;
let mut builder =
result_metadata_apps_builder(apps_server.chatgpt_base_url, "user@example.com").with_config(
|config| {
config
.features
.disable(Feature::ExecutedToolCallMetadata)
.unwrap();
},
);
let test = builder.build_with_auto_env(&server).await?;
let arguments = serde_json::json!({ "search": "launch plan" });
let code = format!(
"const tool = ALL_TOOLS.find(({{ name }}) => name.endsWith(\"{RESULT_METADATA_TOOL}\")); \
const result = await tools[tool.name]({arguments}); \
text(JSON.stringify({{ isError: Boolean(result.isError), hasMeta: Object.hasOwn(result, \"_meta\") }}));"
);
for (call_id, enabled) in [("call-off", false), ("call-on", true)] {
if enabled {
let current_config = test.codex.config().await;
let mut config = test.config.clone();
config
.features
.enable(Feature::ExecutedToolCallMetadata)
.unwrap();
let _ = test
.codex
.refresh_runtime_config(current_config, config)
.await;
// Runtime recording changes without updating the session's execution features.
assert!(
!test
.codex
.config()
.await
.features
.enabled(Feature::ExecutedToolCallMetadata)
);
}
let initial = responses::mount_sse_once(
&server,
sse(vec![
ev_custom_tool_call(call_id, "exec", &code),
ev_completed(call_id),
]),
)
.await;
let follow_up = responses::mount_sse_once(
&server,
sse(vec![
ev_assistant_message(&format!("{call_id}-message"), "done"),
ev_completed(&format!("{call_id}-done")),
]),
)
.await;
test.submit_turn("Search a connected app").await?;
initial.single_request();
let request = follow_up.single_request();
let (body, success) = custom_tool_output_body_and_success(&request, call_id);
assert_ne!(success, Some(false), "Code Mode failed: {body}");
assert_eq!(
serde_json::from_str::<Value>(&body)?,
serde_json::json!({ "isError": false, "hasMeta": false }),
);
assert_eq!(
result_metadata_fixture_calls(&request.input()).count(),
usize::from(enabled)
);
let output = request.custom_tool_call_output(call_id);
assert!(
output["internal_chat_message_metadata_passthrough"]
.get("tool_calls_complete")
.is_none()
);
if enabled {
assert_result_metadata_call(&output, &arguments, /*expected_metadata*/ None);
}
}
assert_eq!(recorded_apps_tool_calls(&server).await.len(), 2);
let captured = codex_core::test_support::history_with_tool_call_metadata(&test.codex).await;
let captured = serde_json::to_value(captured)?;
let captured_output = captured
.as_array()
.unwrap()
.iter()
.find(|item| item["type"] == "custom_tool_call_output" && item["call_id"] == "call-on")
.expect("captured exec output after runtime enablement");
let expected_metadata = Some(result_metadata);
assert_result_metadata_call(captured_output, &arguments, expected_metadata);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn code_mode_result_metadata_keeps_prepared_call_binding_across_runtime_refresh() -> Result<()>
{
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let original_metadata =
serde_json::json!({ "provider": { "origin": "original", "items": [] } });
let apps_server = mount_result_metadata_app(
&server,
Some(original_metadata.clone()),
/*is_error*/ false,
)
.await?;
let refreshed_server = responses::start_mock_server().await;
let refreshed_apps = mount_result_metadata_app(
&refreshed_server,
Some(serde_json::json!({ "provider": { "origin": "refreshed" } })),
/*is_error*/ false,
)
.await?;
let (reached_tx, reached_rx) = oneshot::channel();
let (release_tx, release_rx) = oneshot::channel();
let control = Arc::new(ResultMetadataTestControl {
server: Mutex::new(McpServerContribution::HostedApps {
config: Box::new(mock_apps_mcp_server_config(&apps_server.chatgpt_base_url)),
protocol_mode: None,
}),
gate: Mutex::new(Some((reached_tx, release_rx))),
});
let mut extensions = ExtensionRegistryBuilder::<Config>::new();
extensions.mcp_server_contributor(control.clone());
extensions.tool_lifecycle_contributor(control.clone());
let builder = result_metadata_apps_builder(apps_server.chatgpt_base_url, "user@example.com")
.with_extensions(Arc::new(extensions.build()));
let arguments = serde_json::json!({
"query": "launch plan",
"response_format": "detailed",
"content_types": "messages",
});
let code = format!(
"const tool = ALL_TOOLS.find(({{ name }}) => name.endsWith(\"{RESULT_METADATA_TOOL}\")); \
const pending = tools[tool.name]({arguments}); yield_control(); await pending; \
await tools[tool.name]({arguments}); text(\"done\");"
);
let (test, follow_up) =
run_code_mode_turn_with_builder(&server, "Search a connected app", &code, builder).await?;
let first_items = custom_tool_output_items(&follow_up.single_request(), "call-1");
assert!(
text_item(&first_items, /*index*/ 0).starts_with("Script running with cell ID "),
"expected the held call to yield: {first_items:?}",
);
let cell_id = extract_running_cell_id(text_item(&first_items, /*index*/ 0));
tokio::time::timeout(Duration::from_secs(10), reached_rx).await??;
// Yield may precede call admission. Drain inventory after the lifecycle gate is reached;
// the short wait is only a poll budget while the gate keeps acceptance blocked.
let held_wait = responses::mount_function_call_agent_response(
&server,
"call-2",
&serde_json::to_string(&serde_json::json!({
"cell_id": cell_id,
"yield_time_ms": 1,
}))?,
"wait",
)
.await;
test.submit_turn("Read the pending call inventory").await?;
let held_request = held_wait.completion.single_request();
let held_items = function_tool_output_items(&held_request, "call-2");
assert_eq!(
extract_running_cell_id(text_item(&held_items, /*index*/ 0)),
cell_id
);
let held_input = held_request.input();
let emitted_calls = result_metadata_fixture_calls(&held_input).collect::<Vec<_>>();
assert_eq!(
emitted_calls.len(),
1,
"held wait must not duplicate inventory"
);
let original_output = emitted_calls[0];
assert_result_metadata_call(original_output, &arguments, /*expected_metadata*/ None);
assert_ne!(
original_output["internal_chat_message_metadata_passthrough"]["tool_calls_complete"],
true
);
// The next call uses an extension-owned binding, but the held call keeps its host proof.
*control.server.lock().unwrap() = McpServerContribution::Set {
name: CODEX_APPS_MCP_SERVER_NAME.to_string(),
config: Box::new(mock_apps_mcp_server_config(&refreshed_apps.chatgpt_base_url)),
};
let current_config = test.codex.config().await;
let _ = test
.codex
.refresh_runtime_config(current_config, test.config.clone())
.await;
release_tx.send(()).unwrap();
let wait = responses::mount_function_call_agent_response(
&server,
"call-3",
&serde_json::to_string(&serde_json::json!({
"cell_id": cell_id,
"yield_time_ms": 10_000,
}))?,
"wait",
)
.await;
test.submit_turn("Wait for the accepted app result").await?;
let request = wait.completion.single_request();
assert_eq!(recorded_apps_tool_calls(&server).await.len(), 1);
assert_eq!(recorded_apps_tool_calls(&refreshed_server).await.len(), 1);
assert!(
!request
.body_json()
.to_string()
.contains(RESULT_METADATA_PRIVATE_RESULT)
);
let input = request.input();
assert_eq!(
result_metadata_fixture_calls(&input).count(),
2,
"late results must not duplicate the call"
);
let captured = codex_core::test_support::history_with_tool_call_metadata(&test.codex).await;
let captured = serde_json::to_value(captured)?;
// A's accepted result must update the output that first reported it, not the final wait.
let expected_metadata = Some(original_metadata);
for (call_id, call_type, expected_metadata) in [
(
original_output["call_id"].as_str().unwrap(),
original_output["type"].as_str().unwrap(),
expected_metadata,
),
("call-3", "function_call_output", None),
] {
let output = request.call_output(call_id, call_type);
assert_result_metadata_call(&output, &arguments, /*expected_metadata*/ None);
let captured_output = captured
.as_array()
.unwrap()
.iter()
.find(|item| item["type"] == call_type && item["call_id"] == call_id)
.expect("captured tool output");
assert_result_metadata_call(captured_output, &arguments, expected_metadata);
}
let terminal_output = request.function_call_output("call-3");
assert_eq!(
terminal_output["internal_chat_message_metadata_passthrough"]["tool_calls_complete"],
true
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn code_mode_late_result_metadata_with_large_arguments_survives_waits() -> Result<()> {
skip_if_no_network!(Ok(()));

View File

@@ -1,27 +1,10 @@
//! Direct-call metadata coverage, including malformed calls and metadata budgets.
use anyhow::Result;
use codex_core::ForkSnapshot;
use codex_core::StartThreadOptions;
use codex_core::TurnInputRequest;
use codex_core::TurnStartOptions;
use codex_features::Feature;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_model_provider::RemoteCompactionSupport;
use core_test_support::apps_test_server::AppsTestServer;
use core_test_support::apps_test_server::SEARCH_CALENDAR_LIST_TOOL;
use core_test_support::apps_test_server::SEARCH_CALENDAR_NAMESPACE;
use core_test_support::apps_test_server::recorded_apps_tool_calls;
use core_test_support::apps_test_server::search_capable_apps_builder;
use core_test_support::responses::ev_function_call_with_namespace;
use core_test_support::wait_for_mcp_server;
use wiremock::Mock;
use wiremock::Request;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_partial_json;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::path_regex;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
@@ -653,346 +636,3 @@ async fn direct_function_and_tool_search_mark_complete_attempts(
}
Ok(())
}
#[test_case(false, false; "ungranted_provider")]
#[test_case(true, false; "granted_provider_cold_fork")]
#[test_case(true, true; "granted_provider_warm_fork")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn direct_metadata_limit_respects_provider_support(
include_internal_metadata: bool,
fork_from_running_thread: bool,
) -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let apps = AppsTestServer::mount(&server).await?;
fn metadata_for_query(query: &str) -> Value {
json!({"openai/resource_access": {"payload": "x".repeat(600 * 1024), "query": query}})
}
let raw_bytes = serde_json::to_vec(&metadata_for_query("first"))?.len();
assert!(raw_bytes < 1024 * 1024);
assert!(raw_bytes * 2 > 1024 * 1024);
Mock::given(method("POST"))
.and(path_regex("^/api/codex/ps/mcp/?$"))
.and(body_partial_json(json!({"method": "tools/call"})))
.respond_with(move |request: &Request| {
let body: Value = serde_json::from_slice(&request.body).expect("MCP request");
let query = body["params"]["arguments"]["query"]
.as_str()
.expect("query");
ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
"jsonrpc": "2.0", "id": body["id"],
"result": {
"content": [{"type": "text", "text": format!("result for {query}")}],
"_meta": metadata_for_query(query),
"isError": false
}
}))
})
.with_priority(/*p*/ 1)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/codex/analytics-events/events"))
.respond_with(ResponseTemplate::new(/*s*/ 200))
.mount(&server)
.await;
let mut events = vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call_with_namespace(
"first",
SEARCH_CALENDAR_NAMESPACE,
SEARCH_CALENDAR_LIST_TOOL,
r#"{"query":"first"}"#,
),
ev_completed("resp-1"),
]),
sse(vec![
ev_response_created("resp-2"),
ev_function_call_with_namespace(
"second",
SEARCH_CALENDAR_NAMESPACE,
SEARCH_CALENDAR_LIST_TOOL,
r#"{"query":"second"}"#,
),
ev_completed("resp-2"),
]),
sse(vec![ev_response_created("resp-3"), ev_completed("resp-3")]),
];
if include_internal_metadata {
for query in ["fork", "resume"] {
events.push(sse(vec![
ev_response_created(&format!("resp-{query}")),
ev_function_call_with_namespace(
query,
SEARCH_CALENDAR_NAMESPACE,
SEARCH_CALENDAR_LIST_TOOL,
&json!({"query": query}).to_string(),
),
ev_completed(&format!("resp-{query}")),
]));
events.push(sse(vec![
ev_response_created(&format!("resp-{query}-done")),
ev_completed(&format!("resp-{query}-done")),
]));
}
}
let responses = mount_sse_sequence(&server, events).await;
let mock_url = server.uri();
let configure_metadata = move |config: &mut codex_core::config::Config| {
assert_eq!(config.chatgpt_base_url, mock_url);
assert_eq!(
config.model_provider.base_url.as_deref(),
Some(format!("{mock_url}/v1").as_str())
);
config.model_provider.include_internal_metadata = include_internal_metadata;
config.analytics_enabled = Some(true);
config
.features
.enable(Feature::ExecutedToolCallMetadata)
.expect("enable executed tool call metadata");
config
.features
.disable(Feature::CodeMode)
.expect("disable code mode");
config
.features
.disable(Feature::CodeModeOnly)
.expect("disable code-mode-only tools");
};
let mut builder = search_capable_apps_builder(apps.chatgpt_base_url.clone())
.with_config(configure_metadata.clone());
// build() always selects the local test environment; all network destinations are the mock.
let test = builder.build(&server).await?;
assert!(test.codex.analytics_enabled());
wait_for_mcp_server(&test.codex, CODEX_APPS_MCP_SERVER_NAME).await?;
test.submit_turn_with_approval_and_permission_profile(
"Use [$calendar](app://calendar) to list events twice.",
AskForApproval::OnRequest,
PermissionProfile::read_only(),
)
.await?;
let calls = recorded_apps_tool_calls(&server).await;
assert_eq!(calls.len(), 2);
for (call, query) in calls.iter().zip(["first", "second"]) {
assert_eq!(call["params"]["name"], "calendar_list_events");
assert_eq!(call["params"]["arguments"], json!({"query": query}));
}
let requests = responses.requests();
assert_eq!(requests.len(), 3);
let first_output = requests[2].function_call_output("first");
let second_output = requests[2].function_call_output("second");
let history = test.codex.conversation_history_snapshot().await;
let history = serde_json::to_value(history.items().collect::<Vec<_>>())?;
let recorded_outputs = [&first_output, &second_output].map(|output| {
history
.as_array()
.expect("history items")
.iter()
.find(|item| {
item["type"] == "function_call_output" && item["call_id"] == output["call_id"]
})
.expect("original tool output in history")
});
for ((wire, recorded), query) in [&first_output, &second_output]
.into_iter()
.zip(recorded_outputs)
.zip(["first", "second"])
{
assert_eq!(wire["output"], recorded["output"]);
assert!(
wire["output"]
.to_string()
.contains(&format!("result for {query}"))
);
let recorded_metadata = tool_call_metadata(recorded.clone());
let wire_metadata = tool_call_metadata(wire.clone());
assert_eq!(recorded_metadata["tool_calls_complete"], true);
assert_eq!(
recorded_metadata["executed_tool_calls"][0]["name"],
format!("{SEARCH_CALENDAR_NAMESPACE}{SEARCH_CALENDAR_LIST_TOOL}")
);
assert_eq!(
recorded_metadata["executed_tool_calls"][0]["arguments"],
json!({"query": query})
);
let wire_result_metadata =
wire_metadata["executed_tool_calls"][0].get("tool_result_metadata");
if include_internal_metadata {
assert_eq!(wire_result_metadata, Some(&metadata_for_query(query)));
} else {
// An ungranted provider must not receive internal result metadata.
assert!(wire_result_metadata.is_none());
}
}
let first_metadata = tool_call_metadata(recorded_outputs[0].clone());
let second_metadata = tool_call_metadata(recorded_outputs[1].clone());
assert_eq!(
first_metadata["executed_tool_calls"][0]["tool_result_metadata"],
metadata_for_query("first")
);
let marker = second_metadata["executed_tool_calls"][0]["tool_result_metadata"]
.as_str()
.expect("second result should have an omission marker");
let overage = marker
.strip_prefix("omitted_due_to_size_limit (overage_bytes=")
.and_then(|value| value.strip_suffix(')'))
.and_then(|value| value.parse::<usize>().ok())
.expect("marker should report omitted bytes");
assert!(overage > 0);
if !include_internal_metadata {
return Ok(());
}
let rollout_path = test.codex.rollout_path().expect("rollout path");
if fork_from_running_thread {
test.codex.flush_rollout().await?;
} else {
test.codex.shutdown_and_wait().await?;
test.thread_manager
.remove_thread(&test.session_configured.thread_id)
.await;
}
let rollout = tokio::fs::read_to_string(&rollout_path).await?;
let rollout = rollout
.lines()
.map(serde_json::from_str::<Value>)
.collect::<serde_json::Result<Vec<_>>>()?;
for (call_id, expected) in [("first", &first_metadata), ("second", &second_metadata)] {
let item = rollout
.iter()
.find(|line| {
line["type"] == "response_item"
&& line["payload"]["type"] == "function_call_output"
&& line["payload"]["call_id"] == call_id
})
.expect("persisted tool output");
assert_eq!(tool_call_metadata(item["payload"].clone()), *expected);
}
let forked = test
.thread_manager
.fork_legacy_thread(
ForkSnapshot::Interrupted,
StartThreadOptions::new(test.config.clone()),
rollout_path.clone(),
)
.await?;
wait_for_mcp_server(&forked.thread, CODEX_APPS_MCP_SERVER_NAME).await?;
forked
.thread
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
text: "List events in the fork.".to_string(),
text_elements: Vec::new(),
}]))
.await?;
wait_for_event(&forked.thread, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
forked
.thread
.shutdown_and_wait()
.await
.expect("shutdown fork");
if fork_from_running_thread {
test.codex.shutdown_and_wait().await?;
}
let resumed = search_capable_apps_builder(apps.chatgpt_base_url)
.with_config(configure_metadata)
.resume(&server, test.home.clone(), rollout_path)
.await
.expect("resume original thread");
wait_for_mcp_server(&resumed.codex, CODEX_APPS_MCP_SERVER_NAME)
.await
.expect("start resumed MCP server");
resumed
.submit_text_turn("List events after resume.")
.await
.expect("run resumed turn");
resumed
.codex
.shutdown_and_wait()
.await
.expect("shutdown resumed thread");
let requests = responses.requests();
assert_eq!(requests.len(), 7);
let expected_fork = if fork_from_running_thread {
"warm_fork"
} else {
"cold_fork"
};
let initialization = requests
.iter()
.map(|request| {
let body = request.body_json();
let metadata: Value = serde_json::from_str(
body["client_metadata"]["x-codex-turn-metadata"]
.as_str()
.expect("turn metadata"),
)
.expect("valid turn metadata");
metadata["history_initialization"].clone()
})
.collect::<Vec<_>>();
assert_eq!(
Value::Array(initialization),
json!([
"new",
"new",
"new",
expected_fork,
expected_fork,
"cold_resume",
"cold_resume"
])
);
for request in &requests[3..] {
for original in [&first_output, &second_output] {
let call_id = original["call_id"].as_str().expect("call ID");
let output = request.function_call_output(call_id);
assert_eq!(output["output"], original["output"]);
let passthrough = output.get("internal_chat_message_metadata_passthrough");
assert!(
passthrough
.and_then(|meta| meta.get("executed_tool_calls"))
.is_none()
);
assert!(
passthrough
.and_then(|meta| meta.get("tool_calls_complete"))
.is_none()
);
}
}
for (request, query) in [(&requests[4], "fork"), (&requests[6], "resume")] {
let output = request.function_call_output(query);
assert!(
output["output"]
.to_string()
.contains(&format!("result for {query}"))
);
let metadata = tool_call_metadata(output);
assert_eq!(metadata["tool_calls_complete"], true);
assert_eq!(
metadata["executed_tool_calls"].as_array().map(Vec::len),
Some(1)
);
assert_eq!(
metadata["executed_tool_calls"][0]["name"],
format!("{SEARCH_CALENDAR_NAMESPACE}{SEARCH_CALENDAR_LIST_TOOL}")
);
assert_eq!(
metadata["executed_tool_calls"][0]["arguments"],
json!({"query": query})
);
assert_eq!(
metadata["executed_tool_calls"][0]["tool_result_metadata"],
metadata_for_query(query)
);
}
Ok(())
}

View File

@@ -6,7 +6,6 @@ use chrono::DateTime;
use chrono::Local;
use chrono::Utc;
use codex_config::types::McpServerConfig;
use codex_config::types::OtelExporterKind;
use codex_core::SleepFuture;
use codex_core::TimeFuture;
use codex_core::TimeProvider;
@@ -2397,14 +2396,12 @@ async fn interrupted_guardian_review_across_model_change_does_not_execute_the_co
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[tracing_test::traced_test]
#[test_case(None, false, true; "legacy_fallback")]
#[test_case(None, true, true; "otel_enabled")]
#[test_case(Some("Acting model rejection instructions."), false, true; "catalog_override")]
#[test_case(Some(""), false, true; "empty_override")]
#[test_case(None, false, false; "feedback_disabled")]
#[test_case(None, true; "legacy_fallback")]
#[test_case(Some("Acting model rejection instructions."), true; "catalog_override")]
#[test_case(Some(""), true; "empty_override")]
#[test_case(None, false; "feedback_disabled")]
async fn guardian_denial_rejects_tool_call_with_rationale(
rejection_instructions: Option<&'static str>,
log_assessments: bool,
feedback_enabled: bool,
) -> Result<()> {
skip_if_no_network!(Ok(()));
@@ -2455,12 +2452,6 @@ async fn guardian_denial_rejects_tool_call_with_rationale(
.with_config(move |config| {
config.feedback_enabled = feedback_enabled;
config.otel.log_user_prompt = true;
config.otel.log_guardian_assessments = log_assessments;
config.otel.exporter = OtelExporterKind::OtlpGrpc {
endpoint: "http://127.0.0.1:1".to_string(),
headers: Default::default(),
tls: None,
};
config.permissions.approval_policy = Constrained::allow_any(approval_policy);
config
.set_legacy_sandbox_policy(sandbox_policy_for_config)
@@ -2669,8 +2660,6 @@ async fn guardian_denial_rejects_tool_call_with_rationale(
"Guardian-denied command unexpectedly executed"
);
// Approval workers do not inherit the test span, so select the conversation explicitly.
let thread_id = test.session_configured.thread_id;
let logs = String::from_utf8(
tracing_test::internal::global_buf()
.lock()
@@ -2696,24 +2685,6 @@ async fn guardian_denial_rejects_tool_call_with_rationale(
1,
"Guardian prompt telemetry: {prompt_events:?}"
);
let assessments: Vec<_> = logs
.lines()
.filter(|line| {
line.contains("codex.guardian_assessment")
&& line.contains(&format!("conversation.id={thread_id}"))
})
.collect();
assert_eq!(assessments.len(), usize::from(log_assessments));
if let Some(log) = assessments.first() {
for field in [
"status=\"denied\"",
"outcome=\"deny\"",
"item.id=\"exec-call-denied\"",
"rationale=\"The requested write has unacceptable test risk.\"",
] {
assert!(log.contains(field), "missing {field}: {log}");
}
}
Ok(())
}

View File

@@ -1,9 +1,6 @@
//! Verify MCP prompts and elicitation analytics through actual turns.
//! Verify MCP prompts and elicitations through actual turns.
use anyhow::Result;
use codex_analytics::AnalyticsEventsClient;
use codex_analytics::AppServerRpcTransport;
use codex_app_server_protocol as app;
use codex_core::RestrictRootCapabilities;
use codex_core::StartThreadOptions;
use codex_core::TurnInputRequest;
@@ -14,7 +11,6 @@ use codex_extension_api::McpToolResultInput;
use codex_extension_api::ToolLifecycleContributor;
use codex_extension_api::ToolLifecycleFuture;
use codex_features::Feature;
use codex_login::CodexAuth;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_protocol::SessionId;
use codex_protocol::approvals::ElicitationRequest;
@@ -54,7 +50,6 @@ use wiremock::Respond;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_partial_json;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::path_regex;
const CALL_ID: &str = "calendar-elicitation-call";
@@ -146,7 +141,7 @@ impl ToolLifecycleContributor for RemoveAuthMetadata {
#[test_case(Scenario::LegacyCancelled; "legacy cancelled")]
#[test_case(Scenario::ModernDeclined; "modern declined")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn actual_turn_elicitation_analytics(scenario: Scenario) -> Result<()> {
async fn actual_turn_elicitations(scenario: Scenario) -> Result<()> {
skip_if_no_network!(Ok(()));
let modern = scenario != Scenario::LegacySuccess && scenario != Scenario::LegacyCancelled;
@@ -158,12 +153,6 @@ async fn actual_turn_elicitation_analytics(scenario: Scenario) -> Result<()> {
);
let server = responses::start_mock_server().await;
AppsTestServer::mount_searchable(&server).await?;
Mock::given(method("POST"))
.and(path("/codex/analytics-events/events"))
.respond_with(ResponseTemplate::new(/*status*/ 200))
.mount(&server)
.await;
if auth_failure {
Mock::given(method("POST"))
.and(path_regex("^/api/codex/ps/mcp/?$"))
@@ -200,42 +189,33 @@ async fn actual_turn_elicitation_analytics(scenario: Scenario) -> Result<()> {
)
.await;
let client = AnalyticsEventsClient::new(
codex_core::test_support::auth_manager_from_auth(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
),
server.uri(),
/*analytics_enabled*/ Some(true),
);
let mut builder = search_capable_apps_builder(server.uri())
.with_analytics_events_client(client.clone())
.with_config(move |config| {
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
config.approvals_reviewer = ApprovalsReviewer::User;
if scenario != Scenario::DefaultAuth {
config
.features
.set_enabled(Feature::ToolCallMcpElicitation, modern)
.expect("approval feature should be configurable");
}
let user_config_path = config.codex_home.join("config.toml").abs();
let approval_mode = if scenario == Scenario::DefaultAuth {
"auto"
} else {
"prompt"
};
let user_config = toml::from_str(&format!(
r#"[apps.calendar]
let mut builder = search_capable_apps_builder(server.uri()).with_config(move |config| {
config.permissions.approval_policy = Constrained::allow_any(AskForApproval::OnRequest);
config.approvals_reviewer = ApprovalsReviewer::User;
if scenario != Scenario::DefaultAuth {
config
.features
.set_enabled(Feature::ToolCallMcpElicitation, modern)
.expect("approval feature should be configurable");
}
let user_config_path = config.codex_home.join("config.toml").abs();
let approval_mode = if scenario == Scenario::DefaultAuth {
"auto"
} else {
"prompt"
};
let user_config = toml::from_str(&format!(
r#"[apps.calendar]
default_tools_approval_mode = "{approval_mode}"
approvals_reviewer = "user"
"#,
))
.expect("apps config should parse");
config.config_layer_stack = config
.config_layer_stack
.with_user_config(&user_config_path, user_config)
.expect("apps user config should be valid");
});
))
.expect("apps config should parse");
config.config_layer_stack = config
.config_layer_stack
.with_user_config(&user_config_path, user_config)
.expect("apps user config should be valid");
});
if scenario == Scenario::AuthMetadataRemoved {
let mut extensions = ExtensionRegistryBuilder::new();
extensions.tool_lifecycle_contributor(Arc::new(RemoveAuthMetadata));
@@ -243,31 +223,6 @@ approvals_reviewer = "user"
}
let test = builder.build_with_auto_env(&server).await?;
let session = &test.session_configured;
let thread_id = session.thread_id.to_string();
client.track_initialize(
/*connection_id*/ 1,
app::InitializeParams::default(),
"test-client".to_string(),
AppServerRpcTransport::Stdio,
);
let thread_response = serde_json::from_value(json!({
"thread": {
"id": thread_id, "sessionId": session.session_id.to_string(), "preview": "",
"ephemeral": false, "modelProvider": session.model_provider_id,
"createdAt": 1, "updatedAt": 1, "status": {"type": "idle"},
"cwd": session.cwd, "cliVersion": "0.0.0", "source": "exec", "turns": [],
},
"model": session.model, "modelProvider": session.model_provider_id, "cwd": session.cwd,
"approvalPolicy": app::AskForApproval::from(session.approval_policy),
"approvalsReviewer": app::ApprovalsReviewer::from(session.approvals_reviewer),
"sandbox": app::SandboxPolicy::from(test.config.legacy_sandbox_policy()),
}))?;
client.track_response(
/*connection_id*/ 1,
app::RequestId::Integer(1),
&app::ClientResponsePayload::ThreadStart(thread_response),
);
let request = TurnInputRequest::user_input(vec![UserInput::Text {
text: "Use [$calendar](app://calendar) to create a calendar event.".to_string(),
text_elements: Vec::new(),
@@ -287,13 +242,6 @@ approvals_reviewer = "user"
match event.msg {
EventMsg::TurnStarted(started) => {
assert_eq!(started.turn_id, turn_id);
client.track_notification(&app::ServerNotification::TurnStarted(
serde_json::from_value(json!({
"threadId": thread_id,
"turn": {"id": started.turn_id, "items": [],
"status": "inProgress", "startedAt": started.started_at},
}))?,
));
}
message @ (EventMsg::ItemStarted(_) | EventMsg::ItemCompleted(_)) => {
let (item, item_thread_id, item_turn_id, completed) = match &message {
@@ -315,9 +263,6 @@ approvals_reviewer = "user"
assert_eq!(item.connector_id.as_deref(), Some("calendar"));
target_lifecycle[usize::from(completed)] += 1;
}
let notification =
app::item_event_to_server_notification(message, &thread_id, &event_turn_id);
client.track_notification(&notification);
}
EventMsg::RequestUserInput(request) => {
assert!(!modern, "legacy approval requested for {scenario:?}");
@@ -381,15 +326,6 @@ approvals_reviewer = "user"
}
EventMsg::TurnComplete(completed) => {
assert_eq!(completed.turn_id, turn_id);
client.track_notification(&app::ServerNotification::TurnCompleted(
serde_json::from_value(json!({
"threadId": thread_id,
"turn": {"id": completed.turn_id, "items": [], "status": "completed",
"startedAt": completed.started_at,
"completedAt": completed.completed_at,
"durationMs": completed.duration_ms},
}))?,
));
break;
}
EventMsg::Error(error) => {
@@ -459,61 +395,6 @@ approvals_reviewer = "user"
assert!(!output.to_string().contains(PRIVATE_SENTINEL));
}
tokio::time::timeout(Duration::from_secs(10), client.flush()).await?;
let mut events = Vec::new();
for request in server.received_requests().await.unwrap_or_default() {
if request.method != "POST" || request.url.path() != "/codex/analytics-events/events" {
continue;
}
let payload: Value = serde_json::from_slice(&request.body)?;
let batch = payload["events"].as_array().expect("analytics events");
events.extend(batch.iter().cloned());
}
let mcp_events = events
.iter()
.filter(|event| {
event["event_type"] == "codex_mcp_tool_call_event"
&& event["event_params"]["item_id"] == CALL_ID
})
.collect::<Vec<_>>();
let app_used_events = events
.iter()
.filter(|event| {
event["event_type"] == "codex_app_used"
&& event["event_params"]["connector_id"] == "calendar"
&& event["event_params"]["turn_id"] == turn_id
})
.collect::<Vec<_>>();
assert_eq!(mcp_events.len(), 1);
assert_eq!(app_used_events.len(), usize::from(approved));
assert_eq!(mcp_events[0]["event_params"]["connector_id"], "calendar");
assert_eq!(mcp_events[0]["event_params"]["thread_id"], thread_id);
assert_eq!(mcp_events[0]["event_params"]["turn_id"], turn_id);
assert_eq!(
mcp_events[0]["event_params"]["terminal_status"],
if scenario == Scenario::LegacySuccess {
"completed"
} else {
"failed"
}
);
let expected = match scenario {
Scenario::DefaultAuth | Scenario::ModernAuth | Scenario::AuthMetadataRemoved => {
json!("auth_or_link")
}
Scenario::LegacySuccess => Value::Null,
Scenario::LegacyCancelled | Scenario::ModernDeclined => json!("approval"),
};
for event in mcp_events.iter().chain(app_used_events.iter()) {
assert_eq!(
event["event_params"].get("elicitation_type"),
Some(&expected)
);
}
let target_payload = serde_json::to_string(&(mcp_events, app_used_events))?;
assert!(!target_payload.contains(PRIVATE_SENTINEL));
assert!(!target_payload.contains("https://chatgpt.com/apps/"));
Ok(())
}

View File

@@ -1,16 +1,13 @@
use anyhow::Result;
use codex_analytics::AnalyticsEventsClient;
use codex_core::TurnInputRequest;
use codex_core::config::AgentRoleConfig;
use codex_features::Feature;
use codex_login::CodexAuth;
use codex_protocol::models::PermissionProfile;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::protocol::EventMsg;
use codex_protocol::protocol::Op;
use codex_protocol::protocol::ThreadSettingsOverrides;
use codex_protocol::user_input::UserInput;
use codex_thread_store::ReadThreadParams;
use core_test_support::responses::assert_parent_turn;
use core_test_support::responses::assert_root_turn;
use core_test_support::responses::ev_assistant_message;
@@ -30,10 +27,6 @@ use serde_json::json;
use std::time::Duration;
use tokio::time::Instant;
use tokio::time::sleep;
use wiremock::Mock;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
#[path = "multi_agent_restore_tests.rs"]
mod restore_tests;
@@ -279,7 +272,6 @@ async fn cold_root_resume_restores_agent_identity_and_role_on_followup() -> Resu
});
let initial = initial_builder.build_with_auto_env(&server).await?;
let root_thread_id = initial.session_configured.thread_id;
let root_session_id = initial.session_configured.session_id;
initial
.codex
.start_or_steer_turn(
@@ -400,16 +392,6 @@ async fn cold_root_resume_restores_agent_identity_and_role_on_followup() -> Resu
sibling_thread.flush_rollout().await?;
worker_thread.flush_rollout().await?;
initial.codex.flush_rollout().await?;
let worker_created_at = initial
.thread_store
.read_thread(ReadThreadParams {
thread_id: worker_thread_id,
include_archived: true,
include_history: false,
})
.await?
.created_at
.timestamp();
sibling_thread.shutdown_and_wait().await?;
worker_thread.shutdown_and_wait().await?;
drop(sibling_thread);
@@ -463,25 +445,10 @@ async fn cold_root_resume_restores_agent_identity_and_role_on_followup() -> Resu
)
.await;
Mock::given(method("POST"))
.and(path("/codex/analytics-events/events"))
.respond_with(ResponseTemplate::new(/* status */ 200))
.mount(&server)
.await;
let analytics_client = AnalyticsEventsClient::new(
codex_core::test_support::auth_manager_from_auth(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
),
server.uri(),
/* analytics_enabled */ Some(true),
);
let resumed_model_provider_base_url = format!("{}/v1", server.uri());
let mut resume_builder = test_codex()
.with_analytics_events_client(analytics_client.clone())
.with_config(move |config| {
configure_multi_agent_v2_with_role(config, &resumed_model_provider_base_url);
config.analytics_enabled = Some(true);
});
let mut resume_builder = test_codex().with_config(move |config| {
configure_multi_agent_v2_with_role(config, &resumed_model_provider_base_url);
});
let resumed = resume_builder.restart(&server, &initial).await?;
resumed
.codex
@@ -578,44 +545,6 @@ openai_base_url = "{redirected_base_url}"
matches!(event, EventMsg::TurnComplete(_))
})
.await;
tokio::time::timeout(Duration::from_secs(10), analytics_client.flush()).await?;
let mut worker_initializations = Vec::new();
for request in server.received_requests().await.unwrap_or_default() {
if request.url.path() != "/codex/analytics-events/events" {
continue;
}
let payload: Value = serde_json::from_slice(&request.body)?;
worker_initializations.extend(
payload["events"]
.as_array()
.expect("analytics events")
.iter()
.filter(|event| {
event["event_type"] == "codex_thread_initialized"
&& event["event_params"]["thread_id"] == worker_thread_id.to_string()
})
.map(|event| {
let params = &event["event_params"];
json!({
"session_id": params["session_id"],
"parent_thread_id": params["parent_thread_id"],
"subagent_source": params["subagent_source"],
"initialization_mode": params["initialization_mode"],
"created_at": params["created_at"],
})
}),
);
}
assert_eq!(
worker_initializations,
vec![json!({
"session_id": root_session_id.to_string(),
"parent_thread_id": root_thread_id.to_string(),
"subagent_source": "thread_spawn",
"initialization_mode": "resumed",
"created_at": worker_created_at,
})]
);
assert!(followup_child_request.requests().iter().any(|request| {
request.body_contains_text(FOLLOWUP_TASK)
&& request.body_contains_text(ROLE_DEVELOPER_INSTRUCTIONS)

View File

@@ -3,12 +3,8 @@
use core_test_support::test_codex::local_requests;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use anyhow::Result;
use codex_analytics::AnalyticsEventsClient;
use codex_analytics::PluginMeasurementRow;
use codex_analytics::PluginMeasurementsInput;
use codex_config::LoaderOverrides;
use codex_core::TurnInputRequest;
use codex_core::config::Config;
@@ -28,12 +24,10 @@ use codex_protocol::config_types::CollaborationMode;
use codex_protocol::config_types::ModeKind;
use codex_protocol::config_types::Settings;
use codex_protocol::config_types::TrustLevel;
use codex_protocol::mcp::ClientMcpExtensions;
use codex_protocol::models::PermissionProfile;
use codex_protocol::protocol::AskForApproval;
use codex_protocol::protocol::EventMsg;
#[cfg(unix)]
use codex_protocol::protocol::GranularApprovalConfig;
use codex_protocol::protocol::ThreadSettingsOverrides;
use codex_protocol::user_input::UserInput;
use codex_skills_extension::HostSkillsLoadInput;
@@ -58,7 +52,6 @@ use core_test_support::responses::start_mock_server;
use core_test_support::skip_if_no_network;
use core_test_support::skip_if_remote;
#[cfg(unix)]
use core_test_support::skip_if_sandbox;
use core_test_support::skip_if_target_windows;
use core_test_support::stdio_server_bin;
use core_test_support::submit_thread_settings;
@@ -82,7 +75,6 @@ const SAMPLE_PLUGIN_CONFIG_NAME: &str = "sample@test";
const SAMPLE_REMOTE_PLUGIN_CONFIG_NAME: &str = "sample@openai-curated-remote";
const SAMPLE_PLUGIN_DISPLAY_NAME: &str = "sample";
const SAMPLE_PLUGIN_DESCRIPTION: &str = "inspect sample data";
const SAMPLE_REMOTE_PLUGIN_ID: &str = "plugins~Plugin_sample";
const SAMPLE_PLUGIN_APP_NAMESPACE: &str = "mcp__codex_apps__google_calendar";
const SAMPLE_PLUGIN_MCP_NAMESPACE: &str = "mcp__sample";
const PLUGIN_APP_SEARCH_CALL_ID: &str = "plugin-app-search";
@@ -170,17 +162,6 @@ fn write_plugin_skill_plugin(home: &TempDir) -> std::path::PathBuf {
write_sample_plugin_skill(write_sample_plugin_manifest_and_config(home))
}
fn write_remote_plugin_skill_plugin(home: &TempDir) -> std::path::PathBuf {
let plugin_root = home
.path()
.join("plugins/cache/openai-curated-remote/sample/local");
write_sample_plugin_skill(write_sample_plugin_manifest_and_config_at_root(
home,
plugin_root,
SAMPLE_REMOTE_PLUGIN_CONFIG_NAME,
))
}
fn write_sample_plugin_skill(plugin_root: std::path::PathBuf) -> std::path::PathBuf {
let skill_dir = plugin_root.join("skills/sample-search");
std::fs::create_dir_all(skill_dir.as_path()).expect("create plugin skill dir");
@@ -285,21 +266,6 @@ fn write_plugin_app_plugin_with_name(home: &TempDir, app_name: &str) {
.expect("write plugin app config");
}
async fn build_analytics_plugin_test_codex(
server: &MockServer,
codex_home: Arc<TempDir>,
) -> Result<TestCodex> {
let chatgpt_base_url = server.uri();
let mut builder = test_codex()
.with_home(codex_home)
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_model("gpt-5.2")
.with_config(move |config| {
config.chatgpt_base_url = chatgpt_base_url;
});
builder.build_with_auto_env(server).await
}
async fn build_apps_enabled_plugin_test_codex(
server: &MockServer,
codex_home: Arc<TempDir>,
@@ -367,105 +333,6 @@ fn searched_plugin_tools(
)
}
#[tokio::test]
async fn shared_analytics_client_preserves_session_products() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
Mock::given(path("/codex/analytics-events/events"))
.respond_with(ResponseTemplate::new(200))
.mount(&server)
.await;
let client = AnalyticsEventsClient::new(
codex_core::test_support::auth_manager_from_auth(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
),
server.uri(),
/*analytics_enabled*/ Some(true),
);
let mut products = [Some("aeon"), Some("tpp"), None];
let mut sessions = Vec::new();
for product in products {
sessions.push(
test_codex()
.with_analytics_events_client(client.clone())
.with_config(move |config| {
config.apps_mcp_product_sku = product.map(str::to_string);
})
.build_with_auto_env(&server)
.await?,
);
}
// All Sessions have registered before events are interleaved on their shared client.
let mut expected = Vec::new();
for (position, index) in [0, 1, 2, 0, 0].into_iter().enumerate() {
if position == 4 {
client.flush().await;
let session = &mut sessions[0];
session.codex.ensure_rollout_materialized().await;
session.codex.shutdown_and_wait().await?;
session
.thread_manager
.remove_thread(&session.session_configured.thread_id)
.await;
let mut config = session.config.clone();
config.analytics_enabled = Some(false);
let resumed = session
.thread_manager
.resume_legacy_thread_from_rollout(
config,
session.codex.rollout_path().expect("rollout path"),
session.thread_manager.auth_manager(),
/*parent_trace*/ None,
ClientMcpExtensions::default(),
)
.await?;
assert_eq!(resumed.thread_id, session.session_configured.thread_id);
session.codex = resumed.thread;
products[0] = None;
}
let thread_id = sessions[index].session_configured.thread_id.to_string();
client.track_plugin_measurements(PluginMeasurementsInput {
thread_id: thread_id.clone(),
turn_id: "turn".into(),
item_id: "item".into(),
originator: "test_client".into(),
model_slug: None,
reasoning_effort: None,
plugin_id: "sample@test".into(),
execution_id: "execution".into(),
operation: "build".into(),
rows: vec![PluginMeasurementRow {
measurement_name: "duration_ms".into(),
number_value: 1.0,
dimensions: Default::default(),
}],
});
expected.push((thread_id, products[index].map(str::to_string)));
}
client.flush().await;
let mut actual = Vec::new();
for request in server.received_requests().await.unwrap_or_default() {
if request.url.path() != "/codex/analytics-events/events" {
continue;
}
let product = request
.headers
.get("x-openai-product-sku")
.map(|value| value.to_str().unwrap().to_string());
let body: serde_json::Value = serde_json::from_slice(&request.body)?;
for event in body["events"].as_array().unwrap() {
if event["event_type"] == "codex_plugin_measurement_event" {
let thread_id = event["event_params"]["thread_id"].as_str().unwrap();
actual.push((thread_id.to_string(), product.clone()));
}
}
}
actual.sort();
expected.sort();
assert_eq!(actual, expected);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn persisted_remote_plugin_command_attribution_flows_through_turn_context() -> Result<()> {
skip_if_target_windows!(Ok(()), "executes a POSIX shell script");
@@ -478,19 +345,7 @@ async fn persisted_remote_plugin_command_attribution_flows_through_turn_context(
let server = start_mock_server().await;
let codex_home = Arc::new(TempDir::new()?);
let script_path = write_remote_plugin_script_and_config(codex_home.as_ref());
std::fs::write(
&script_path,
r#"printf '%s' '{"version":1,"measurements":[{"name":"files_scanned","value":7}]}' > "$CODEX_PLUGIN_METRICS_OUTPUT"
"#,
)?;
let plugin_root = script_path
.parent()
.and_then(std::path::Path::parent)
.expect("plugin root");
std::fs::write(
plugin_root.join("analytics.yaml"),
"version: 1\noperations: {scan: {path: ./scripts/run.sh, measurements: {files_scanned: {}}}}\n",
)?;
std::fs::write(&script_path, "printf done\n")?;
let builder = test_codex();
let command = shlex::try_join(["/bin/sh", script_path.to_string_lossy().as_ref()])?;
let call_id = "remote-plugin-command";
@@ -576,316 +431,6 @@ async fn persisted_remote_plugin_command_attribution_flows_through_turn_context(
assert_eq!(script_path, Some("scripts/run.sh"));
}
let measurement = wait_for_analytics_event(&server, "codex_plugin_measurement_event").await;
assert_eq!(
serde_json::json!({
"plugin_id": measurement["event_params"]["plugin_id"],
"operation": measurement["event_params"]["operation"],
"measurement_name": measurement["event_params"]["measurement_name"],
"number_value": measurement["event_params"]["number_value"],
}),
serde_json::json!({
"plugin_id": REMOTE_PLUGIN_CONFIG_NAME,
"operation": "scan",
"measurement_name": "files_scanned",
"number_value": 7.0,
})
);
Ok(())
}
#[cfg(unix)]
#[test_case(codex_exec_server::LOCAL_ENVIRONMENT_ID; "local")]
#[test_case(codex_exec_server::REMOTE_ENVIRONMENT_ID; "remote")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn plugin_metrics_stdin_works_with_sandbox_approval_disabled(
environment_id: &str,
) -> Result<()> {
skip_if_no_network!(Ok(()));
skip_if_sandbox!(Ok(()));
let server = start_mock_server().await;
let home = Arc::new(TempDir::new()?);
let script = write_remote_plugin_script_and_config(home.as_ref());
std::fs::write(
&script,
r#"test -n "${CODEX_PLUGIN_METRICS_OUTPUT:-}" || exit 2
IFS= read -r input
test "$input" = continue || exit 3
printf '%s' '{"version":1,"measurements":[{"name":"files_scanned","value":7}]}' > "$CODEX_PLUGIN_METRICS_OUTPUT" || exit 4
printf 'STDIN_OK\n'
"#,
)?;
std::fs::write(
script
.parent()
.unwrap()
.parent()
.unwrap()
.join("analytics.yaml"),
"version: 1\noperations: {scan: {path: ./scripts/run.sh, measurements: {files_scanned: {}}}}\n",
)?;
let command = shlex::try_join(["/bin/sh", script.to_string_lossy().as_ref()])?;
let responses = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_function_call(
"open",
"exec_command",
&serde_json::json!({
"cmd": command,
"login": false,
"tty": true,
"yield_time_ms": 1000,
"environment_id": environment_id,
})
.to_string(),
),
ev_completed("opened"),
]),
sse(vec![
ev_function_call(
"input",
"write_stdin",
&serde_json::json!({
"session_id": 1000,
"chars": "continue\n",
"yield_time_ms": 1000,
})
.to_string(),
),
ev_completed("sent"),
]),
sse(vec![ev_completed("done")]),
],
)
.await;
let base_url = server.uri();
let mut builder = test_codex()
.with_home(home)
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_model("gpt-5.2")
.with_config(move |config| {
config.chatgpt_base_url = base_url;
config.analytics_enabled = Some(true);
config
.features
.enable(Feature::SkipHostSkillDiscovery)
.unwrap();
});
// Exercise both native and executor-managed sandboxes with the same plugin fixture.
let _executor = if environment_id == codex_exec_server::REMOTE_ENVIRONMENT_ID {
let executor = core_test_support::exec_server::ExecServerProcess::start().await?;
builder = builder.with_exec_server_url(executor.websocket_url.clone());
Some(executor)
} else {
None
};
let test = builder.build(&server).await?;
let (sandbox_policy, permission_profile) =
turn_permission_fields(PermissionProfile::read_only(), test.config.cwd.as_path());
test.codex
.start_or_steer_turn(
TurnInputRequest::user_input(vec![UserInput::Text {
text: "send input to the plugin".into(),
text_elements: Vec::new(),
}])
.with_thread_settings(ThreadSettingsOverrides {
approval_policy: Some(AskForApproval::Granular(GranularApprovalConfig {
sandbox_approval: false,
rules: false,
skill_approval: false,
request_permissions: false,
mcp_elicitations: false,
})),
sandbox_policy: Some(sandbox_policy),
permission_profile,
..Default::default()
}),
)
.await?;
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
let output = responses.function_call_output_text("input").unwrap();
assert!(output.contains("Process exited with code 0"), "{output}");
assert!(output.contains("STDIN_OK"), "{output}");
let measurement = wait_for_analytics_event(&server, "codex_plugin_measurement_event").await;
assert_eq!(
serde_json::json!({
"plugin_id": measurement["event_params"]["plugin_id"],
"measurement_name": measurement["event_params"]["measurement_name"],
"number_value": measurement["event_params"]["number_value"],
}),
serde_json::json!({
"plugin_id": REMOTE_PLUGIN_CONFIG_NAME,
"measurement_name": "files_scanned",
"number_value": 7.0,
}),
);
Ok(())
}
#[cfg(unix)]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn remote_plugin_measurements_require_the_frontend_version() -> Result<()> {
skip_if_no_network!(Ok(()));
// This fixture needs a real remote transport with separately controlled frontend
// and executor caches, rather than the runner's automatic executor selection.
let executor = core_test_support::exec_server::ExecServerProcess::start().await?;
let server = start_mock_server().await;
let home = Arc::new(TempDir::new()?);
let frontend_script = write_remote_plugin_script_and_config(home.as_ref());
let script = r#"if [ -n "${CODEX_PLUGIN_METRICS_OUTPUT:-}" ]; then
printf '%s' '{"version":1,"measurements":[{"name":"duration_ms","value":7,"dimensions":{"release":"v1"}}]}' > "$CODEX_PLUGIN_METRICS_OUTPUT"
else
printf 'no metrics sidecar\n'
fi
"#;
std::fs::write(&frontend_script, script)?;
std::fs::write(
frontend_script
.parent()
.unwrap()
.parent()
.unwrap()
.join("analytics.yaml"),
"version: 1\noperations:\n dependency_install:\n path: ./scripts/run.sh\n measurements:\n duration_ms:\n dimensions:\n release: [v1]\n",
)?;
let executor_home = TempDir::new()?;
let mut responses = Vec::new();
for (version, call_id) in [("2.0.0", "wrong-version"), ("1.2.3", "matching-version")] {
let root = executor_home.path().join(format!(
"plugins/cache/openai-curated-remote/sample/{version}"
));
std::fs::create_dir_all(root.join("scripts"))?;
let path = root.join("scripts/run.sh");
std::fs::write(&path, script)?;
// The executor's declaration is never an authority, even for matching bytes.
std::fs::write(
root.join("analytics.yaml"),
"version: 1\noperations: {untrusted: {path: ./scripts/run.sh, measurements: {other: {}}}}\n",
)?;
// A plugin-shaped alias must use the canonical plugin's identity and version.
let alias = executor_home.path().join(format!(
"plugins/cache/openai-curated-remote/apparent-plugin/{version}"
));
std::fs::create_dir_all(alias.parent().unwrap())?;
std::os::unix::fs::symlink(&root, &alias)?;
let alias_script = alias.join("scripts/run.sh");
let command = shlex::try_join(["/bin/sh", alias_script.to_string_lossy().as_ref()])?;
responses.push(sse(vec![
ev_response_created(call_id),
ev_function_call(
call_id,
"exec_command",
&serde_json::json!({
"cmd": command,
"login": false,
"environment_id": codex_exec_server::REMOTE_ENVIRONMENT_ID,
"yield_time_ms": 1000,
})
.to_string(),
),
ev_completed(call_id),
]));
}
responses.push(sse(vec![
ev_response_created("done"),
ev_assistant_message("done-message", "done"),
ev_completed("done"),
]));
let response_mock = mount_sse_sequence(&server, responses).await;
let base_url = server.uri();
let mut builder = test_codex()
.with_exec_server_url(executor.websocket_url.clone())
.with_home(home)
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_model("gpt-5.2")
.with_config(move |config| {
config.chatgpt_base_url = base_url;
config.analytics_enabled = Some(true);
config
.features
.enable(Feature::SkipHostSkillDiscovery)
.unwrap();
});
let test = builder.build(&server).await?;
let manager = test.thread_manager.environment_manager();
let remote = manager.default_environment().unwrap();
tokio::time::timeout(Duration::from_secs(30), remote.wait_until_ready()).await??;
assert!(remote.is_remote());
let (sandbox_policy, permission_profile) =
turn_permission_fields(PermissionProfile::Disabled, test.config.cwd.as_path());
test.codex
.start_or_steer_turn(
TurnInputRequest::user_input(vec![UserInput::Text {
text: "run both plugin versions".into(),
text_elements: Vec::new(),
}])
.with_thread_settings(ThreadSettingsOverrides {
approval_policy: Some(AskForApproval::Never),
sandbox_policy: Some(sandbox_policy),
permission_profile,
..Default::default()
}),
)
.await?;
for call_id in ["wrong-version", "matching-version"] {
let expected = (Some(REMOTE_PLUGIN_CONFIG_NAME), Some("scripts/run.sh"));
let begin = wait_for_event_match(&test.codex, |event| match event {
EventMsg::ExecCommandBegin(event) if event.call_id == call_id => Some(event.clone()),
_ => None,
})
.await;
let end = wait_for_event_match(&test.codex, |event| match event {
EventMsg::ExecCommandEnd(event) if event.call_id == call_id => Some(event.clone()),
_ => None,
})
.await;
assert_eq!(end.exit_code, 0, "{}", end.aggregated_output);
assert_eq!(
(begin.plugin_id.as_deref(), begin.script_path.as_deref()),
expected
);
assert_eq!(
(end.plugin_id.as_deref(), end.script_path.as_deref()),
expected
);
}
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
assert!(
response_mock
.function_call_output_text("wrong-version")
.unwrap()
.contains("no metrics sidecar")
);
let event = wait_for_analytics_event(&server, "codex_plugin_measurement_event").await;
assert_eq!(
serde_json::json!({
"plugin_id": event["event_params"]["plugin_id"],
"operation": event["event_params"]["operation"],
"measurement_name": event["event_params"]["measurement_name"],
"number_value": event["event_params"]["number_value"],
"dimensions": event["event_params"]["dimensions"],
"thread_id": event["event_params"]["thread_id"],
"item_id": event["event_params"]["item_id"],
}),
serde_json::json!({
"plugin_id": REMOTE_PLUGIN_CONFIG_NAME,
"operation": "dependency_install",
"measurement_name": "duration_ms",
"number_value": 7.0,
"dimensions": {"release": "v1"},
"thread_id": test.session_configured.thread_id.to_string(),
"item_id": "matching-version",
})
);
Ok(())
}
@@ -2241,205 +1786,3 @@ async fn explicitly_requested_mcp_waits_for_startup(request: ExplicitMcpRequest)
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn explicit_plugin_mentions_track_plugin_used_analytics() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let _resp_mock = mount_sse_once(
&server,
sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]),
)
.await;
let codex_home = Arc::new(TempDir::new()?);
write_plugin_skill_plugin(codex_home.as_ref());
let test_codex = build_analytics_plugin_test_codex(&server, codex_home).await?;
let codex = Arc::clone(&test_codex.codex);
codex
.start_or_steer_turn(
TurnInputRequest::user_input(vec![codex_protocol::user_input::UserInput::Mention {
name: "sample".into(),
path: format!("plugin://{SAMPLE_PLUGIN_CONFIG_NAME}"),
}])
.with_responses_metadata(Some(std::collections::HashMap::from([]))),
)
.await?;
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
let event = wait_for_analytics_event(&server, "codex_plugin_used").await;
assert_eq!(event["event_params"]["plugin_id"], "sample@test");
assert_eq!(event["event_params"]["plugin_name"], "sample");
assert_eq!(event["event_params"]["marketplace_name"], "test");
assert_eq!(event["event_params"]["has_skills"], true);
assert_eq!(event["event_params"]["mcp_server_count"], 0);
assert_eq!(
event["event_params"]["mcp_server_names"],
serde_json::json!([])
);
assert_eq!(
event["event_params"]["connector_ids"],
serde_json::json!([])
);
assert_eq!(
event["event_params"]["product_client_id"],
serde_json::json!(codex_login::default_client::originator().value)
);
assert_eq!(event["event_params"]["model_slug"], "gpt-5.2");
assert!(event["event_params"]["thread_id"].as_str().is_some());
assert!(event["event_params"]["turn_id"].as_str().is_some());
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn explicit_plugin_skill_invocation_tracks_remote_plugin_id() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let _resp_mock = mount_sse_once(
&server,
sse(vec![ev_response_created("resp-1"), ev_completed("resp-1")]),
)
.await;
let codex_home = Arc::new(TempDir::new()?);
let skill_path = dunce::canonicalize(write_remote_plugin_skill_plugin(codex_home.as_ref()))?;
persist_sample_remote_plugin_id(codex_home.as_ref());
let test_codex = build_analytics_plugin_test_codex(&server, codex_home).await?;
let codex = Arc::clone(&test_codex.codex);
codex
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Skill {
name: "sample:sample-search".into(),
path: skill_path,
}]))
.await?;
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
let event = wait_for_analytics_event(&server, "skill_invocation").await;
assert_eq!(
event["event_params"]["plugin_id"],
SAMPLE_REMOTE_PLUGIN_CONFIG_NAME
);
assert_eq!(
event["event_params"]["remote_plugin_id"],
SAMPLE_REMOTE_PLUGIN_ID
);
assert_eq!(event["event_params"]["invoke_type"], "explicit");
Ok(())
}
#[derive(Clone, Copy)]
enum ImplicitPluginSkillInvocation {
SkillDocumentRead,
SkillScriptRun,
}
#[test_case(ImplicitPluginSkillInvocation::SkillDocumentRead; "skill document read")]
#[test_case(ImplicitPluginSkillInvocation::SkillScriptRun; "skill script run")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn implicit_plugin_skill_invocation_tracks_remote_plugin_id(
invocation: ImplicitPluginSkillInvocation,
) -> Result<()> {
skip_if_target_windows!(Ok(()), "executes POSIX cat and bash commands");
skip_if_remote!(Ok(()), "shell commands use host plugin-cache paths");
skip_if_no_network!(Ok(()));
let server = start_mock_server().await;
let codex_home = Arc::new(TempDir::new()?);
let skill_path = write_remote_plugin_skill_plugin(codex_home.as_ref());
persist_sample_remote_plugin_id(codex_home.as_ref());
let command = match invocation {
ImplicitPluginSkillInvocation::SkillDocumentRead => {
format!("cat {}", skill_path.display())
}
ImplicitPluginSkillInvocation::SkillScriptRun => {
let script_path = skill_path
.parent()
.expect("skill path should have a parent")
.join("scripts/test.sh");
std::fs::create_dir_all(
script_path
.parent()
.expect("script path should have a parent"),
)?;
std::fs::write(&script_path, "echo skill script invoked\n")?;
format!("bash {}", script_path.display())
}
};
let command_args = serde_json::json!({
"cmd": command,
"login": false,
})
.to_string();
let _resp_mock = mount_sse_sequence(
&server,
vec![
sse(vec![
ev_response_created("resp-1"),
ev_function_call("call-1", "exec_command", &command_args),
ev_completed("resp-1"),
]),
sse(vec![ev_response_created("resp-2"), ev_completed("resp-2")]),
],
)
.await;
let test_codex = build_analytics_plugin_test_codex(&server, codex_home).await?;
let codex = Arc::clone(&test_codex.codex);
codex
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
text: "inspect the sample skill".into(),
text_elements: Vec::new(),
}]))
.await?;
wait_for_event(&codex, |ev| matches!(ev, EventMsg::TurnComplete(_))).await;
let event = wait_for_analytics_event(&server, "skill_invocation").await;
assert_eq!(
event["event_params"]["plugin_id"],
SAMPLE_REMOTE_PLUGIN_CONFIG_NAME
);
assert_eq!(
event["event_params"]["remote_plugin_id"],
SAMPLE_REMOTE_PLUGIN_ID
);
assert_eq!(event["event_params"]["invoke_type"], "implicit");
Ok(())
}
fn persist_sample_remote_plugin_id(home: &TempDir) {
let plugin_id =
PluginId::parse(SAMPLE_REMOTE_PLUGIN_CONFIG_NAME).expect("remote plugin id should parse");
PluginStore::new(home.path().to_path_buf())
.write_remote_plugin_id(&plugin_id, SAMPLE_REMOTE_PLUGIN_ID)
.expect("persist remote plugin id");
}
async fn wait_for_analytics_event(server: &MockServer, event_type: &str) -> serde_json::Value {
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let requests = server.received_requests().await.unwrap_or_default();
if let Some(event) = requests
.into_iter()
.filter(|request| request.url.path() == "/codex/analytics-events/events")
.find_map(|request| {
let payload: serde_json::Value = serde_json::from_slice(&request.body).ok()?;
payload["events"].as_array().and_then(|events| {
events
.iter()
.find(|event| event["event_type"] == event_type)
.cloned()
})
})
{
break event;
}
if Instant::now() >= deadline {
panic!("timed out waiting for {event_type} analytics request");
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
}

View File

@@ -60,7 +60,6 @@ use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::time::Duration;
use std::time::Instant;
use tempfile::TempDir;
use test_case::test_case;
use tokio::sync::Notify;
@@ -1375,56 +1374,6 @@ async fn run_remote_plugin_install_metadata_case() -> Result<()> {
assert_eq!(meta["remote_plugin_id"], REMOTE_PLUGIN_ID);
assert_eq!(meta["app_connector_ids"], json!([APP_CONNECTOR_ID]));
let deadline = Instant::now() + Duration::from_secs(10);
let analytics_event = loop {
let requests = server.received_requests().await.unwrap_or_default();
if let Some(event) = requests
.into_iter()
.filter(|request| request.url.path() == "/codex/analytics-events/events")
.find_map(|request| {
let payload: Value = serde_json::from_slice(&request.body).ok()?;
payload["events"].as_array().and_then(|events| {
events
.iter()
.find(|event| event["event_type"] == "codex_plugin_install_requested")
.cloned()
})
})
{
break event;
}
if Instant::now() >= deadline {
panic!("timed out waiting for plugin install request analytics");
}
tokio::time::sleep(Duration::from_millis(50)).await;
};
assert_eq!(
meta["suggestion_id"],
analytics_event["event_params"]["suggestion_id"]
);
let thread_id = analytics_event["event_params"]["thread_id"].clone();
let turn_id = analytics_event["event_params"]["turn_id"].clone();
assert_eq!(
analytics_event,
json!({
"event_type": "codex_plugin_install_requested",
"event_params": {
"suggestion_id": "request_plugin_install_install-github",
"plugins": [{
"plugin_id": "github@openai-curated-remote",
"remote_plugin_id": REMOTE_PLUGIN_ID,
"plugin_name": "GitHub",
"connector_ids": [APP_CONNECTOR_ID],
}],
"source": "endpoint_recommendation",
"thread_id": thread_id,
"turn_id": turn_id,
"model_slug": "gpt-5.5",
"product_client_id": codex_login::default_client::originator().value,
}
})
);
resolve_install_elicitation(&test, elicitation, ElicitationAction::Decline).await?;
let requests = mock.requests();

View File

@@ -18,7 +18,6 @@ use std::time::Duration;
use anyhow::Result;
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use codex_analytics::CompactionTrigger;
use codex_config::ConfigLayerEntry;
use codex_config::ConfigLayerSource;
use codex_config::ConfigLayerStack;
@@ -30,6 +29,7 @@ use codex_core::StartThreadOptions;
use codex_core::TurnInput;
use codex_core::TurnInputRequest;
use codex_core::compact::AutoCompactionDisabled;
use codex_core::compaction_metadata::CompactionTrigger;
use codex_core::config::Config;
use codex_core::config::TokenBudgetConfig;
use codex_exec_server::CreateDirectoryOptions;

View File

@@ -36,10 +36,6 @@ use codex_history::RolloutItem;
use codex_login::CodexAuth;
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
use codex_models_manager::bundled_models_response;
use codex_otel::OtelExporter;
use codex_otel::OtelHttpProtocol;
use codex_otel::OtelProvider;
use codex_otel::OtelSettings;
use codex_otel::THREAD_SKILLS_KEPT_TOTAL_METRIC;
use codex_protocol::capabilities::CapabilityRootLocation;
use codex_protocol::capabilities::SelectedCapabilityRoot;
@@ -120,16 +116,13 @@ use opentelemetry_sdk::metrics::data::MetricData;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use sha1::Digest;
use tempfile::TempDir;
use test_case::test_case;
use tokio::time::Duration;
use tokio::time::Instant;
use toml::toml;
use tracing::Level;
use tracing_subscriber::fmt::format::FmtSpan;
use tracing_test::internal::MockWriter;
use wiremock::MockServer;
#[path = "skills_extension/cloud_skill_tests.rs"]
mod cloud_skill_tests;
@@ -381,25 +374,6 @@ fn catalog_extensions(
(Arc::new(extensions.build()), event_rx)
}
async fn wait_for_analytics_events(
server: &MockServer,
event_type: &str,
expected_count: usize,
) -> Vec<Value> {
let deadline = Instant::now() + Duration::from_secs(10);
loop {
let events = responses::received_analytics_events(server, event_type).await;
if events.len() >= expected_count {
return events;
}
assert!(
Instant::now() < deadline,
"timed out waiting for {event_type} analytics"
);
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
fn configure_catalog_test(config: &mut Config) {
config.include_skill_instructions = true;
config
@@ -2562,15 +2536,6 @@ async fn executor_skill_invocation_is_environment_scoped_and_deduplicated() -> R
);
}
let events = wait_for_analytics_events(&server, "skill_invocation", /*expected_count*/ 1).await;
assert_eq!(events.len(), 1, "executor skill should be counted once");
assert_eq!(events[0]["skill_name"], "selected-environment-skill");
assert_eq!(
events[0]["skill_id"],
format!("{:x}", sha1::Sha1::digest(SELECTED_RESOURCE.as_bytes()))
);
assert_eq!(events[0]["event_params"]["invoke_type"], "implicit");
Ok(())
}
@@ -2732,27 +2697,16 @@ async fn assert_catalog_model_switch(max_context_tokens: Option<usize>) -> Resul
)
.await;
let codex_home = Arc::new(TempDir::new()?);
// Use the normal metrics sink to verify core's model attribution.
let telemetry = OtelProvider::try_new(&OtelSettings {
http_client_factory: codex_core::test_support::default_http_client_factory(),
environment: "test".to_string(),
service_name: "skills-model-switch".to_string(),
service_version: env!("CARGO_PKG_VERSION").to_string(),
codex_home: codex_home.path().to_path_buf(),
exporter: OtelExporter::None,
trace_exporter: OtelExporter::None,
metrics_exporter: OtelExporter::OtlpHttp {
endpoint: format!("{}/metrics", server.uri()),
headers: Default::default(),
protocol: OtelHttpProtocol::Json,
tls: None,
},
runtime_metrics: true,
span_attributes: Default::default(),
tracestate: Default::default(),
})
.map_err(|error| anyhow::anyhow!("{error}"))?
.expect("metrics provider");
// Use the process-global local metrics sink to verify core's model attribution.
let telemetry = codex_otel::install_global_metrics(codex_otel::MetricsClient::new(
codex_otel::MetricsConfig::in_memory(
"test",
"skills-model-switch",
env!("CARGO_PKG_VERSION"),
opentelemetry_sdk::metrics::InMemoryMetricExporter::default(),
)
.with_runtime_reader(),
)?);
let skill_count = 800;
let catalog = SkillCatalog {
is_partial: false,
@@ -2932,7 +2886,7 @@ async fn assert_catalog_model_switch(max_context_tokens: Option<usize>) -> Resul
expected_warnings.dedup();
assert_eq!(warnings, expected_warnings);
let snapshot = telemetry.metrics().expect("metrics client").snapshot()?;
let snapshot = telemetry.snapshot()?;
let metric = snapshot
.scope_metrics()
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
@@ -2964,9 +2918,7 @@ async fn assert_catalog_model_switch(max_context_tokens: Option<usize>) -> Resul
(MODEL_B.to_string(), 1, included_counts[1] as f64),
]
);
telemetry
.shutdown_with_timeout(Duration::from_secs(/*secs*/ 5))
.await?;
telemetry.shutdown()?;
Ok(())
}
@@ -3261,17 +3213,6 @@ async fn production_turn_uses_provider_host_catalog_and_core_snapshot_injection(
let user_text = request.message_input_texts("user").join("\n");
assert!(user_text.contains(&snapshot_contents));
assert!(!user_text.contains(provider_contents));
let app_mentioned_events =
wait_for_analytics_events(&server, "codex_app_mentioned", /*expected_count*/ 1).await;
let app_mentioned_event = &app_mentioned_events[0];
assert_eq!(
app_mentioned_event["event_params"]["connector_id"],
"calendar"
);
assert_eq!(
app_mentioned_event["event_params"]["invoke_type"],
"explicit"
);
Ok(())
}

View File

@@ -4,9 +4,6 @@ use super::*;
use pretty_assertions::assert_eq;
use tokio::sync::Mutex;
#[path = "yielded_skill_tests.rs"]
mod yielded_skill_tests;
struct FakeCloudSkillProvider {
catalog: SkillCatalog,
resources: std::collections::HashMap<String, String>,
@@ -275,10 +272,6 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings,
"next_cursor": null,
})
);
let events = wait_for_analytics_events(&server, "skill_invocation", /*expected_count*/ 1).await;
assert_eq!(events.len(), 1);
assert_eq!(events[0]["skill_name"], "demo:explicit-only");
assert_eq!(events[0]["event_params"]["invoke_type"], "explicit");
let response = responses::mount_sse_sequence(
&server,
@@ -368,15 +361,6 @@ text({ names: result.skills.map(skill => skill.name), warnings: result.warnings,
);
}
let events = wait_for_analytics_events(&server, "skill_invocation", /*expected_count*/ 2).await;
assert_eq!(events.len(), 2, "repeated main reads must be deduplicated");
assert_eq!(events[1]["skill_name"], "demo:explicit-only");
assert_eq!(
events[1]["skill_id"],
format!("{:x}", sha1::Sha1::digest(MAIN_RESOURCE.as_bytes()))
);
assert_eq!(events[1]["event_params"]["invoke_type"], "implicit");
for (name, has_more) in [
("alpha-visible", true),
("bravo-visible-skill", true),

View File

@@ -1,166 +0,0 @@
//! Skill analytics retain the originating turn when Code Mode resumes a yielded cell.
use super::*;
use codex_core::TurnInputSubmission;
use codex_protocol::openai_models::ToolMode;
use pretty_assertions::assert_eq;
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn yielded_skill_read_keeps_originating_turn_metadata() -> Result<()> {
skip_if_no_network!(Ok(()));
const PACKAGE: &str = "skill://demo/yielded";
const RESOURCE: &str = "skill://demo/yielded/SKILL.md";
let server = responses::start_mock_server().await;
let mut extensions = ExtensionRegistryBuilder::new();
install_with_providers(
&mut extensions,
SkillProviders::new().with_cloud_provider(Arc::new(FakeCloudSkillProvider {
catalog: SkillCatalog {
is_partial: false,
entries: vec![SkillCatalogEntry::new(
SkillPackageId(PACKAGE.to_string()),
SkillAuthority::new(SkillSourceKind::Cloud, CODEX_APPS_MCP_SERVER_NAME),
"demo:yielded",
"Instructions for the yielded skill.",
SkillResourceId::new(RESOURCE),
)],
warnings: Vec::new(),
},
resources: std::collections::HashMap::from([(
RESOURCE.to_string(),
"Yielded skill instructions.".to_string(),
)]),
reads: Mutex::default(),
read_barrier: None,
})),
|config: &Config| SkillsExtensionConfig {
include_instructions: config.include_skill_instructions,
catalog_deltas_enabled: config.features.enabled(Feature::SkillCatalogDeltas),
omit_descriptions: false,
max_context_tokens: config.skill_max_context_tokens,
bundled_skills_enabled: false,
cloud_skill_enabled: true,
shadow_selection_enabled: false,
},
);
let chatgpt_base_url = server.uri();
let mut builder = test_codex()
.with_auth(CodexAuth::create_dummy_chatgpt_auth_for_testing())
.with_exec_server_url("none")
.with_extensions(Arc::new(extensions.build()))
.with_model_info_override("gpt-5.5", |model| {
model.tool_mode = Some(ToolMode::CodeMode);
model.experimental_supported_tools = vec!["test_sync_tool".to_string()];
})
.with_config(move |config| {
config.chatgpt_base_url = chatgpt_base_url;
config.cloud_skill_enabled = true;
config.features.enable(Feature::CodeMode).unwrap();
config.features.enable(Feature::CodeModeHost).unwrap();
})
.with_code_mode_host_program(codex_utils_cargo_bin::cargo_bin("codex-code-mode-host")?);
let test = builder.build_with_auto_env(&server).await?;
// A cannot read its skill until B has become the active turn.
let read_after_barrier = format!(
r#"await tools.test_sync_tool({{barrier: {{
id: "yielded-skill-turns", participants: 2, timeout_ms: 60000
}}}});
text(await tools.skills__read({{package: "{PACKAGE}"}}));"#
);
mount_sse_once(
&server,
sse(vec![
ev_response_created("resp-a"),
responses::ev_custom_tool_call(
"call-a",
"exec",
&format!("// @exec: {{\"yield_time_ms\": 1}}\n{read_after_barrier}"),
),
ev_completed("resp-a"),
]),
)
.await;
let yielded = mount_sse_once(
&server,
sse(vec![
ev_response_created("resp-a-done"),
ev_completed("resp-a-done"),
]),
)
.await;
let request = TurnInputRequest::user_input(vec![UserInput::Text {
text: "Start a skill read and leave it running.".to_string(),
text_elements: Vec::new(),
}]);
let submitted = test.codex.start_or_steer_turn(request).await?;
let TurnInputSubmission::Started {
turn_id: turn_a, ..
} = submitted
else {
anyhow::bail!("expected turn A to start, got {submitted:?}");
};
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
let (output, _) = yielded
.single_request()
.custom_tool_call_output_content_and_success("call-a")
.expect("yielded cell output");
assert!(
output
.expect("yielded cell status")
.starts_with("Script running with cell ID ")
);
mount_sse_once(
&server,
sse(vec![
ev_response_created("resp-b"),
responses::ev_custom_tool_call(
"call-b",
"exec",
&format!("// @exec: {{\"yield_time_ms\": 60000}}\n{read_after_barrier}"),
),
ev_completed("resp-b"),
]),
)
.await;
mount_sse_once(
&server,
sse(vec![
ev_response_created("resp-b-done"),
ev_completed("resp-b-done"),
]),
)
.await;
let submitted = test
.codex
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
text: "Read the skill in this turn and release the previous read.".to_string(),
text_elements: Vec::new(),
}]))
.await?;
let TurnInputSubmission::Started {
turn_id: turn_b, ..
} = submitted
else {
anyhow::bail!("expected turn B to start, got {submitted:?}");
};
wait_for_event(&test.codex, |event| {
matches!(event, EventMsg::TurnComplete(_))
})
.await;
let events = wait_for_analytics_events(&server, "skill_invocation", /*expected_count*/ 2).await;
assert_eq!(events.len(), 2);
for turn_id in [&turn_a, &turn_b] {
let event = events
.iter()
.find(|event| event["event_params"]["turn_id"] == *turn_id)
.expect("each skill read should retain its originating turn");
assert_eq!(event["skill_name"], "demo:yielded");
}
Ok(())
}

View File

@@ -110,7 +110,7 @@ async fn steer_joins_existing_turn_without_extending_sampling(
tracing_opentelemetry::layer()
.with_tracer(telemetry.tracer("turn-phase-test"))
.with_filter(tracing_subscriber::filter::filter_fn(
codex_otel::OtelProvider::trace_export_filter,
codex_otel::trace_export_filter,
)),
)
.try_init()?;