aKode fase 2b-1: rimossi plugin remoti e share, bundle download, UI usage/crediti/banner/workspace ChatGPT; fix argomenti MCP (inviati vuoti dopo e4209e2) e overlay TUI; test analytics-upload rimossi; test sicurezza MCP adattati
Some checks failed
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
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (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
Some checks failed
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
blocking-ci / rust-ci (push) Has been cancelled
blocking-ci / sdk (push) Has been cancelled
blocking-ci / CI required (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:
@@ -236,86 +236,6 @@ async fn run_codex_thread_interactive_respects_pre_cancelled_spawn() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delegate_start_analytics_honors_child_opt_out_with_enabled_parent() {
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_login::CodexAuth;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(path("/codex/analytics-events/events"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let client = AnalyticsEventsClient::new(
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
|
||||
server.uri(),
|
||||
/*analytics_enabled*/ Some(true),
|
||||
);
|
||||
let (mut parent_session, parent_ctx, _rx_events) =
|
||||
crate::session::tests::make_session_and_context_with_rx().await;
|
||||
Arc::get_mut(&mut parent_session)
|
||||
.expect("parent session should be uniquely owned")
|
||||
.services
|
||||
.analytics_events_client = client.clone();
|
||||
parent_session
|
||||
.set_app_server_client_info(
|
||||
Some("codex-test".to_string()),
|
||||
Some("1.0.0".to_string()),
|
||||
/*mcp_elicitations_auto_deny*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("set parent client metadata");
|
||||
|
||||
let mut expected_events = Vec::new();
|
||||
for analytics_enabled in [false, true] {
|
||||
let mut config = parent_ctx.config.as_ref().clone();
|
||||
config.permissions.approval_policy = Constrained::allow_only(AskForApproval::Never);
|
||||
config.analytics_enabled = Some(analytics_enabled);
|
||||
let (session, io) = run_codex_thread_interactive(
|
||||
config,
|
||||
Arc::clone(&parent_session.services.auth_manager),
|
||||
Arc::clone(&parent_session.services.models_manager),
|
||||
Arc::clone(&parent_session),
|
||||
Arc::clone(&parent_ctx),
|
||||
parent_ctx.initial_environments.clone(),
|
||||
CancellationToken::new(),
|
||||
SubAgentSource::Review,
|
||||
codex_extension_api::SessionIsolation::Inherit,
|
||||
/*initial_history*/ None,
|
||||
crate::session::GitEnrichmentPolicy::Fresh,
|
||||
codex_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
|
||||
)
|
||||
.await
|
||||
.expect("delegate session should start");
|
||||
if analytics_enabled {
|
||||
expected_events.push(serde_json::json!([
|
||||
"codex_thread_initialized",
|
||||
session.thread_id().to_string(),
|
||||
]));
|
||||
}
|
||||
io.shutdown_and_wait()
|
||||
.await
|
||||
.expect("delegate session should shut down");
|
||||
}
|
||||
client.flush().await;
|
||||
let events = server
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("analytics requests")
|
||||
.into_iter()
|
||||
.flat_map(|request| {
|
||||
let payload: Value = serde_json::from_slice(&request.body).expect("analytics payload");
|
||||
payload["events"].as_array().expect("events array").clone()
|
||||
})
|
||||
.map(|event| serde_json::json!([event["event_type"], event["event_params"]["thread_id"]]))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(events, expected_events);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delegate_isolation_does_not_depend_on_attribution() {
|
||||
let (mut parent_session, mut parent_ctx, _rx_events) =
|
||||
|
||||
@@ -645,7 +645,8 @@ async fn handle_approved_mcp_tool_call(
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok((None, request_meta))
|
||||
// The model-supplied arguments are what the MCP server receives.
|
||||
Ok((arguments_value, request_meta))
|
||||
})
|
||||
.await
|
||||
.map_err(|error| {
|
||||
|
||||
@@ -16,7 +16,6 @@ use crate::state::ActiveTurn;
|
||||
use crate::test_support::models_manager_with_provider;
|
||||
use crate::tools::hook_names::HookToolName;
|
||||
use crate::turn_metadata::ExecutionMetadata;
|
||||
use codex_app_server_protocol as app_server_protocol;
|
||||
use codex_config::CONFIG_TOML_FILE;
|
||||
use codex_config::config_toml::ConfigToml;
|
||||
use codex_config::types::AppConfig;
|
||||
@@ -2275,153 +2274,6 @@ fn accepted_elicitation_without_content_defaults_to_accept() {
|
||||
assert_eq!(response, ReviewDecision::Approved);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dispatched_mcp_approval_with_closed_response_is_classified_as_approval() {
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
let server = wiremock::MockServer::start().await;
|
||||
wiremock::Mock::given(method("POST"))
|
||||
.and(path("/codex/analytics-events/events"))
|
||||
.respond_with(wiremock::ResponseTemplate::new(200))
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let (mut session, turn_context, rx_event) = make_session_and_context_with_rx().await;
|
||||
let client = codex_analytics::AnalyticsEventsClient::new(
|
||||
crate::test_support::auth_manager_from_auth(
|
||||
codex_login::CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
),
|
||||
server.uri(),
|
||||
/*analytics_enabled*/ Some(true),
|
||||
);
|
||||
Arc::get_mut(&mut session)
|
||||
.expect("session should be uniquely owned")
|
||||
.services
|
||||
.analytics_events_client = client.clone();
|
||||
*session.active_turn.lock().await = Some(ActiveTurn::default());
|
||||
|
||||
let call_id = "modern-missing-response";
|
||||
let thread_id = session.thread_id.to_string();
|
||||
let turn_id = turn_context.sub_id.clone();
|
||||
client.track_initialize(
|
||||
/*connection_id*/ 1,
|
||||
app_server_protocol::InitializeParams::default(),
|
||||
"test-client".to_string(),
|
||||
codex_analytics::AppServerRpcTransport::Stdio,
|
||||
);
|
||||
let response = serde_json::from_value(serde_json::json!({
|
||||
"thread": {
|
||||
"id": thread_id, "sessionId": thread_id, "preview": "", "ephemeral": false,
|
||||
"modelProvider": "openai", "createdAt": 1, "updatedAt": 1,
|
||||
"status": {"type": "idle"}, "cwd": &turn_context.config.cwd,
|
||||
"cliVersion": "0.0.0", "source": "exec", "turns": [],
|
||||
},
|
||||
"model": "test-model", "modelProvider": "openai", "cwd": &turn_context.config.cwd,
|
||||
"approvalPolicy": "on-request", "approvalsReviewer": "user",
|
||||
"sandbox": {"type": "dangerFullAccess"},
|
||||
}))
|
||||
.expect("thread-start response should deserialize");
|
||||
client.track_response(
|
||||
/*connection_id*/ 1,
|
||||
app_server_protocol::RequestId::Integer(1),
|
||||
&app_server_protocol::ClientResponsePayload::ThreadStart(response),
|
||||
);
|
||||
client.track_notification(&app_server_protocol::ServerNotification::TurnStarted(
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"threadId": thread_id,
|
||||
"turn": {"id": turn_id, "items": [], "status": "inProgress"},
|
||||
}))
|
||||
.expect("turn-started notification should deserialize"),
|
||||
));
|
||||
let mut item = serde_json::json!({
|
||||
"type": "mcpToolCall", "id": call_id, "server": "calendar", "tool": "send",
|
||||
"status": "inProgress", "arguments": {},
|
||||
"appContext": {"connectorId": "calendar"},
|
||||
});
|
||||
client.track_notification(&app_server_protocol::ServerNotification::ItemStarted(
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"threadId": thread_id, "turnId": turn_id, "startedAtMs": 1, "item": item,
|
||||
}))
|
||||
.expect("item-started notification should deserialize"),
|
||||
));
|
||||
|
||||
let action = ApprovalAction::McpToolCall {
|
||||
id: call_id.to_string(),
|
||||
environment_id: test_environment_id(&turn_context).to_owned(),
|
||||
server: "calendar".to_string(),
|
||||
tool_name: "send".to_string(),
|
||||
arguments: None,
|
||||
connector_id: Some("calendar".to_string()),
|
||||
connector_name: None,
|
||||
connector_description: None,
|
||||
connected_account_email: None,
|
||||
tool_title: None,
|
||||
tool_description: None,
|
||||
annotations: None,
|
||||
hook_tool_name: HookToolName::new("mcp__calendar__send"),
|
||||
approval_policy: AskForApproval::OnRequest,
|
||||
reviewer: ApprovalsReviewer::User,
|
||||
approval_mode: AppToolApproval::Auto,
|
||||
allow_session_remember: true,
|
||||
allow_persistent_approval: true,
|
||||
prompt_permissions: None,
|
||||
};
|
||||
let approval = tokio::spawn({
|
||||
let session = Arc::clone(&session);
|
||||
let turn_context = Arc::clone(&turn_context);
|
||||
async move { request_mcp_tool_user_approval(&session, &turn_context, call_id, &action).await }
|
||||
});
|
||||
let event = tokio::time::timeout(std::time::Duration::from_secs(1), rx_event.recv())
|
||||
.await
|
||||
.expect("approval request should be dispatched")
|
||||
.expect("approval request should be received");
|
||||
assert!(matches!(event.msg, EventMsg::ElicitationRequest(_)));
|
||||
*session.active_turn.lock().await = None;
|
||||
assert_eq!(
|
||||
approval.await.expect("approval task should complete"),
|
||||
ApprovalResolution {
|
||||
decision: ReviewDecision::Abort,
|
||||
source: ApprovalResolutionSource::User,
|
||||
cancellation_reason: Some(McpApprovalCancellationReason::Interrupted),
|
||||
}
|
||||
);
|
||||
|
||||
item["status"] = serde_json::json!("failed");
|
||||
client.track_notification(&app_server_protocol::ServerNotification::ItemCompleted(
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"threadId": thread_id, "turnId": turn_id, "completedAtMs": 2, "item": item,
|
||||
}))
|
||||
.expect("item-completed notification should deserialize"),
|
||||
));
|
||||
client.flush().await;
|
||||
let events = server
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("analytics requests should be recorded")
|
||||
.into_iter()
|
||||
.flat_map(|request| {
|
||||
serde_json::from_slice::<serde_json::Value>(&request.body)
|
||||
.expect("analytics request should deserialize")["events"]
|
||||
.as_array()
|
||||
.expect("analytics events should be an array")
|
||||
.clone()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mcp_events = events
|
||||
.iter()
|
||||
.filter(|event| {
|
||||
event["event_type"] == "codex_mcp_tool_call_event"
|
||||
&& event["event_params"]["item_id"] == call_id
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(mcp_events.len(), 1);
|
||||
assert_eq!(
|
||||
mcp_events[0]["event_params"]["elicitation_type"],
|
||||
"approval"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn persist_codex_app_tool_approval_writes_tool_override() {
|
||||
let tmp = tempdir().expect("tempdir");
|
||||
|
||||
@@ -65,10 +65,8 @@ use core_test_support::test_codex::TurnInputRequest as ExternalTurnInputRequest;
|
||||
|
||||
use codex_features::Feature;
|
||||
use codex_file_system::FileSystemSandboxContext;
|
||||
use codex_http_client::ClientRouteClass;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::OutboundProxyPolicy;
|
||||
use codex_http_client::RouteAwareClientPool;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::auth::AgentIdentityAuthPolicy;
|
||||
use codex_model_provider::create_model_provider;
|
||||
@@ -5293,143 +5291,6 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn emit_subagent_session_started_includes_fork_lineage_and_originator() {
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::ThreadArchivedNotification;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/codex/analytics-events/events"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let auth_manager =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let analytics_events_client = AnalyticsEventsClient::new(
|
||||
auth_manager,
|
||||
server.uri(),
|
||||
/*analytics_enabled*/ Some(true),
|
||||
);
|
||||
|
||||
let parent_thread_id = ThreadId::new();
|
||||
let forked_from_thread_id = ThreadId::new();
|
||||
let child_thread_id = ThreadId::new();
|
||||
let mut session_configuration = make_session_configuration_for_tests().await;
|
||||
session_configuration.forked_from_thread_id = Some(forked_from_thread_id);
|
||||
session_configuration.thread_source = Some(ThreadSource::GuardianReview);
|
||||
|
||||
emit_subagent_session_started(
|
||||
&analytics_events_client,
|
||||
AppServerClientMetadata {
|
||||
client_name: Some("codex-tui".to_string()),
|
||||
client_version: Some("1.0.0".to_string()),
|
||||
},
|
||||
SessionId::from(child_thread_id),
|
||||
child_thread_id,
|
||||
Some(parent_thread_id),
|
||||
session_configuration.thread_config_snapshot(Vec::new()),
|
||||
SubAgentSource::Other(crate::guardian::GUARDIAN_REVIEWER_NAME.to_string()),
|
||||
/*resumed_created_at*/ None,
|
||||
);
|
||||
|
||||
let event = timeout(Duration::from_secs(1), async {
|
||||
'wait_for_event: loop {
|
||||
if let Some(requests) = server.received_requests().await {
|
||||
for request in requests {
|
||||
let payload: serde_json::Value =
|
||||
serde_json::from_slice(&request.body).expect("valid analytics payload");
|
||||
if let Some(event) = payload["events"].as_array().and_then(|events| {
|
||||
events
|
||||
.iter()
|
||||
.find(|event| event["event_type"] == "codex_thread_initialized")
|
||||
}) {
|
||||
break 'wait_for_event event.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("subagent initialization analytics should be emitted");
|
||||
|
||||
assert_eq!(event["event_params"]["initialization_mode"], "new");
|
||||
assert_eq!(event["event_params"]["thread_source"], "guardian_review");
|
||||
assert_eq!(
|
||||
event["event_params"]["parent_thread_id"],
|
||||
parent_thread_id.to_string()
|
||||
);
|
||||
assert_eq!(
|
||||
event["event_params"]["forked_from_thread_id"],
|
||||
forked_from_thread_id.to_string()
|
||||
);
|
||||
assert_eq!(
|
||||
event["event_params"]["app_server_client"]["product_client_id"],
|
||||
"test_originator"
|
||||
);
|
||||
|
||||
let prewarmed_thread_id = ThreadId::new();
|
||||
emit_subagent_session_started(
|
||||
&analytics_events_client,
|
||||
AppServerClientMetadata {
|
||||
client_name: None,
|
||||
client_version: None,
|
||||
},
|
||||
SessionId::from(parent_thread_id),
|
||||
prewarmed_thread_id,
|
||||
Some(parent_thread_id),
|
||||
session_configuration.thread_config_snapshot(Vec::new()),
|
||||
SubAgentSource::Other(crate::guardian::GUARDIAN_REVIEWER_NAME.to_string()),
|
||||
/*resumed_created_at*/ None,
|
||||
);
|
||||
// Archive analytics exposes retained lineage even before a parent connection exists.
|
||||
analytics_events_client.track_notification(&ServerNotification::ThreadArchived(
|
||||
ThreadArchivedNotification {
|
||||
thread_id: prewarmed_thread_id.to_string(),
|
||||
},
|
||||
));
|
||||
analytics_events_client.flush().await;
|
||||
let events = server
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("analytics requests")
|
||||
.into_iter()
|
||||
.flat_map(|request| {
|
||||
let payload: serde_json::Value =
|
||||
serde_json::from_slice(&request.body).expect("valid analytics payload");
|
||||
payload["events"]
|
||||
.as_array()
|
||||
.expect("analytics events")
|
||||
.clone()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let [initialization, archive] = events.as_slice() else {
|
||||
panic!("expected one complete initialization and one archive: {events:?}");
|
||||
};
|
||||
assert_eq!(initialization, &event);
|
||||
assert_eq!(
|
||||
json!([
|
||||
archive["event_type"],
|
||||
archive["event_params"]["thread_id"],
|
||||
archive["event_params"]["thread_source"],
|
||||
archive["event_params"]["parent_thread_id"],
|
||||
]),
|
||||
json!([
|
||||
"codex_thread_archive_event",
|
||||
prewarmed_thread_id.to_string(),
|
||||
"guardian_review",
|
||||
parent_thread_id.to_string(),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
async fn resolved_environments_for_configuration(
|
||||
session_configuration: &SessionConfiguration,
|
||||
environment_selections: &[TurnEnvironmentSelection],
|
||||
@@ -6780,24 +6641,6 @@ async fn response_metadata_builders_capture_fresh_mcp_attribution() {
|
||||
assert_eq!(compaction.mcp_attribution, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn responses_metadata_uses_selected_harness_analytics_client() {
|
||||
for enabled in [true, false] {
|
||||
let (mut session, mut turn_context) = make_session_and_context().await;
|
||||
session.services.analytics_events_client = AnalyticsEventsClient::new(
|
||||
Arc::clone(&session.services.auth_manager),
|
||||
turn_context.config.chatgpt_base_url.clone(),
|
||||
Some(enabled),
|
||||
);
|
||||
Arc::make_mut(&mut turn_context.config).analytics_enabled = Some(!enabled);
|
||||
let step_context = StepContext::for_test(Arc::new(turn_context));
|
||||
let metadata = session
|
||||
.responses_metadata(&step_context, CodexResponsesRequestKind::Turn)
|
||||
.await;
|
||||
assert_eq!(metadata.analytics_enabled, Some(enabled));
|
||||
}
|
||||
}
|
||||
|
||||
// todo: use online model info
|
||||
pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
let (tx_event, _rx_event) = async_channel::unbounded();
|
||||
@@ -6955,7 +6798,6 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) {
|
||||
exec_policy,
|
||||
auth_manager: auth_manager.clone(),
|
||||
runtime_auth: Default::default(),
|
||||
.with_legacy_custom_ca_fallback(),
|
||||
session_telemetry: session_telemetry.clone(),
|
||||
models_manager: Arc::clone(&models_manager),
|
||||
git_root_discovery: Arc::default(),
|
||||
@@ -9295,7 +9137,6 @@ where
|
||||
exec_policy,
|
||||
auth_manager: Arc::clone(&auth_manager),
|
||||
runtime_auth: Default::default(),
|
||||
.with_legacy_custom_ca_fallback(),
|
||||
session_telemetry: session_telemetry.clone(),
|
||||
models_manager: Arc::clone(&models_manager),
|
||||
git_root_discovery: Arc::default(),
|
||||
@@ -10766,92 +10607,6 @@ async fn record_context_updates_emits_realtime_end_when_session_stops_being_live
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_initial_context_reuses_in_flight_recommendation_prewarm() {
|
||||
use wiremock::Mock;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
use wiremock::matchers::query_param;
|
||||
|
||||
core_test_support::skip_if_no_network!();
|
||||
|
||||
let server = start_mock_server().await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/ps/plugins/suggested/codex"))
|
||||
.and(query_param("scope", "GLOBAL"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"enabled": true,
|
||||
"plugins": [{
|
||||
"id": "plugin_github",
|
||||
"name": "github",
|
||||
"display_name": "GitHub"
|
||||
}]
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let (session, turn_context, _rx_event) = make_session_and_context_with_auth_and_config_and_rx(
|
||||
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
|
||||
/*dynamic_tools*/ Vec::new(),
|
||||
|config| {
|
||||
config.chatgpt_base_url = server.uri();
|
||||
config
|
||||
.features
|
||||
.disable(Feature::ToolSuggest)
|
||||
.expect("test config should allow feature update");
|
||||
for enabled_feature in [
|
||||
Feature::Apps,
|
||||
Feature::Plugins,
|
||||
Feature::RemotePlugin,
|
||||
Feature::RecommendedPlugins,
|
||||
] {
|
||||
config
|
||||
.features
|
||||
.enable(enabled_feature)
|
||||
.expect("test config should allow feature update");
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let plugins_manager = &session.services.plugins_manager;
|
||||
let plugins_config = turn_context.config.plugins_config_input();
|
||||
let auth = session.services.auth_manager.auth().await;
|
||||
// Cached plugin loading and auth let initial context reach the shared recommendation lookup
|
||||
// without awaiting unrelated I/O.
|
||||
plugins_manager.plugins_for_config(&plugins_config).await;
|
||||
let prewarm =
|
||||
plugins_manager.recommended_plugins_mode_for_config(&plugins_config, auth.as_ref());
|
||||
tokio::pin!(prewarm);
|
||||
assert!(futures::poll!(prewarm.as_mut()).is_pending());
|
||||
|
||||
// Keep the OnceCell initializer unpolled while first-thread context joins its in-flight fetch.
|
||||
// This does not depend on how quickly the HTTP server returns its response.
|
||||
let world_state = WorldState::default();
|
||||
let step_context = StepContext::for_test(Arc::clone(&turn_context));
|
||||
let initial_context =
|
||||
session.build_initial_context_with_world_state(&step_context, &world_state);
|
||||
tokio::pin!(initial_context);
|
||||
assert!(futures::poll!(initial_context.as_mut()).is_pending());
|
||||
|
||||
let (_, (initial_context, _)) = tokio::join!(prewarm, initial_context);
|
||||
let initial_context =
|
||||
crate::context_manager::updates::merge_world_state_updates(initial_context);
|
||||
assert_eq!(
|
||||
developer_input_texts(&initial_context)
|
||||
.into_iter()
|
||||
.filter(|text| text.starts_with("<recommended_plugins>"))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![concat!(
|
||||
"<recommended_plugins>\n",
|
||||
"Here is a list of plugins that are available but not installed.\n\n",
|
||||
"- GitHub (github@openai-curated-remote)\n",
|
||||
"</recommended_plugins>",
|
||||
)]
|
||||
);
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn build_initial_context_describes_active_realtime_state() {
|
||||
let (session, mut turn_context) = make_session_and_context().await;
|
||||
|
||||
@@ -430,262 +430,6 @@ async fn fixed_thread_text_supersedes_the_live_provider_and_isolated_helpers_rej
|
||||
}
|
||||
}
|
||||
|
||||
#[test_case::test_case(None, "chatgpt.com", 1; "ordinary_openai")]
|
||||
#[test_case::test_case(Some(codex_features::RuntimeAuthMode::DualHeader), "chatgpt.com", 0; "dual_header_openai")]
|
||||
#[test_case::test_case(Some(codex_features::RuntimeAuthMode::AssertionOnly), "chatgpt.com", 0; "assertion_only_openai")]
|
||||
#[test_case::test_case(Some(codex_features::RuntimeAuthMode::DualHeader), "example.test", 1; "dual_header_custom_backend")]
|
||||
#[test_case::test_case(Some(codex_features::RuntimeAuthMode::AssertionOnly), "example.test", 1; "assertion_only_custom_backend")]
|
||||
#[tokio::test]
|
||||
async fn resumed_analytics_validates_openai_destination(
|
||||
mode: Option<codex_features::RuntimeAuthMode>,
|
||||
host: &str,
|
||||
expected_requests: usize,
|
||||
) {
|
||||
let proxy = MockServer::start().await;
|
||||
wiremock::Mock::given(wiremock::matchers::path("/codex/analytics-events/events"))
|
||||
.respond_with(wiremock::ResponseTemplate::new(200))
|
||||
.mount(&proxy)
|
||||
.await;
|
||||
let home = tempdir().expect("tempdir");
|
||||
let mut config = test_config().await;
|
||||
config.codex_home = home.path().abs();
|
||||
config.cwd = home.path().abs();
|
||||
config.chatgpt_base_url = format!("http://{host}:{}", proxy.address().port());
|
||||
config.model_provider.base_url = Some(proxy.uri());
|
||||
config.respect_system_proxy = true;
|
||||
config.cli_auth_credentials_store_mode = codex_login::AuthCredentialsStoreMode::File;
|
||||
config.analytics_enabled = Some(true);
|
||||
if let Some(mode) = mode {
|
||||
config
|
||||
.features
|
||||
.enable(Feature::RuntimeAgentInstances)
|
||||
.unwrap();
|
||||
config.runtime_auth_mode = mode;
|
||||
} else {
|
||||
config
|
||||
.features
|
||||
.disable(Feature::RuntimeAgentInstances)
|
||||
.unwrap();
|
||||
}
|
||||
codex_http_client::cache_system_proxy_route_for_test(
|
||||
&format!("{}/codex/analytics-events/events", config.chatgpt_base_url),
|
||||
proxy.uri(),
|
||||
);
|
||||
codex_login::login_with_api_key(
|
||||
&config.codex_home,
|
||||
"resumed-key",
|
||||
codex_login::AuthCredentialsStoreMode::File,
|
||||
codex_login::AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let resumed_auth =
|
||||
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false)
|
||||
.await
|
||||
.unwrap();
|
||||
let original_auth = CodexAuth::from_api_key("startup-key");
|
||||
let mut manager = ThreadManager::with_models_provider_and_home_for_tests(
|
||||
original_auth.clone(),
|
||||
config.model_provider.clone(),
|
||||
config.codex_home.to_path_buf(),
|
||||
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
|
||||
);
|
||||
let startup_analytics = AnalyticsEventsClient::new(
|
||||
AuthManager::from_auth_for_testing(original_auth),
|
||||
proxy.uri(),
|
||||
/*analytics_enabled*/ Some(true),
|
||||
);
|
||||
Arc::get_mut(&mut manager.state)
|
||||
.expect("unshared thread manager state")
|
||||
.analytics_events_client = Some(startup_analytics);
|
||||
|
||||
let original = manager
|
||||
.start_thread(StartThreadOptions {
|
||||
history_mode: Some(ThreadHistoryMode::Legacy),
|
||||
..StartThreadOptions::new(config.clone())
|
||||
})
|
||||
.await
|
||||
.expect("start original thread");
|
||||
original.thread.ensure_rollout_materialized().await;
|
||||
original.thread.flush_rollout().await.unwrap();
|
||||
original.thread.shutdown_and_wait().await.unwrap();
|
||||
manager.remove_thread(&original.thread_id).await;
|
||||
|
||||
let resumed = manager
|
||||
.resume_thread_with_history(
|
||||
config,
|
||||
InitialHistory::Resumed(ResumedHistory {
|
||||
history_revision: None,
|
||||
conversation_id: original.thread_id,
|
||||
history: Arc::new(Vec::new()),
|
||||
rollout_path: original.thread.rollout_path(),
|
||||
}),
|
||||
resumed_auth,
|
||||
/*parent_trace*/ None,
|
||||
ClientMcpExtensions::default(),
|
||||
)
|
||||
.await
|
||||
.expect("resume with another auth owner");
|
||||
let analytics = &resumed.thread.session.services.analytics_events_client;
|
||||
analytics.track_plugin_used(
|
||||
codex_analytics::TrackEventsContext {
|
||||
turn_metadata: None,
|
||||
model_slug: "test-model".to_string(),
|
||||
turn_id: "test-turn".to_string(),
|
||||
thread_id: resumed.thread_id.to_string(),
|
||||
product_client_id: "codex_work_cca".to_string(),
|
||||
},
|
||||
codex_plugin::PluginTelemetryMetadata {
|
||||
plugin_id: Some(codex_plugin::PluginId::parse("test@local").expect("valid plugin ID")),
|
||||
remote_plugin_id: None,
|
||||
capability_summary: None,
|
||||
},
|
||||
);
|
||||
analytics.flush().await;
|
||||
resumed.thread.shutdown_and_wait().await.unwrap();
|
||||
|
||||
let requests: Vec<_> = proxy
|
||||
.received_requests()
|
||||
.await
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter(|request| request.url.path() == "/codex/analytics-events/events")
|
||||
.collect();
|
||||
assert_eq!(requests.len(), expected_requests);
|
||||
for request in requests {
|
||||
assert_eq!(request.headers["authorization"], "Bearer resumed-key");
|
||||
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread opt-out wins over a shared client without disabling its siblings.
|
||||
#[tokio::test]
|
||||
async fn thread_analytics_opt_out_overrides_shared_client() {
|
||||
let server = MockServer::start().await;
|
||||
wiremock::Mock::given(wiremock::matchers::method("POST"))
|
||||
.and(wiremock::matchers::path("/codex/analytics-events/events"))
|
||||
.respond_with(wiremock::ResponseTemplate::new(200))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let temp_dir = tempdir().expect("tempdir");
|
||||
let mut config = test_config().await;
|
||||
config.chatgpt_base_url = server.uri();
|
||||
config.model_provider.base_url = Some(server.uri());
|
||||
let auth = CodexAuth::create_dummy_chatgpt_auth_for_testing();
|
||||
let shared_client = AnalyticsEventsClient::new(
|
||||
AuthManager::from_auth_for_testing(auth.clone()),
|
||||
server.uri(),
|
||||
/*analytics_enabled*/ Some(true),
|
||||
);
|
||||
let mut expected_thread_ids = Vec::new();
|
||||
let mut opted_out_thread_ids = Vec::new();
|
||||
|
||||
for (name, client_override, expected_enabled) in [
|
||||
(
|
||||
"enabled_override",
|
||||
Some(shared_client.clone()),
|
||||
[false, true, true],
|
||||
),
|
||||
(
|
||||
"disabled_override",
|
||||
Some(AnalyticsEventsClient::disabled()),
|
||||
[false, false, false],
|
||||
),
|
||||
("no_override", None, [false, true, true]),
|
||||
] {
|
||||
config.codex_home = temp_dir.path().join(name).abs();
|
||||
config.cwd = config.codex_home.abs();
|
||||
std::fs::create_dir_all(&config.codex_home).expect("create codex home");
|
||||
let mut manager = ThreadManager::with_models_provider_and_home_for_tests(
|
||||
auth.clone(),
|
||||
config.model_provider.clone(),
|
||||
config.codex_home.to_path_buf(),
|
||||
Arc::new(codex_exec_server::EnvironmentManager::default_for_tests()),
|
||||
);
|
||||
Arc::get_mut(&mut manager.state)
|
||||
.expect("unshared thread manager state")
|
||||
.analytics_events_client = client_override;
|
||||
|
||||
for (setting, enabled) in [Some(false), Some(true), None]
|
||||
.into_iter()
|
||||
.zip(expected_enabled)
|
||||
{
|
||||
config.analytics_enabled = setting;
|
||||
let started = manager
|
||||
.start_thread(StartThreadOptions::new(config.clone()))
|
||||
.await
|
||||
.expect("start analytics test thread");
|
||||
let services = &started.thread.session.services;
|
||||
assert_eq!(started.thread.analytics_enabled(), enabled);
|
||||
assert_eq!(
|
||||
services
|
||||
.session_extension_data
|
||||
.get::<AnalyticsEventsClient>()
|
||||
.expect("analytics client in session store")
|
||||
.is_enabled(),
|
||||
enabled,
|
||||
);
|
||||
let thread_id = started.thread_id.to_string();
|
||||
if enabled {
|
||||
expected_thread_ids.push(thread_id.clone());
|
||||
} else {
|
||||
opted_out_thread_ids.push(thread_id.clone());
|
||||
}
|
||||
services.analytics_events_client.track_app_used(
|
||||
codex_analytics::TrackEventsContext {
|
||||
turn_metadata: None,
|
||||
model_slug: "test-model".to_string(),
|
||||
turn_id: format!("test-turn-{thread_id}"),
|
||||
thread_id,
|
||||
product_client_id: "codex_work_cca".to_string(),
|
||||
},
|
||||
codex_analytics::AppInvocation {
|
||||
connector_id: Some("test-connector".to_string()),
|
||||
app_name: None,
|
||||
invocation_type: None,
|
||||
},
|
||||
/*elicitation_type*/ None,
|
||||
);
|
||||
services.analytics_events_client.flush().await;
|
||||
}
|
||||
let shutdown = manager
|
||||
.shutdown_all_threads_bounded(Duration::from_secs(10))
|
||||
.await;
|
||||
assert_eq!(shutdown.completed.len(), 3);
|
||||
}
|
||||
|
||||
let events: Vec<serde_json::Value> = server
|
||||
.received_requests()
|
||||
.await
|
||||
.expect("analytics requests")
|
||||
.into_iter()
|
||||
.filter(|request| request.url.path() == "/codex/analytics-events/events")
|
||||
.flat_map(|request| {
|
||||
request.body_json::<serde_json::Value>().expect("JSON body")["events"]
|
||||
.as_array()
|
||||
.expect("events array")
|
||||
.clone()
|
||||
})
|
||||
.collect();
|
||||
assert!(events.iter().all(|event| {
|
||||
!opted_out_thread_ids
|
||||
.iter()
|
||||
.any(|thread_id| event["event_params"]["thread_id"] == thread_id.as_str())
|
||||
}));
|
||||
let mut actual_thread_ids: Vec<String> = events
|
||||
.iter()
|
||||
.filter(|event| event["event_type"] == "codex_app_used")
|
||||
.map(|event| {
|
||||
event["event_params"]["thread_id"]
|
||||
.as_str()
|
||||
.expect("app usage thread ID")
|
||||
.to_string()
|
||||
})
|
||||
.collect();
|
||||
actual_thread_ids.sort();
|
||||
expected_thread_ids.sort();
|
||||
assert_eq!(actual_thread_ids, expected_thread_ids);
|
||||
}
|
||||
|
||||
/// Controls without a custom allocation policy still produce distinct thread identifiers.
|
||||
#[test]
|
||||
fn thread_id_generator_defaults_to_standard_ids() {
|
||||
@@ -2196,11 +1940,11 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
|
||||
.expect("thread-scoped MCP resolution should identify its source")
|
||||
.clone(),
|
||||
));
|
||||
let mut server = codex_mcp::codex_apps_mcp_server_config(
|
||||
"https://selected.invalid",
|
||||
/*apps_mcp_product_sku*/ None,
|
||||
/*originator*/ None,
|
||||
);
|
||||
let mut server: codex_config::McpServerConfig =
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"url": "https://selected.invalid/mcp",
|
||||
}))
|
||||
.expect("valid MCP server config");
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } =
|
||||
&selected_root.location;
|
||||
let source_environment_id = environment_id.clone();
|
||||
@@ -2414,20 +2158,10 @@ async fn start_thread_seeds_extension_data_for_mcp_and_lifecycle_contributors()
|
||||
));
|
||||
assert_eq!(Some(server), expected.build().server(name));
|
||||
}
|
||||
let codex_apps_server = codex_mcp::configured_mcp_servers(&first_resolved.config)
|
||||
.remove(codex_mcp::CODEX_APPS_MCP_SERVER_NAME)
|
||||
.expect("Codex Apps server should be configured");
|
||||
let codex_apps_headers = match codex_apps_server.transport {
|
||||
codex_config::McpServerTransportConfig::StreamableHttp { http_headers, .. } => http_headers,
|
||||
codex_config::McpServerTransportConfig::Stdio { .. } => {
|
||||
panic!("Codex Apps server should use streamable HTTP")
|
||||
}
|
||||
};
|
||||
assert_eq!(
|
||||
codex_apps_headers
|
||||
.expect("Codex Apps headers should be configured")
|
||||
.get("originator"),
|
||||
Some(&"codex_work_desktop".to_string())
|
||||
// aKode never contributes the ChatGPT-hosted Codex Apps server.
|
||||
assert!(
|
||||
!codex_mcp::configured_mcp_servers(&first_resolved.config)
|
||||
.contains_key(codex_mcp::CODEX_APPS_MCP_SERVER_NAME)
|
||||
);
|
||||
for (policy, disabled_plugin_ids, selected_enabled, expected_mcp_loads) in [
|
||||
("", vec!["plugin-selected-a".to_string()], false, 1),
|
||||
|
||||
Reference in New Issue
Block a user