WIP fase 2b-3: rimozione sottosistemi solo-ChatGPT (plugin remoti, image gen, daybreak, cyber, attestation, cloud config, app/connettori) - test in corso

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-10 16:07:22 +01:00
parent 231e8cd136
commit 5afc7e9f7f
1223 changed files with 6225 additions and 113722 deletions

View File

@@ -8,9 +8,7 @@ use ctor::ctor;
use std::sync::OnceLock;
use tempfile::TempDir;
use codex_config::CloudConfigBundleLoader;
use codex_config::LoaderOverrides;
use codex_config::test_support::CloudConfigBundleFixture;
use codex_config::test_support::ManagedConfigFixture;
use codex_core::CodexThread;
use codex_core::config::Config;
use codex_core::config::ConfigBuilder;
@@ -24,7 +22,7 @@ use regex_lite::Regex;
use std::path::Path;
use std::path::PathBuf;
pub mod apps_test_server;
pub mod mcp_test_server;
#[cfg(unix)]
pub mod code_mode_host;
pub mod context_snapshot;
@@ -199,31 +197,31 @@ pub fn fetch_dotslash_file(
/// temporary directory. Using a per-test directory keeps tests hermetic and
/// avoids clobbering a developer’s real `~/.codex`.
pub async fn load_default_config_for_test(codex_home: &TempDir) -> Config {
load_default_config_for_test_with_cloud_config_bundle(
codex_home,
CloudConfigBundleLoader::default(),
)
.await
load_default_config_for_test_with_managed_config(codex_home, ManagedConfigFixture::default())
.await
}
/// Returns a default `Config` with test-provided cloud bundle requirements applied.
/// during config construction.
pub async fn load_default_config_for_test_with_cloud_config_bundle(
/// Returns a default `Config` with test-provided local managed requirements and
/// config applied. The fixture is written below `codex_home` and loaded as the
/// system `requirements.toml` / `config.toml`.
pub async fn load_default_config_for_test_with_managed_config(
codex_home: &TempDir,
cloud_config_bundle: CloudConfigBundleLoader,
managed_config: ManagedConfigFixture,
) -> Config {
let loader_overrides = managed_config
.loader_overrides_for_tests(codex_home.path())
.expect("managed config fixture should be writable");
ConfigBuilder::default()
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
.loader_overrides(loader_overrides)
.codex_home(codex_home.path().to_path_buf())
.harness_overrides(default_test_overrides())
.cloud_config_bundle(cloud_config_bundle)
.build()
.await
.expect("defaults for test should always succeed")
}
pub fn managed_network_requirements_loader() -> CloudConfigBundleLoader {
CloudConfigBundleFixture::loader_with_enterprise_requirement(
pub fn managed_network_requirements() -> ManagedConfigFixture {
ManagedConfigFixture::requirements(
r#"
[experimental_network]
enabled = true

View File

@@ -1,14 +1,11 @@
use crate::PathExt;
//! Mock streamable HTTP MCP server for tests that exercise generic MCP behaviour through a
//! user-configured `[mcp_servers.calendar]` registration.
use crate::test_codex::TestCodexBuilder;
use crate::test_codex::test_codex;
use anyhow::Result;
use codex_config::types::AppToolApproval;
use codex_core::config::Config;
use codex_extension_api::ExtensionFuture;
use codex_extension_api::McpServerContribution;
use codex_extension_api::McpServerContributionContext;
use codex_extension_api::McpServerContributor;
use codex_features::Feature;
use codex_login::CodexAuth;
use codex_models_manager::bundled_models_response;
use codex_protocol::config_types::ApprovalsReviewer;
@@ -27,85 +24,58 @@ use wiremock::Request;
use wiremock::Respond;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::path_regex;
const CONNECTOR_ID: &str = "calendar";
pub const LINK_ID: &str = "link_calendar";
const CONNECTOR_NAME: &str = "Calendar";
const DISCOVERABLE_CALENDAR_ID: &str = "connector_2128aebfecb84f64a069897515042a44";
const DISCOVERABLE_GMAIL_ID: &str = "connector_68df038e0ba48191908c8434991bbac2";
const CONNECTOR_DESCRIPTION: &str = "Plan events and manage your calendar.";
const CODEX_APPS_META_KEY: &str = "_codex_apps";
const CODEX_APPS_MCP_PATH_REGEX: &str = "^/(?:api/codex|backend-api)/ps/mcp/?$";
const HOSTED_PLUGIN_RUNTIME_MCP_PATH_REGEX: &str = "^/(?:api/codex|backend-api)/ps/mcp/?$";
/// Name of the user-configured MCP server registration backed by this mock.
pub const MCP_TEST_SERVER_NAME: &str = "calendar";
/// URL path of the mock MCP endpoint.
pub const MCP_TEST_SERVER_PATH: &str = "/mcp";
const MCP_PATH_REGEX: &str = "^/mcp/?$";
const PROTOCOL_VERSION: &str = "2025-11-25";
const SERVER_NAME: &str = "codex-apps-test";
const SERVER_NAME: &str = "calendar-mcp-test";
const SERVER_VERSION: &str = "1.0.0";
const SEARCHABLE_TOOL_COUNT: usize = 100;
const CALENDAR_CREATE_EVENT_TOOL_NAME: &str = "calendar_create_event";
const CALENDAR_APP_ONLY_TOOL_NAME: &str = "calendar_app_only_action";
pub const CALENDAR_CREATE_EVENT_TOOL_NAME: &str = "calendar_create_event";
pub const CALENDAR_APP_ONLY_TOOL_NAME: &str = "calendar_app_only_action";
pub const CALENDAR_EXTRACT_TEXT_TOOL_NAME: &str = "calendar_extract_text";
const CALENDAR_LIST_EVENTS_TOOL_NAME: &str = "calendar_list_events";
pub const DIRECT_CALENDAR_CREATE_EVENT_TOOL: &str = "mcp__codex_apps__calendar__create_event";
pub const DIRECT_CALENDAR_APP_ONLY_TOOL: &str = "mcp__codex_apps__calendar__app_only_action";
pub const DIRECT_CALENDAR_LIST_EVENTS_TOOL: &str = "mcp__codex_apps__calendar__list_events";
pub const DIRECT_CALENDAR_EXTRACT_TEXT_TOOL: &str = "mcp__codex_apps__calendar__extract_text";
pub const SEARCH_CALENDAR_NAMESPACE: &str = "mcp__codex_apps__calendar";
pub const SEARCH_CALENDAR_APP_ONLY_TOOL: &str = "_app_only_action";
pub const SEARCH_CALENDAR_CREATE_TOOL: &str = "_create_event";
pub const SEARCH_CALENDAR_EXTRACT_TEXT_TOOL: &str = "_extract_text";
pub const SEARCH_CALENDAR_LIST_TOOL: &str = "_list_events";
pub const CALENDAR_CREATE_EVENT_RESOURCE_URI: &str =
"connector://calendar/tools/calendar_create_event";
pub const CALENDAR_LIST_EVENTS_TOOL_NAME: &str = "calendar_list_events";
/// Model-visible namespace of the mock server's tools.
pub const CALENDAR_NAMESPACE: &str = "mcp__calendar";
/// Flattened model-visible names (namespace + raw tool name).
pub const DIRECT_CALENDAR_CREATE_EVENT_TOOL: &str = "mcp__calendar__calendar_create_event";
pub const DIRECT_CALENDAR_APP_ONLY_TOOL: &str = "mcp__calendar__calendar_app_only_action";
pub const DIRECT_CALENDAR_LIST_EVENTS_TOOL: &str = "mcp__calendar__calendar_list_events";
pub const DIRECT_CALENDAR_EXTRACT_TEXT_TOOL: &str = "mcp__calendar__calendar_extract_text";
pub const CALENDAR_CREATE_EVENT_MCP_APP_RESOURCE_URI: &str =
"ui://widget/calendar-create-event.html";
const CALENDAR_LIST_EVENTS_RESOURCE_URI: &str = "connector://calendar/tools/calendar_list_events";
pub const DOCUMENT_EXTRACT_TEXT_RESOURCE_URI: &str =
"connector://calendar/tools/calendar_extract_text";
type AppsStartupInitializeGate = Arc<Mutex<VecDeque<mpsc::Receiver<()>>>>;
type McpStartupInitializeGate = Arc<Mutex<VecDeque<mpsc::Receiver<()>>>>;
pub struct HostedMessagingServer(pub String);
#[derive(Clone)]
pub struct McpTestServer {
/// Base URL of the mock server; the MCP endpoint lives at [`MCP_TEST_SERVER_PATH`].
pub base_url: String,
}
impl McpServerContributor<Config> for HostedMessagingServer {
fn id(&self) -> &'static str {
"hosted_user_messaging_fixture"
}
fn contribute<'a>(
&'a self,
_context: McpServerContributionContext<'a, Config>,
) -> ExtensionFuture<'a, Vec<McpServerContribution>> {
Box::pin(async move {
vec![McpServerContribution::HostedApps {
config: Box::new(
serde_json::from_value(json!({
"url": self.0,
"default_tools_approval_mode": "approve",
"supports_parallel_tool_calls": true
}))
.expect("host-owned messaging MCP config"),
),
protocol_mode: None,
}]
})
impl McpTestServer {
/// Full URL of the mock MCP endpoint.
pub fn mcp_url(&self) -> String {
mcp_test_server_url(&self.base_url)
}
}
#[derive(Clone)]
pub struct AppsTestServer {
pub chatgpt_base_url: String,
pub fn mcp_test_server_url(base_url: &str) -> String {
format!("{}{MCP_TEST_SERVER_PATH}", base_url.trim_end_matches('/'))
}
#[derive(Clone)]
pub struct AppsTestServerStartupControl {
pub struct McpTestServerStartupControl {
initialize_attempts: Arc<AtomicUsize>,
remaining_initialize_failures: Arc<AtomicUsize>,
successful_initialize_gate: AppsStartupInitializeGate,
successful_initialize_gate: McpStartupInitializeGate,
}
impl AppsTestServerStartupControl {
impl McpTestServerStartupControl {
pub fn fail_next_initialize_attempts(&self, attempts: usize) {
self.remaining_initialize_failures
.store(attempts, Ordering::SeqCst);
@@ -121,132 +91,86 @@ impl AppsTestServerStartupControl {
let (release, gate) = mpsc::channel();
self.successful_initialize_gate
.lock()
.expect("Apps initialization gate lock should not be poisoned")
.expect("MCP initialization gate lock should not be poisoned")
.push_back(gate);
release
}
}
#[derive(Clone, Copy)]
pub enum AppsTestToolLoading {
pub enum McpTestToolLoading {
Direct,
Searchable,
}
#[derive(Clone)]
enum AppsTestToolsListBehavior {
enum McpTestToolsListBehavior {
AlwaysAvailable,
AvailableWhen(Arc<AtomicBool>),
AlwaysUnavailable,
Custom(Arc<Mutex<Vec<Value>>>),
}
impl AppsTestServer {
impl McpTestServer {
pub async fn mount(server: &MockServer) -> Result<Self> {
Self::mount_with_connector_name(server, CONNECTOR_NAME).await
}
pub async fn mount_searchable(server: &MockServer) -> Result<Self> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
mount_streamable_http_json_rpc(
Self::mount_with(
server,
CONNECTOR_NAME.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
/*searchable*/ true,
/*include_app_only_tool*/ false,
AppsTestToolsListBehavior::AlwaysAvailable,
)
.await;
Ok(Self {
chatgpt_base_url: server.uri(),
})
}
pub async fn mount_hosted_plugin_runtime_searchable(server: &MockServer) -> Result<Self> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
mount_streamable_http_json_rpc_at_path(
server,
HOSTED_PLUGIN_RUNTIME_MCP_PATH_REGEX,
CONNECTOR_NAME.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
/*searchable*/ true,
/*include_app_only_tool*/ false,
AppsTestToolsListBehavior::AlwaysAvailable,
)
.await;
Ok(Self {
chatgpt_base_url: server.uri(),
})
}
pub async fn mount_with_connector_name(
server: &MockServer,
connector_name: &str,
) -> Result<Self> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
mount_streamable_http_json_rpc(
server,
connector_name.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
/*searchable*/ false,
/*include_app_only_tool*/ false,
AppsTestToolsListBehavior::AlwaysAvailable,
McpTestToolsListBehavior::AlwaysAvailable,
)
.await;
Ok(Self {
chatgpt_base_url: server.uri(),
})
.await
}
/// Mounts the server with enough extra tools to push tool loading into search mode.
pub async fn mount_searchable(server: &MockServer) -> Result<Self> {
Self::mount_with(
server,
/*searchable*/ true,
/*include_app_only_tool*/ false,
McpTestToolsListBehavior::AlwaysAvailable,
)
.await
}
pub async fn mount_with_app_only_tool(
server: &MockServer,
tool_loading: AppsTestToolLoading,
tool_loading: McpTestToolLoading,
) -> Result<Self> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
mount_streamable_http_json_rpc(
Self::mount_with(
server,
CONNECTOR_NAME.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
matches!(tool_loading, AppsTestToolLoading::Searchable),
matches!(tool_loading, McpTestToolLoading::Searchable),
/*include_app_only_tool*/ true,
AppsTestToolsListBehavior::AlwaysAvailable,
McpTestToolsListBehavior::AlwaysAvailable,
)
.await;
Ok(Self {
chatgpt_base_url: server.uri(),
})
.await
}
pub async fn mount_with_startup_control(
server: &MockServer,
) -> Result<(Self, AppsTestServerStartupControl)> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
let control = AppsTestServerStartupControl {
) -> Result<(Self, McpTestServerStartupControl)> {
let control = McpTestServerStartupControl {
initialize_attempts: Arc::new(AtomicUsize::new(0)),
remaining_initialize_failures: Arc::new(AtomicUsize::new(0)),
successful_initialize_gate: Arc::new(Mutex::new(VecDeque::new())),
};
mount_streamable_http_json_rpc_with_startup_control(
mount_streamable_http_json_rpc(
server,
CODEX_APPS_MCP_PATH_REGEX,
CONNECTOR_NAME.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
/*searchable*/ true,
/*include_app_only_tool*/ false,
AppsTestToolsListBehavior::AlwaysAvailable,
Some(Arc::clone(&control.initialize_attempts)),
Some(Arc::clone(&control.remaining_initialize_failures)),
Some(Arc::clone(&control.successful_initialize_gate)),
McpJsonRpcResponder {
searchable: true,
include_app_only_tool: false,
tools_list_behavior: McpTestToolsListBehavior::AlwaysAvailable,
initialize_attempts: Some(Arc::clone(&control.initialize_attempts)),
remaining_initialize_failures: Some(Arc::clone(
&control.remaining_initialize_failures,
)),
successful_initialize_gate: Some(Arc::clone(&control.successful_initialize_gate)),
},
)
.await;
Ok((
Self {
chatgpt_base_url: server.uri(),
base_url: server.uri(),
},
control,
))
@@ -256,9 +180,11 @@ impl AppsTestServer {
server: &MockServer,
tools_available: Arc<AtomicBool>,
) -> Result<Self> {
Self::mount_with_tools_list_behavior(
Self::mount_with(
server,
AppsTestToolsListBehavior::AvailableWhen(tools_available),
/*searchable*/ false,
/*include_app_only_tool*/ false,
McpTestToolsListBehavior::AvailableWhen(tools_available),
)
.await
}
@@ -267,31 +193,45 @@ impl AppsTestServer {
server: &MockServer,
tools: Arc<Mutex<Vec<Value>>>,
) -> Result<Self> {
Self::mount_with_tools_list_behavior(server, AppsTestToolsListBehavior::Custom(tools)).await
Self::mount_with(
server,
/*searchable*/ false,
/*include_app_only_tool*/ false,
McpTestToolsListBehavior::Custom(tools),
)
.await
}
pub async fn mount_without_tools(server: &MockServer) -> Result<Self> {
Self::mount_with_tools_list_behavior(server, AppsTestToolsListBehavior::AlwaysUnavailable)
.await
}
async fn mount_with_tools_list_behavior(
server: &MockServer,
tools_list_behavior: AppsTestToolsListBehavior,
) -> Result<Self> {
mount_oauth_metadata(server).await;
mount_connectors_directory(server).await;
mount_streamable_http_json_rpc(
Self::mount_with(
server,
CONNECTOR_NAME.to_string(),
CONNECTOR_DESCRIPTION.to_string(),
/*searchable*/ false,
/*include_app_only_tool*/ false,
tools_list_behavior,
McpTestToolsListBehavior::AlwaysUnavailable,
)
.await
}
async fn mount_with(
server: &MockServer,
searchable: bool,
include_app_only_tool: bool,
tools_list_behavior: McpTestToolsListBehavior,
) -> Result<Self> {
mount_streamable_http_json_rpc(
server,
McpJsonRpcResponder {
searchable,
include_app_only_tool,
tools_list_behavior,
initialize_attempts: None,
remaining_initialize_failures: None,
successful_initialize_gate: None,
},
)
.await;
Ok(Self {
chatgpt_base_url: server.uri(),
base_url: server.uri(),
})
}
}
@@ -308,61 +248,83 @@ pub fn configure_search_capable_model(config: &mut Config) {
config.model_catalog = Some(model_catalog);
}
fn configure_apps(config: &mut Config, apps_base_url: &str) {
config
.features
.enable(Feature::Apps)
.expect("test config should allow feature update");
config.chatgpt_base_url = apps_base_url.to_string();
/// The `[mcp_servers.calendar]` registration pointing at the mock server.
pub fn mcp_test_server_config(base_url: &str) -> codex_config::McpServerConfig {
#[expect(clippy::expect_used, reason = "static test config is valid")]
serde_json::from_value(json!({
"url": mcp_test_server_url(base_url),
"startup_timeout_sec": 30,
}))
.expect("valid mock MCP server config")
}
pub fn configure_search_capable_apps(config: &mut Config, apps_base_url: &str) {
configure_apps(config, apps_base_url);
/// Adds the mock server as the user-configured `calendar` MCP server.
pub fn configure_mcp_test_server(config: &mut Config, base_url: &str) {
let mut servers = config.mcp_servers.get().clone();
servers.insert(
MCP_TEST_SERVER_NAME.to_string(),
mcp_test_server_config(base_url),
);
config
.mcp_servers
.set(servers)
.expect("test config should accept MCP servers");
}
/// Updates the `calendar` registration in place.
pub fn update_mcp_test_server_config(
config: &mut Config,
update: impl FnOnce(&mut codex_config::McpServerConfig),
) {
let mut servers = config.mcp_servers.get().clone();
let server = servers
.get_mut(MCP_TEST_SERVER_NAME)
.expect("calendar MCP server should be configured");
update(server);
config
.mcp_servers
.set(servers)
.expect("test config should accept MCP servers");
}
pub fn configure_search_capable_mcp_test_server(config: &mut Config, base_url: &str) {
configure_mcp_test_server(config, base_url);
configure_search_capable_model(config);
}
pub fn apps_enabled_builder(apps_base_url: impl Into<String>) -> TestCodexBuilder {
let apps_base_url = apps_base_url.into();
pub fn mcp_server_builder(base_url: impl Into<String>) -> TestCodexBuilder {
let base_url = base_url.into();
test_codex()
.with_auth(CodexAuth::from_api_key("Test API Key"))
.with_config(move |config| configure_apps(config, apps_base_url.as_str()))
.with_config(move |config| configure_mcp_test_server(config, base_url.as_str()))
}
pub fn set_default_app_approval_mode_and_reviewer(
/// Sets the default tool approval mode of the `calendar` server and the session reviewer.
pub fn set_mcp_test_server_approval_mode_and_reviewer(
config: &mut Config,
approval_mode: AppToolApproval,
reviewer: ApprovalsReviewer,
) {
let path = config.codex_home.join("config.toml").abs();
let user_config = serde_json::from_value(json!({
"apps": { "_default": {
"approvals_reviewer": reviewer,
"default_tools_approval_mode": approval_mode,
} }
}))
.expect("apps config should parse");
config.config_layer_stack = config
.config_layer_stack
.with_user_config(&path, user_config)
.expect("apps user config should be valid");
update_mcp_test_server_config(config, |server| {
server.default_tools_approval_mode = Some(approval_mode);
});
config.approvals_reviewer = reviewer;
}
pub fn search_capable_apps_builder(apps_base_url: impl Into<String>) -> TestCodexBuilder {
let apps_base_url = apps_base_url.into();
pub fn search_capable_mcp_server_builder(base_url: impl Into<String>) -> TestCodexBuilder {
let base_url = base_url.into();
test_codex()
.with_auth(CodexAuth::from_api_key("Test API Key"))
.with_config(move |config| configure_search_capable_apps(config, apps_base_url.as_str()))
.with_config(move |config| {
configure_search_capable_mcp_test_server(config, base_url.as_str())
})
}
fn apps_tool_call_id(body: &Value) -> Option<&str> {
body.get("params")?
.get("_meta")?
.get(CODEX_APPS_META_KEY)?
.get("call_id")?
.as_str()
fn mcp_tool_call_id(body: &Value) -> Option<&str> {
body.pointer("/params/_meta/callId")?.as_str()
}
pub async fn recorded_apps_tool_calls(server: &MockServer) -> Vec<Value> {
pub async fn recorded_mcp_tool_calls(server: &MockServer) -> Vec<Value> {
server
.received_requests()
.await
@@ -370,32 +332,32 @@ pub async fn recorded_apps_tool_calls(server: &MockServer) -> Vec<Value> {
.into_iter()
.filter_map(|request| {
let body: Value = serde_json::from_slice(&request.body).ok()?;
(request.url.path() == "/api/codex/ps/mcp"
(request.url.path() == MCP_TEST_SERVER_PATH
&& body.get("method").and_then(Value::as_str) == Some("tools/call"))
.then_some(body)
})
.collect()
}
pub async fn recorded_apps_tool_call_by_call_id(server: &MockServer, call_id: &str) -> Value {
let matches = recorded_apps_tool_calls(server)
pub async fn recorded_mcp_tool_call_by_call_id(server: &MockServer, call_id: &str) -> Value {
let matches = recorded_mcp_tool_calls(server)
.await
.into_iter()
.filter(|body| apps_tool_call_id(body) == Some(call_id))
.filter(|body| mcp_tool_call_id(body) == Some(call_id))
.collect::<Vec<_>>();
assert_eq!(
matches.len(),
1,
"expected exactly one apps tools/call request for call_id {call_id}"
"expected exactly one MCP tools/call request for call_id {call_id}"
);
matches
.into_iter()
.next()
.expect("matching apps tools/call request should be recorded")
.expect("matching MCP tools/call request should be recorded")
}
pub async fn recorded_apps_tool_call_by_name(server: &MockServer, tool_name: &str) -> Value {
let matches = recorded_apps_tool_calls(server)
pub async fn recorded_mcp_tool_call_by_name(server: &MockServer, tool_name: &str) -> Value {
let matches = recorded_mcp_tool_calls(server)
.await
.into_iter()
.filter(|body| body.pointer("/params/name").and_then(Value::as_str) == Some(tool_name))
@@ -403,142 +365,32 @@ pub async fn recorded_apps_tool_call_by_name(server: &MockServer, tool_name: &st
assert_eq!(
matches.len(),
1,
"expected exactly one apps tools/call request for tool {tool_name}"
"expected exactly one MCP tools/call request for tool {tool_name}"
);
matches
.into_iter()
.next()
.expect("matching apps tools/call request should be recorded")
.expect("matching MCP tools/call request should be recorded")
}
async fn mount_oauth_metadata(server: &MockServer) {
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"authorization_endpoint": format!("{}/oauth/authorize", server.uri()),
"token_endpoint": format!("{}/oauth/token", server.uri()),
"scopes_supported": [""],
})))
.mount(server)
.await;
}
async fn mount_connectors_directory(server: &MockServer) {
Mock::given(method("GET"))
.and(path("/connectors/directory/list"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"apps": [
{
"id": DISCOVERABLE_CALENDAR_ID,
"name": "Google Calendar",
"description": "Plan events and schedules.",
},
{
"id": DISCOVERABLE_GMAIL_ID,
"name": "Gmail",
"description": "Find and summarize email threads.",
}
],
"nextToken": null
})))
.mount(server)
.await;
Mock::given(method("GET"))
.and(path("/connectors/directory/list_workspace"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"apps": [],
"nextToken": null
})))
.mount(server)
.await;
}
async fn mount_streamable_http_json_rpc(
server: &MockServer,
connector_name: String,
connector_description: String,
searchable: bool,
include_app_only_tool: bool,
tools_list_behavior: AppsTestToolsListBehavior,
) {
mount_streamable_http_json_rpc_at_path(
server,
CODEX_APPS_MCP_PATH_REGEX,
connector_name,
connector_description,
searchable,
include_app_only_tool,
tools_list_behavior,
)
.await;
}
async fn mount_streamable_http_json_rpc_at_path(
server: &MockServer,
mcp_path_regex: &str,
connector_name: String,
connector_description: String,
searchable: bool,
include_app_only_tool: bool,
tools_list_behavior: AppsTestToolsListBehavior,
) {
mount_streamable_http_json_rpc_with_startup_control(
server,
mcp_path_regex,
connector_name,
connector_description,
searchable,
include_app_only_tool,
tools_list_behavior,
/*initialize_attempts*/ None,
/*remaining_initialize_failures*/ None,
/*successful_initialize_gate*/ None,
)
.await;
}
#[allow(clippy::too_many_arguments)]
async fn mount_streamable_http_json_rpc_with_startup_control(
server: &MockServer,
mcp_path_regex: &str,
connector_name: String,
connector_description: String,
searchable: bool,
include_app_only_tool: bool,
tools_list_behavior: AppsTestToolsListBehavior,
initialize_attempts: Option<Arc<AtomicUsize>>,
remaining_initialize_failures: Option<Arc<AtomicUsize>>,
successful_initialize_gate: Option<AppsStartupInitializeGate>,
) {
async fn mount_streamable_http_json_rpc(server: &MockServer, responder: McpJsonRpcResponder) {
Mock::given(method("POST"))
.and(path_regex(mcp_path_regex))
.respond_with(CodexAppsJsonRpcResponder {
connector_name,
connector_description,
searchable,
include_app_only_tool,
tools_list_behavior,
initialize_attempts,
remaining_initialize_failures,
successful_initialize_gate,
})
.and(path_regex(MCP_PATH_REGEX))
.respond_with(responder)
.mount(server)
.await;
}
struct CodexAppsJsonRpcResponder {
connector_name: String,
connector_description: String,
struct McpJsonRpcResponder {
searchable: bool,
include_app_only_tool: bool,
tools_list_behavior: AppsTestToolsListBehavior,
tools_list_behavior: McpTestToolsListBehavior,
initialize_attempts: Option<Arc<AtomicUsize>>,
remaining_initialize_failures: Option<Arc<AtomicUsize>>,
successful_initialize_gate: Option<AppsStartupInitializeGate>,
successful_initialize_gate: Option<McpStartupInitializeGate>,
}
impl Respond for CodexAppsJsonRpcResponder {
impl Respond for McpJsonRpcResponder {
fn respond(&self, request: &Request) -> ResponseTemplate {
let body: Value = match serde_json::from_slice(&request.body) {
Ok(body) => body,
@@ -572,12 +424,12 @@ impl Respond for CodexAppsJsonRpcResponder {
})
{
return ResponseTemplate::new(400).set_body_json(json!({
"error": "simulated non-retryable Apps MCP startup failure",
"error": "simulated non-retryable MCP startup failure",
}));
}
let gate = self.successful_initialize_gate.as_ref().and_then(|gate| {
gate.lock()
.expect("Apps initialization gate lock should not be poisoned")
.expect("MCP initialization gate lock should not be poisoned")
.pop_front()
});
// This responder's dedicated mock server stays paused while the test controls
@@ -586,7 +438,7 @@ impl Respond for CodexAppsJsonRpcResponder {
&& gate.recv().is_err()
{
return ResponseTemplate::new(500).set_body_json(json!({
"error": "Apps initialization gate was dropped before release",
"error": "MCP initialization gate was dropped before release",
}));
}
let id = body.get("id").cloned().unwrap_or(Value::Null);
@@ -614,12 +466,12 @@ impl Respond for CodexAppsJsonRpcResponder {
"notifications/initialized" => ResponseTemplate::new(202),
"tools/list" => {
let tools_available = match &self.tools_list_behavior {
AppsTestToolsListBehavior::AlwaysAvailable
| AppsTestToolsListBehavior::Custom(_) => true,
AppsTestToolsListBehavior::AvailableWhen(tools_available) => {
McpTestToolsListBehavior::AlwaysAvailable
| McpTestToolsListBehavior::Custom(_) => true,
McpTestToolsListBehavior::AvailableWhen(tools_available) => {
tools_available.load(Ordering::SeqCst)
}
AppsTestToolsListBehavior::AlwaysUnavailable => false,
McpTestToolsListBehavior::AlwaysUnavailable => false,
};
let id = body.get("id").cloned().unwrap_or(Value::Null);
let mut response = json!({
@@ -646,16 +498,7 @@ impl Respond for CodexAppsJsonRpcResponder {
"additionalProperties": false
},
"_meta": {
"connector_id": CONNECTOR_ID,
"link_id": LINK_ID,
"connector_name": self.connector_name.clone(),
"connector_description": self.connector_description.clone(),
"openai/outputTemplate": CALENDAR_CREATE_EVENT_MCP_APP_RESOURCE_URI,
"_codex_apps": {
"resource_uri": CALENDAR_CREATE_EVENT_RESOURCE_URI,
"contains_mcp_source": true,
"connector_id": CONNECTOR_ID
}
"openai/outputTemplate": CALENDAR_CREATE_EVENT_MCP_APP_RESOURCE_URI
}
},
{
@@ -673,15 +516,6 @@ impl Respond for CodexAppsJsonRpcResponder {
"additionalProperties": false
},
"_meta": {
"connector_id": CONNECTOR_ID,
"link_id": LINK_ID,
"connector_name": self.connector_name.clone(),
"connector_description": self.connector_description.clone(),
"_codex_apps": {
"resource_uri": CALENDAR_LIST_EVENTS_RESOURCE_URI,
"contains_mcp_source": true,
"connector_id": CONNECTOR_ID
}
}
},
{
@@ -708,27 +542,18 @@ impl Respond for CodexAppsJsonRpcResponder {
"additionalProperties": false
},
"_meta": {
"connector_id": CONNECTOR_ID,
"link_id": LINK_ID,
"connector_name": self.connector_name.clone(),
"connector_description": self.connector_description.clone(),
"openai/fileParams": ["file"],
"_codex_apps": {
"resource_uri": DOCUMENT_EXTRACT_TEXT_RESOURCE_URI,
"contains_mcp_source": true,
"connector_id": CONNECTOR_ID
}
"openai/fileParams": ["file"]
}
}
],
"nextCursor": null
}
});
if let AppsTestToolsListBehavior::Custom(tools) = &self.tools_list_behavior {
if let McpTestToolsListBehavior::Custom(tools) = &self.tools_list_behavior {
response["result"]["tools"] = json!(
tools
.lock()
.expect("Apps test tools lock should not be poisoned")
.expect("MCP test tools lock should not be poisoned")
.clone()
);
}
@@ -759,11 +584,7 @@ impl Respond for CodexAppsJsonRpcResponder {
},
"additionalProperties": false
},
"_meta": {
"connector_id": CONNECTOR_ID,
"connector_name": self.connector_name.clone(),
"connector_description": self.connector_description.clone()
}
"_meta": {}
}));
}
}
@@ -782,9 +603,6 @@ impl Respond for CodexAppsJsonRpcResponder {
"additionalProperties": false
},
"_meta": {
"connector_id": CONNECTOR_ID,
"connector_name": self.connector_name.clone(),
"connector_description": self.connector_description.clone(),
"ui": {
"visibility": ["app"]
}
@@ -811,7 +629,6 @@ impl Respond for CodexAppsJsonRpcResponder {
.pointer("/params/arguments/file/file_id")
.and_then(Value::as_str)
.unwrap_or_default();
let codex_apps_meta = body.pointer("/params/_meta/_codex_apps").cloned();
ResponseTemplate::new(200).set_body_json(json!({
"jsonrpc": "2.0",
@@ -822,7 +639,7 @@ impl Respond for CodexAppsJsonRpcResponder {
"text": format!("called {tool_name} for {title} at {starts_at} with {file_id}")
}],
"structuredContent": {
"_codex_apps": codex_apps_meta,
"called": tool_name,
},
"isError": false
}
@@ -844,15 +661,3 @@ impl Respond for CodexAppsJsonRpcResponder {
}
}
/// Builds an MCP server config that points at this mock apps server. aKode no longer ships a
/// production helper for the ChatGPT-hosted apps server; tests that exercise the generic
/// streamable HTTP and ChatGPT-auth MCP paths use this mock-only config instead.
pub fn mock_apps_mcp_server_config(mock_base_url: &str) -> codex_config::McpServerConfig {
#[expect(clippy::expect_used, reason = "static test config is valid")]
serde_json::from_value(json!({
"url": format!("{}/api/codex/ps/mcp", mock_base_url.trim_end_matches('/')),
"auth": "chatgpt",
"startup_timeout_sec": 30,
}))
.expect("valid mock apps MCP server config")
}

View File

@@ -822,14 +822,12 @@ pub fn ev_response_created(id: &str) -> Value {
})
}
pub fn ev_model_verification_metadata(id: &str, verifications: Vec<&str>) -> Value {
pub fn ev_response_metadata(id: &str, metadata: Value) -> Value {
serde_json::json!({
"type": "response.metadata",
"sequence_number": 1,
"response_id": id,
"metadata": {
"openai_verification_recommendation": verifications,
}
"metadata": metadata,
})
}

View File

@@ -35,12 +35,22 @@ impl StreamingSseServer {
self.requests.lock().await.clone()
}
/// Waits for `count` requests; panics after a generous bound instead of hanging the suite.
pub async fn wait_for_request_count(&self, count: usize) {
loop {
if self.requests.lock().await.len() >= count {
return;
let wait = async {
loop {
if self.requests.lock().await.len() >= count {
return;
}
self.request_notify.notified().await;
}
self.request_notify.notified().await;
};
if tokio::time::timeout(std::time::Duration::from_secs(60), wait)
.await
.is_err()
{
let received = self.requests.lock().await.len();
panic!("timed out waiting for {count} streaming requests; received {received}");
}
}

View File

@@ -17,7 +17,7 @@ use anyhow::Result;
use anyhow::anyhow;
use codex_agent_graph_store::AgentGraphStore;
use codex_attachment_store::AttachmentStore;
use codex_config::CloudConfigBundleLoader;
use codex_config::test_support::ManagedConfigFixture;
use codex_core::CodexThread;
pub use codex_core::StartThreadOptions;
use codex_core::ThreadManager;
@@ -84,7 +84,7 @@ use wiremock::MockServer;
use crate::TempDirExt;
use crate::TestEnvironment;
use crate::load_default_config_for_test;
use crate::load_default_config_for_test_with_cloud_config_bundle;
use crate::load_default_config_for_test_with_managed_config;
use crate::responses::WebSocketTestServer;
use crate::responses::output_value_to_text;
use crate::responses::start_mock_server;
@@ -405,15 +405,20 @@ impl TestAuth {
}
}
/// Host-supplied header auth without credentials, for tests that exercise the merged
/// provider catalog refresh path.
pub fn header_auth_for_testing() -> CodexAuth {
CodexAuth::Headers(codex_login::AuthHeaders::new(Default::default()))
}
pub struct TestCodexBuilder {
apps_tools_cache: codex_core::CodexAppsToolsCache,
config_mutators: Vec<Box<ConfigMutator>>,
thread_manager_configurer: Option<Box<dyn FnOnce(ThreadManager) -> ThreadManager + Send>>,
auth: TestAuth,
pre_build_hooks: Vec<Box<PreBuildHook>>,
workspace_setups: Vec<Box<WorkspaceSetup>>,
home: Option<Arc<TempDir>>,
cloud_config_bundle: Option<CloudConfigBundleLoader>,
managed_config: Option<ManagedConfigFixture>,
user_shell_override: Option<Shell>,
exec_server_url: Option<String>,
extensions: Arc<ExtensionRegistry<Config>>,
@@ -440,8 +445,10 @@ impl TestCodexBuilder {
self
}
pub fn with_apps_tools_cache(mut self, cache: codex_core::CodexAppsToolsCache) -> Self {
self.apps_tools_cache = cache;
/// Authenticate with host-supplied (empty) request headers. Header auth refreshes the
/// provider catalog from the provider base URL and merges it over the bundled catalog.
pub fn with_header_auth(mut self) -> Self {
self.auth = TestAuth::Cached(header_auth_for_testing());
self
}
@@ -565,11 +572,9 @@ impl TestCodexBuilder {
self
}
pub fn with_cloud_config_bundle(
mut self,
cloud_config_bundle: CloudConfigBundleLoader,
) -> Self {
self.cloud_config_bundle = Some(cloud_config_bundle);
/// Loads the fixture as local managed requirements / config (system files).
pub fn with_managed_config(mut self, managed_config: ManagedConfigFixture) -> Self {
self.managed_config = Some(managed_config);
self
}
@@ -905,7 +910,6 @@ impl TestCodexBuilder {
let thread_manager = ThreadManager::new(
&config,
startup,
self.apps_tools_cache.clone(),
SessionSource::Exec,
Arc::clone(&environment_manager),
Arc::new(extensions.build()),
@@ -915,7 +919,6 @@ impl TestCodexBuilder {
self.agent_graph_store.clone().or_else(|| {
codex_core::local_agent_graph_store_from_state_db(state_db.as_ref())
}),
/*attestation_provider*/ None,
/*external_time_provider*/ self.external_time_provider.clone(),
);
let thread_manager = match self.thread_manager_configurer.take() {
@@ -1032,8 +1035,8 @@ impl TestCodexBuilder {
for hook in self.pre_build_hooks.drain(..) {
hook(home.path());
}
let mut config = if let Some(cloud_config_bundle) = self.cloud_config_bundle.take() {
load_default_config_for_test_with_cloud_config_bundle(home, cloud_config_bundle).await
let mut config = if let Some(managed_config) = self.managed_config.take() {
load_default_config_for_test_with_managed_config(home, managed_config).await
} else {
load_default_config_for_test(home).await
};
@@ -1041,18 +1044,7 @@ impl TestCodexBuilder {
// specific model can still override this with a config mutator.
config.model = Some("gpt-5.5".to_string());
config.cwd = cwd_override;
if self.catalog_discovery {
let catalog_url = model_provider
.base_url
.as_deref()
.map(|base_url| format!("{}/models", base_url.trim_end_matches('/')));
config.model_provider = ModelProviderInfo {
model_catalog_url: catalog_url.map(Into::into),
..model_provider
};
} else {
config.model_provider = model_provider;
}
config.model_provider = model_provider;
if let Ok(path) = codex_utils_cargo_bin::cargo_bin("codex") {
config.codex_self_exe = Some(path);
} else if let Ok(path) = codex_utils_cargo_bin::cargo_bin("codex-exec") {
@@ -1076,6 +1068,15 @@ impl TestCodexBuilder {
for mutator in mutators {
mutator(&mut config);
}
// Apply after config mutators so tests that replace the provider still get catalog
// discovery from the provider they selected.
if self.catalog_discovery && config.model_provider.model_catalog_url.is_none() {
config.model_provider.model_catalog_url = config
.model_provider
.base_url
.as_deref()
.map(|base_url| format!("{}/models", base_url.trim_end_matches('/')).into());
}
ensure_test_model_catalog(&mut config)?;
Ok((config, cwd))
@@ -1575,7 +1576,6 @@ fn function_call_output<'a>(bodies: &'a [Value], call_id: &str) -> &'a Value {
pub fn test_codex() -> TestCodexBuilder {
TestCodexBuilder {
apps_tools_cache: Default::default(),
thread_manager_configurer: None,
config_mutators: vec![Box::new(|config| {
config
@@ -1592,7 +1592,7 @@ pub fn test_codex() -> TestCodexBuilder {
pre_build_hooks: vec![],
workspace_setups: vec![],
home: None,
cloud_config_bundle: None,
managed_config: None,
user_shell_override: None,
exec_server_url: None,
extensions: empty_extension_registry(),