aKode fase 2b-1 (WIP): rimossi cloud-config, apps MCP ChatGPT, upload file, connectors-extension, rate limits backend; plugin remoti in corso (test non ancora compilanti)
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:
Andrea
2026-11-09 13:55:36 +01:00
parent 137106bf17
commit e4209e2755
166 changed files with 155 additions and 31558 deletions

View File

@@ -1,641 +0,0 @@
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
use app_test_support::write_chatgpt_auth;
use axum::Json;
use axum::Router;
use axum::extract::State;
use axum::routing::get;
use codex_app_server_protocol::AppsInstalledParams;
use codex_app_server_protocol::AppsInstalledResponse;
use codex_app_server_protocol::AppsListParams;
use codex_app_server_protocol::AppsListResponse;
use codex_app_server_protocol::InstalledApp;
use codex_app_server_protocol::JSONRPCError;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::UserInput;
use codex_config::types::AuthCredentialsStoreMode;
use codex_features::Feature;
use core_test_support::responses;
use pretty_assertions::assert_eq;
use rmcp::handler::server::ServerHandler;
use rmcp::model::CallToolRequestParams;
use rmcp::model::CallToolResult;
use rmcp::model::ContentBlock;
use rmcp::model::ListToolsResult;
use rmcp::model::ServerCapabilities;
use rmcp::model::ServerConfig;
use rmcp::model::Tool;
use rmcp::transport::StreamableHttpServerConfig;
use rmcp::transport::StreamableHttpService;
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
use serde_json::json;
use tempfile::TempDir;
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
use tokio::time::timeout;
use super::app_list::connector_tool;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
#[tokio::test]
async fn installed_apps_force_refresh_only_refreshes_tools_snapshot() -> Result<()> {
let fixture = InstalledAppsFixture::start().await?;
let codex_home = configured_codex_home(fixture.base_url())?;
let mut app_server = start_app_server(codex_home.path()).await?;
let initially_empty = send_installed_request(&mut app_server, /*force_refresh*/ false).await?;
assert_eq!(initially_empty, AppsInstalledResponse { apps: Vec::new() });
assert_eq!(fixture.list_tools_calls(), 0);
let refreshed = send_installed_request(&mut app_server, /*force_refresh*/ true).await?;
assert_eq!(
refreshed.apps,
vec![
InstalledApp {
id: "alpha".to_string(),
runtime_name: Some("Alpha Tool Name".to_string()),
enabled: true,
callable: true,
},
InstalledApp {
id: "blocked".to_string(),
runtime_name: Some("Policy Blocked Tool Name".to_string()),
enabled: true,
callable: false,
},
InstalledApp {
id: "disabled".to_string(),
runtime_name: Some("Locally Disabled Tool Name".to_string()),
enabled: false,
callable: false,
},
]
);
assert_eq!(fixture.list_tools_calls(), 1);
let cached = send_installed_request(&mut app_server, /*force_refresh*/ false).await?;
assert_eq!(cached, refreshed);
assert_eq!(fixture.list_tools_calls(), 1);
fixture.set_tools(Vec::new());
let empty = send_installed_request(&mut app_server, /*force_refresh*/ true).await?;
assert_eq!(empty, AppsInstalledResponse { apps: Vec::new() });
assert_eq!(fixture.list_tools_calls(), 2);
let cached_empty = send_installed_request(&mut app_server, /*force_refresh*/ false).await?;
assert_eq!(cached_empty, empty);
assert_eq!(fixture.list_tools_calls(), 2);
assert_eq!(fixture.directory_calls(), 0);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn installed_apps_threadless_refresh_updates_existing_thread_tools() -> Result<()> {
let fixture = InstalledAppsFixture::start().await?;
fixture.set_tools(vec![connector_tool("alpha", "Alpha")?]);
let responses_server = responses::start_mock_server().await;
let codex_home = configured_codex_home(fixture.base_url())?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123")
.plan_type("sci_plus"),
AuthCredentialsStoreMode::File,
)?;
MockResponsesConfig::new(&responses_server.uri())
.with_root_config(&format!(
"chatgpt_base_url = {:?}\nmcp_oauth_credentials_store = \"file\"",
fixture.base_url(),
))
.enable_feature(Feature::Apps)
.disable_feature(Feature::CodeMode)
.disable_feature(Feature::CodeModeOnly)
.disable_feature(Feature::ToolSearch)
.write(codex_home.path())?;
let mut app_server = start_app_server(codex_home.path()).await?;
let ThreadStartResponse { thread, .. } = app_server
.start_thread(ThreadStartParams::default())
.await?;
for (index, (connector_id, connector_name)) in [("alpha", "Alpha"), ("beta", "Beta")]
.into_iter()
.enumerate()
{
if index > 0 {
fixture.set_tools(vec![connector_tool(connector_id, connector_name)?]);
send_installed_request(&mut app_server, /*force_refresh*/ true).await?;
}
let response_id = format!("response-{connector_id}");
let response = responses::mount_sse_once(
&responses_server,
responses::sse(vec![
responses::ev_response_created(&response_id),
responses::ev_assistant_message("message", "done"),
responses::ev_completed(&response_id),
]),
)
.await;
app_server
.start_turn_and_wait_for_completion(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: "Show the available apps".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let body = response.single_request().body_json();
for candidate in ["alpha", "beta"] {
assert_eq!(
responses::namespace_child_tool(
&body,
&format!("mcp__codex_apps__{candidate}"),
&format!("connector_{candidate}"),
)
.is_some(),
candidate == connector_id,
"the existing thread should expose the refreshed Apps catalog: {body}",
);
}
assert_eq!(fixture.list_tools_calls(), index + 1);
}
let request_id = app_server
.send_apps_list_request(AppsListParams {
limit: None,
cursor: None,
thread_id: None,
force_refetch: true,
})
.await?;
let _: AppsListResponse =
timeout(DEFAULT_TIMEOUT, app_server.read_response(request_id)).await??;
assert_eq!(fixture.directory_calls(), 2);
Ok(())
}
#[tokio::test]
async fn installed_apps_global_disable_retains_tool_derived_identities() -> Result<()> {
let fixture = InstalledAppsFixture::start().await?;
let codex_home = configured_codex_home(fixture.base_url())?;
let committed = {
let mut app_server = start_app_server(codex_home.path()).await?;
send_installed_request(&mut app_server, /*force_refresh*/ true).await?
};
let mut expected_disabled = committed;
for app in &mut expected_disabled.apps {
app.enabled = false;
app.callable = false;
}
let config_path = codex_home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(&config_path, config.replace("apps = true", "apps = false"))?;
let mut app_server = start_app_server(codex_home.path()).await?;
let cached = send_installed_request(&mut app_server, /*force_refresh*/ false).await?;
assert_eq!(cached, expected_disabled);
let force_refresh = send_installed_request(&mut app_server, /*force_refresh*/ true).await?;
assert_eq!(force_refresh, cached);
assert_eq!(fixture.list_tools_calls(), 1);
Ok(())
}
#[tokio::test]
async fn installed_apps_thread_id_uses_effective_thread_config() -> Result<()> {
let fixture = InstalledAppsFixture::start().await?;
let codex_home = configured_codex_home(fixture.base_url())?;
let mut app_server = start_app_server(codex_home.path()).await?;
let mut expected = send_installed_request(&mut app_server, /*force_refresh*/ true).await?;
let request_id = app_server
.send_thread_start_request_with_auto_env(ThreadStartParams {
config: Some(HashMap::from([(
"apps.alpha.enabled".to_string(),
json!(false),
)])),
..Default::default()
})
.await?;
let ThreadStartResponse { thread, .. } =
timeout(DEFAULT_TIMEOUT, app_server.read_response(request_id)).await??;
let alpha = expected
.apps
.iter_mut()
.find(|app| app.id == "alpha")
.expect("alpha app should be installed");
alpha.enabled = false;
alpha.callable = false;
for force_refresh in [false, true] {
let request_id = app_server
.send_apps_installed_request(AppsInstalledParams {
thread_id: Some(thread.id.clone()),
force_refresh,
})
.await?;
let response: AppsInstalledResponse =
timeout(DEFAULT_TIMEOUT, app_server.read_response(request_id)).await??;
assert_eq!(response, expected);
}
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn installed_apps_thread_refresh_updates_live_tools_and_retains_them_on_failure() -> Result<()>
{
let fixture = InstalledAppsFixture::start().await?;
fixture.set_tools(vec![connector_tool("alpha", "Alpha")?]);
let responses_server = responses::start_mock_server().await;
let codex_home = configured_codex_home(fixture.base_url())?;
MockResponsesConfig::new(&responses_server.uri())
.with_root_config(&format!(
"chatgpt_base_url = {:?}\nmcp_oauth_credentials_store = \"file\"",
fixture.base_url()
))
.enable_feature(Feature::Apps)
.write(codex_home.path())?;
let mut app_server = start_app_server(codex_home.path()).await?;
let ThreadStartResponse { thread, .. } = app_server
.start_thread(ThreadStartParams::default())
.await?;
let initial_model_request = responses::mount_sse_once(
&responses_server,
responses::sse(vec![responses::ev_completed("before-refresh")]),
)
.await;
let completed = timeout(
DEFAULT_TIMEOUT,
app_server.start_turn_and_wait_for_completion(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: "Which tools are available?".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
}),
)
.await??;
assert_eq!(completed.turn.status, TurnStatus::Completed);
assert!(
initial_model_request
.single_request()
.tool_by_name("mcp__codex_apps__alpha", "connector_alpha")
.is_some()
);
fixture.set_tools(vec![connector_tool("beta", "Beta")?]);
let expected = AppsInstalledResponse {
apps: vec![InstalledApp {
id: "beta".to_string(),
runtime_name: Some("Beta".to_string()),
enabled: true,
callable: true,
}],
};
for (call_id, refresh_fails) in [("after-refresh", false), ("after-failed-refresh", true)] {
if refresh_fails {
fixture.fail_next_list_tools();
}
let list_tools_calls = fixture.list_tools_calls();
let mut request_id = app_server
.send_apps_installed_request(AppsInstalledParams {
thread_id: Some(thread.id.clone()),
force_refresh: true,
})
.await?;
if refresh_fails {
let error = timeout(
DEFAULT_TIMEOUT,
app_server.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(error.error.code, -32603);
request_id = app_server
.send_apps_installed_request(AppsInstalledParams {
thread_id: Some(thread.id.clone()),
force_refresh: false,
})
.await?;
}
let installed: AppsInstalledResponse =
timeout(DEFAULT_TIMEOUT, app_server.read_response(request_id)).await??;
assert_eq!(installed, expected);
assert_eq!(fixture.list_tools_calls(), list_tools_calls + 1);
let model_requests = responses::mount_sse_sequence(
&responses_server,
vec![
responses::sse(vec![
responses::ev_function_call_with_namespace(
call_id,
"mcp__codex_apps__beta",
"connector_beta",
"{}",
),
responses::ev_completed(call_id),
]),
responses::sse(vec![responses::ev_completed("done")]),
],
)
.await;
let completed = timeout(
DEFAULT_TIMEOUT,
app_server.start_turn_and_wait_for_completion(TurnStartParams {
thread_id: thread.id.clone(),
input: vec![UserInput::Text {
text: "Call Beta.".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
}),
)
.await??;
assert_eq!(completed.turn.status, TurnStatus::Completed);
let requests = model_requests.requests();
assert_eq!(requests.len(), 2);
assert!(
requests[0]
.tool_by_name("mcp__codex_apps__beta", "connector_beta")
.is_some()
);
assert!(
requests[0]
.tool_by_name("mcp__codex_apps__alpha", "connector_alpha")
.is_none()
);
assert_eq!(
requests[1].function_call_output(call_id)["output"][1],
json!({"type": "input_text", "text": "called connector_beta"})
);
assert_eq!(fixture.list_tools_calls(), list_tools_calls + 1);
}
Ok(())
}
#[tokio::test]
async fn installed_apps_failed_force_refresh_retains_previous_snapshot() -> Result<()> {
let fixture = InstalledAppsFixture::start().await?;
let codex_home = configured_codex_home(fixture.base_url())?;
let mut app_server = start_app_server(codex_home.path()).await?;
let committed = send_installed_request(&mut app_server, /*force_refresh*/ true).await?;
fixture.fail_next_list_tools();
let request_id = app_server
.send_apps_installed_request(AppsInstalledParams {
thread_id: None,
force_refresh: true,
})
.await?;
let error: JSONRPCError = timeout(
DEFAULT_TIMEOUT,
app_server.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(error.error.code, -32603);
let retained = send_installed_request(&mut app_server, /*force_refresh*/ false).await?;
assert_eq!(retained, committed);
assert_eq!(fixture.list_tools_calls(), 2);
Ok(())
}
async fn start_app_server(codex_home: &Path) -> Result<TestAppServer> {
TestAppServer::builder()
.with_codex_home(codex_home)
.without_managed_config()
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await
}
async fn send_installed_request(
app_server: &mut TestAppServer,
force_refresh: bool,
) -> Result<AppsInstalledResponse> {
let request_id = app_server
.send_apps_installed_request(AppsInstalledParams {
thread_id: None,
force_refresh,
})
.await?;
timeout(DEFAULT_TIMEOUT, app_server.read_response(request_id)).await?
}
fn configured_codex_home(base_url: &str) -> Result<TempDir> {
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
r#"
chatgpt_base_url = "{base_url}"
mcp_oauth_credentials_store = "file"
[features]
apps = true
[apps.blocked]
default_tools_enabled = false
[apps.disabled]
enabled = false
"#,
),
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123")
.plan_type("team"),
AuthCredentialsStoreMode::File,
)?;
Ok(codex_home)
}
#[derive(Clone)]
struct InstalledAppsMcpServer {
state: Arc<InstalledAppsServerState>,
}
impl ServerHandler for InstalledAppsMcpServer {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
}
async fn call_tool(
&self,
request: CallToolRequestParams,
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
Ok(
CallToolResult::success(vec![ContentBlock::text(format!("called {}", request.name))])
.into(),
)
}
fn list_tools(
&self,
_request: Option<rmcp::model::PaginatedRequestParams>,
_context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
) -> impl std::future::Future<Output = Result<ListToolsResult, rmcp::ErrorData>> + Send + '_
{
let state = Arc::clone(&self.state);
async move {
state.list_tools_calls.fetch_add(1, Ordering::SeqCst);
let should_fail = state.fail_next.swap(false, Ordering::SeqCst);
if should_fail {
return Err(rmcp::ErrorData::internal_error(
"injected tools/list failure",
None,
));
}
Ok(ListToolsResult::with_all_items(
state
.tools
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone(),
))
}
}
}
struct InstalledAppsServerState {
tools: Mutex<Vec<Tool>>,
list_tools_calls: AtomicUsize,
directory_calls: AtomicUsize,
fail_next: AtomicBool,
}
struct InstalledAppsFixture {
base_url: String,
state: Arc<InstalledAppsServerState>,
handle: JoinHandle<()>,
}
impl InstalledAppsFixture {
async fn start() -> Result<Self> {
let mut synthetic_link = connector_tool("link-only", "Link Only")?;
synthetic_link
.meta
.as_mut()
.expect("connector tool should have metadata")
.0
.insert("_codex_apps".to_string(), json!({ "synthetic_link": true }));
let state = Arc::new(InstalledAppsServerState {
tools: Mutex::new(vec![
connector_tool("alpha", "Alpha Tool Name")?,
connector_tool("blocked", "Policy Blocked Tool Name")?,
connector_tool("disabled", "Locally Disabled Tool Name")?,
connector_tool("alpha", "Duplicate Alpha Tool Name")?,
connector_tool("", "Empty Connector ID")?,
Tool::new(
"missing_connector_id",
"Missing connector id",
Arc::new(Default::default()),
),
synthetic_link,
]),
list_tools_calls: AtomicUsize::new(0),
directory_calls: AtomicUsize::new(0),
fail_next: AtomicBool::new(false),
});
let listener = TcpListener::bind("127.0.0.1:0").await?;
let address = listener.local_addr()?;
let mcp_service = StreamableHttpService::new(
{
let state = Arc::clone(&state);
move || {
Ok(InstalledAppsMcpServer {
state: Arc::clone(&state),
})
}
},
Arc::new(LocalSessionManager::default()),
StreamableHttpServerConfig::default(),
);
let router = Router::new()
.route(
"/api/codex/config/bundle",
get(|| async { Json(json!({})) }),
)
.route("/connectors/directory/list", get(list_directory_apps))
.route(
"/connectors/directory/list_workspace",
get(list_directory_apps),
)
.nest_service("/api/codex/ps/mcp", mcp_service)
.with_state(Arc::clone(&state));
let handle = tokio::spawn(async move {
let _ = axum::serve(listener, router).await;
});
Ok(Self {
base_url: format!("http://{address}"),
state,
handle,
})
}
fn base_url(&self) -> &str {
&self.base_url
}
fn list_tools_calls(&self) -> usize {
self.state.list_tools_calls.load(Ordering::SeqCst)
}
fn set_tools(&self, tools: Vec<Tool>) {
*self
.state
.tools
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = tools;
}
fn directory_calls(&self) -> usize {
self.state.directory_calls.load(Ordering::SeqCst)
}
fn fail_next_list_tools(&self) {
self.state.fail_next.store(true, Ordering::SeqCst);
}
}
impl Drop for InstalledAppsFixture {
fn drop(&mut self) {
self.handle.abort();
}
}
async fn list_directory_apps(
State(state): State<Arc<InstalledAppsServerState>>,
) -> Json<serde_json::Value> {
state.directory_calls.fetch_add(1, Ordering::SeqCst);
Json(json!({ "apps": [], "next_token": null }))
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,941 +0,0 @@
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::time::Duration;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::ChatGptIdTokenClaims;
use app_test_support::TestAppServer;
use app_test_support::encode_id_token;
use app_test_support::write_chatgpt_auth;
use axum::Json;
use axum::Router;
use axum::extract::State;
use axum::http::HeaderMap;
use axum::http::StatusCode;
use axum::http::header::AUTHORIZATION;
use axum::routing::any;
use axum::routing::post;
use codex_app_server::chatgpt_connectors as connectors;
use codex_app_server_protocol::AppsReadParams;
use codex_app_server_protocol::AppsReadResponse;
use codex_app_server_protocol::ConnectorMetadata;
use codex_app_server_protocol::JSONRPCError;
use codex_app_server_protocol::LoginAccountResponse;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_config::LoaderOverrides;
use codex_config::types::AuthCredentialsStoreMode;
use codex_core::config::ConfigBuilder;
use codex_http_client::DestinationPolicy;
use codex_http_client::HttpError;
use codex_http_client::NetworkPolicyController;
use codex_http_client::NetworkPolicyDenied;
use codex_login::AuthManager;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
use tokio::time::timeout;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
#[test]
fn app_read_deserializes_legacy_tool_summaries() -> Result<()> {
let response: AppsReadResponse = serde_json::from_value(json!({
"apps": [{
"id": "alpha",
"name": "Alpha",
"description": null,
"iconUrl": null,
"iconUrlDark": null,
"distributionChannel": null,
"installUrl": null,
"pluginDisplayNames": [],
"toolSummaries": [{
"name": "search",
"title": "Search",
"description": "Search Alpha",
}],
}],
"missingAppIds": [],
}))?;
assert_eq!(
serde_json::to_value(response)?,
json!({
"apps": [{
"id": "alpha",
"name": "Alpha",
"description": null,
"iconUrl": null,
"iconUrlDark": null,
"distributionChannel": null,
"installUrl": null,
"pluginDisplayNames": [],
"toolSummaries": [{
"name": "search",
"title": "Search",
"description": "Search Alpha",
"isEnabled": true,
"disabledReason": null,
"isReadOnly": false,
}],
}],
"missingAppIds": [],
})
);
Ok(())
}
#[tokio::test]
async fn connector_requests_preserve_account_policy() -> Result<()> {
let state = BatchServerState::new(json!({ "apps": [] }), "chatgpt-token", "codex");
let (server_url, server_handle) = start_batch_server(state.clone()).await?;
let home = TempDir::new()?;
write_apps_config(home.path(), &server_url, /*apps_mcp_product_sku*/ None)?;
write_auth(home.path())?;
let mut config = ConfigBuilder::default()
.codex_home(home.path().to_path_buf())
.fallback_cwd(Some(home.path().to_path_buf()))
.loader_overrides(LoaderOverrides::without_managed_config_for_tests())
.build()
.await?;
let controller = NetworkPolicyController::default();
let policy = controller.policy();
controller.publish(policy.revision(), DestinationPolicy::Unrestricted);
config.application_network_policy = policy.clone();
let manager =
AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await?;
let (auth, factory) = manager.auth_with_http_client_factory().await.unwrap();
config.application_network_policy = factory.network_policy().clone();
let app_ids = vec!["alpha".to_string()];
connectors::read_connector_metadata(
&config, &auth, /*runtime*/ None, &app_ids, /*include_tools*/ false,
)
.await?;
assert_eq!(state.requests().len(), 1);
policy.invalidate();
controller.publish(policy.revision(), DestinationPolicy::Unrestricted);
let error = timeout(
DEFAULT_TIMEOUT,
connectors::read_connector_metadata(
&config, &auth, /*runtime*/ None, &app_ids, /*include_tools*/ false,
),
)
.await?
.err()
.expect("old credentials must retain their revoked policy");
assert!(matches!(
error.downcast_ref::<HttpError>(),
Some(HttpError::Policy(NetworkPolicyDenied::Revoked))
));
assert_eq!(state.requests().len(), 1);
controller.publish(
policy.revision(),
DestinationPolicy::Restricted {
allowed_hosts: Default::default(),
},
);
let (auth, factory) = manager.auth_with_http_client_factory().await.unwrap();
config.application_network_policy = factory.network_policy().clone();
let error = timeout(
DEFAULT_TIMEOUT,
connectors::list_all_connectors_with_options(
&config,
Some(&auth),
/*runtime*/ None,
/*force_refetch*/ true,
&[],
),
)
.await?
.unwrap_err();
assert!(matches!(
error.downcast_ref::<HttpError>(),
Some(HttpError::Policy(NetworkPolicyDenied::Destination))
));
server_handle.abort();
Ok(())
}
#[tokio::test]
async fn app_read_applies_network_policy_to_cached_client_after_reload() -> Result<()> {
let state = BatchServerState::new(json!({ "apps": [] }), "chatgpt-token", "codex");
let (server_url, server_handle) = start_batch_server(state.clone()).await?;
let home = TempDir::new()?;
write_apps_config(home.path(), &server_url, /*apps_mcp_product_sku*/ None)?;
write_auth(home.path())?;
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.without_auto_env()
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
read_apps(&mut app, vec!["alpha"], /*include_tools*/ false).await?;
assert_eq!(state.requests().len(), 1);
std::fs::write(
home.path().join("requirements.toml"),
"[application.network]",
)?;
let reload_id = app.send_request("config/read", Some(json!({}))).await?;
let _: Value = timeout(DEFAULT_TIMEOUT, app.read_response(reload_id)).await??;
let request_id = app
.send_apps_read_request(AppsReadParams {
app_ids: vec!["alpha".to_string()],
thread_id: None,
include_tools: false,
})
.await?;
let error = timeout(
DEFAULT_TIMEOUT,
app.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(
error.error.message,
"failed to read app metadata: Failed to send request"
);
assert_eq!(state.requests().len(), 1);
server_handle.abort();
Ok(())
}
#[tokio::test]
async fn app_read_deduplicates_orders_partial_misses_and_reuses_cached_metadata() -> Result<()> {
let access_token = encode_id_token(
&ChatGptIdTokenClaims::new()
.email("external@example.com")
.plan_type("plus")
.chatgpt_account_id("account-123"),
)?;
let mut beta_response = app_response(
"beta",
"Beta",
Some("https://files.openai.com/content?id=beta"),
);
let beta_icon_dark_url = beta_response
.as_object_mut()
.expect("app response is an object")
.remove("icon_dark_url")
.expect("app response contains icon_dark_url");
beta_response["icon_url_dark"] = beta_icon_dark_url;
let state = BatchServerState::new(
json!({
"apps": [
app_response("alpha", "Alpha", Some("https://files.openai.com/content?id=alpha")),
beta_response,
]
}),
&access_token,
"tpp",
);
let (server_url, server_handle) = start_batch_server(state.clone()).await?;
let codex_home = TempDir::new()?;
write_apps_config(codex_home.path(), &server_url, Some("tpp"))?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
let login_id = mcp
.send_chatgpt_auth_tokens_login_request(
access_token,
"account-123".to_string(),
Some("plus".to_string()),
)
.await?;
let login_response: LoginAccountResponse =
timeout(DEFAULT_TIMEOUT, mcp.read_response(login_id)).await??;
assert_eq!(login_response, LoginAccountResponse::ChatgptAuthTokens {});
let raw_response = read_apps_raw(
&mut mcp,
vec!["beta", "missing", "alpha", "beta", "forbidden"],
/*include_tools*/ true,
)
.await?;
assert_eq!(
raw_response,
json!({
"apps": [
metadata_json("beta", "Beta", Some("https://files.openai.com/content?id=beta")),
metadata_json("alpha", "Alpha", Some("https://files.openai.com/content?id=alpha")),
],
"missingAppIds": ["missing", "forbidden"],
})
);
let response: AppsReadResponse = serde_json::from_value(raw_response)?;
assert_eq!(
response,
AppsReadResponse {
apps: vec![
metadata(
"beta",
"Beta",
Some("https://files.openai.com/content?id=beta")
),
metadata(
"alpha",
"Alpha",
Some("https://files.openai.com/content?id=alpha")
),
],
missing_app_ids: vec!["missing".to_string(), "forbidden".to_string()],
}
);
assert_eq!(
state.requests(),
vec![json!({
"app_ids": ["beta", "missing", "alpha", "forbidden"],
"include_tools": true,
})]
);
let cached_response =
read_apps(&mut mcp, vec!["alpha", "beta"], /*include_tools*/ true).await?;
assert_eq!(
cached_response,
AppsReadResponse {
apps: vec![
metadata(
"alpha",
"Alpha",
Some("https://files.openai.com/content?id=alpha")
),
metadata(
"beta",
"Beta",
Some("https://files.openai.com/content?id=beta")
),
],
missing_app_ids: Vec::new(),
}
);
assert_eq!(state.requests().len(), 1);
server_handle.abort();
let _ = server_handle.await;
Ok(())
}
#[tokio::test]
async fn app_read_refetches_metadata_only_cache_entries_when_tools_are_requested() -> Result<()> {
let state = BatchServerState::new(
json!({
"apps": [app_response("cached", "Cached", /*icon_url*/ None)]
}),
"chatgpt-token",
"codex",
);
let (server_url, server_handle) = start_batch_server(state.clone()).await?;
let codex_home = TempDir::new()?;
write_apps_config(
codex_home.path(),
&server_url,
/*apps_mcp_product_sku*/ None,
)?;
write_auth(codex_home.path())?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
assert_eq!(
read_apps(&mut mcp, vec!["cached"], /*include_tools*/ false).await?,
AppsReadResponse {
apps: vec![metadata_without_tools(
"cached", "Cached", /*icon_url*/ None
)],
missing_app_ids: Vec::new(),
}
);
assert_eq!(
state.requests(),
vec![json!({
"app_ids": ["cached"],
"include_tools": false,
})]
);
assert_eq!(
read_apps(&mut mcp, vec!["cached"], /*include_tools*/ true).await?,
AppsReadResponse {
apps: vec![metadata("cached", "Cached", /*icon_url*/ None)],
missing_app_ids: Vec::new(),
}
);
assert_eq!(
state.requests(),
vec![
json!({
"app_ids": ["cached"],
"include_tools": false,
}),
json!({
"app_ids": ["cached"],
"include_tools": true,
}),
]
);
assert_eq!(
read_apps(&mut mcp, vec!["cached"], /*include_tools*/ false).await?,
AppsReadResponse {
apps: vec![metadata_without_tools(
"cached", "Cached", /*icon_url*/ None
)],
missing_app_ids: Vec::new(),
}
);
assert_eq!(
read_apps(&mut mcp, vec!["cached"], /*include_tools*/ true).await?,
AppsReadResponse {
apps: vec![metadata("cached", "Cached", /*icon_url*/ None)],
missing_app_ids: Vec::new(),
}
);
assert_eq!(state.requests().len(), 2);
server_handle.abort();
let _ = server_handle.await;
Ok(())
}
#[tokio::test]
async fn app_read_thread_id_uses_effective_thread_config() -> Result<()> {
let state = BatchServerState::new(
json!({
"apps": [app_response("alpha", "Alpha", /*icon_url*/ None)]
}),
"chatgpt-token",
"codex",
);
let (server_url, server_handle) = start_batch_server(state.clone()).await?;
let codex_home = TempDir::new()?;
write_apps_config(
codex_home.path(),
&server_url,
/*apps_mcp_product_sku*/ None,
)?;
write_auth(codex_home.path())?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_managed_config()
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
assert_eq!(
read_apps(&mut mcp, vec!["alpha"], /*include_tools*/ false).await?,
AppsReadResponse {
apps: vec![metadata_without_tools(
"alpha", "Alpha", /*icon_url*/ None
)],
missing_app_ids: Vec::new(),
}
);
let request_id = mcp
.send_thread_start_request_with_auto_env(ThreadStartParams {
config: Some(HashMap::from([(
"features.connectors".to_string(),
json!(false),
)])),
..Default::default()
})
.await?;
let ThreadStartResponse { thread, .. } =
timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??;
let request_id = mcp
.send_apps_read_request(AppsReadParams {
app_ids: vec!["alpha".to_string()],
thread_id: Some(thread.id),
include_tools: false,
})
.await?;
let response: AppsReadResponse =
timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await??;
assert_eq!(
response,
AppsReadResponse {
apps: Vec::new(),
missing_app_ids: vec!["alpha".to_string()],
}
);
assert_eq!(state.requests().len(), 1);
server_handle.abort();
let _ = server_handle.await;
Ok(())
}
#[tokio::test]
async fn app_read_backend_failure_preserves_fresh_cached_records() -> Result<()> {
let state = BatchServerState::new(
json!({
"apps": [app_response("cached", "Cached", /*icon_url*/ None)]
}),
"chatgpt-token",
"codex",
);
let (server_url, server_handle) = start_batch_server(state.clone()).await?;
let codex_home = TempDir::new()?;
write_apps_config(
codex_home.path(),
&server_url,
/*apps_mcp_product_sku*/ None,
)?;
write_auth(codex_home.path())?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.without_managed_config()
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
assert_eq!(
read_apps(&mut mcp, vec!["cached"], /*include_tools*/ true).await?,
AppsReadResponse {
apps: vec![metadata("cached", "Cached", /*icon_url*/ None)],
missing_app_ids: Vec::new(),
}
);
state.set_status(StatusCode::INTERNAL_SERVER_ERROR);
let request_id = mcp
.send_apps_read_request(AppsReadParams {
app_ids: vec!["cached".to_string(), "uncached".to_string()],
thread_id: None,
include_tools: true,
})
.await?;
let error: JSONRPCError = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert!(
error.error.message.contains("failed to read app metadata"),
"unexpected error: {error:?}"
);
assert_eq!(
read_apps(&mut mcp, vec!["cached"], /*include_tools*/ true).await?,
AppsReadResponse {
apps: vec![metadata("cached", "Cached", /*icon_url*/ None)],
missing_app_ids: Vec::new(),
}
);
assert_eq!(state.requests().len(), 2);
server_handle.abort();
let _ = server_handle.await;
Ok(())
}
#[tokio::test]
async fn app_read_adds_plugin_display_names_without_starting_mcp() -> Result<()> {
let state = BatchServerState::new(
json!({
"apps": [
app_response("alpha", "Alpha", /*icon_url*/ None),
app_response("unclaimed", "Unclaimed", /*icon_url*/ None),
]
}),
"chatgpt-token",
"codex",
);
let (server_url, server_handle) = start_batch_server(state.clone()).await?;
let codex_home = TempDir::new()?;
std::fs::write(
codex_home.path().join("config.toml"),
format!(
r#"
chatgpt_base_url = "{server_url}"
[features]
connectors = true
plugins = true
[plugins."alpha-z@test"]
enabled = true
[plugins."alpha-a@test"]
enabled = true
[plugins."disabled@test"]
enabled = false
"#,
),
)?;
write_plugin_app(codex_home.path(), "alpha-z", "Alpha Z", "alpha")?;
write_plugin_app(codex_home.path(), "alpha-a", "Alpha A", "alpha")?;
write_plugin_app(
codex_home.path(),
"disabled",
"Disabled Plugin",
"unclaimed",
)?;
write_auth(codex_home.path())?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
let response = read_apps(
&mut mcp,
vec!["alpha", "unclaimed"],
/*include_tools*/ false,
)
.await?;
let mut alpha = metadata_without_tools("alpha", "Alpha", /*icon_url*/ None);
alpha.plugin_display_names = vec!["Alpha A".to_string(), "Alpha Z".to_string()];
assert_eq!(
response,
AppsReadResponse {
apps: vec![
alpha,
metadata_without_tools("unclaimed", "Unclaimed", /*icon_url*/ None),
],
missing_app_ids: Vec::new(),
}
);
assert_eq!(
state.requests(),
vec![json!({
"app_ids": ["alpha", "unclaimed"],
"include_tools": false,
})]
);
assert_eq!(state.mcp_requests(), 0);
server_handle.abort();
let _ = server_handle.await;
Ok(())
}
#[tokio::test]
async fn app_read_rejects_more_than_one_hundred_input_ids() -> Result<()> {
let codex_home = TempDir::new()?;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
let request_id = mcp
.send_apps_read_request(AppsReadParams {
app_ids: (0..101).map(|index| format!("app-{index}")).collect(),
thread_id: None,
include_tools: false,
})
.await?;
let error: JSONRPCError = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
assert_eq!(error.error.message, "app/read accepts at most 100 appIds");
Ok(())
}
async fn read_apps(
mcp: &mut TestAppServer,
app_ids: Vec<&str>,
include_tools: bool,
) -> Result<AppsReadResponse> {
Ok(serde_json::from_value(
read_apps_raw(mcp, app_ids, include_tools).await?,
)?)
}
async fn read_apps_raw(
mcp: &mut TestAppServer,
app_ids: Vec<&str>,
include_tools: bool,
) -> Result<Value> {
let request_id = mcp
.send_apps_read_request(AppsReadParams {
app_ids: app_ids.into_iter().map(str::to_string).collect(),
thread_id: None,
include_tools,
})
.await?;
timeout(DEFAULT_TIMEOUT, mcp.read_response(request_id)).await?
}
fn metadata(id: &str, name: &str, icon_url: Option<&str>) -> ConnectorMetadata {
serde_json::from_value(metadata_json(id, name, icon_url)).expect("valid app metadata JSON")
}
fn metadata_json(id: &str, name: &str, icon_url: Option<&str>) -> Value {
json!({
"id": id,
"name": name,
"description": format!("{name} description"),
"iconUrl": icon_url,
"iconUrlDark": format!("https://files.openai.com/content?id={id}-dark"),
"distributionChannel": "ECOSYSTEM_DIRECTORY",
"installUrl": format!("https://chatgpt.com/apps/{}/{id}", name.to_ascii_lowercase()),
"pluginDisplayNames": [],
"toolSummaries": [{
"name": format!("{id}_tool"),
"title": format!("{name} Tool"),
"description": format!("Use {name}"),
"isEnabled": false,
"disabledReason": "disabled_by_admin",
"isReadOnly": true,
}],
})
}
fn metadata_without_tools(id: &str, name: &str, icon_url: Option<&str>) -> ConnectorMetadata {
ConnectorMetadata {
tool_summaries: None,
..metadata(id, name, icon_url)
}
}
fn app_response(id: &str, name: &str, icon_url: Option<&str>) -> Value {
let mut response = json!({
"id": id,
"name": name,
"description": format!("{name} description"),
"icon_url": null,
"icon_dark_url": format!("https://files.openai.com/content?id={id}-dark"),
"distribution_channel": "ECOSYSTEM_DIRECTORY",
"tools": [{
"name": format!("{id}_tool"),
"title": format!("{name} Tool"),
"description": format!("Use {name}"),
"is_enabled": false,
"disabled_reason": "disabled_by_admin",
"is_read_only": true,
}],
"branding": {
"category": "PRODUCTIVITY",
"developer": "Test Developer",
"website": "https://example.com",
"privacy_policy": "https://example.com/privacy",
"terms_of_service": "https://example.com/terms",
"is_discoverable_app": true,
},
"app_metadata": {
"review": { "status": "RELEASED" },
"categories": ["PRODUCTIVITY"],
"sub_categories": ["CALENDAR"],
"seo_description": "Search description",
"screenshots": [{
"url": "https://example.com/screenshot.png",
"cdn_url": "must-not-escape",
"file_id": "file-1",
"user_prompt": "Use this app",
}],
"developer": "Test Developer",
"version": "1.0.0",
"version_id": "version-1",
"version_notes": "Initial release",
"first_party_requires_install": true,
"show_in_composer_when_unlinked": true,
"subtitle": "must-not-escape",
"mcp_server_instructions": "must-not-escape",
},
"labels": null,
"actions": [{ "name": "must_not_escape_metadata_boundary" }],
"model_description": "must not escape metadata boundary",
"icon_assets": { "256_square": "must-not-escape" },
});
if let Some(icon_url) = icon_url {
response["icon_url"] = json!(icon_url);
}
response
}
fn write_plugin_app(
codex_home: &Path,
plugin_name: &str,
display_name: &str,
connector_id: &str,
) -> Result<()> {
let plugin_root = codex_home
.join("plugins/cache/test")
.join(plugin_name)
.join("local");
std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?;
std::fs::write(
plugin_root.join(".codex-plugin/plugin.json"),
serde_json::to_vec(&json!({
"name": plugin_name,
"interface": { "displayName": display_name },
}))?,
)?;
std::fs::write(
plugin_root.join(".app.json"),
serde_json::to_vec(&json!({
"apps": { "app": { "id": connector_id } }
}))?,
)?;
Ok(())
}
fn write_apps_config(
codex_home: &Path,
base_url: &str,
apps_mcp_product_sku: Option<&str>,
) -> std::io::Result<()> {
let apps_mcp_product_sku = apps_mcp_product_sku
.map(|product_sku| format!("apps_mcp_product_sku = \"{product_sku}\"\n"))
.unwrap_or_default();
std::fs::write(
codex_home.join("config.toml"),
format!(
r#"
chatgpt_base_url = "{base_url}"
{apps_mcp_product_sku}
[features]
connectors = true
"#
),
)
}
fn write_auth(codex_home: &Path) -> Result<()> {
write_chatgpt_auth(
codex_home,
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123")
.plan_type("plus"),
AuthCredentialsStoreMode::File,
)
}
#[derive(Clone)]
struct BatchServerState {
requests: Arc<StdMutex<Vec<Value>>>,
mcp_requests: Arc<StdMutex<usize>>,
response: Arc<StdMutex<Value>>,
status: Arc<StdMutex<StatusCode>>,
access_token: String,
expected_product_sku: String,
}
impl BatchServerState {
fn new(response: Value, access_token: &str, expected_product_sku: &str) -> Self {
Self {
requests: Arc::new(StdMutex::new(Vec::new())),
mcp_requests: Arc::new(StdMutex::new(0)),
response: Arc::new(StdMutex::new(response)),
status: Arc::new(StdMutex::new(StatusCode::OK)),
access_token: access_token.to_string(),
expected_product_sku: expected_product_sku.to_string(),
}
}
fn requests(&self) -> Vec<Value> {
self.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
fn set_status(&self, status: StatusCode) {
*self
.status
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = status;
}
fn mcp_requests(&self) -> usize {
*self
.mcp_requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
async fn start_batch_server(state: BatchServerState) -> Result<(String, JoinHandle<()>)> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let addr = listener.local_addr()?;
let router = Router::new()
.route("/ps/apps/batch", post(batch_apps))
.route("/api/codex/ps/mcp", any(unexpected_mcp_request))
.with_state(state);
let handle = tokio::spawn(async move {
let _ = axum::serve(listener, router).await;
});
Ok((format!("http://{addr}"), handle))
}
async fn unexpected_mcp_request(State(state): State<BatchServerState>) -> StatusCode {
*state
.mcp_requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) += 1;
StatusCode::INTERNAL_SERVER_ERROR
}
async fn batch_apps(
State(state): State<BatchServerState>,
headers: HeaderMap,
Json(body): Json<Value>,
) -> Result<Json<Value>, StatusCode> {
let bearer_ok = headers
.get(AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value == format!("Bearer {}", state.access_token));
let account_ok = headers
.get("chatgpt-account-id")
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value == "account-123");
// Rejecting a mismatch makes both the configured override and default fallback observable.
let product_sku_ok = headers
.get("oai-product-sku")
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value == state.expected_product_sku);
if !bearer_ok || !account_ok || !product_sku_ok {
return Err(StatusCode::UNAUTHORIZED);
}
let include_tools = body
.get("include_tools")
.and_then(Value::as_bool)
.unwrap_or_default();
state
.requests
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(body);
let status = *state
.status
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if status != StatusCode::OK {
return Err(status);
}
let mut response = state
.response
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
if !include_tools && let Some(apps) = response.get_mut("apps").and_then(Value::as_array_mut) {
for app in apps {
app["tools"] = Value::Null;
}
}
Ok(Json(response))
}

View File

@@ -1,539 +0,0 @@
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use anyhow::Context;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::TestAppServer;
use app_test_support::create_final_assistant_message_sse_response;
use app_test_support::to_response;
use app_test_support::write_chatgpt_auth;
use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url;
use codex_app_server_protocol::LoginAccountResponse;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ThreadHistoryMode;
use codex_app_server_protocol::ThreadResumeParams;
use codex_app_server_protocol::ThreadResumeResponse;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::UserInput;
use codex_config::types::AuthCredentialsStoreMode;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_rollout::RolloutItem;
use core_test_support::responses;
use core_test_support::skip_if_no_network;
use pretty_assertions::assert_eq;
use serde::de::DeserializeOwned;
use serde_json::json;
use tempfile::TempDir;
use test_case::test_case;
use tokio::time::Duration;
use tokio::time::timeout;
use wiremock::Mock;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
// macOS and Windows Bazel CI can spend tens of seconds starting app-server
// subprocesses or processing test RPCs under load.
#[cfg(any(target_os = "macos", windows))]
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(60);
#[cfg(not(any(target_os = "macos", windows)))]
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
const COMMIT_ATTRIBUTION: &str = "Co-authored-by: Codex <noreply@openai.com>";
const PR_ATTRIBUTION: &str = "Generated with [Codex](https://openai.com/codex/).";
const ATTRIBUTION_DISABLED: &str = "attribution is disabled for the current workspace";
const LEGACY_COMMIT_ATTRIBUTION_INSTRUCTIONS: &str = "\
When you write or edit a git commit message, ensure the message ends with this trailer exactly once:
Co-authored-by: Codex <noreply@openai.com>
Rules:
- Keep existing trailers and append this trailer at the end if missing.
- Do not duplicate this trailer if it already exists.
- Keep one blank line between the commit body and trailer block.";
#[derive(Clone, Copy)]
enum LegacyAttribution {
CommitOnly,
UnlinkedPullRequest,
}
#[test_case("dual_header", false; "dual_header")]
#[test_case("assertion_only", false; "assertion_only")]
#[test_case("dual_header", true; "dual_header_custom_destination")]
#[test_case("assertion_only", true; "assertion_only_custom_destination")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn git_attribution_runtime_auth_uses_request_destination(
mode: &str,
custom_destination: bool,
) -> Result<()> {
use base64::Engine;
use core_test_support::runtime_auth::PROBE_SERVER;
use core_test_support::runtime_auth::run_harness_through_proxy;
skip_if_no_network!(Ok(()));
let token = format!(
"e30.{}.c2ln",
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({
"exp": chrono::Utc::now().timestamp() + 3600,
"session_id": "session-a", "iss": "https://auth.openai.com",
"https://api.openai.com/auth": {
"chatgpt_user_id": "user-123", "chatgpt_account_id": "workspace-enabled",
},
}))?)
);
if let Ok(server_url) = std::env::var(PROBE_SERVER) {
let home = TempDir::new()?;
let base_url = if custom_destination {
format!("{server_url}/backend-api")
} else {
"https://chatgpt.com/backend-api".into()
};
write_mock_responses_config_toml_with_chatgpt_base_url(
home.path(),
&server_url,
&base_url,
)?;
let config_path = home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(
config_path,
format!(
"{config}\n[features.runtime_agent_instances]\nenabled = {}\nmode = {mode:?}\n",
!custom_destination
),
)?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new(&token)
.account_id("workspace-enabled")
.chatgpt_user_id("user-123")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.with_env_overrides(&[("OPENAI_API_KEY", None), ("CODEX_ACCESS_TOKEN", None)])
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
.await?;
let id = app
.send_thread_start_request_with_auto_env(ThreadStartParams {
// Extensions retain the harness URL, even when a thread overrides it.
config: Some(HashMap::from([
(
"chatgpt_base_url".into(),
json!("https://chatgpt.com/backend-api"),
),
(
"features.runtime_agent_instances".into(),
json!({"enabled": true, "mode": mode}),
),
])),
..Default::default()
})
.await?;
let ThreadStartResponse { thread, .. } = read_response(&mut app, id).await?;
run_turn(&mut app, &thread.id, "Hello").await?;
return Ok(());
}
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
vec![create_final_assistant_message_sse_response("Done")?],
)
.await;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/agent/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-a", "agent_host_id": "host-a",
"actor": {"kind": "chatgpt", "user_id": "user-123", "account_id": "workspace-enabled"},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/backend-api/wham/settings/user"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"commit_attribution_enabled": true,
})))
.expect(1)
.mount(&server)
.await;
let case = if custom_destination {
format!("{mode}_custom_destination")
} else {
mode.into()
};
run_harness_through_proxy(
&server,
&format!("suite::v2::git_attribution::git_attribution_runtime_auth_uses_request_destination::{case}"),
/*realtime_target*/ None,
)
.await?;
let requests = server
.received_requests()
.await
.context("captured requests")?;
let settings = requests
.iter()
.find(|request| request.url.path() == "/backend-api/wham/settings/user")
.context("git-attribution settings request")?;
let authorization = settings.headers["authorization"].to_str()?;
if custom_destination || mode == "dual_header" {
assert!(authorization.starts_with("Bearer e30."));
} else {
assert!(authorization.starts_with("AgentAssertion 1."));
}
assert_eq!(
settings.headers.contains_key("x-openai-agent-assertion"),
!custom_destination && mode == "dual_header",
);
let model_requests = response_mock.requests();
assert_eq!(model_requests.len(), 1);
assert!(
model_requests[0]
.message_input_texts("developer")
.join("\n")
.contains(COMMIT_ATTRIBUTION)
);
server.verify().await;
Ok(())
}
#[tokio::test]
async fn git_attribution_follows_authenticated_workspace_policy() -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let settings_server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
[
"Unavailable",
"Recovered",
"Cached",
"After switch",
"After switching back",
]
.into_iter()
.map(create_final_assistant_message_sse_response)
.collect::<Result<Vec<_>>>()?,
)
.await;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
.mount(&server)
.await;
let enabled_settings_requests = Arc::new(AtomicUsize::new(0));
Mock::given(method("GET"))
.and(path("/backend-api/wham/settings/user"))
.and(header("chatgpt-account-id", "workspace-enabled"))
.respond_with({
let enabled_settings_requests = enabled_settings_requests.clone();
move |_request: &wiremock::Request| {
if enabled_settings_requests.fetch_add(1, Ordering::SeqCst) == 0 {
ResponseTemplate::new(503)
} else {
ResponseTemplate::new(200).set_body_json(json!({
"commit_attribution_enabled": true,
}))
}
}
})
.expect(3)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/backend-api/wham/settings/user"))
.and(header("chatgpt-account-id", "workspace-disabled"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"commit_attribution_enabled": false,
})))
.expect(1)
.mount(&server)
.await;
let codex_home = TempDir::new()?;
write_mock_responses_config_toml_with_chatgpt_base_url(
codex_home.path(),
&server.uri(),
&format!("{}/backend-api", server.uri()),
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-enabled")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.with_env_overrides(&[("OPENAI_API_KEY", None), ("CODEX_ACCESS_TOKEN", None)])
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??;
let request_id = app_server
.send_thread_start_request_with_auto_env(ThreadStartParams {
config: Some(HashMap::from([(
"chatgpt_base_url".to_string(),
json!(format!("{}/backend-api", settings_server.uri())),
)])),
history_mode: Some(ThreadHistoryMode::Legacy),
..Default::default()
})
.await?;
let ThreadStartResponse { thread, .. } = read_response(&mut app_server, request_id).await?;
run_turn(&mut app_server, &thread.id, "First turn").await?;
run_turn(&mut app_server, &thread.id, "Second turn").await?;
run_turn(&mut app_server, &thread.id, "Third turn").await?;
let request_id = app_server
.send_chatgpt_auth_tokens_login_request(
"e30.e30.c2ln".to_string(),
"workspace-disabled".to_string(),
Some("enterprise".to_string()),
)
.await?;
let _: LoginAccountResponse = read_response(&mut app_server, request_id).await?;
run_turn(&mut app_server, &thread.id, "Turn after workspace switch").await?;
let request_id = app_server
.send_chatgpt_auth_tokens_login_request(
"e30.e30.c2ln".to_string(),
"workspace-enabled".to_string(),
Some("enterprise".to_string()),
)
.await?;
let _: LoginAccountResponse = read_response(&mut app_server, request_id).await?;
run_turn(&mut app_server, &thread.id, "Turn after switching back").await?;
let requests = response_mock.requests();
assert_eq!(requests.len(), 5);
for (request, expected) in requests
.into_iter()
.zip([(0, 0), (1, 0), (1, 0), (1, 1), (2, 1)])
{
let developer_text = request.message_input_texts("developer").join("\n");
assert_eq!(
(
developer_text.matches(COMMIT_ATTRIBUTION).count(),
developer_text.matches(PR_ATTRIBUTION).count(),
developer_text.matches(ATTRIBUTION_DISABLED).count(),
),
(expected.0, expected.0, expected.1)
);
}
server.verify().await;
assert!(
settings_server
.received_requests()
.await
.context("failed to fetch thread-override requests")?
.iter()
.all(|request| request.url.path() != "/backend-api/wham/settings/user"),
"attribution settings must use the process-level base URL"
);
Ok(())
}
#[test_case(LegacyAttribution::CommitOnly; "commit_only")]
#[test_case(LegacyAttribution::UnlinkedPullRequest; "unlinked_pull_request")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cold_resume_replaces_legacy_attribution_without_duplication(
legacy_attribution: LegacyAttribution,
) -> Result<()> {
skip_if_no_network!(Ok(()));
let server = responses::start_mock_server().await;
let response_mock = responses::mount_sse_sequence(
&server,
["Initial", "Resumed", "Resumed again"]
.into_iter()
.map(create_final_assistant_message_sse_response)
.collect::<Result<Vec<_>>>()?,
)
.await;
Mock::given(method("GET"))
.and(path("/backend-api/wham/config/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
.mount(&server)
.await;
let settings_requests = Arc::new(AtomicUsize::new(0));
Mock::given(method("GET"))
.and(path("/backend-api/wham/settings/user"))
.and(header("chatgpt-account-id", "workspace-resume"))
.respond_with({
let settings_requests = Arc::clone(&settings_requests);
move |_request: &wiremock::Request| {
ResponseTemplate::new(200).set_body_json(json!({
"commit_attribution_enabled": settings_requests
.fetch_add(1, Ordering::SeqCst)
== 0,
}))
}
})
.expect(2)
.mount(&server)
.await;
let codex_home = TempDir::new()?;
write_mock_responses_config_toml_with_chatgpt_base_url(
codex_home.path(),
&server.uri(),
&format!("{}/backend-api", server.uri()),
)?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("workspace-resume")
.plan_type("enterprise"),
AuthCredentialsStoreMode::File,
)?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.with_env_overrides(&[("OPENAI_API_KEY", None), ("CODEX_ACCESS_TOKEN", None)])
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??;
let request_id = app_server
.send_thread_start_request(ThreadStartParams::default())
.await?;
let ThreadStartResponse { thread, .. } = read_response(&mut app_server, request_id).await?;
run_turn(&mut app_server, &thread.id, "persist enabled attribution").await?;
let rollout_path = thread
.path
.context("initial thread should have a rollout path")?;
let status = timeout(DEFAULT_READ_TIMEOUT, app_server.shutdown_gracefully()).await??;
anyhow::ensure!(
status.success(),
"initial app-server did not exit successfully"
);
replace_attribution_fragment_with_legacy(&rollout_path, legacy_attribution)?;
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.with_env_overrides(&[("OPENAI_API_KEY", None), ("CODEX_ACCESS_TOKEN", None)])
.without_auto_env()
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??;
let request_id = app_server
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread.id,
..Default::default()
})
.await?;
let ThreadResumeResponse { thread, .. } = read_response(&mut app_server, request_id).await?;
run_turn(&mut app_server, &thread.id, "resume disabled attribution").await?;
run_turn(&mut app_server, &thread.id, "continue disabled attribution").await?;
let requests = response_mock.requests();
assert_eq!(requests.len(), 3);
let initial_text = requests[0].message_input_texts("developer").join("\n");
assert_eq!(initial_text.matches(COMMIT_ATTRIBUTION).count(), 1);
assert_eq!(initial_text.matches(PR_ATTRIBUTION).count(), 1);
assert_eq!(initial_text.matches(ATTRIBUTION_DISABLED).count(), 0);
for request in &requests[1..] {
let developer_text = request.message_input_texts("developer").join("\n");
assert_eq!(developer_text.matches(COMMIT_ATTRIBUTION).count(), 1);
assert_eq!(developer_text.matches(PR_ATTRIBUTION).count(), 0);
assert_eq!(developer_text.matches(ATTRIBUTION_DISABLED).count(), 1);
}
server.verify().await;
Ok(())
}
fn replace_attribution_fragment_with_legacy(
rollout_path: &Path,
legacy_attribution: LegacyAttribution,
) -> Result<()> {
let rollout = std::fs::read_to_string(rollout_path)?;
let mut replaced = false;
let mut removed_saved_attribution = false;
let lines = rollout
.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| {
let mut line = codex_rollout::parse_rollout_line(line)?;
if let RolloutItem::ResponseItem(response_item) = &mut line.item
&& let ResponseItem::Message { role, content, .. } = &mut response_item.item
&& role == "developer"
{
for item in content {
if let ContentItem::InputText { text } = item
&& text.contains("<git_attribution>")
{
*text = match legacy_attribution {
LegacyAttribution::CommitOnly => {
LEGACY_COMMIT_ATTRIBUTION_INSTRUCTIONS.to_string()
}
LegacyAttribution::UnlinkedPullRequest => {
text.replace(PR_ATTRIBUTION, "Generated with Codex.")
}
};
replaced = true;
}
}
}
if let RolloutItem::WorldState(world_state) = &mut line.item
&& world_state.state.remove("git_attribution").is_some()
{
removed_saved_attribution = true;
}
serde_json::to_string(&line)
})
.collect::<std::result::Result<Vec<_>, _>>()?;
anyhow::ensure!(replaced, "rollout did not contain git attribution context");
anyhow::ensure!(
removed_saved_attribution,
"rollout did not contain saved git attribution state"
);
std::fs::write(rollout_path, format!("{}\n", lines.join("\n")))?;
Ok(())
}
async fn read_response<T: DeserializeOwned>(
app_server: &mut TestAppServer,
request_id: i64,
) -> Result<T> {
let response = timeout(
DEFAULT_READ_TIMEOUT,
app_server.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
to_response(response)
}
async fn run_turn(app_server: &mut TestAppServer, thread_id: &str, text: &str) -> Result<()> {
timeout(
DEFAULT_READ_TIMEOUT,
app_server.start_turn_and_wait_for_completion(TurnStartParams {
thread_id: thread_id.to_string(),
input: vec![UserInput::Text {
text: text.to_string(),
text_elements: Vec::new(),
}],
..Default::default()
}),
)
.await??;
Ok(())
}

View File

@@ -6,9 +6,6 @@ mod account_gcp;
mod account_thread_usage;
mod agent_message_board;
mod analytics;
mod app_installed;
mod app_list;
mod app_read;
mod application_network;
#[path = "attached_thread_tests.rs"]
mod attached_thread;
@@ -78,7 +75,6 @@ mod fs;
mod gateway_oauth;
#[path = "gcp_setup_tests.rs"]
mod gcp_setup;
mod git_attribution;
mod guardian_v2;
mod history_notes_extension;
mod hooks_list;
@@ -118,18 +114,11 @@ mod plugin_install;
mod plugin_list;
mod plugin_manifest_cache;
mod plugin_read;
mod plugin_reconcile;
mod plugin_search;
mod plugin_share;
mod plugin_uninstall;
mod process_exec;
mod projects;
mod rate_limit_reset_credits;
mod rate_limits;
#[path = "rate_limits_identity_tests.rs"]
mod rate_limits_identity;
mod realtime_conversation;
mod recommended_plugins;
#[cfg(debug_assertions)]
mod remote_thread_store;
mod request_permissions;

View File

@@ -77,9 +77,6 @@ use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
#[path = "plugin_runtime_auth.rs"]
mod runtime_auth_tests;
// Plugin install tests wait on connector discovery after the install response path
// starts, which is noticeably slower on Windows CI.
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);

View File

@@ -1,332 +0,0 @@
//! Exercises blocking plugin reconciliation through the public JSON-RPC API.
use std::time::Duration;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::MockResponsesConfig;
use app_test_support::TestAppServer;
use app_test_support::write_chatgpt_auth;
use codex_app_server_protocol::PluginReconcileChangedPlugin;
use codex_app_server_protocol::PluginReconcileResponse;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::TurnStatus;
use codex_app_server_protocol::UserInput;
use codex_config::types::AuthCredentialsStoreMode;
use codex_features::Feature;
use core_test_support::responses;
use flate2::Compression;
use flate2::write::GzEncoder;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use tempfile::TempDir;
use test_case::test_case;
use tokio::time::timeout;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
use super::analytics::wait_for_matching_analytics_event;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const REMOTE_PLUGIN_ID: &str = "plugins~Plugin_00000000000000000000000000000000";
#[test_case("WORKSPACE", "workspace-directory"; "workspace")]
#[test_case("GLOBAL", "openai-curated-remote"; "global")]
#[tokio::test]
async fn plugin_reconcile_syncs_bundles_and_reports_changes(
scope: &str,
marketplace: &str,
) -> Result<()> {
let server = MockServer::start().await;
// Both scopes must retain background-sync behavior with remote_plugin disabled.
let (mut app_server, codex_home) = start_app_server(&server).await?;
let thread = app_server.start_thread(Default::default()).await?.thread;
let bundle_url = format!("{}/bundle", server.uri());
let plugin_id = format!("linear@{marketplace}");
let first = PluginReconcileChangedPlugin {
id: plugin_id.clone(),
has_mcps: true,
has_apps: false,
has_hooks: true,
has_skills: true,
};
let second = PluginReconcileChangedPlugin {
id: plugin_id.clone(),
has_mcps: false,
has_apps: true,
has_hooks: false,
has_skills: false,
};
let updated = PluginReconcileChangedPlugin {
id: plugin_id,
has_mcps: true,
has_apps: true,
has_hooks: true,
has_skills: true,
};
let failed_id = "plugins~Plugin_11111111111111111111111111111111";
let mut missing_bundle = installed_plugin("1.0.0", &bundle_url, "WORKSPACE");
missing_bundle["id"] = json!(failed_id);
missing_bundle["name"] = json!("missing-bundle");
missing_bundle["release"]["bundle_download_url"] = Value::Null;
let mut first_pass_failure = Some(missing_bundle);
// v1.1 drops hooks; v2 restores them and drops Apps. Both updates must report
// both sides, while uninstall below reports only v2's remaining capabilities.
// Enablement changes report cached capabilities without downloading the bundle again.
for (version, enabled, capabilities, expected_plugins, expected_downloads) in [
("1.0.0", true, &first, vec![first.clone()], 1),
("1.0.0", true, &first, Vec::new(), 0),
("1.0.0", false, &first, vec![first.clone()], 0),
("1.0.0", true, &first, vec![first.clone()], 0),
("1.1.0", true, &second, vec![updated.clone()], 1),
("2.0.0", true, &first, vec![updated], 1),
] {
let mut files = vec![(
".codex-plugin/plugin.json",
json!({"name": "linear"}).to_string(),
)];
if capabilities.has_mcps {
files.push((
".mcp.json",
json!({"mcpServers": {"example": {"command": "unused", "enabled": false}}})
.to_string(),
));
}
if capabilities.has_apps {
files.push((
".app.json",
json!({"apps": {"example": {"id": "connector_example"}}}).to_string(),
));
}
if capabilities.has_hooks {
files.push((
"hooks/hooks.json",
json!({"hooks": {"UserPromptSubmit": [{"hooks": [{
"type": "command", "command": format!("echo hook {version}")
}]}]}})
.to_string(),
));
}
if capabilities.has_skills {
files.push((
"skills/example/SKILL.md",
"---\nname: example\ndescription: Example skill\n---\nExample skill".to_string(),
));
}
let mut archive = tar::Builder::new(GzEncoder::new(Vec::new(), Compression::default()));
for (path, contents) in files {
let mut header = tar::Header::new_gnu();
header.set_size(contents.len() as u64);
header.set_mode(/*mode*/ 0o644);
header.set_cksum();
archive.append_data(&mut header, path, contents.as_bytes())?;
}
let bundle = archive.into_inner()?.finish()?;
let mut plugin = installed_plugin(version, &bundle_url, scope);
plugin["enabled"] = json!(enabled);
let mut plugins = vec![plugin];
let mut failures = Vec::new();
if let Some(failure) = first_pass_failure.take() {
plugins.push(failure);
failures.push(failed_id.to_string());
}
let expected = PluginReconcileResponse {
changed_plugins: expected_plugins,
failed_remote_plugin_ids: failures.clone(),
failed_materialization_remote_plugin_ids: failures,
};
let active_plugin_ids = if enabled {
vec![REMOTE_PLUGIN_ID.to_string()]
} else {
Vec::new()
};
mount_installed_snapshot(&server, plugins).await;
Mock::given(method("GET"))
.and(path("/bundle"))
.respond_with(ResponseTemplate::new(200).set_body_bytes(bundle))
.expect(expected_downloads)
.mount(&server)
.await;
assert_eq!(reconcile(&mut app_server).await?, expected);
// A turn exercises the loaded registry, not fresh hooks/list discovery. Hooks run
// on the app-server host even when the thread uses a remote executor.
assert_eq!(
turn_hook_runs(
&mut app_server,
&server,
thread.id.clone(),
active_plugin_ids
)
.await?,
usize::from(scope == "WORKSPACE" && enabled && capabilities.has_hooks),
);
server.verify().await;
server.reset().await;
}
// Uninstall must report removed capabilities and stop already-loaded hooks.
mount_installed_snapshot(&server, Vec::new()).await;
assert_eq!(
reconcile(&mut app_server).await?,
PluginReconcileResponse {
changed_plugins: vec![first],
..Default::default()
}
);
assert_eq!(
turn_hook_runs(&mut app_server, &server, thread.id.clone(), Vec::new()).await?,
0
);
server.verify().await;
server.reset().await;
// The next RPC must honor the latest config without contacting the plugin service.
let config_path = codex_home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(
config_path,
config.replace("plugins = true", "plugins = false"),
)?;
assert_eq!(
reconcile(&mut app_server).await?,
PluginReconcileResponse::default()
);
let requests = server.received_requests().await.expect("recorded requests");
assert!(requests.iter().all(|request| {
!request.url.path().starts_with("/backend-api/ps/plugins/")
&& request.url.path() != "/bundle"
}));
Ok(())
}
async fn turn_hook_runs(
app_server: &mut TestAppServer,
server: &MockServer,
thread_id: String,
active_plugin_ids: Vec<String>,
) -> Result<usize> {
Mock::given(method("POST"))
.and(path("/backend-api/codex/analytics-events/events"))
.respond_with(ResponseTemplate::new(200))
.mount(server)
.await;
let _response = responses::mount_sse_once(
server,
responses::sse(vec![
responses::ev_response_created("response"),
responses::ev_completed("response"),
]),
)
.await;
app_server.clear_message_buffer();
let completed = timeout(
DEFAULT_TIMEOUT,
app_server.start_turn_and_wait_for_completion(TurnStartParams {
thread_id: thread_id.clone(),
input: vec![UserInput::Text {
text: "run hooks".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
}),
)
.await??;
assert_eq!(completed.turn.status, TurnStatus::Completed);
let event = wait_for_matching_analytics_event(server, DEFAULT_TIMEOUT, |event| {
event["event_type"] == "codex_turn_event"
&& event["event_params"]["turn_id"] == completed.turn.id
})
.await?;
assert_eq!(event["event_params"]["thread_id"], thread_id);
assert_eq!(
event["event_params"]["active_plugin_ids_at_turn_start"],
json!(active_plugin_ids)
);
Ok(app_server
.pending_notification_methods()
.iter()
.filter(|method| method.as_str() == "hook/started")
.count())
}
async fn reconcile(app_server: &mut TestAppServer) -> Result<PluginReconcileResponse> {
let request = app_server
.send_raw_request(
"plugin/reconcile",
Some(json!({"reason": "tooling_changed"})),
)
.await?;
timeout(DEFAULT_TIMEOUT, app_server.read_response(request)).await?
}
async fn start_app_server(server: &MockServer) -> Result<(TestAppServer, TempDir)> {
let codex_home = TempDir::new()?;
let base_url = format!("{}/backend-api/", server.uri());
MockResponsesConfig::new(&server.uri())
.with_root_config(&format!("chatgpt_base_url = \"{base_url}\""))
.disable_feature(Feature::Apps)
.enable_feature(Feature::Plugins)
.enable_feature(Feature::CodexHooks)
.disable_feature(Feature::RemotePlugin)
.disable_feature(Feature::PluginSharing)
.write(codex_home.path())?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
let app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_managed_config()
.with_env_overrides(&[(
"CODEX_TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS",
Some("1"),
)])
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
Ok((app_server, codex_home))
}
async fn mount_installed_snapshot(server: &MockServer, plugins: Vec<Value>) {
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.and(query_param("includeDownloadUrls", "true"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": plugins,
"pagination": { "limit": 200, "next_page_token": null },
})))
.expect(1)
.mount(server)
.await;
}
fn installed_plugin(version: &str, bundle_url: &str, scope: &str) -> Value {
json!({
"id": REMOTE_PLUGIN_ID,
"name": "linear",
"scope": scope,
"discoverability": (scope == "WORKSPACE").then_some("LISTED"),
"installation_policy": "AVAILABLE",
"authentication_policy": "ON_USE",
"release": {
"version": version,
"display_name": "Linear",
"description": "Track work in Linear",
"bundle_download_url": bundle_url,
"interface": {},
},
"enabled": true,
})
}

View File

@@ -1,194 +0,0 @@
//! Cover direct plugin mutations when runtime authentication is enabled after startup.
use super::*;
use anyhow::Context;
use base64::Engine;
use codex_app_server_protocol::PluginUninstallParams;
use codex_app_server_protocol::PluginUninstallResponse;
use core_test_support::runtime_auth::PROBE_SERVER;
use core_test_support::runtime_auth::run_harness_through_proxy;
use pretty_assertions::assert_eq;
use test_case::test_case;
#[test_case("dual_header", "install"; "install_dual_header")]
#[test_case("assertion_only", "install"; "install_assertion_only")]
#[test_case("dual_header", "uninstall"; "uninstall_dual_header")]
#[test_case("assertion_only", "uninstall"; "uninstall_assertion_only")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn direct_mutation_initializes_runtime_after_config_reload(
mode: &str,
operation: &str,
) -> Result<()> {
core_test_support::skip_if_no_network!(Ok(()));
let token = format!(
"e30.{}.c2ln",
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(
json!({
"exp": 4_102_444_800_u64,
"session_id": "session-a",
"iss": "https://auth.openai.com",
"https://api.openai.com/auth": {
"chatgpt_user_id": "user-123", "chatgpt_account_id": "account-123",
},
})
.to_string()
)
);
if std::env::var(PROBE_SERVER).is_ok() {
let home = TempDir::new()?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new(&token)
.account_id("account-123")
.chatgpt_user_id("user-123")
.chatgpt_account_id("account-123"),
AuthCredentialsStoreMode::File,
)?;
write_remote_plugin_catalog_config(home.path(), "https://chatgpt.com/backend-api")?;
let config_path = home.path().join("config.toml");
let initial = std::fs::read_to_string(&config_path)?;
std::fs::write(
&config_path,
format!(
"{initial}\n[features.runtime_agent_instances]\nenabled = false\nmode = {mode:?}\n"
),
)?;
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.without_auto_env()
.with_env_overrides(&[
("OPENAI_API_KEY", None),
("CODEX_ACCESS_TOKEN", None),
(TEST_ALLOW_HTTP_REMOTE_PLUGIN_BUNDLE_DOWNLOADS, Some("1")),
])
.build_initialized_with_timeout(DEFAULT_TIMEOUT)
.await?;
std::fs::write(
&config_path,
format!(
"{initial}\n[features.runtime_agent_instances]\nenabled = true\nmode = {mode:?}\n"
),
)?;
let cache = home
.path()
.join("plugins/cache/openai-curated-remote/linear");
match operation {
"install" => {
let id = send_remote_plugin_install_request(&mut app, REMOTE_PLUGIN_ID).await?;
let response: PluginInstallResponse =
timeout(DEFAULT_TIMEOUT, app.read_response(id)).await??;
assert_eq!(
response,
PluginInstallResponse {
auth_policy: PluginAuthPolicy::OnUse,
apps_needing_auth: Vec::new(),
}
);
assert!(cache.join("1.2.3/.codex-plugin/plugin.json").is_file());
}
"uninstall" => {
std::fs::create_dir_all(cache.join("1.2.3/.codex-plugin"))?;
std::fs::write(
cache.join("1.2.3/.codex-plugin/plugin.json"),
r#"{"name":"linear","version":"1.2.3"}"#,
)?;
let id = app
.send_plugin_uninstall_request(PluginUninstallParams {
plugin_id: REMOTE_PLUGIN_ID.into(),
})
.await?;
let response: PluginUninstallResponse =
timeout(DEFAULT_TIMEOUT, app.read_response(id)).await??;
assert_eq!(response, PluginUninstallResponse {});
assert!(!cache.exists());
}
_ => unreachable!("test operation"),
}
return Ok(());
}
let server = MockServer::start().await;
let bundle = mount_remote_plugin_bundle(
&server,
/*status_code*/ 200,
remote_plugin_bundle_tar_gz_bytes("linear")?,
)
.await;
Mock::given(method("POST"))
.and(path("/agent/register"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"runtime_agent_instance_id": "runtime-a", "agent_host_id": "host-a",
"actor": {"kind": "chatgpt", "user_id": "user-123", "account_id": "account-123"},
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path(format!("/backend-api/ps/plugins/{REMOTE_PLUGIN_ID}")))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": REMOTE_PLUGIN_ID, "name": "linear", "scope": "GLOBAL",
"installation_policy": "AVAILABLE", "authentication_policy": "ON_USE", "status": "ENABLED",
"release": {
"version": "1.2.3", "bundle_download_url": bundle, "display_name": "Linear",
"description": "Track work in Linear.",
"app_ids": [], "interface": {}, "skills": [],
},
})))
.expect(1)
.mount(&server).await;
Mock::given(method("POST"))
.and(path(format!(
"/backend-api/ps/plugins/{REMOTE_PLUGIN_ID}/{operation}"
)))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"id": REMOTE_PLUGIN_ID, "enabled": operation == "install",
})))
.expect(1)
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/backend-api/ps/plugins/installed"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"plugins": [], "pagination": {"limit": 50, "next_page_token": null},
})))
.mount(&server)
.await;
run_harness_through_proxy(
&server,
&format!("suite::v2::plugin_install::runtime_auth_tests::direct_mutation_initializes_runtime_after_config_reload::{operation}_{mode}"),
/*realtime_target*/ None,
).await?;
let requests = server
.received_requests()
.await
.context("recorded requests")?;
let plugin_requests = requests
.iter()
.filter(|request| {
request
.url
.path()
.starts_with(&format!("/backend-api/ps/plugins/{REMOTE_PLUGIN_ID}"))
})
.collect::<Vec<_>>();
assert_eq!(plugin_requests.len(), 2);
for request in plugin_requests {
let proof = if mode == "dual_header" {
assert_eq!(request.headers["authorization"], format!("Bearer {token}"));
request.headers["x-openai-agent-assertion"].to_str()?
} else {
assert!(!request.headers.contains_key("x-openai-agent-assertion"));
request.headers["authorization"]
.to_str()?
.strip_prefix("AgentAssertion ")
.context("assertion auth")?
};
let claims: serde_json::Value = serde_json::from_slice(
&base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(proof.split('.').nth(2).context("assertion payload")?)?,
)?;
assert_eq!(claims["runtime_agent_instance"], "runtime-a");
}
server.verify().await;
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,354 +0,0 @@
use std::path::Path;
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::TestAppServer;
use app_test_support::write_chatgpt_auth;
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditOutcome;
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditParams;
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse;
use codex_app_server_protocol::GetAccountParams;
use codex_app_server_protocol::JSONRPCError;
use codex_app_server_protocol::LoginAccountResponse;
use codex_app_server_protocol::RequestId;
use codex_config::types::AuthCredentialsStoreMode;
use pretty_assertions::assert_eq;
use serde_json::json;
use tempfile::TempDir;
use tokio::time::timeout;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::body_json;
use wiremock::matchers::header;
use wiremock::matchers::method;
use wiremock::matchers::path;
const DEFAULT_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(/*secs*/ 10);
const RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR: &str =
"CODEX_TEST_RATE_LIMIT_RESET_REQUEST_TIMEOUT_MS";
const SERVER_TIMEOUT_READ_TIMEOUT: std::time::Duration =
std::time::Duration::from_secs(/*secs*/ 15);
const INVALID_REQUEST_ERROR_CODE: i64 = -32600;
const INTERNAL_ERROR_CODE: i64 = -32603;
#[tokio::test]
async fn consume_rate_limit_reset_credit_requires_chatgpt_auth() -> Result<()> {
let codex_home = TempDir::new()?;
let mut mcp = initialized_app_server(codex_home.path()).await?;
let consume_id = mcp
.send_consume_account_rate_limit_reset_credit_request(
ConsumeAccountRateLimitResetCreditParams {
idempotency_key: "request-1".to_string(),
credit_id: None,
},
)
.await?;
let consume_error = read_error_response(&mut mcp, consume_id).await?;
assert_eq!(consume_error.error.code, INVALID_REQUEST_ERROR_CODE);
assert_eq!(
consume_error.error.message,
"codex account authentication required for rate limit reset credits"
);
login_with_api_key(&mut mcp, "sk-test-key").await?;
let consume_id = send_consume_reset_credit(&mut mcp, "request-2").await?;
let consume_error = read_error_response(&mut mcp, consume_id).await?;
assert_eq!(consume_error.error.code, INVALID_REQUEST_ERROR_CODE);
assert_eq!(
consume_error.error.message,
"chatgpt authentication required for rate limit reset credits"
);
Ok(())
}
#[tokio::test]
async fn consume_account_rate_limit_reset_credit_maps_backend_outcomes() -> Result<()> {
let (codex_home, server) = chatgpt_test_context().await?;
let cases = [
(
"request-reset",
"reset",
ConsumeAccountRateLimitResetCreditOutcome::Reset,
2,
),
(
"request-nothing",
"nothing_to_reset",
ConsumeAccountRateLimitResetCreditOutcome::NothingToReset,
0,
),
(
"request-no-credit",
"no_credit",
ConsumeAccountRateLimitResetCreditOutcome::NoCredit,
0,
),
(
"request-retry",
"already_redeemed",
ConsumeAccountRateLimitResetCreditOutcome::AlreadyRedeemed,
0,
),
];
for (idempotency_key, backend_code, _, windows_reset) in cases {
Mock::given(method("POST"))
.and(path("/api/codex/rate-limit-reset-credits/consume"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.and(body_json(json!({ "redeem_request_id": idempotency_key })))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"code": backend_code,
"windows_reset": windows_reset
})))
.mount(&server)
.await;
}
let mut mcp = initialized_app_server(codex_home.path()).await?;
for (idempotency_key, _, expected_outcome, _) in cases {
assert_eq!(
consume_reset_credit(&mut mcp, idempotency_key).await?,
ConsumeAccountRateLimitResetCreditResponse {
outcome: expected_outcome,
}
);
}
Ok(())
}
#[tokio::test]
async fn consume_account_rate_limit_reset_credit_forwards_selected_credit_id() -> Result<()> {
let (codex_home, server) = chatgpt_test_context().await?;
Mock::given(method("POST"))
.and(path("/api/codex/rate-limit-reset-credits/consume"))
.and(header("authorization", "Bearer chatgpt-token"))
.and(header("chatgpt-account-id", "account-123"))
.and(body_json(json!({
"redeem_request_id": "request-selected",
"credit_id": "credit-123",
})))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(json!({ "code": "reset", "windows_reset": 2 })),
)
.expect(1)
.mount(&server)
.await;
let mut mcp = initialized_app_server(codex_home.path()).await?;
let request_id = mcp
.send_consume_account_rate_limit_reset_credit_request(
ConsumeAccountRateLimitResetCreditParams {
idempotency_key: "request-selected".to_string(),
credit_id: Some("credit-123".to_string()),
},
)
.await?;
assert_eq!(
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_response::<ConsumeAccountRateLimitResetCreditResponse>(request_id),
)
.await??,
ConsumeAccountRateLimitResetCreditResponse {
outcome: ConsumeAccountRateLimitResetCreditOutcome::Reset,
}
);
Ok(())
}
#[tokio::test]
async fn consume_account_rate_limit_reset_credit_rejects_empty_idempotency_key() -> Result<()> {
let (codex_home, _server) = chatgpt_test_context().await?;
let mut mcp = initialized_app_server(codex_home.path()).await?;
let request_id = mcp
.send_consume_account_rate_limit_reset_credit_request(
ConsumeAccountRateLimitResetCreditParams {
idempotency_key: String::new(),
credit_id: None,
},
)
.await?;
let error = read_error_response(&mut mcp, request_id).await?;
assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE);
assert_eq!(error.error.message, "idempotencyKey must not be empty");
Ok(())
}
#[tokio::test]
async fn consume_account_rate_limit_reset_credit_rejects_empty_credit_id() -> Result<()> {
let (codex_home, _server) = chatgpt_test_context().await?;
let mut mcp = initialized_app_server(codex_home.path()).await?;
let request_id = mcp
.send_consume_account_rate_limit_reset_credit_request(
ConsumeAccountRateLimitResetCreditParams {
idempotency_key: "request-1".to_string(),
credit_id: Some(String::new()),
},
)
.await?;
let error = read_error_response(&mut mcp, request_id).await?;
assert_eq!(error.error.code, INVALID_REQUEST_ERROR_CODE);
assert_eq!(error.error.message, "creditId must not be empty");
Ok(())
}
#[tokio::test]
async fn consume_account_rate_limit_reset_credit_surfaces_backend_failure() -> Result<()> {
let (codex_home, server) = chatgpt_test_context().await?;
Mock::given(method("POST"))
.and(path("/api/codex/rate-limit-reset-credits/consume"))
.respond_with(ResponseTemplate::new(500).set_body_string("boom"))
.mount(&server)
.await;
let mut mcp = initialized_app_server(codex_home.path()).await?;
let request_id = send_consume_reset_credit(&mut mcp, "request-1").await?;
let error = read_error_response(&mut mcp, request_id).await?;
assert_eq!(error.error.code, INTERNAL_ERROR_CODE);
assert!(
error
.error
.message
.contains("failed to consume rate limit reset"),
"unexpected error message: {}",
error.error.message
);
Ok(())
}
#[tokio::test]
async fn consume_timeout_releases_account_auth_queue() -> Result<()> {
let (codex_home, server) = chatgpt_test_context().await?;
Mock::given(method("GET"))
.and(path("/api/codex/accounts/check"))
.respond_with(
ResponseTemplate::new(200).set_body_json(json!({"accounts": [{
"id": "account-123", "workspace_backend_origin": "https://chatgpt.com",
"account_routing_override": "NO_CONSTRAINT"
}]})),
)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/api/codex/rate-limit-reset-credits/consume"))
.respond_with(
ResponseTemplate::new(200)
.set_delay(std::time::Duration::from_secs(/*secs*/ 1))
.set_body_json(json!({ "code": "reset", "windows_reset": 2 })),
)
.mount(&server)
.await;
let mut mcp = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_auto_env()
.with_env_overrides(&[
("OPENAI_API_KEY", None),
(RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR, Some("100")),
])
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
.await?;
let consume_id = send_consume_reset_credit(&mut mcp, "request-timeout").await?;
let account_id = mcp
.send_get_account_request(GetAccountParams {
refresh_token: false,
})
.await?;
let consume_error: JSONRPCError = timeout(
SERVER_TIMEOUT_READ_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(consume_id)),
)
.await??;
assert_eq!(consume_error.error.code, INTERNAL_ERROR_CODE);
assert_eq!(
consume_error.error.message,
"rate limit reset consume timed out"
);
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(account_id)),
)
.await??;
Ok(())
}
async fn chatgpt_test_context() -> Result<(TempDir, MockServer)> {
let codex_home = TempDir::new()?;
write_chatgpt_auth(
codex_home.path(),
ChatGptAuthFixture::new("chatgpt-token")
.account_id("account-123")
.plan_type("pro"),
AuthCredentialsStoreMode::File,
)?;
let server = MockServer::start().await;
write_chatgpt_base_url(codex_home.path(), &server.uri())?;
Ok((codex_home, server))
}
async fn initialized_app_server(codex_home: &Path) -> Result<TestAppServer> {
TestAppServer::builder()
.with_codex_home(codex_home)
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build_initialized_with_timeout(DEFAULT_READ_TIMEOUT)
.await
}
async fn consume_reset_credit(
mcp: &mut TestAppServer,
idempotency_key: &str,
) -> Result<ConsumeAccountRateLimitResetCreditResponse> {
let request_id = send_consume_reset_credit(mcp, idempotency_key).await?;
timeout(DEFAULT_READ_TIMEOUT, mcp.read_response(request_id)).await?
}
async fn send_consume_reset_credit(mcp: &mut TestAppServer, idempotency_key: &str) -> Result<i64> {
mcp.send_consume_account_rate_limit_reset_credit_request(
ConsumeAccountRateLimitResetCreditParams {
idempotency_key: idempotency_key.to_string(),
credit_id: None,
},
)
.await
}
async fn read_error_response(mcp: &mut TestAppServer, request_id: i64) -> Result<JSONRPCError> {
let error = timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_stream_until_error_message(RequestId::Integer(request_id)),
)
.await??;
Ok(error)
}
async fn login_with_api_key(mcp: &mut TestAppServer, api_key: &str) -> Result<()> {
let request_id = mcp.send_login_account_api_key_request(api_key).await?;
assert_eq!(
timeout(
DEFAULT_READ_TIMEOUT,
mcp.read_response::<LoginAccountResponse>(request_id),
)
.await??,
LoginAccountResponse::ApiKey {}
);
Ok(())
}
fn write_chatgpt_base_url(codex_home: &Path, base_url: &str) -> std::io::Result<()> {
std::fs::write(
codex_home.join("config.toml"),
format!("chatgpt_base_url = \"{base_url}\"\n"),
)
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,236 +0,0 @@
//! Account readiness is verified after an in-flight backend read, including concurrent login.
use anyhow::Result;
use app_test_support::ChatGptAuthFixture;
use app_test_support::ChatGptIdTokenClaims;
use app_test_support::TestAppServer;
use app_test_support::encode_id_token;
use app_test_support::write_chatgpt_auth;
use axum::Json;
use axum::Router;
use axum::http::HeaderMap;
use axum::routing::get;
use codex_app_server_protocol::GetAccountRateLimitsResponse;
use codex_app_server_protocol::LoginAccountResponse;
use codex_app_server_protocol::RequestId;
use codex_config::types::AuthCredentialsStoreMode;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
use std::time::Duration;
use tempfile::TempDir;
use test_case::test_case;
use tokio::net::TcpListener;
use tokio::sync::Notify;
use tokio::time::timeout;
const READ_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
#[test_case("workspace-a", "user-b", /*verified*/ false; "user_switch")]
#[test_case("workspace-b", "user-a", /*verified*/ false; "workspace_switch")]
#[test_case("workspace-a", "user-a", /*verified*/ true; "same_identity_token_refresh")]
#[tokio::test]
async fn identity_is_rechecked_after_backend_response(
account: &str,
user: &str,
verified: bool,
) -> Result<()> {
let old_token = encode_id_token(
&ChatGptIdTokenClaims::new()
.chatgpt_account_id("workspace-a")
.chatgpt_user_id("user-a"),
)?;
let home = TempDir::new()?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new(&old_token)
.account_id("workspace-a")
.chatgpt_user_id("user-a")
.plan_type("team"),
AuthCredentialsStoreMode::File,
)?;
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let request_entered = Arc::clone(&entered);
let response_release = Arc::clone(&release);
let listener = TcpListener::bind("127.0.0.1:0").await?;
std::fs::write(
home.path().join("config.toml"),
format!("chatgpt_base_url = \"http://{}\"\n", listener.local_addr()?),
)?;
let expected_authorization = format!("Bearer {old_token}");
let router = Router::new().route(
"/api/codex/usage",
get(move |headers: HeaderMap| {
let expected_authorization = expected_authorization.clone();
let entered = Arc::clone(&request_entered);
let release = Arc::clone(&response_release);
async move {
assert_eq!(headers["authorization"], expected_authorization);
assert_eq!(headers["chatgpt-account-id"], "workspace-a");
entered.notify_one();
release.notified().await;
Json(json!({
"account_id": "workspace-a", "user_id": "user-a", "plan_type": "team",
"rate_limit": {"allowed": true, "limit_reached": false,
"primary_window": {"used_percent": 42, "limit_window_seconds": 3600,
"reset_after_seconds": 120, "reset_at": 2000000000}}
}))
}
}),
);
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build_initialized_with_timeout(READ_TIMEOUT)
.await?;
let initial_login = app
.send_chatgpt_auth_tokens_login_request(
old_token,
"workspace-a".into(),
Some("team".into()),
)
.await?;
let _: LoginAccountResponse = app.read_response(initial_login).await?;
let request = app
.send_request(
"account/rateLimits/read",
Some(json!({"excludeResetCreditDetails": true})),
)
.await?;
timeout(READ_TIMEOUT, entered.notified()).await?;
let token = encode_id_token(
&ChatGptIdTokenClaims::new()
.chatgpt_account_id(account)
.chatgpt_user_id(user)
.plan_type("team"),
)?;
let login = app
.send_chatgpt_auth_tokens_login_request(token, account.into(), Some("team".into()))
.await?;
let response: LoginAccountResponse = timeout(READ_TIMEOUT, app.read_response(login)).await??;
assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {});
release.notify_one();
if !verified {
let error = timeout(
READ_TIMEOUT,
app.read_stream_until_error_message(RequestId::Integer(request)),
)
.await??;
server.abort();
assert_eq!(
error.error.message,
"failed to fetch codex rate limits: application network permission was revoked"
);
return Ok(());
}
let response: GetAccountRateLimitsResponse =
timeout(READ_TIMEOUT, app.read_response(request)).await??;
server.abort();
let snapshot = json!({
"limitId": "codex", "planType": "team",
"primary": {"usedPercent": 42, "windowDurationMins": 60, "resetsAt": 2000000000}
});
let expected: GetAccountRateLimitsResponse = serde_json::from_value(json!({
"ordinaryUsageAllowed": if verified { Some(true) } else { None },
"accountId": "workspace-a",
"rateLimits": snapshot, "rateLimitsByLimitId": {"codex": snapshot}
}))?;
assert_eq!(response, expected);
Ok(())
}
#[test_case(false; "same_login")]
#[test_case(true; "same_user_external_login")]
#[tokio::test]
async fn security_setup_rechecks_login_mode_after_backend_response(
change_login: bool,
) -> Result<()> {
use codex_app_server_protocol::GetAccountSecuritySetupResponse;
let token = encode_id_token(
&ChatGptIdTokenClaims::new()
.chatgpt_account_id("workspace-a")
.chatgpt_user_id("user-a"),
)?;
let home = TempDir::new()?;
write_chatgpt_auth(
home.path(),
ChatGptAuthFixture::new(&token)
.account_id("workspace-a")
.chatgpt_user_id("user-a")
.plan_type("team"),
AuthCredentialsStoreMode::File,
)?;
let entered = Arc::new(Notify::new());
let release = Arc::new(Notify::new());
let request_entered = Arc::clone(&entered);
let response_release = Arc::clone(&release);
let listener = TcpListener::bind("127.0.0.1:0").await?;
std::fs::write(
home.path().join("config.toml"),
format!(
"chatgpt_base_url = \"http://{}/backend-api\"\n",
listener.local_addr()?
),
)?;
let expected_authorization = format!("Bearer {token}");
let router = Router::new().route(
"/backend-api/wham/security-setup",
get(move |headers: HeaderMap| {
let expected_authorization = expected_authorization.clone();
let entered = Arc::clone(&request_entered);
let release = Arc::clone(&response_release);
async move {
assert_eq!(headers["authorization"], expected_authorization);
assert_eq!(headers["chatgpt-account-id"], "workspace-a");
entered.notify_one();
release.notified().await;
Json(json!({"notice": {
"title": "Set up security",
"description": "Account security reminder",
"action": {"label": "Settings", "url": "https://chatgpt.com/cyber"}
}}))
}
}),
);
let server = tokio::spawn(async move { axum::serve(listener, router).await });
let mut app = TestAppServer::builder()
.with_codex_home(home.path())
.without_auto_env()
.with_env_overrides(&[("OPENAI_API_KEY", None)])
.build_initialized_with_timeout(READ_TIMEOUT)
.await?;
let request = app
.send_request("account/securitySetup/read", /*params*/ None)
.await?;
timeout(READ_TIMEOUT, entered.notified()).await?;
if change_login {
let login = app
.send_chatgpt_auth_tokens_login_request(
token,
"workspace-a".into(),
Some("team".into()),
)
.await?;
let response: LoginAccountResponse =
timeout(READ_TIMEOUT, app.read_response(login)).await??;
assert_eq!(response, LoginAccountResponse::ChatgptAuthTokens {});
}
release.notify_one();
let response: GetAccountSecuritySetupResponse =
timeout(READ_TIMEOUT, app.read_response(request)).await??;
server.abort();
if change_login {
assert_eq!(response.notice, None);
} else {
let notice = response
.notice
.expect("unchanged saved login gets its notice");
assert_eq!(notice.account_id, "workspace-a");
assert_eq!(notice.user_id, "user-a");
assert_eq!(notice.title, "Set up security");
}
Ok(())
}

View File

@@ -1,225 +0,0 @@
use anyhow::Result;
use anyhow::bail;
use app_test_support::ChatGptIdTokenClaims;
use app_test_support::TestAppServer;
use app_test_support::encode_id_token;
use app_test_support::to_response;
use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url;
use codex_app_server_protocol::AccountLoginCompletedNotification;
use codex_app_server_protocol::JSONRPCResponse;
use codex_app_server_protocol::LoginAccountResponse;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::ServerNotification;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::TurnStartParams;
use codex_app_server_protocol::UserInput;
use core_test_support::apps_test_server::AppsTestServer;
use core_test_support::responses;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use std::time::Duration;
use tempfile::TempDir;
use tokio::time::timeout;
use wiremock::Mock;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use wiremock::matchers::query_param;
const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(20);
const WORKSPACE_ID: &str = "123e4567-e89b-42d3-a456-426614174010";
enum ToolSuggestFeature {
Enabled,
Disabled,
}
#[tokio::test]
async fn first_turn_after_external_login_waits_for_recommended_plugins() -> Result<()> {
recommended_plugins_after_external_login(ToolSuggestFeature::Enabled).await
}
#[tokio::test]
async fn first_turn_after_external_login_waits_for_recommended_plugins_without_tool_suggest()
-> Result<()> {
recommended_plugins_after_external_login(ToolSuggestFeature::Disabled).await
}
async fn recommended_plugins_after_external_login(
tool_suggest_feature: ToolSuggestFeature,
) -> Result<()> {
let tool_suggest_enabled = matches!(tool_suggest_feature, ToolSuggestFeature::Enabled);
let recommended_plugins_config = if tool_suggest_enabled {
""
} else {
"recommended_plugins = true\n"
};
let server = responses::start_mock_server().await;
let apps_server = AppsTestServer::mount(&server).await?;
Mock::given(method("GET"))
.and(path("/ps/plugins/suggested/codex"))
.and(query_param("scope", "GLOBAL"))
.respond_with(
ResponseTemplate::new(200)
.set_delay(Duration::from_millis(250))
.set_body_json(json!({
"enabled": true,
"plugins": [{
"id": "plugin_github",
"name": "github",
"display_name": "GitHub"
}]
})),
)
.expect(1)
.mount(&server)
.await;
let response = responses::sse(vec![
responses::ev_response_created("resp-1"),
responses::ev_assistant_message("msg-1", "done"),
responses::ev_completed("resp-1"),
]);
let responses_mock = responses::mount_sse_once(&server, response).await;
let codex_home = TempDir::new()?;
write_mock_responses_config_toml_with_chatgpt_base_url(
codex_home.path(),
&server.uri(),
&apps_server.chatgpt_base_url,
)?;
let config_path = codex_home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?;
std::fs::write(
config_path,
format!(
"{config}\n[features]\napps = true\nplugins = true\ntool_suggest = {tool_suggest_enabled}\n{recommended_plugins_config}"
),
)?;
let sqlite_home = codex_home.path().to_string_lossy();
let mut app_server = TestAppServer::builder()
.with_codex_home(codex_home.path())
.without_managed_config()
.with_env_overrides(&[("CODEX_SQLITE_HOME", Some(sqlite_home.as_ref()))])
.build()
.await?;
timeout(DEFAULT_READ_TIMEOUT, app_server.initialize()).await??;
let access_token = encode_id_token(
&ChatGptIdTokenClaims::new()
.email("embedded@example.com")
.plan_type("pro")
.chatgpt_account_id(WORKSPACE_ID),
)?;
let login_id = app_server
.send_chatgpt_auth_tokens_login_request(
access_token,
WORKSPACE_ID.to_string(),
Some("pro".to_string()),
)
.await?;
let login_response: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
app_server.read_stream_until_response_message(RequestId::Integer(login_id)),
)
.await??;
assert_eq!(
to_response::<LoginAccountResponse>(login_response)?,
LoginAccountResponse::ChatgptAuthTokens {}
);
// Login clears the recommendation cache after its RPC response. Wait for completion so
// thread startup and the background refresh share the same cache generation.
let notification = timeout(
DEFAULT_READ_TIMEOUT,
app_server.read_stream_until_notification_message("account/login/completed"),
)
.await??;
let ServerNotification::AccountLoginCompleted(payload) = notification.try_into()? else {
bail!("unexpected notification")
};
assert_eq!(
payload,
AccountLoginCompletedNotification {
login_id: None,
success: true,
error: None,
onboarding_entrypoint: None,
}
);
let thread_id = app_server
.send_thread_start_request_with_auto_env(ThreadStartParams {
model: Some("mock-model".to_string()),
..Default::default()
})
.await?;
let thread_response: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
app_server.read_stream_until_response_message(RequestId::Integer(thread_id)),
)
.await??;
let ThreadStartResponse { thread, .. } = to_response(thread_response)?;
let turn_id = app_server
.send_turn_start_request(TurnStartParams {
thread_id: thread.id,
input: vec![UserInput::Text {
text: "suggest a plugin".to_string(),
text_elements: Vec::new(),
}],
..Default::default()
})
.await?;
let _: JSONRPCResponse = timeout(
DEFAULT_READ_TIMEOUT,
app_server.read_stream_until_response_message(RequestId::Integer(turn_id)),
)
.await??;
timeout(
DEFAULT_READ_TIMEOUT,
app_server.read_stream_until_notification_message("turn/completed"),
)
.await??;
let requests = responses_mock.requests();
let request = requests
.iter()
.find(|request| {
request
.message_input_texts("user")
.iter()
.any(|text| text.contains("suggest a plugin"))
})
.expect("turn request");
let recommendations = request
.message_input_texts("developer")
.into_iter()
.filter(|text| text.starts_with("<recommended_plugins>"))
.collect::<Vec<_>>();
assert_eq!(
recommendations,
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>",
)]
);
let body = request.body_json();
let tool_names = body
.get("tools")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|tool| tool.get("name").and_then(Value::as_str))
.collect::<Vec<_>>();
assert_eq!(
tool_names.contains(&"request_plugin_install"),
tool_suggest_enabled
);
assert!(!tool_names.contains(&"list_available_plugins_to_install"));
Ok(())
}

View File

@@ -9,14 +9,11 @@ use app_test_support::create_final_assistant_message_sse_response;
use app_test_support::to_response;
use app_test_support::write_chatgpt_auth;
use app_test_support::write_mock_responses_config_toml_with_chatgpt_base_url;
use codex_app_server_protocol::AppInfo;
use codex_app_server_protocol::CapabilityRootLocation;
use codex_app_server_protocol::EnvironmentAddResponse;
use codex_app_server_protocol::EnvironmentInfoResponse;
use codex_app_server_protocol::RequestId;
use codex_app_server_protocol::SelectedCapabilityRoot;
use codex_app_server_protocol::ThreadResumeParams;
use codex_app_server_protocol::ThreadResumeResponse;
use codex_app_server_protocol::ThreadStartParams;
use codex_app_server_protocol::ThreadStartResponse;
use codex_app_server_protocol::TurnEnvironmentParams;
@@ -25,7 +22,6 @@ use codex_app_server_protocol::TurnStartResponse;
use codex_app_server_protocol::UserInput;
use codex_config::types::AuthCredentialsStoreMode;
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
use codex_protocol::protocol::PLUGINS_INSTRUCTIONS_OPEN_TAG;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathUri;
use core_test_support::process::wait_for_pid_file;
@@ -33,7 +29,6 @@ use core_test_support::responses;
use core_test_support::responses::ResponsesRequest;
use core_test_support::stdio_server_bin;
use pretty_assertions::assert_eq;
use pretty_assertions::assert_ne;
use serde_json::json;
use tempfile::TempDir;
use test_case::test_case;
@@ -45,8 +40,6 @@ use tokio::time::timeout;
use super::analytics::mount_analytics_capture;
use super::analytics::wait_for_matching_analytics_event;
use super::app_list::connector_tool;
use super::app_list::start_apps_server_with_delays;
const READ_TIMEOUT: Duration = Duration::from_secs(20);
const EXECUTOR_ID: &str = "executor-1";
@@ -62,7 +55,6 @@ const NO_SELECTED_SKILLS_MESSAGE: &str = "No selected-environment skills are cur
const RESTORED_SELECTED_SKILLS_MESSAGE: &str =
"The previously listed selected-environment skills are available again.";
const MCP_SERVER_NAME: &str = "executor_probe";
const MCP_CALL_ID: &str = "selected-executor-mcp-call";
const CONNECTOR_ID: &str = "calendar";
#[derive(Clone, Copy)]
@@ -196,314 +188,6 @@ async fn selected_plugin_mcp_startup_respects_explicit_mentions(
Ok(())
}
#[test_case(false; "direct selected root discovery")]
#[test_case(true; "batched executor capability discovery")]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn managed_plugins_requirement_disables_selected_executor_plugin_capabilities(
executor_capability_discovery: bool,
) -> Result<()> {
let responses_server = responses::start_mock_server().await;
let (apps_url, apps_server_handle) = start_apps_server_with_delays(
vec![AppInfo {
id: CONNECTOR_ID.to_string(),
name: "Calendar".to_string(),
description: None,
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: None,
is_accessible: false,
is_enabled: true,
plugin_display_names: Vec::new(),
}],
vec![connector_tool(CONNECTOR_ID, "Calendar")?],
Duration::ZERO,
Duration::ZERO,
)
.await?;
let fixture = selected_capability_fixture(&responses_server.uri(), &apps_url)?;
let config_path = fixture.codex_home.path().join("config.toml");
let config = std::fs::read_to_string(&config_path)?.replace(
"executor_capability_discovery = true",
&format!("executor_capability_discovery = {executor_capability_discovery}\nplugins = true"),
);
std::fs::write(config_path, config)?;
std::fs::write(
fixture.codex_home.path().join("requirements.toml"),
"[features]\nplugins = false\n",
)?;
let response_mock = responses::mount_sse_once(
&responses_server,
responses::sse(vec![
responses::ev_response_created("disabled-selected-plugin"),
responses::ev_assistant_message("disabled-selected-plugin-message", "Done"),
responses::ev_completed("disabled-selected-plugin"),
]),
)
.await;
let mut app_server = TestAppServer::builder()
.with_codex_home(fixture.codex_home.path())
.without_auto_env()
.build()
.await?;
timeout(READ_TIMEOUT, app_server.initialize()).await??;
let thread_id = start_thread(
&mut app_server,
fixture.selected_root,
fixture.environment_cwd.clone(),
)
.await?;
let mut exec_server =
spawn_exec_server(fixture.codex_home.path(), &fixture.exec_server_url).await?;
add_environment(&mut app_server, &fixture.exec_server_url).await?;
run_turn(
&mut app_server,
&thread_id,
"Inspect the disabled selected plugin capabilities",
fixture.environment_cwd,
&[LOCAL_ENVIRONMENT_ID, EXECUTOR_ID],
)
.await?;
assert!(
!fixture.pid_file.exists(),
"the disabled selected plugin MCP server must never start"
);
assert_selected_capabilities_absent(&response_mock.single_request());
exec_server.kill().await?;
apps_server_handle.abort();
let _ = apps_server_handle.await;
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn selected_capability_stack_tracks_environment_selection_and_resume() -> Result<()> {
let responses_server = responses::start_mock_server().await;
let (apps_url, apps_server_handle) = start_apps_server_with_delays(
vec![AppInfo {
id: CONNECTOR_ID.to_string(),
name: "Calendar".to_string(),
description: None,
logo_url: None,
logo_url_dark: None,
icon_assets: None,
icon_dark_assets: None,
distribution_channel: None,
branding: None,
app_metadata: None,
labels: None,
install_url: None,
is_accessible: false,
is_enabled: true,
plugin_display_names: Vec::new(),
}],
vec![connector_tool(CONNECTOR_ID, "Calendar")?],
Duration::ZERO,
Duration::ZERO,
)
.await?;
let fixture = selected_capability_fixture(&responses_server.uri(), &apps_url)?;
let response_mock = responses::mount_sse_sequence(
&responses_server,
vec![
responses::sse(vec![
responses::ev_response_created("environment-unavailable"),
responses::ev_assistant_message("unavailable-message", "Waiting"),
responses::ev_completed("environment-unavailable"),
]),
responses::sse(vec![
responses::ev_response_created("environment-available-call"),
responses::ev_function_call_with_namespace(
MCP_CALL_ID,
&format!("mcp__{MCP_SERVER_NAME}"),
"echo",
&json!({
"message": "hello from the selected executor",
"env_var": EXECUTOR_ENV_NAME,
})
.to_string(),
),
responses::ev_completed("environment-available-call"),
]),
responses::sse(vec![
responses::ev_response_created("environment-available-done"),
responses::ev_assistant_message("available-message", "Done"),
responses::ev_completed("environment-available-done"),
]),
responses::sse(vec![
responses::ev_response_created("unchanged-step"),
responses::ev_assistant_message("unchanged-message", "Still ready"),
responses::ev_completed("unchanged-step"),
]),
responses::sse(vec![
responses::ev_response_created("resumed-unavailable-step"),
responses::ev_assistant_message(
"resumed-unavailable-message",
"Unavailable after resume",
),
responses::ev_completed("resumed-unavailable-step"),
]),
responses::sse(vec![
responses::ev_response_created("reattached-step"),
responses::ev_assistant_message("reattached-message", "Ready after reattach"),
responses::ev_completed("reattached-step"),
]),
],
)
.await;
let mut app_server = TestAppServer::builder()
.with_codex_home(fixture.codex_home.path())
// This fixture owns environments.toml and selects its environments explicitly.
.without_auto_env()
.build()
.await?;
timeout(READ_TIMEOUT, app_server.initialize()).await??;
let thread_id = start_thread(
&mut app_server,
fixture.selected_root.clone(),
fixture.environment_cwd.clone(),
)
.await?;
run_turn(
&mut app_server,
&thread_id,
"Inspect the current capabilities",
fixture.environment_cwd.clone(),
&[LOCAL_ENVIRONMENT_ID],
)
.await?;
let initial_requests = response_mock.requests();
assert_selected_capabilities_absent(&initial_requests[0]);
let mut exec_server =
spawn_exec_server(fixture.codex_home.path(), &fixture.exec_server_url).await?;
add_environment(&mut app_server, &fixture.exec_server_url).await?;
// The next turn selects the executor; its server mention waits for MCP startup.
run_turn(
&mut app_server,
&thread_id,
&format!("Use ${SKILL_NAME} and call [${MCP_SERVER_NAME}](mcp://{MCP_SERVER_NAME})"),
fixture.environment_cwd.clone(),
&[LOCAL_ENVIRONMENT_ID, EXECUTOR_ID],
)
.await?;
let first_mcp_pid = wait_for_pid_file(&fixture.pid_file).await?;
run_turn(
&mut app_server,
&thread_id,
"Continue with the same selected capabilities",
fixture.environment_cwd.clone(),
&[LOCAL_ENVIRONMENT_ID, EXECUTOR_ID],
)
.await?;
assert_eq!(first_mcp_pid, wait_for_pid_file(&fixture.pid_file).await?);
exec_server.kill().await?;
drop(app_server);
std::fs::remove_file(&fixture.pid_file)?;
let mut app_server = TestAppServer::builder()
.with_codex_home(fixture.codex_home.path())
// This fixture owns environments.toml and selects its environments explicitly.
.without_auto_env()
.build()
.await?;
timeout(READ_TIMEOUT, app_server.initialize()).await??;
let request_id = app_server
.send_thread_resume_request(ThreadResumeParams {
thread_id: thread_id.clone(),
..Default::default()
})
.await?;
let response = timeout(
READ_TIMEOUT,
app_server.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let ThreadResumeResponse { thread, .. } = to_response(response)?;
assert_eq!(thread_id, thread.id);
run_turn(
&mut app_server,
&thread_id,
"Inspect capabilities while the selected executor is unavailable",
fixture.environment_cwd.clone(),
&[LOCAL_ENVIRONMENT_ID],
)
.await?;
let requests = response_mock.requests();
assert_eq!(5, requests.len());
assert_selected_plugin_tools_absent(&requests[4]);
assert!(
latest_selected_skill_update(&requests[4])
.is_some_and(|text| text.contains(NO_SELECTED_SKILLS_MESSAGE))
);
exec_server = spawn_exec_server(fixture.codex_home.path(), &fixture.exec_server_url).await?;
add_environment(&mut app_server, &fixture.exec_server_url).await?;
run_turn(
&mut app_server,
&thread_id,
&format!(
"Use ${SKILL_NAME} with [${MCP_SERVER_NAME}](mcp://{MCP_SERVER_NAME}) after reattaching the selected executor"
),
fixture.environment_cwd,
&[LOCAL_ENVIRONMENT_ID, EXECUTOR_ID],
)
.await?;
let resumed_mcp_pid = wait_for_pid_file(&fixture.pid_file).await?;
assert_ne!(first_mcp_pid, resumed_mcp_pid);
let requests = response_mock.requests();
assert_eq!(6, requests.len());
for request in &requests[1..4] {
assert_selected_skill_is_injected(request, /*expected_count*/ 1);
assert_selected_plugin_tools(request);
assert_plugin_guidance_count(request, /*expected_count*/ 0);
}
assert_plugin_guidance_count(&requests[4], /*expected_count*/ 0);
assert_selected_skill_is_injected(&requests[5], /*expected_count*/ 2);
assert!(
latest_selected_skill_update(&requests[5])
.is_some_and(|text| text.contains(RESTORED_SELECTED_SKILLS_MESSAGE))
);
assert_eq!(
1,
requests[5]
.message_input_texts("developer")
.into_iter()
.filter(|text| text.contains(SKILL_DESCRIPTION))
.count(),
"reattaching should retain the original catalog without repeating it"
);
assert_selected_plugin_tools(&requests[5]);
let output = requests[2].function_call_output(MCP_CALL_ID);
let output = output["output"]
.as_str()
.expect("MCP function output should be text");
assert!(output.contains("ECHOING: hello from the selected executor"));
assert!(output.contains(EXECUTOR_ENV_VALUE));
exec_server.kill().await?;
apps_server_handle.abort();
let _ = apps_server_handle.await;
Ok(())
}
struct SelectedCapabilityFixture {
codex_home: TempDir,
_plugin: TempDir,
@@ -635,60 +319,6 @@ fn selected_capability_fixture(
})
}
fn assert_selected_capabilities_absent(request: &ResponsesRequest) {
assert!(
request
.message_input_texts("developer")
.into_iter()
.all(|text| !text.contains(SKILL_DESCRIPTION))
);
assert_selected_plugin_tools_absent(request);
assert_plugin_guidance_count(request, /*expected_count*/ 0);
}
fn assert_selected_plugin_tools_absent(request: &ResponsesRequest) {
assert!(
request
.tool_by_name(&format!("mcp__{MCP_SERVER_NAME}"), "echo")
.is_none()
);
let connector = request
.tool_by_name("mcp__codex_apps__calendar", "connector_calendar")
.expect("host connector should remain model-visible");
assert!(
connector["description"]
.as_str()
.is_some_and(|description| !description.contains(PLUGIN_DISPLAY_NAME))
);
}
fn assert_plugin_guidance_count(request: &ResponsesRequest, expected_count: usize) {
assert_eq!(
expected_count,
request
.message_input_texts("developer")
.into_iter()
.filter(|text| text.starts_with(PLUGINS_INSTRUCTIONS_OPEN_TAG))
.count()
);
}
fn assert_selected_skill_is_injected(request: &ResponsesRequest, expected_count: usize) {
assert_selected_skill_catalog_available(request);
let skill_fragments = request
.message_input_texts("user")
.into_iter()
.filter(|text| text.starts_with("<skill>"))
.collect::<Vec<_>>();
assert_eq!(expected_count, skill_fragments.len());
for fragment in skill_fragments {
assert!(fragment.contains(&format!("<name>{SKILL_NAME}</name>")));
assert!(fragment.contains(SKILL_BODY_MARKER));
assert!(!fragment.contains(LOCAL_SKILL_BODY_MARKER));
}
}
fn assert_selected_skill_catalog_available(request: &ResponsesRequest) {
let latest_update = latest_selected_skill_update(request)
.expect("selected skill availability should be model-visible");
@@ -712,22 +342,6 @@ fn latest_selected_skill_update(request: &ResponsesRequest) -> Option<String> {
})
}
fn assert_selected_plugin_tools(request: &ResponsesRequest) {
assert!(
request
.tool_by_name(&format!("mcp__{MCP_SERVER_NAME}"), "echo")
.is_some()
);
let connector = request
.tool_by_name("mcp__codex_apps__calendar", "connector_calendar")
.expect("selected connector should be model-visible");
assert!(
connector["description"]
.as_str()
.is_some_and(|description| description.contains(PLUGIN_DISPLAY_NAME))
);
}
async fn start_thread(
app_server: &mut TestAppServer,
selected_root: SelectedCapabilityRoot,
@@ -754,46 +368,6 @@ async fn start_thread(
Ok(thread.id)
}
async fn run_turn(
app_server: &mut TestAppServer,
thread_id: &str,
text: &str,
environment_cwd: AbsolutePathBuf,
environment_ids: &[&str],
) -> Result<()> {
let request_id = app_server
.send_turn_start_request(TurnStartParams {
thread_id: thread_id.to_string(),
input: vec![UserInput::Text {
text: text.to_string(),
text_elements: Vec::new(),
}],
environments: Some(
environment_ids
.iter()
.map(|environment_id| TurnEnvironmentParams {
environment_id: (*environment_id).to_string(),
cwd: environment_cwd.clone().into(),
runtime_workspace_roots: None,
})
.collect(),
),
..Default::default()
})
.await?;
timeout(
READ_TIMEOUT,
app_server.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
timeout(
READ_TIMEOUT,
app_server.read_stream_until_notification_message("turn/completed"),
)
.await??;
Ok(())
}
async fn add_environment(app_server: &mut TestAppServer, exec_server_url: &str) -> Result<()> {
let request_id = app_server
.send_raw_request(