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
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:
@@ -39,7 +39,6 @@ codex-analytics = { workspace = true }
|
||||
codex-app-server-daemon = { workspace = true }
|
||||
codex-arg0 = { workspace = true }
|
||||
codex-aws-auth = { workspace = true }
|
||||
codex-cloud-config = { workspace = true }
|
||||
codex-code-mode = { workspace = true }
|
||||
codex-config = { workspace = true }
|
||||
codex-network-proxy = { workspace = true }
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
use codex_app_server_protocol::AppBranding as ApiAppBranding;
|
||||
use codex_app_server_protocol::AppInfo as ApiAppInfo;
|
||||
use codex_app_server_protocol::AppMetadata as ApiAppMetadata;
|
||||
use codex_app_server_protocol::AppReview as ApiAppReview;
|
||||
use codex_app_server_protocol::AppScreenshot as ApiAppScreenshot;
|
||||
use codex_app_server_protocol::AppToolSummary as ApiAppToolSummary;
|
||||
use codex_app_server_protocol::ConnectorMetadata as ApiConnectorMetadata;
|
||||
use codex_connectors::AppBranding;
|
||||
use codex_connectors::AppInfo;
|
||||
use codex_connectors::AppMetadata;
|
||||
use codex_connectors::AppReview;
|
||||
use codex_connectors::AppScreenshot;
|
||||
use codex_connectors::ConnectorMetadata;
|
||||
use codex_connectors::ConnectorToolSummary;
|
||||
use codex_connectors::metadata::connector_install_url;
|
||||
|
||||
/// Converts connector-domain app metadata owned by `codex-connectors` into the app-server wire
|
||||
/// type owned by `codex-app-server-protocol`.
|
||||
///
|
||||
/// The types stay separate so app-server protocol ownership does not leak into the connector
|
||||
/// domain crate. Because this crate owns neither type, Rust's orphan rules require an explicit
|
||||
/// conversion function instead of a `From` implementation.
|
||||
pub(crate) fn app_info_to_api(app: AppInfo) -> ApiAppInfo {
|
||||
let AppInfo {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
logo_url,
|
||||
logo_url_dark,
|
||||
icon_assets,
|
||||
icon_dark_assets,
|
||||
distribution_channel,
|
||||
branding,
|
||||
app_metadata,
|
||||
labels,
|
||||
install_url,
|
||||
is_accessible,
|
||||
is_enabled,
|
||||
plugin_display_names,
|
||||
} = app;
|
||||
ApiAppInfo {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
logo_url,
|
||||
logo_url_dark,
|
||||
icon_assets,
|
||||
icon_dark_assets,
|
||||
distribution_channel,
|
||||
branding: branding.map(app_branding_to_api),
|
||||
app_metadata: app_metadata.map(app_metadata_to_api),
|
||||
labels,
|
||||
install_url,
|
||||
is_accessible,
|
||||
is_enabled,
|
||||
plugin_display_names,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts metadata-only connector data into the app-server wire type.
|
||||
///
|
||||
/// Keeping this separate from app_info_to_api makes it impossible for app/read to accidentally
|
||||
/// expose full runtime tool state from the broader app/list path.
|
||||
pub(crate) fn connector_metadata_to_api(metadata: ConnectorMetadata) -> ApiConnectorMetadata {
|
||||
let ConnectorMetadata {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
icon_url,
|
||||
icon_url_dark,
|
||||
distribution_channel,
|
||||
tool_summaries,
|
||||
} = metadata;
|
||||
let install_url = Some(connector_install_url(&name, &id));
|
||||
ApiConnectorMetadata {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
icon_url,
|
||||
icon_url_dark,
|
||||
distribution_channel,
|
||||
install_url,
|
||||
plugin_display_names: Vec::new(),
|
||||
tool_summaries: tool_summaries.map(|tools| {
|
||||
tools
|
||||
.into_iter()
|
||||
.map(|tool| {
|
||||
let ConnectorToolSummary {
|
||||
name,
|
||||
title,
|
||||
description,
|
||||
is_enabled,
|
||||
disabled_reason,
|
||||
is_read_only,
|
||||
} = tool;
|
||||
ApiAppToolSummary {
|
||||
name,
|
||||
title,
|
||||
description,
|
||||
is_enabled,
|
||||
disabled_reason,
|
||||
is_read_only,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn app_branding_to_api(branding: AppBranding) -> ApiAppBranding {
|
||||
let AppBranding {
|
||||
category,
|
||||
developer,
|
||||
website,
|
||||
privacy_policy,
|
||||
terms_of_service,
|
||||
is_discoverable_app,
|
||||
} = branding;
|
||||
ApiAppBranding {
|
||||
category,
|
||||
developer,
|
||||
website,
|
||||
privacy_policy,
|
||||
terms_of_service,
|
||||
is_discoverable_app,
|
||||
}
|
||||
}
|
||||
|
||||
fn app_review_to_api(review: AppReview) -> ApiAppReview {
|
||||
let AppReview { status } = review;
|
||||
ApiAppReview { status }
|
||||
}
|
||||
|
||||
fn app_screenshot_to_api(screenshot: AppScreenshot) -> ApiAppScreenshot {
|
||||
let AppScreenshot {
|
||||
url,
|
||||
file_id,
|
||||
user_prompt,
|
||||
} = screenshot;
|
||||
ApiAppScreenshot {
|
||||
url,
|
||||
file_id,
|
||||
user_prompt,
|
||||
}
|
||||
}
|
||||
|
||||
fn app_metadata_to_api(metadata: AppMetadata) -> ApiAppMetadata {
|
||||
let AppMetadata {
|
||||
review,
|
||||
categories,
|
||||
sub_categories,
|
||||
seo_description,
|
||||
screenshots,
|
||||
developer,
|
||||
version,
|
||||
version_id,
|
||||
version_notes,
|
||||
first_party_requires_install,
|
||||
show_in_composer_when_unlinked,
|
||||
} = metadata;
|
||||
ApiAppMetadata {
|
||||
review: review.map(app_review_to_api),
|
||||
categories,
|
||||
sub_categories,
|
||||
seo_description,
|
||||
screenshots: screenshots
|
||||
.map(|screenshots| screenshots.into_iter().map(app_screenshot_to_api).collect()),
|
||||
developer,
|
||||
version,
|
||||
version_id,
|
||||
version_notes,
|
||||
first_party_requires_install,
|
||||
show_in_composer_when_unlinked,
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@ async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() -
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("GET"))
|
||||
.respond_with(ResponseTemplate::new(200))
|
||||
.expect(2)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let home = tempdir()?;
|
||||
@@ -44,28 +44,15 @@ async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() -
|
||||
.build()
|
||||
.await?;
|
||||
config.chatgpt_base_url = server.uri();
|
||||
let cloud_endpoint = format!("{}/api/codex/config/bundle", server.uri());
|
||||
let policy = EmbeddedNetworkPolicy::load(&overrides).await;
|
||||
let bootstrap_auth = policy.bind_bootstrap_auth(config.auth_config());
|
||||
let bootstrap = bootstrap_auth
|
||||
.auth_route_config
|
||||
.http_client_factory()
|
||||
.build_client(&cloud_endpoint, ClientRouteClass::Auth)?;
|
||||
let application = policy
|
||||
.bind(config.http_client_factory())
|
||||
.build_client(&server.uri(), ClientRouteClass::Other)?;
|
||||
assert!(bootstrap.get(&cloud_endpoint).send().await.is_err());
|
||||
assert!(application.get(server.uri()).send().await.is_err());
|
||||
policy.activate(&mut config);
|
||||
let caller_factory = config.http_client_factory();
|
||||
let caller_client = caller_factory.build_client(&server.uri(), ClientRouteClass::Other)?;
|
||||
let worktree_bootstrap = policy.clone().bind_bootstrap_auth(config.auth_config());
|
||||
let worktree_client = worktree_bootstrap
|
||||
.auth_route_config
|
||||
.http_client_factory()
|
||||
.build_client(&cloud_endpoint, ClientRouteClass::Auth)?;
|
||||
assert!(caller_client.get(server.uri()).send().await.is_err());
|
||||
assert!(worktree_client.get(&cloud_endpoint).send().await.is_err());
|
||||
assert!(
|
||||
caller_factory
|
||||
.network_policy()
|
||||
@@ -86,29 +73,17 @@ async fn embedded_transports_stay_blocked_until_the_same_policy_is_published() -
|
||||
|
||||
std::fs::remove_file(&requirements)?;
|
||||
let unrestricted = manager.refresh_application_network_policy().await?;
|
||||
let unrelated_endpoint = format!("{}/not-the-config-endpoint", server.uri()).parse()?;
|
||||
assert_eq!(
|
||||
bootstrap_auth
|
||||
.auth_route_config
|
||||
.http_client_factory()
|
||||
.network_policy()
|
||||
.acquire(&unrelated_endpoint)
|
||||
.map(|_| ()),
|
||||
Err(NetworkPolicyDenied::Destination),
|
||||
);
|
||||
caller_client.get(server.uri()).send().await?;
|
||||
worktree_client.get(&cloud_endpoint).send().await?;
|
||||
assert!(
|
||||
caller_factory
|
||||
.network_policy()
|
||||
.acquire_for_unsupported_sdk()
|
||||
.is_ok()
|
||||
);
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 2);
|
||||
assert_eq!(server.received_requests().await.unwrap().len(), 1);
|
||||
std::fs::write(&requirements, "[malformed")?;
|
||||
assert!(manager.refresh_application_network_policy().await.is_err());
|
||||
assert!(caller_client.get(server.uri()).send().await.is_err());
|
||||
assert!(worktree_client.get(&cloud_endpoint).send().await.is_err());
|
||||
assert!(
|
||||
caller_factory
|
||||
.network_policy()
|
||||
|
||||
@@ -1,243 +0,0 @@
|
||||
use codex_core::config::Config;
|
||||
use codex_features::Feature;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_http_client::HttpClient;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::default_client::RESIDENCY_HEADER_NAME;
|
||||
use codex_login::default_client::create_client_with_chatgpt_cookies;
|
||||
use codex_login::default_client::default_headers;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context;
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
const OAI_PRODUCT_SKU_HEADER: &str = "OAI-Product-Sku";
|
||||
const CODEX_PRODUCT_SKU: &str = "codex";
|
||||
|
||||
struct CachedChatGptClient {
|
||||
factory: HttpClientFactory,
|
||||
residency: Option<Vec<u8>>,
|
||||
client: HttpClient,
|
||||
}
|
||||
|
||||
static CHATGPT_CLIENT: LazyLock<Mutex<Option<CachedChatGptClient>>> =
|
||||
LazyLock::new(|| Mutex::new(None));
|
||||
|
||||
/// Reuse the client and cookies without changing the caller's captured account policy.
|
||||
fn chatgpt_client(factory: HttpClientFactory) -> HttpClient {
|
||||
let residency = default_headers()
|
||||
.get(RESIDENCY_HEADER_NAME)
|
||||
.map(|value| value.as_bytes().to_vec());
|
||||
let mut cached = CHATGPT_CLIENT
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(cached_client) = cached.as_ref()
|
||||
&& cached_client.factory == factory
|
||||
&& cached_client.residency == residency
|
||||
{
|
||||
return cached_client.client.clone();
|
||||
}
|
||||
|
||||
let client = create_client_with_chatgpt_cookies(&factory);
|
||||
*cached = Some(CachedChatGptClient {
|
||||
factory,
|
||||
residency,
|
||||
client: client.clone(),
|
||||
});
|
||||
client
|
||||
}
|
||||
|
||||
/// Make a GET request to the ChatGPT backend API.
|
||||
#[cfg(test)]
|
||||
pub(crate) async fn chatgpt_get_request<T: DeserializeOwned>(
|
||||
config: &Config,
|
||||
path: String,
|
||||
) -> anyhow::Result<T> {
|
||||
let mut config = config.clone();
|
||||
let (auth, runtime) = standalone_auth(&mut config).await?;
|
||||
chatgpt_get_request_with_timeout(
|
||||
&config,
|
||||
&auth,
|
||||
runtime.as_ref(),
|
||||
path,
|
||||
/*timeout*/ None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn standalone_auth(
|
||||
config: &mut Config,
|
||||
) -> anyhow::Result<(
|
||||
CodexAuth,
|
||||
Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
)> {
|
||||
// Standalone commands create one owner. Freeze the caller's account policy before loading
|
||||
// credentials; this temporary manager does not own later account changes.
|
||||
config.application_network_policy = config
|
||||
.application_network_policy
|
||||
.clone()
|
||||
.for_current_account();
|
||||
if config.features.enabled(Feature::RuntimeAgentInstances) {
|
||||
codex_model_provider::validate_runtime_destination(Some(&config.chatgpt_base_url))?;
|
||||
}
|
||||
let auth_manager =
|
||||
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?;
|
||||
let runtime = if config.features.enabled(Feature::RuntimeAgentInstances)
|
||||
&& codex_runtime_agent_instance::is_openai_api_url(&config.chatgpt_base_url)
|
||||
{
|
||||
let installation_id = codex_core::resolve_installation_id(&config.codex_home).await?;
|
||||
codex_core::build_runtime_auth_manager(config, auth_manager.clone(), &installation_id)
|
||||
.map(|runtime| (runtime, config.runtime_auth_mode))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let auth = auth_manager
|
||||
.auth()
|
||||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?;
|
||||
Ok((auth, runtime))
|
||||
}
|
||||
|
||||
pub(crate) async fn chatgpt_get_request_with_timeout<T: DeserializeOwned>(
|
||||
config: &Config,
|
||||
auth: &CodexAuth,
|
||||
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
path: String,
|
||||
timeout: Option<Duration>,
|
||||
) -> anyhow::Result<T> {
|
||||
let chatgpt_base_url = &config.chatgpt_base_url;
|
||||
anyhow::ensure!(
|
||||
auth.uses_codex_backend(),
|
||||
"ChatGPT backend requests require Codex backend auth"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
auth.get_account_id().is_some(),
|
||||
"ChatGPT account ID not available, please re-run `codex login`"
|
||||
);
|
||||
let url = format!(
|
||||
"{}/{}",
|
||||
chatgpt_base_url.trim_end_matches('/'),
|
||||
path.trim_start_matches('/')
|
||||
);
|
||||
|
||||
let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?;
|
||||
let mut request = client
|
||||
.get(&url)
|
||||
.headers(default_headers())
|
||||
.headers(
|
||||
request_auth
|
||||
.auth
|
||||
.apply_auth_headers(Default::default())
|
||||
.await?,
|
||||
)
|
||||
.header(OAI_PRODUCT_SKU_HEADER, CODEX_PRODUCT_SKU)
|
||||
.header("Content-Type", "application/json");
|
||||
if let Some(timeout) = timeout {
|
||||
request = request.timeout(timeout);
|
||||
}
|
||||
let response = request.send().await.context("Failed to send request")?;
|
||||
|
||||
if response.status().is_success() {
|
||||
let result: T = response
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse JSON response")?;
|
||||
Ok(result)
|
||||
} else {
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
anyhow::bail!("Request failed with status {status}: {body}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Make a POST request to the ChatGPT backend API with an already-captured auth identity.
|
||||
///
|
||||
/// Callers must capture `auth` and `config.application_network_policy` together and preserve
|
||||
/// that snapshot rather than reacquiring either while the request is in flight.
|
||||
pub(crate) async fn chatgpt_post_request_with_timeout<
|
||||
TResponse: DeserializeOwned,
|
||||
TRequest: Serialize + ?Sized,
|
||||
>(
|
||||
config: &Config,
|
||||
auth: &CodexAuth,
|
||||
path: String,
|
||||
body: &TRequest,
|
||||
timeout: Duration,
|
||||
product_sku: &str,
|
||||
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
) -> anyhow::Result<TResponse> {
|
||||
anyhow::ensure!(
|
||||
auth.uses_codex_backend(),
|
||||
"ChatGPT backend requests require Codex backend auth"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
auth.get_account_id().is_some(),
|
||||
"ChatGPT account ID not available, please re-run codex login"
|
||||
);
|
||||
|
||||
let url = format!(
|
||||
"{}/{}",
|
||||
config.chatgpt_base_url.trim_end_matches('/'),
|
||||
path.trim_start_matches('/')
|
||||
);
|
||||
let (client, request_auth) = prepare_client_auth(config, auth, runtime, &url).await?;
|
||||
let response = client
|
||||
.post(&url)
|
||||
.headers(default_headers())
|
||||
.headers(
|
||||
request_auth
|
||||
.auth
|
||||
.apply_auth_headers(Default::default())
|
||||
.await?,
|
||||
)
|
||||
.header(OAI_PRODUCT_SKU_HEADER, product_sku)
|
||||
.header("Content-Type", "application/json")
|
||||
.timeout(timeout)
|
||||
.json(body)
|
||||
.send()
|
||||
.await
|
||||
.context("Failed to send request")?;
|
||||
|
||||
if response.status().is_success() {
|
||||
response
|
||||
.json()
|
||||
.await
|
||||
.context("Failed to parse JSON response")
|
||||
} else {
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
anyhow::bail!("Request failed with status {status}: {body}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep request credentials and the transport bound to the same account snapshot.
|
||||
async fn prepare_client_auth(
|
||||
config: &Config,
|
||||
auth: &CodexAuth,
|
||||
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
url: &str,
|
||||
) -> anyhow::Result<(HttpClient, codex_model_provider::ResolvedProviderAuth)> {
|
||||
if runtime.is_some() {
|
||||
codex_model_provider::validate_runtime_destination(Some(url))?;
|
||||
}
|
||||
let resolved = codex_model_provider::auth_provider_for_request(
|
||||
auth,
|
||||
runtime,
|
||||
/*headers*/ &Default::default(),
|
||||
)
|
||||
.await?;
|
||||
let factory = resolved.bind_http_client_factory(config.http_client_factory())?;
|
||||
let client = chatgpt_client(factory);
|
||||
Ok((client, resolved))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "chatgpt_client_runtime_auth_tests.rs"]
|
||||
mod runtime_auth_tests;
|
||||
@@ -1,321 +0,0 @@
|
||||
//! Test captured ChatGPT credentials and runtime proofs on helper requests.
|
||||
|
||||
use super::*;
|
||||
use base64::Engine;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
#[tokio::test]
|
||||
async fn helpers_use_captured_auth_and_strip_cross_origin_proofs() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let server = MockServer::start().await;
|
||||
let redirected = MockServer::start().await;
|
||||
Mock::given(path("/"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
|
||||
.expect(1)
|
||||
.mount(&redirected)
|
||||
.await;
|
||||
Mock::given(path("/agent/register"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"runtime_agent_instance_id": "runtime-chatgpt", "agent_host_id": "host-a",
|
||||
"actor": {"kind": "chatgpt", "user_id": "user-a", "account_id": "workspace-a"},
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/data"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/redirect"))
|
||||
.respond_with(ResponseTemplate::new(307).insert_header("location", redirected.uri()))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path("/ps/apps/batch"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"apps": [{"id": "calendar", "name": "Calendar", "description": "Calendar metadata"}],
|
||||
})))
|
||||
.expect(1).mount(&server).await;
|
||||
let home = tempfile::TempDir::new().unwrap();
|
||||
let mut config = codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
config.chatgpt_base_url = server.uri();
|
||||
let token = actor_token();
|
||||
let auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
&token,
|
||||
"workspace-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
let runtime = (
|
||||
Arc::new(RuntimeAuthManager::new(
|
||||
AuthManager::from_auth_for_testing(auth.clone()),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: uuid::Uuid::nil(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: Some("codex".into()),
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/agent/register", server.uri()).parse().unwrap(),
|
||||
)),
|
||||
mode,
|
||||
);
|
||||
// No saved auth exists: these helpers must use the supplied snapshot, not reload auth.
|
||||
let get: serde_json::Value = chatgpt_get_request_with_timeout(
|
||||
&config,
|
||||
&auth,
|
||||
Some(&runtime),
|
||||
"data".into(),
|
||||
/*timeout*/ None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let post: serde_json::Value = chatgpt_post_request_with_timeout(
|
||||
&config,
|
||||
&auth,
|
||||
"data".into(),
|
||||
&json!({}),
|
||||
Duration::from_secs(10),
|
||||
"codex",
|
||||
Some(&runtime),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let metadata = crate::chatgpt_connectors::read_connector_metadata(
|
||||
&config,
|
||||
&auth,
|
||||
Some(&runtime),
|
||||
&["calendar".into()],
|
||||
/*include_tools*/ false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(metadata.apps.len(), 1);
|
||||
assert_eq!(metadata.apps[0].name, "Calendar");
|
||||
assert!(metadata.missing_app_ids.is_empty());
|
||||
assert_eq!(get, json!({"ok": true}));
|
||||
assert_eq!(post, get);
|
||||
let redirected_result = chatgpt_get_request_with_timeout::<serde_json::Value>(
|
||||
&config,
|
||||
&auth,
|
||||
Some(&runtime),
|
||||
"redirect".into(),
|
||||
/*timeout*/ None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(redirected_result, get);
|
||||
let forwarded = redirected.received_requests().await.unwrap();
|
||||
assert_eq!(forwarded.len(), 1);
|
||||
assert!(!forwarded[0].headers.contains_key("authorization"));
|
||||
assert!(
|
||||
!forwarded[0]
|
||||
.headers
|
||||
.contains_key("x-openai-agent-assertion")
|
||||
);
|
||||
redirected.verify().await;
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let metadata_request = requests
|
||||
.iter()
|
||||
.find(|request| request.url.path() == "/ps/apps/batch")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
metadata_request.headers["authorization"],
|
||||
format!("Bearer {token}")
|
||||
);
|
||||
assert!(
|
||||
!metadata_request
|
||||
.headers
|
||||
.contains_key("x-openai-agent-assertion")
|
||||
);
|
||||
let proofs: HashSet<_> = requests
|
||||
.iter()
|
||||
.filter(|r| !matches!(r.url.path(), "/agent/register" | "/ps/apps/batch"))
|
||||
.map(|r| {
|
||||
assert_eq!(r.headers["chatgpt-account-id"], "workspace-a");
|
||||
let authorization = r.headers["authorization"].to_str().unwrap();
|
||||
match mode {
|
||||
RuntimeAuthMode::DualHeader => {
|
||||
assert_eq!(authorization, format!("Bearer {token}"));
|
||||
r.headers["x-openai-agent-assertion"].to_str().unwrap()
|
||||
}
|
||||
RuntimeAuthMode::AssertionOnly => {
|
||||
assert!(!r.headers.contains_key("x-openai-agent-assertion"));
|
||||
authorization.strip_prefix("AgentAssertion ").unwrap()
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(proofs.len(), 3);
|
||||
server.verify().await;
|
||||
}
|
||||
}
|
||||
|
||||
fn actor_token() -> String {
|
||||
let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json!({
|
||||
"iss": "https://auth.openai.com/", "session_id": "login-a",
|
||||
"https://api.openai.com/auth": {"user_id": "user-a", "chatgpt_account_id": "workspace-a"},
|
||||
}).to_string());
|
||||
format!("header.{claims}.signature")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn standalone_apply_keeps_custom_backend_auth_when_runtime_feature_is_enabled() {
|
||||
let server = MockServer::start().await;
|
||||
let token = actor_token();
|
||||
Mock::given(path("/task"))
|
||||
.and(wiremock::matchers::header(
|
||||
"authorization",
|
||||
format!("Bearer {token}"),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let home = tempfile::TempDir::new().unwrap();
|
||||
codex_login::auth::login_with_chatgpt_auth_tokens(
|
||||
home.path(),
|
||||
&token,
|
||||
"workspace-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
let mut config = codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
config.chatgpt_base_url = server.uri();
|
||||
config
|
||||
.features
|
||||
.enable(Feature::RuntimeAgentInstances)
|
||||
.unwrap();
|
||||
let response: serde_json::Value = chatgpt_get_request(&config, "task".into()).await.unwrap();
|
||||
assert_eq!(response, json!({"ok": true}));
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert!(!requests[0].headers.contains_key("x-openai-agent-assertion"));
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn connector_requests_reject_unsupported_openai_destinations() {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
for base_url in [
|
||||
"http://chatgpt.com",
|
||||
"https://future.openai.com/backend-api",
|
||||
] {
|
||||
let home = tempfile::TempDir::new().unwrap();
|
||||
let mut config = codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
config.chatgpt_base_url = base_url.to_string();
|
||||
config.features.enable(Feature::Apps).unwrap();
|
||||
let auth = CodexAuth::from_external_chatgpt_tokens(
|
||||
&actor_token(),
|
||||
"workspace-a",
|
||||
/*chatgpt_plan_type*/ None,
|
||||
)
|
||||
.unwrap();
|
||||
let runtime = (
|
||||
Arc::new(RuntimeAuthManager::for_chatgpt(
|
||||
AuthManager::from_auth_for_testing(auth.clone()),
|
||||
uuid::Uuid::nil().to_string(),
|
||||
base_url.to_string(),
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: Some("codex".to_string()),
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
)),
|
||||
mode,
|
||||
);
|
||||
|
||||
// Keep a broken validation path from sending the test credential to the network.
|
||||
let controller = codex_http_client::NetworkPolicyController::default();
|
||||
config.application_network_policy = controller.policy();
|
||||
assert!(controller.publish(
|
||||
config.application_network_policy.revision(),
|
||||
codex_http_client::DestinationPolicy::Restricted {
|
||||
allowed_hosts: Default::default(),
|
||||
},
|
||||
));
|
||||
|
||||
let directory_error = crate::chatgpt_connectors::list_all_connectors_with_options(
|
||||
&config,
|
||||
Some(&auth),
|
||||
Some(&runtime),
|
||||
/*force_refetch*/ true,
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
.expect_err("reject unsupported directory destination");
|
||||
let metadata_error = crate::chatgpt_connectors::read_connector_metadata(
|
||||
&config,
|
||||
&auth,
|
||||
Some(&runtime),
|
||||
&["calendar".to_string()],
|
||||
/*include_tools*/ false,
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.expect("reject unsupported metadata destination");
|
||||
for error in [directory_error, metadata_error] {
|
||||
assert!(
|
||||
matches!(
|
||||
error
|
||||
.downcast_ref::<codex_protocol::error::CodexErr>()
|
||||
.map(codex_protocol::error::CodexErr::details),
|
||||
Some(codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_))
|
||||
),
|
||||
"{base_url} ({mode:?}): {error:#}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn standalone_apply_rejects_unsupported_openai_destination() {
|
||||
let home = tempfile::TempDir::new().unwrap();
|
||||
let mut config = codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.unwrap();
|
||||
config.chatgpt_base_url = "https://future.openai.com/backend-api".into();
|
||||
config
|
||||
.features
|
||||
.enable(Feature::RuntimeAgentInstances)
|
||||
.unwrap();
|
||||
|
||||
let error = chatgpt_get_request::<serde_json::Value>(&config, "task".into())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error
|
||||
.downcast_ref::<codex_protocol::error::CodexErr>()
|
||||
.map(codex_protocol::error::CodexErr::details),
|
||||
Some(codex_protocol::error::CodexErrorDetails::UnsupportedOperation(_))
|
||||
));
|
||||
}
|
||||
@@ -1,525 +0,0 @@
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::time::Duration;
|
||||
|
||||
mod chatgpt_client;
|
||||
|
||||
use self::chatgpt_client::chatgpt_get_request_with_timeout;
|
||||
use self::chatgpt_client::chatgpt_post_request_with_timeout;
|
||||
|
||||
use codex_connectors::AppInfo;
|
||||
use codex_connectors::AppToolPolicyEvaluator;
|
||||
use codex_connectors::ConnectorDirectoryCacheContext;
|
||||
use codex_connectors::ConnectorDirectoryCacheKey;
|
||||
use codex_connectors::ConnectorMetadata;
|
||||
use codex_connectors::ConnectorMetadataStore;
|
||||
use codex_connectors::ConnectorToolSummary;
|
||||
use codex_connectors::DirectoryListResponse;
|
||||
use codex_connectors::merge::merge_connectors;
|
||||
use codex_connectors::merge::merge_plugin_connectors;
|
||||
use codex_core::config::Config;
|
||||
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools;
|
||||
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager;
|
||||
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager;
|
||||
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options;
|
||||
pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options_and_status;
|
||||
pub use codex_core::connectors::list_cached_accessible_connectors_from_mcp_tools;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_plugin::AppConnectorId;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::sync::Arc;
|
||||
|
||||
const DIRECTORY_CONNECTORS_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
const CONNECTOR_METADATA_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
const DEFAULT_APPS_PRODUCT_SKU: &str = "codex";
|
||||
|
||||
async fn apps_enabled(config: &Config) -> anyhow::Result<bool> {
|
||||
let auth_manager =
|
||||
AuthManager::shared_from_config(config, /*enable_codex_api_key_env*/ false).await?;
|
||||
let auth = auth_manager.auth().await;
|
||||
Ok(config
|
||||
.features
|
||||
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend)))
|
||||
}
|
||||
|
||||
pub async fn list_connectors(config: &Config) -> anyhow::Result<Vec<AppInfo>> {
|
||||
if !apps_enabled(config).await? {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let (connectors_result, accessible_result) = tokio::join!(
|
||||
list_all_connectors(config),
|
||||
list_accessible_connectors_from_mcp_tools(config),
|
||||
);
|
||||
let connectors = connectors_result?;
|
||||
let accessible = accessible_result?;
|
||||
Ok(
|
||||
AppToolPolicyEvaluator::new(&config.config_layer_stack).apply_app_enabled_state(
|
||||
merge_connectors_with_accessible(
|
||||
connectors, accessible, /*all_connectors_loaded*/ true,
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
pub async fn list_all_connectors(config: &Config) -> anyhow::Result<Vec<AppInfo>> {
|
||||
if !apps_enabled(config).await? {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut config = config.clone();
|
||||
let (auth, runtime) = self::chatgpt_client::standalone_auth(&mut config).await?;
|
||||
list_all_connectors_with_options(
|
||||
&config,
|
||||
Some(&auth),
|
||||
runtime.as_ref(),
|
||||
/*force_refetch*/ false,
|
||||
&[],
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn list_cached_all_connectors(
|
||||
config: &Config,
|
||||
auth: Option<&CodexAuth>,
|
||||
plugin_apps: &[AppConnectorId],
|
||||
) -> Option<Vec<AppInfo>> {
|
||||
if !config
|
||||
.features
|
||||
.apps_enabled_for_auth(auth.is_some_and(CodexAuth::uses_codex_backend))
|
||||
{
|
||||
return Some(Vec::new());
|
||||
}
|
||||
|
||||
let auth = auth?;
|
||||
let cache_context = connector_directory_cache_context(config, auth);
|
||||
let connectors = codex_connectors::cached_directory_connectors(&cache_context)?;
|
||||
Some(merge_directory_and_plugin_connectors(
|
||||
connectors.to_vec(),
|
||||
plugin_apps,
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn list_all_connectors_with_options(
|
||||
config: &Config,
|
||||
auth: Option<&CodexAuth>,
|
||||
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
force_refetch: bool,
|
||||
plugin_apps: &[AppConnectorId],
|
||||
) -> anyhow::Result<Vec<AppInfo>> {
|
||||
if !config
|
||||
.features
|
||||
.apps_enabled_for_auth(auth.is_some_and(CodexAuth::uses_codex_backend))
|
||||
{
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let auth = auth.ok_or_else(|| anyhow::anyhow!("ChatGPT auth not available"))?;
|
||||
let runtime = codex_model_provider::runtime_auth_for_url(runtime, &config.chatgpt_base_url)?;
|
||||
let cache_context = connector_directory_cache_context(config, auth);
|
||||
let connectors = codex_connectors::list_all_connectors_with_options(
|
||||
cache_context,
|
||||
auth.is_workspace_account(),
|
||||
force_refetch,
|
||||
|path| async move {
|
||||
chatgpt_get_request_with_timeout::<DirectoryListResponse>(
|
||||
config,
|
||||
auth,
|
||||
runtime,
|
||||
path,
|
||||
Some(DIRECTORY_CONNECTORS_TIMEOUT),
|
||||
)
|
||||
.await
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(merge_directory_and_plugin_connectors(
|
||||
connectors,
|
||||
plugin_apps,
|
||||
))
|
||||
}
|
||||
|
||||
pub struct ConnectorMetadataReadResult {
|
||||
pub apps: Vec<ConnectorMetadata>,
|
||||
pub missing_app_ids: Vec<String>,
|
||||
}
|
||||
|
||||
/// Reads display metadata without loading MCP connector tools or runtime state.
|
||||
///
|
||||
/// The store is created before awaiting the backend request, so a response that arrives after an
|
||||
/// account or backend change can only commit to the scope under which it was requested.
|
||||
/// Capture `auth` and `config.application_network_policy` together using
|
||||
/// `AuthManager::auth_with_http_client_factory` so the request retains that account's policy.
|
||||
pub async fn read_connector_metadata(
|
||||
config: &Config,
|
||||
auth: &CodexAuth,
|
||||
runtime: Option<&(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
app_ids: &[String],
|
||||
include_tools: bool,
|
||||
) -> anyhow::Result<ConnectorMetadataReadResult> {
|
||||
anyhow::ensure!(
|
||||
auth.uses_codex_backend(),
|
||||
"ChatGPT backend requests require Codex backend auth"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
auth.get_account_id().is_some(),
|
||||
"ChatGPT account ID not available, please re-run codex login"
|
||||
);
|
||||
|
||||
let runtime = codex_model_provider::runtime_auth_for_url(runtime, &config.chatgpt_base_url)?;
|
||||
let store = ConnectorMetadataStore::new(
|
||||
config.chatgpt_base_url.clone(),
|
||||
auth.get_account_id(),
|
||||
auth.get_chatgpt_user_id(),
|
||||
auth.is_workspace_account(),
|
||||
);
|
||||
let mut metadata_by_id = store.fresh_records(app_ids, include_tools);
|
||||
let missing_ids = app_ids
|
||||
.iter()
|
||||
.filter(|app_id| !metadata_by_id.contains_key(app_id.as_str()))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
if !missing_ids.is_empty() {
|
||||
let product_sku = config
|
||||
.apps_mcp_product_sku
|
||||
.as_deref()
|
||||
.unwrap_or(DEFAULT_APPS_PRODUCT_SKU);
|
||||
let response: GetAppsResponse = chatgpt_post_request_with_timeout(
|
||||
config,
|
||||
auth,
|
||||
"/ps/apps/batch".to_string(),
|
||||
&GetAppsRequest {
|
||||
app_ids: &missing_ids,
|
||||
include_tools,
|
||||
},
|
||||
CONNECTOR_METADATA_TIMEOUT,
|
||||
product_sku,
|
||||
runtime,
|
||||
)
|
||||
.await?;
|
||||
let mut requested_ids = missing_ids.iter().cloned().collect::<HashSet<_>>();
|
||||
let fetched = response
|
||||
.apps
|
||||
.into_iter()
|
||||
.map(batch_app_to_metadata)
|
||||
.filter(|metadata| requested_ids.remove(&metadata.id))
|
||||
.collect::<Vec<_>>();
|
||||
store.commit(&fetched);
|
||||
metadata_by_id.extend(
|
||||
fetched
|
||||
.into_iter()
|
||||
.map(|metadata| (metadata.id.clone(), metadata)),
|
||||
);
|
||||
}
|
||||
|
||||
let mut apps = Vec::new();
|
||||
let mut missing_app_ids = Vec::new();
|
||||
for app_id in app_ids {
|
||||
if let Some(mut metadata) = metadata_by_id.remove(app_id) {
|
||||
if !include_tools {
|
||||
metadata.tool_summaries = None;
|
||||
}
|
||||
apps.push(metadata);
|
||||
} else {
|
||||
missing_app_ids.push(app_id.clone());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ConnectorMetadataReadResult {
|
||||
apps,
|
||||
missing_app_ids,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct GetAppsRequest<'a> {
|
||||
app_ids: &'a [String],
|
||||
include_tools: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GetAppsResponse {
|
||||
apps: Vec<BatchApp>,
|
||||
}
|
||||
|
||||
/// The explicit metadata-only projection of Plugin Service's public app response.
|
||||
///
|
||||
/// Serde ignores all other backend fields, including full actions, model descriptions, and
|
||||
/// runtime state.
|
||||
#[derive(Deserialize)]
|
||||
struct BatchApp {
|
||||
id: String,
|
||||
name: String,
|
||||
description: Option<String>,
|
||||
icon_url: Option<String>,
|
||||
#[serde(default, rename = "icon_dark_url", alias = "icon_url_dark")]
|
||||
icon_url_dark: Option<String>,
|
||||
#[serde(default)]
|
||||
distribution_channel: Option<String>,
|
||||
#[serde(default)]
|
||||
tools: Option<Vec<BatchAppToolSummary>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct BatchAppToolSummary {
|
||||
name: String,
|
||||
title: Option<String>,
|
||||
description: String,
|
||||
#[serde(default)]
|
||||
is_enabled: Option<bool>,
|
||||
#[serde(default)]
|
||||
disabled_reason: Option<String>,
|
||||
#[serde(default)]
|
||||
is_read_only: bool,
|
||||
}
|
||||
|
||||
fn batch_app_to_metadata(app: BatchApp) -> ConnectorMetadata {
|
||||
let BatchApp {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
icon_url,
|
||||
icon_url_dark,
|
||||
distribution_channel,
|
||||
tools,
|
||||
} = app;
|
||||
ConnectorMetadata {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
icon_url,
|
||||
icon_url_dark,
|
||||
distribution_channel,
|
||||
tool_summaries: tools.map(|tools| {
|
||||
tools
|
||||
.into_iter()
|
||||
.map(|tool| {
|
||||
let BatchAppToolSummary {
|
||||
name,
|
||||
title,
|
||||
description,
|
||||
is_enabled,
|
||||
disabled_reason,
|
||||
is_read_only,
|
||||
} = tool;
|
||||
ConnectorToolSummary {
|
||||
name,
|
||||
title,
|
||||
description,
|
||||
is_enabled: is_enabled.unwrap_or(true),
|
||||
disabled_reason,
|
||||
is_read_only,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn connector_directory_cache_context(
|
||||
config: &Config,
|
||||
auth: &CodexAuth,
|
||||
) -> ConnectorDirectoryCacheContext {
|
||||
ConnectorDirectoryCacheContext::new(
|
||||
config.codex_home.to_path_buf(),
|
||||
ConnectorDirectoryCacheKey::new(
|
||||
config.chatgpt_base_url.clone(),
|
||||
auth.get_account_id(),
|
||||
auth.get_chatgpt_user_id(),
|
||||
auth.is_workspace_account(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn merge_directory_and_plugin_connectors(
|
||||
connectors: Vec<AppInfo>,
|
||||
plugin_apps: &[AppConnectorId],
|
||||
) -> Vec<AppInfo> {
|
||||
merge_plugin_connectors(
|
||||
connectors,
|
||||
plugin_apps
|
||||
.iter()
|
||||
.map(|connector_id| connector_id.0.clone()),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn connectors_for_plugin_apps(
|
||||
connectors: Vec<AppInfo>,
|
||||
plugin_apps: &[AppConnectorId],
|
||||
) -> Vec<AppInfo> {
|
||||
let connectors = merge_plugin_connectors(
|
||||
connectors,
|
||||
plugin_apps
|
||||
.iter()
|
||||
.map(|connector_id| connector_id.0.clone()),
|
||||
);
|
||||
let mut connectors_by_id = connectors
|
||||
.into_iter()
|
||||
.map(|connector| (connector.id.clone(), connector))
|
||||
.collect::<HashMap<_, _>>();
|
||||
|
||||
plugin_apps
|
||||
.iter()
|
||||
.filter_map(|connector_id| connectors_by_id.remove(connector_id.0.as_str()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn merge_connectors_with_accessible(
|
||||
connectors: Vec<AppInfo>,
|
||||
accessible_connectors: Vec<AppInfo>,
|
||||
all_connectors_loaded: bool,
|
||||
) -> Vec<AppInfo> {
|
||||
let accessible_connectors = if all_connectors_loaded {
|
||||
let connector_ids: HashSet<&str> = connectors
|
||||
.iter()
|
||||
.map(|connector| connector.id.as_str())
|
||||
.collect();
|
||||
accessible_connectors
|
||||
.into_iter()
|
||||
.filter(|connector| connector_ids.contains(connector.id.as_str()))
|
||||
.collect()
|
||||
} else {
|
||||
accessible_connectors
|
||||
};
|
||||
merge_connectors(connectors, accessible_connectors)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use codex_connectors::metadata::connector_install_url;
|
||||
use codex_plugin::AppConnectorId;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn batch_app_accepts_missing_optional_metadata() {
|
||||
let app = serde_json::from_value::<BatchApp>(json!({
|
||||
"id": "alpha",
|
||||
"name": "Alpha",
|
||||
"description": "Alpha description",
|
||||
"icon_url": null,
|
||||
"tools": [{
|
||||
"name": "search",
|
||||
"title": "Search",
|
||||
"description": "Search Alpha",
|
||||
}],
|
||||
}))
|
||||
.expect("valid legacy batch app");
|
||||
|
||||
assert_eq!(
|
||||
batch_app_to_metadata(app),
|
||||
ConnectorMetadata {
|
||||
id: "alpha".to_string(),
|
||||
name: "Alpha".to_string(),
|
||||
description: Some("Alpha description".to_string()),
|
||||
icon_url: None,
|
||||
icon_url_dark: None,
|
||||
distribution_channel: None,
|
||||
tool_summaries: Some(vec![ConnectorToolSummary {
|
||||
name: "search".to_string(),
|
||||
title: Some("Search".to_string()),
|
||||
description: "Search Alpha".to_string(),
|
||||
is_enabled: true,
|
||||
disabled_reason: None,
|
||||
is_read_only: false,
|
||||
}]),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
fn app(id: &str) -> AppInfo {
|
||||
AppInfo {
|
||||
id: id.to_string(),
|
||||
name: id.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(),
|
||||
}
|
||||
}
|
||||
|
||||
fn merged_app(id: &str, is_accessible: bool) -> AppInfo {
|
||||
AppInfo {
|
||||
id: id.to_string(),
|
||||
name: id.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: Some(connector_install_url(id, id)),
|
||||
is_accessible,
|
||||
is_enabled: true,
|
||||
plugin_display_names: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn excludes_accessible_connectors_not_in_all_when_all_loaded() {
|
||||
let merged = merge_connectors_with_accessible(
|
||||
vec![app("alpha")],
|
||||
vec![app("alpha"), app("beta")],
|
||||
/*all_connectors_loaded*/ true,
|
||||
);
|
||||
assert_eq!(merged, vec![merged_app("alpha", /*is_accessible*/ true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_accessible_connectors_not_in_all_while_all_loading() {
|
||||
let merged = merge_connectors_with_accessible(
|
||||
vec![app("alpha")],
|
||||
vec![app("alpha"), app("beta")],
|
||||
/*all_connectors_loaded*/ false,
|
||||
);
|
||||
assert_eq!(
|
||||
merged,
|
||||
vec![
|
||||
merged_app("alpha", /*is_accessible*/ true),
|
||||
merged_app("beta", /*is_accessible*/ true)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connectors_for_plugin_apps_returns_only_requested_plugin_apps() {
|
||||
let connectors = connectors_for_plugin_apps(
|
||||
vec![app("alpha"), app("beta")],
|
||||
&[
|
||||
AppConnectorId("gmail".to_string()),
|
||||
AppConnectorId("alpha".to_string()),
|
||||
AppConnectorId("gmail".to_string()),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
connectors,
|
||||
vec![merged_app("gmail", /*is_accessible*/ false), app("alpha")]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn connectors_for_plugin_apps_preserves_formerly_disallowed_plugin_apps() {
|
||||
let connector_id = "asdk_app_6938a94a61d881918ef32cb999ff937c";
|
||||
let connectors =
|
||||
connectors_for_plugin_apps(Vec::new(), &[AppConnectorId(connector_id.to_string())]);
|
||||
assert_eq!(
|
||||
connectors,
|
||||
vec![merged_app(connector_id, /*is_accessible*/ false)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,5 @@
|
||||
use codex_app_server_protocol::ModelProviderError;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_cloud_config::managed_config_bundle_loader;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::LoaderOverrides;
|
||||
@@ -191,37 +190,14 @@ impl ConfigManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// aKode never fetches managed config bundles from a remote service, so an
|
||||
/// auth change only resets any previously installed loader.
|
||||
pub(crate) fn update_managed_config_loader(
|
||||
&self,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
config: &Config,
|
||||
_auth_manager: Arc<AuthManager>,
|
||||
_config: &Config,
|
||||
) {
|
||||
// Keep config-server settings and their refresh worker when only
|
||||
// ChatGPT/API-key credentials change.
|
||||
if self
|
||||
.current_managed_config_loader()
|
||||
.config_server()
|
||||
.is_some()
|
||||
{
|
||||
self.revoke_mcp_ema();
|
||||
return;
|
||||
}
|
||||
let loader = managed_config_bundle_loader(
|
||||
auth_manager,
|
||||
config.chatgpt_base_url.clone(),
|
||||
self.codex_home.clone(),
|
||||
config
|
||||
.http_client_factory()
|
||||
.with_network_policy(self.local_network_policy.policy()),
|
||||
config.config_layer_stack.requirements_toml(),
|
||||
);
|
||||
if let Ok(mut guard) = self.cloud_config_bundle.write() {
|
||||
guard.retire_ema_policy();
|
||||
*guard = loader;
|
||||
} else {
|
||||
warn!("failed to update cloud config bundle loader");
|
||||
}
|
||||
self.revoke_mcp_ema();
|
||||
self.clear_chatgpt_config_loader();
|
||||
}
|
||||
|
||||
pub(crate) fn clear_chatgpt_config_loader(&self) {
|
||||
|
||||
@@ -18,7 +18,6 @@ use codex_extension_api::ExtensionWarning;
|
||||
use codex_extension_api::TurnStartAdmission;
|
||||
use codex_goal_extension::GoalExtensionConfig;
|
||||
use codex_goal_extension::GoalService;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_login::AuthManager;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::Event;
|
||||
@@ -42,8 +41,6 @@ pub(crate) struct ThreadExtensionDependencies {
|
||||
pub(crate) environment_manager: Arc<EnvironmentManager>,
|
||||
pub(crate) executor_skill_provider: Arc<dyn codex_skills_extension::SkillProvider>,
|
||||
pub(crate) cloud_skill_provider: Option<Arc<dyn codex_skills_extension::SkillProvider>>,
|
||||
pub(crate) git_attribution_base_url: String,
|
||||
pub(crate) http_client_factory: HttpClientFactory,
|
||||
/// Process-scoped queue shared by idle dispatch and app-server requests.
|
||||
pub(crate) queue_service: Option<Arc<QueuedItemService>>,
|
||||
pub(crate) turn_start_admission: Option<Arc<dyn TurnStartAdmission>>,
|
||||
@@ -64,8 +61,6 @@ pub(crate) fn thread_extensions(
|
||||
environment_manager,
|
||||
executor_skill_provider,
|
||||
cloud_skill_provider,
|
||||
git_attribution_base_url,
|
||||
http_client_factory,
|
||||
queue_service,
|
||||
turn_start_admission,
|
||||
} = dependencies;
|
||||
@@ -98,15 +93,9 @@ pub(crate) fn thread_extensions(
|
||||
},
|
||||
);
|
||||
}
|
||||
codex_git_attribution::install(
|
||||
&mut builder,
|
||||
auth_manager.clone(),
|
||||
git_attribution_base_url,
|
||||
http_client_factory,
|
||||
);
|
||||
codex_git_attribution::install(&mut builder);
|
||||
codex_guardian_v2::install(&mut builder, thread_manager);
|
||||
codex_memories_extension::install(&mut builder, codex_otel::global());
|
||||
codex_mcp_extension::install(&mut builder);
|
||||
codex_mcp_extension::install_plugins(&mut builder, environment_manager);
|
||||
codex_web_search_extension::install(&mut builder, auth_manager.clone());
|
||||
codex_image_generation_extension::install(&mut builder, auth_manager, |config: &Config| {
|
||||
|
||||
@@ -67,35 +67,6 @@ impl EmbeddedNetworkPolicy {
|
||||
pub fn bind_config(&self, config: &mut Config) {
|
||||
config.application_network_policy = self.effective.policy();
|
||||
}
|
||||
|
||||
/// Limits cloud discovery and each authentication request to their exact local-policy endpoints.
|
||||
pub fn bind_bootstrap_auth(
|
||||
&self,
|
||||
mut auth: codex_login::AuthConfig,
|
||||
) -> codex_login::AuthConfig {
|
||||
let factory = auth
|
||||
.auth_route_config
|
||||
.http_client_factory()
|
||||
.clone()
|
||||
.with_network_policy(self.local.policy());
|
||||
let endpoint = codex_backend_client::Client::new(
|
||||
auth.chatgpt_base_url
|
||||
.as_deref()
|
||||
.unwrap_or("https://chatgpt.com/backend-api/"),
|
||||
factory.clone(),
|
||||
)
|
||||
.config_bundle_url();
|
||||
auth.auth_route_config = codex_login::AuthRouteConfig::from_http_client_factory(
|
||||
factory.clone().with_network_policy(
|
||||
self.local
|
||||
.policy()
|
||||
.restrict_to_endpoints(endpoint.parse().into_iter().collect()),
|
||||
),
|
||||
)
|
||||
.with_local_bootstrap_factory(factory)
|
||||
.with_application_network_policy(self.effective.policy());
|
||||
auth
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn configure(
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
//! Embedded startup preserves caller configuration and bootstrap access across authentication.
|
||||
|
||||
use super::EmbeddedNetworkPolicy;
|
||||
use super::configure;
|
||||
use crate::config_manager::ConfigManager;
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::LoaderOverrides;
|
||||
@@ -12,138 +9,12 @@ use codex_config::NoopThreadConfigLoader;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::config::ConfigOverrides;
|
||||
use codex_core::config::set_project_trust_level;
|
||||
use codex_http_client::DestinationPolicy;
|
||||
use codex_http_client::HttpClientFactory;
|
||||
use codex_http_client::NetworkPermit;
|
||||
use codex_http_client::NetworkPolicyDenied;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use codex_model_provider::DEFAULT_CHATGPT_BASE_URL;
|
||||
use codex_protocol::config_types::TrustLevel;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct BootstrapExternalAuth(CodexAuth);
|
||||
|
||||
impl ExternalAuth for BootstrapExternalAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
|
||||
fn refresh(&self, _context: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bootstrap_discovery_survives_identity_installation_but_account_access_is_revoked()
|
||||
-> anyhow::Result<()> {
|
||||
let home = tempfile::tempdir()?;
|
||||
let overrides = LoaderOverrides::without_managed_config_for_tests();
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.loader_overrides(overrides.clone())
|
||||
.build()
|
||||
.await?;
|
||||
let policy = EmbeddedNetworkPolicy::load(&overrides).await;
|
||||
let auth_config = policy.bind_bootstrap_auth(config.auth_config());
|
||||
let bootstrap = auth_config.auth_route_config.http_client_factory().clone();
|
||||
let bundle_url =
|
||||
codex_backend_client::Client::new(config.chatgpt_base_url.clone(), bootstrap.clone())
|
||||
.config_bundle_url()
|
||||
.parse()?;
|
||||
let content_url = "https://chatgpt.com/backend-api/codex/responses".parse()?;
|
||||
let manager = AuthManager::new(
|
||||
home.path().to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::Ephemeral,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
Some(config.chatgpt_base_url.clone()),
|
||||
AuthKeyringBackendKind::default(),
|
||||
auth_config.auth_route_config,
|
||||
)
|
||||
.await;
|
||||
assert!(manager.auth_cached().is_none());
|
||||
|
||||
bootstrap.network_policy().acquire(&bundle_url)?;
|
||||
let mut previous_access: Option<(HttpClientFactory, NetworkPermit)> = None;
|
||||
for identity in ["bootstrap-account-one", "bootstrap-account-two"] {
|
||||
let token = format!(
|
||||
"e30.{}.signature",
|
||||
URL_SAFE_NO_PAD.encode(serde_json::to_vec(&serde_json::json!({
|
||||
"sub": "bootstrap-user",
|
||||
"https://api.openai.com/auth": {
|
||||
"chatgpt_user_id": "bootstrap-user",
|
||||
"chatgpt_account_id": identity,
|
||||
},
|
||||
}))?),
|
||||
);
|
||||
let auth = CodexAuth::from_external_chatgpt_tokens(&token, identity, Some("enterprise"))?;
|
||||
manager
|
||||
.set_external_auth(Arc::new(BootstrapExternalAuth(auth)))
|
||||
.await?;
|
||||
|
||||
if let Some((client, permit)) = previous_access.take() {
|
||||
assert_eq!(permit.check(), Err(NetworkPolicyDenied::Revoked));
|
||||
assert_eq!(
|
||||
client.network_policy().acquire(&content_url).err(),
|
||||
Some(NetworkPolicyDenied::Revoked)
|
||||
);
|
||||
}
|
||||
|
||||
// Discovery must remain possible after both initial login and a workspace change.
|
||||
bootstrap.network_policy().acquire(&bundle_url)?;
|
||||
assert_eq!(
|
||||
bootstrap.network_policy().acquire(&content_url).err(),
|
||||
Some(NetworkPolicyDenied::Destination)
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.application_network_policy()
|
||||
.acquire(&content_url)
|
||||
.err(),
|
||||
Some(NetworkPolicyDenied::Unavailable)
|
||||
);
|
||||
|
||||
assert!(policy.effective.publish(
|
||||
policy.effective.policy().revision(),
|
||||
DestinationPolicy::Unrestricted,
|
||||
));
|
||||
let client = manager.http_client_factory();
|
||||
let permit = client.network_policy().acquire(&content_url)?;
|
||||
previous_access = Some((client, permit));
|
||||
}
|
||||
|
||||
let (client, permit) = previous_access.expect("the last identity has active account access");
|
||||
manager.clear_external_auth();
|
||||
assert_eq!(permit.check(), Err(NetworkPolicyDenied::Revoked));
|
||||
assert_eq!(
|
||||
client.network_policy().acquire(&content_url).err(),
|
||||
Some(NetworkPolicyDenied::Revoked)
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.application_network_policy()
|
||||
.acquire(&content_url)
|
||||
.err(),
|
||||
Some(NetworkPolicyDenied::Unavailable)
|
||||
);
|
||||
bootstrap.network_policy().acquire(&bundle_url)?;
|
||||
|
||||
// Losing local requirements must still close the bootstrap route.
|
||||
policy.local.unavailable(policy.local.policy().revision());
|
||||
assert_eq!(
|
||||
bootstrap.network_policy().acquire(&bundle_url).err(),
|
||||
Some(NetworkPolicyDenied::Unavailable)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn startup_reloads_the_callers_selected_project() -> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
|
||||
@@ -99,13 +99,11 @@ pub use codex_agent_message_board_host::delete_agent_message_boards;
|
||||
pub use codex_agent_message_board_host::install_agent_message_board;
|
||||
|
||||
mod analytics_utils;
|
||||
mod app_info;
|
||||
mod app_server_tracing;
|
||||
mod attestation;
|
||||
mod auth_mode;
|
||||
mod bespoke_event_handling;
|
||||
#[doc(hidden)]
|
||||
pub mod chatgpt_connectors;
|
||||
mod code_mode_host;
|
||||
mod codex_home_metrics;
|
||||
mod command_exec;
|
||||
@@ -155,7 +153,6 @@ mod thread_state;
|
||||
mod thread_status;
|
||||
mod transport;
|
||||
mod turn_admission;
|
||||
mod turn_cost_worker;
|
||||
mod user_verification;
|
||||
mod user_verification_response;
|
||||
|
||||
|
||||
@@ -560,8 +560,6 @@ enabled = false
|
||||
goal_service: Arc::new(codex_goal_extension::GoalService::new()),
|
||||
environment_manager: Arc::clone(&environment_manager),
|
||||
executor_skill_provider: Arc::clone(&executor_skill_provider),
|
||||
git_attribution_base_url: good_config.chatgpt_base_url.clone(),
|
||||
http_client_factory: good_config.http_client_factory(),
|
||||
queue_service: None,
|
||||
turn_start_admission: None,
|
||||
},
|
||||
|
||||
@@ -26,7 +26,6 @@ use crate::outgoing_message::RequestContext;
|
||||
use crate::plugin_config_reload;
|
||||
use crate::plugin_config_reload::PluginStartupConfig;
|
||||
use crate::request_processors::AccountRequestProcessor;
|
||||
use crate::request_processors::AppsRequestProcessor;
|
||||
use crate::request_processors::CatalogRequestProcessor;
|
||||
use crate::request_processors::CommandExecRequestProcessor;
|
||||
use crate::request_processors::ConfigRequestProcessor;
|
||||
@@ -61,7 +60,6 @@ use crate::thread_state::ConnectionCapabilities;
|
||||
use crate::thread_state::ThreadStateManager;
|
||||
use crate::transport::AppServerTransport;
|
||||
use crate::transport::RemoteControlHandle;
|
||||
use crate::turn_cost_worker::TurnCostWorker;
|
||||
use codex_analytics::AnalyticsEventsClient;
|
||||
use codex_analytics::AppServerRpcTransport;
|
||||
use codex_app_server_protocol::ClientNotification;
|
||||
@@ -155,10 +153,8 @@ pub(crate) struct MessageProcessor {
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
startup_warnings: StartupWarnings,
|
||||
models_refresh_worker: ModelsRefreshWorker,
|
||||
turn_cost_worker: Option<TurnCostWorker>,
|
||||
skills_watcher: Arc<SkillsWatcher>,
|
||||
account_processor: Arc<AccountRequestProcessor>,
|
||||
apps_processor: AppsRequestProcessor,
|
||||
catalog_processor: CatalogRequestProcessor,
|
||||
command_exec_processor: CommandExecRequestProcessor,
|
||||
process_exec_processor: ProcessExecRequestProcessor,
|
||||
@@ -400,8 +396,6 @@ impl MessageProcessor {
|
||||
environment_manager: Arc::clone(&environment_manager_for_extensions),
|
||||
executor_skill_provider: Arc::clone(&executor_skill_provider),
|
||||
cloud_skill_provider: cloud_skill_provider.clone(),
|
||||
git_attribution_base_url: config.chatgpt_base_url.clone(),
|
||||
http_client_factory: config.http_client_factory(),
|
||||
queue_service: queue_service.clone(),
|
||||
turn_start_admission: Some(Arc::clone(&turn_start_admission)),
|
||||
},
|
||||
@@ -440,11 +434,6 @@ impl MessageProcessor {
|
||||
Arc::clone(&thread_manager),
|
||||
));
|
||||
let models_refresh_worker = crate::models_refresh_worker::spawn(&model_catalog);
|
||||
let turn_cost_worker = TurnCostWorker::spawn(
|
||||
Arc::clone(&config),
|
||||
Arc::clone(&auth_manager),
|
||||
runtime_auth.map(|runtime| (runtime, config.runtime_auth_mode)),
|
||||
);
|
||||
thread_manager
|
||||
.plugins_manager()
|
||||
.set_analytics_events_client(analytics_events_client.clone());
|
||||
@@ -458,7 +447,6 @@ impl MessageProcessor {
|
||||
let thread_watch_manager =
|
||||
crate::thread_status::ThreadWatchManager::new_with_outgoing(outgoing.clone());
|
||||
let thread_list_state_permit = Arc::new(Semaphore::new(/*permits*/ 1));
|
||||
let app_list_shutdown_token = CancellationToken::new();
|
||||
let request_serialization_queues = RequestSerializationQueues::default();
|
||||
let config_processor = ConfigRequestProcessor::new(
|
||||
outgoing.clone(),
|
||||
@@ -483,12 +471,6 @@ impl MessageProcessor {
|
||||
config_manager.clone(),
|
||||
Arc::clone(&model_catalog),
|
||||
);
|
||||
let apps_processor = AppsRequestProcessor::new(
|
||||
Arc::clone(&thread_manager),
|
||||
outgoing.clone(),
|
||||
config_manager.clone(),
|
||||
app_list_shutdown_token,
|
||||
);
|
||||
let catalog_processor = CatalogRequestProcessor::new(
|
||||
outgoing.clone(),
|
||||
Arc::clone(&skills_watcher),
|
||||
@@ -574,7 +556,6 @@ impl MessageProcessor {
|
||||
state_db.clone(),
|
||||
log_db,
|
||||
Arc::clone(&skills_watcher),
|
||||
turn_cost_worker.as_ref().map(TurnCostWorker::handle),
|
||||
config_warnings.clone(),
|
||||
sample_responses,
|
||||
);
|
||||
@@ -588,7 +569,6 @@ impl MessageProcessor {
|
||||
thread_state_manager,
|
||||
thread_watch_manager,
|
||||
Arc::clone(&skills_watcher),
|
||||
turn_cost_worker.as_ref().map(TurnCostWorker::handle),
|
||||
);
|
||||
if let Some(startup_config) = plugin_startup_tasks {
|
||||
let reload_config = match startup_config {
|
||||
@@ -650,10 +630,8 @@ impl MessageProcessor {
|
||||
config: config_warnings,
|
||||
},
|
||||
models_refresh_worker,
|
||||
turn_cost_worker,
|
||||
skills_watcher,
|
||||
account_processor,
|
||||
apps_processor,
|
||||
catalog_processor,
|
||||
command_exec_processor,
|
||||
process_exec_processor,
|
||||
@@ -681,7 +659,6 @@ impl MessageProcessor {
|
||||
|
||||
pub(crate) fn clear_runtime_references(&self) {
|
||||
self.account_processor.clear_external_auth();
|
||||
self.apps_processor.shutdown();
|
||||
self.models_refresh_worker.shutdown();
|
||||
self.skills_watcher.shutdown();
|
||||
}
|
||||
@@ -915,9 +892,6 @@ impl MessageProcessor {
|
||||
|
||||
pub(crate) async fn drain_background_tasks(&self) {
|
||||
self.models_refresh_worker.shutdown();
|
||||
if let Some(worker) = &self.turn_cost_worker {
|
||||
worker.shutdown();
|
||||
}
|
||||
self.thread_processor.drain_background_tasks().await;
|
||||
}
|
||||
|
||||
@@ -1706,15 +1680,22 @@ impl MessageProcessor {
|
||||
ClientRequest::PluginShareDelete { params, .. } => {
|
||||
self.plugin_processor.plugin_share_delete(params).await
|
||||
}
|
||||
ClientRequest::AppsRead { params, .. } => self.apps_processor.apps_read(params).await,
|
||||
ClientRequest::AppsList { params, .. } => {
|
||||
self.apps_processor.apps_list(&request_id, params).await
|
||||
// ChatGPT apps/connectors are not available in aKode.
|
||||
ClientRequest::AppsRead { .. } => Err(method_not_found(
|
||||
"ChatGPT apps are not available in aKode",
|
||||
)),
|
||||
ClientRequest::AppsList { .. } => Ok(Some(
|
||||
codex_app_server_protocol::AppsListResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
}
|
||||
.into(),
|
||||
)),
|
||||
ClientRequest::AppsInstalled { .. } => {
|
||||
Ok(Some(
|
||||
codex_app_server_protocol::AppsInstalledResponse { apps: Vec::new() }.into(),
|
||||
))
|
||||
}
|
||||
ClientRequest::AppsInstalled { params, .. } => self
|
||||
.apps_processor
|
||||
.apps_installed(params)
|
||||
.await
|
||||
.map(|response| Some(response.into())),
|
||||
ClientRequest::SkillsConfigWrite { params, .. } => {
|
||||
self.catalog_processor.skills_config_write(params).await
|
||||
}
|
||||
@@ -1948,25 +1929,13 @@ impl MessageProcessor {
|
||||
.await
|
||||
.into(),
|
||||
)),
|
||||
ClientRequest::GetAccountRateLimits { params, .. } => {
|
||||
self.account_processor.get_account_rate_limits(params).await
|
||||
}
|
||||
ClientRequest::ConsumeAccountRateLimitResetCredit { params, .. } => {
|
||||
self.account_processor
|
||||
.consume_account_rate_limit_reset_credit(params)
|
||||
.await
|
||||
}
|
||||
ClientRequest::GetAccountTokenUsage { params, .. } => {
|
||||
self.account_processor.get_account_token_usage(params).await
|
||||
}
|
||||
ClientRequest::GetWorkspaceMessages { .. } => {
|
||||
self.account_processor.get_workspace_messages().await
|
||||
}
|
||||
ClientRequest::SendAddCreditsNudgeEmail { params, .. } => {
|
||||
self.account_processor
|
||||
.send_add_credits_nudge_email(params)
|
||||
.await
|
||||
}
|
||||
ClientRequest::GetAccountRateLimits { .. }
|
||||
| ClientRequest::ConsumeAccountRateLimitResetCredit { .. }
|
||||
| ClientRequest::GetAccountTokenUsage { .. }
|
||||
| ClientRequest::GetWorkspaceMessages { .. }
|
||||
| ClientRequest::SendAddCreditsNudgeEmail { .. } => Err(method_not_found(
|
||||
"ChatGPT usage, credits and workspace messages are not available in aKode",
|
||||
)),
|
||||
ClientRequest::GitDiffToRemote { params, .. } => {
|
||||
self.git_processor.git_diff_to_remote(params).await
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use crate::bespoke_event_handling::apply_bespoke_event_handling;
|
||||
use crate::chatgpt_connectors as connectors;
|
||||
use crate::command_exec::CommandExecManager;
|
||||
use crate::command_exec::StartCommandExecParams;
|
||||
use crate::config_manager::ConfigManager;
|
||||
@@ -22,23 +21,12 @@ use codex_analytics::InputError;
|
||||
use codex_analytics::TurnSteerRequestError;
|
||||
use codex_app_server_protocol::Account;
|
||||
use codex_app_server_protocol::AccountLoginCompletedNotification;
|
||||
use codex_app_server_protocol::AccountTokenUsageDailyBucket;
|
||||
use codex_app_server_protocol::AccountTokenUsageSummary;
|
||||
use codex_app_server_protocol::AccountUpdatedNotification;
|
||||
use codex_app_server_protocol::AddCreditsNudgeCreditType;
|
||||
use codex_app_server_protocol::AddCreditsNudgeEmailStatus;
|
||||
use codex_app_server_protocol::AdditionalContextEntry;
|
||||
use codex_app_server_protocol::AdditionalContextKind;
|
||||
use codex_app_server_protocol::AppListUpdatedNotification;
|
||||
use codex_app_server_protocol::AppSummary;
|
||||
use codex_app_server_protocol::AppTemplateSummary;
|
||||
use codex_app_server_protocol::AppTemplateUnavailableReason;
|
||||
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::AppsReadParams;
|
||||
use codex_app_server_protocol::AppsReadResponse;
|
||||
use codex_app_server_protocol::AskForApproval;
|
||||
use codex_app_server_protocol::AuthMode;
|
||||
use codex_app_server_protocol::CancelLoginAccountParams;
|
||||
@@ -55,9 +43,6 @@ use codex_app_server_protocol::CommandExecResizeParams;
|
||||
use codex_app_server_protocol::CommandExecTerminateParams;
|
||||
use codex_app_server_protocol::CommandExecWriteParams;
|
||||
use codex_app_server_protocol::ConfigWarningNotification;
|
||||
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditOutcome;
|
||||
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditParams;
|
||||
use codex_app_server_protocol::ConsumeAccountRateLimitResetCreditResponse;
|
||||
use codex_app_server_protocol::ConversationGitInfo;
|
||||
use codex_app_server_protocol::ConversationSummary;
|
||||
use codex_app_server_protocol::DeprecationNoticeNotification;
|
||||
@@ -79,15 +64,11 @@ use codex_app_server_protocol::ExperimentalFeatureStage as ApiExperimentalFeatur
|
||||
use codex_app_server_protocol::FeedbackUploadParams;
|
||||
use codex_app_server_protocol::FeedbackUploadResponse;
|
||||
use codex_app_server_protocol::GetAccountParams;
|
||||
use codex_app_server_protocol::GetAccountRateLimitsResponse;
|
||||
use codex_app_server_protocol::GetAccountResponse;
|
||||
use codex_app_server_protocol::GetAccountTokenUsageParams;
|
||||
use codex_app_server_protocol::GetAccountTokenUsageResponse;
|
||||
use codex_app_server_protocol::GetAuthStatusParams;
|
||||
use codex_app_server_protocol::GetAuthStatusResponse;
|
||||
use codex_app_server_protocol::GetConversationSummaryParams;
|
||||
use codex_app_server_protocol::GetConversationSummaryResponse;
|
||||
use codex_app_server_protocol::GetWorkspaceMessagesResponse;
|
||||
use codex_app_server_protocol::GitDiffToRemoteParams;
|
||||
use codex_app_server_protocol::GitDiffToRemoteResponse;
|
||||
use codex_app_server_protocol::GitInfo as ApiGitInfo;
|
||||
@@ -97,7 +78,6 @@ use codex_app_server_protocol::HooksListParams;
|
||||
use codex_app_server_protocol::HooksListResponse;
|
||||
use codex_app_server_protocol::InitializeParams;
|
||||
use codex_app_server_protocol::InitializeResponse;
|
||||
use codex_app_server_protocol::InstalledApp;
|
||||
use codex_app_server_protocol::JSONRPCErrorError;
|
||||
use codex_app_server_protocol::ListMcpServerStatusParams;
|
||||
use codex_app_server_protocol::ListMcpServerStatusResponse;
|
||||
@@ -169,17 +149,11 @@ use codex_app_server_protocol::PluginSource;
|
||||
use codex_app_server_protocol::PluginSummary;
|
||||
use codex_app_server_protocol::PluginUninstallParams;
|
||||
use codex_app_server_protocol::PluginUninstallResponse;
|
||||
use codex_app_server_protocol::RateLimitResetCredit;
|
||||
use codex_app_server_protocol::RateLimitResetCreditStatus;
|
||||
use codex_app_server_protocol::RateLimitResetCreditsSummary;
|
||||
use codex_app_server_protocol::RateLimitResetType;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::ReviewStartParams;
|
||||
use codex_app_server_protocol::ReviewStartResponse;
|
||||
use codex_app_server_protocol::ReviewTarget as ApiReviewTarget;
|
||||
use codex_app_server_protocol::SandboxMode;
|
||||
use codex_app_server_protocol::SendAddCreditsNudgeEmailParams;
|
||||
use codex_app_server_protocol::SendAddCreditsNudgeEmailResponse;
|
||||
use codex_app_server_protocol::ServerNotification;
|
||||
use codex_app_server_protocol::SkillSummary;
|
||||
use codex_app_server_protocol::SkillsConfigWriteParams;
|
||||
@@ -316,29 +290,16 @@ use codex_app_server_protocol::WindowsSandboxSetupCompletedNotification;
|
||||
use codex_app_server_protocol::WindowsSandboxSetupMode;
|
||||
use codex_app_server_protocol::WindowsSandboxSetupStartParams;
|
||||
use codex_app_server_protocol::WindowsSandboxSetupStartResponse;
|
||||
use codex_app_server_protocol::WorkspaceMessage;
|
||||
use codex_app_server_protocol::WorkspaceMessageType;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_backend_client::AddCreditsNudgeCreditType as BackendAddCreditsNudgeCreditType;
|
||||
use codex_backend_client::Client as BackendClient;
|
||||
use codex_backend_client::CodexWorkspaceMessage as BackendWorkspaceMessage;
|
||||
use codex_backend_client::CodexWorkspaceMessageType as BackendWorkspaceMessageType;
|
||||
use codex_backend_client::CodexWorkspaceMessagesResponse as BackendWorkspaceMessagesResponse;
|
||||
use codex_backend_client::ConsumeRateLimitResetCreditCode as BackendConsumeRateLimitResetCreditCode;
|
||||
use codex_backend_client::RateLimitResetCreditDetails as BackendRateLimitResetCreditDetails;
|
||||
use codex_backend_client::RateLimitResetCreditsDetails as BackendRateLimitResetCreditsDetails;
|
||||
use codex_backend_client::RequestError as BackendRequestError;
|
||||
use codex_backend_client::TokenUsageProfile;
|
||||
use codex_config::CloudConfigBundleLoadError;
|
||||
use codex_config::CloudConfigBundleLoadErrorCode;
|
||||
use codex_config::ConfigLayerStack;
|
||||
use codex_config::loader::project_trust_key;
|
||||
use codex_config::types::McpServerTransportConfig;
|
||||
use codex_connectors::AppInfo;
|
||||
use codex_core::CodexThread;
|
||||
use codex_core::CodexThreadSettingsOverrides;
|
||||
use codex_core::ForkSnapshot;
|
||||
use codex_core::McpManager;
|
||||
use codex_core::NewThread;
|
||||
use codex_core::NotSubmittedReason;
|
||||
#[cfg(test)]
|
||||
@@ -356,7 +317,6 @@ use codex_core::config::ConfigOverrides;
|
||||
use codex_core::config::NetworkProxyAuditMetadata;
|
||||
use codex_core::config::edit::ConfigEdit;
|
||||
use codex_core::config::edit::ConfigEditsBuilder;
|
||||
use codex_core::connectors::AccessibleConnectorsStatus;
|
||||
use codex_core::exec::ExecCapturePolicy;
|
||||
use codex_core::exec::ExecExpiration;
|
||||
use codex_core::exec::ExecParams;
|
||||
@@ -376,7 +336,6 @@ use codex_core_plugins::PluginInstallError as CorePluginInstallError;
|
||||
use codex_core_plugins::PluginInstallRequest;
|
||||
use codex_core_plugins::PluginReadRequest;
|
||||
use codex_core_plugins::PluginUninstallError as CorePluginUninstallError;
|
||||
use codex_core_plugins::PluginsManager;
|
||||
use codex_core_plugins::loader::load_plugin_apps;
|
||||
use codex_core_plugins::manifest::PluginManifestInterface;
|
||||
use codex_core_plugins::marketplace::MarketplaceError;
|
||||
@@ -525,7 +484,6 @@ use tokio::sync::broadcast;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::sync::DropGuard;
|
||||
use tokio_util::task::TaskTracker;
|
||||
use toml::Value as TomlValue;
|
||||
use tracing::Instrument;
|
||||
@@ -538,7 +496,6 @@ use uuid::Uuid;
|
||||
use codex_app_server_protocol::ServerRequest;
|
||||
|
||||
pub(crate) mod account_processor;
|
||||
mod apps_processor;
|
||||
mod bedrock_auth;
|
||||
mod catalog_processor;
|
||||
mod command_exec_processor;
|
||||
@@ -580,7 +537,6 @@ mod turn_processor;
|
||||
mod windows_sandbox_processor;
|
||||
|
||||
pub(crate) use account_processor::AccountRequestProcessor;
|
||||
pub(crate) use apps_processor::AppsRequestProcessor;
|
||||
pub(crate) use catalog_processor::CatalogRequestProcessor;
|
||||
pub(crate) use command_exec_processor::CommandExecRequestProcessor;
|
||||
pub(crate) use config_processor::ConfigRequestProcessor;
|
||||
|
||||
@@ -7,9 +7,7 @@ use crate::auth_mode::auth_mode_to_api;
|
||||
use crate::external_auth::ExternalAuthBridge;
|
||||
use crate::model_catalog::ModelCatalog;
|
||||
use crate::outgoing_message::AccountNotification;
|
||||
use chrono::DateTime;
|
||||
use codex_app_server_protocol::DesktopOnboardingEntrypoint;
|
||||
use codex_app_server_protocol::GetAccountRateLimitsParams;
|
||||
use codex_login::LoginOnboardingEntrypoint;
|
||||
use codex_login::login_with_bedrock_access_keys;
|
||||
use codex_mcp::ema_auth_scope;
|
||||
@@ -17,13 +15,11 @@ use codex_model_provider::is_supported_amazon_bedrock_region;
|
||||
use codex_otel::auth_storage::AuthStorageOriginator;
|
||||
use codex_rmcp_client::EnterpriseOAuthCredentialGuard;
|
||||
|
||||
mod backend_client;
|
||||
mod bedrock_gov_cloud;
|
||||
mod bedrock_setup;
|
||||
mod enterprise_login;
|
||||
mod gateway_oauth;
|
||||
mod gcp_setup;
|
||||
mod rate_limit_resets;
|
||||
mod security_setup;
|
||||
mod workspace_routing;
|
||||
mod workspace_switching;
|
||||
@@ -34,10 +30,6 @@ pub(crate) use gcp_setup::handle_gcp_setup;
|
||||
|
||||
// Duration before a browser ChatGPT login attempt is abandoned.
|
||||
const LOGIN_CHATGPT_TIMEOUT: Duration = Duration::from_secs(10 * 60);
|
||||
const ACCOUNT_TOKEN_USAGE_FETCH_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
|
||||
const THREAD_USAGE_FETCH_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 60);
|
||||
const ACCOUNT_WORKSPACE_MESSAGES_FETCH_TIMEOUT: Duration =
|
||||
Duration::from_millis(/*millis*/ 1000);
|
||||
// Packaged clients use this together with the OAuth client ID override for staging login.
|
||||
const LOGIN_ISSUER_OVERRIDE_ENV_VAR: &str = "CODEX_APP_SERVER_LOGIN_ISSUER";
|
||||
// The development success-page redirect remains debug-only.
|
||||
@@ -205,41 +197,6 @@ impl AccountRequestProcessor {
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn get_account_rate_limits(
|
||||
&self,
|
||||
params: Option<GetAccountRateLimitsParams>,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.get_account_rate_limits_response(params.unwrap_or_default())
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn get_account_token_usage(
|
||||
&self,
|
||||
params: Option<GetAccountTokenUsageParams>,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.get_account_token_usage_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn get_workspace_messages(
|
||||
&self,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.get_workspace_messages_response()
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn send_add_credits_nudge_email(
|
||||
&self,
|
||||
params: SendAddCreditsNudgeEmailParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.send_add_credits_nudge_email_response(params)
|
||||
.await
|
||||
.map(|response| Some(response.into()))
|
||||
}
|
||||
|
||||
pub(crate) async fn cancel_active_login(&self) {
|
||||
self.cancel_gateway_login();
|
||||
self.enterprise_login.cancel(/*login_id*/ None).await;
|
||||
@@ -1169,376 +1126,6 @@ impl AccountRequestProcessor {
|
||||
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn get_account_rate_limits_response(
|
||||
&self,
|
||||
params: GetAccountRateLimitsParams,
|
||||
) -> Result<GetAccountRateLimitsResponse, JSONRPCErrorError> {
|
||||
let Some((auth, http_client_factory)) =
|
||||
self.auth_manager.auth_with_http_client_factory().await
|
||||
else {
|
||||
return Err(invalid_request(
|
||||
"codex account authentication required to read rate limits",
|
||||
));
|
||||
};
|
||||
|
||||
if !auth.uses_codex_backend() {
|
||||
return Err(invalid_request(
|
||||
"chatgpt authentication required to read rate limits",
|
||||
));
|
||||
}
|
||||
|
||||
let client = self.backend_client(&auth, http_client_factory).await?;
|
||||
|
||||
let usage_request = async {
|
||||
if params.supports_luna_reserve
|
||||
&& auth.auth_mode() == codex_protocol::auth::AuthMode::Chatgpt
|
||||
&& !auth.is_fedramp_account()
|
||||
{
|
||||
client.get_rate_limits_with_luna_reserve().await
|
||||
} else {
|
||||
client.get_rate_limits_with_reset_credits().await
|
||||
}
|
||||
};
|
||||
let (response, detailed_rate_limit_reset_credits) = tokio::join!(usage_request, async {
|
||||
if params.exclude_reset_credit_details {
|
||||
None
|
||||
} else {
|
||||
Self::detailed_rate_limit_reset_credits(&client).await
|
||||
}
|
||||
},);
|
||||
let response = response
|
||||
.map_err(|err| internal_error(format!("failed to fetch codex rate limits: {err}")))?;
|
||||
if response.rate_limits.is_empty() {
|
||||
return Err(internal_error(
|
||||
"failed to fetch codex rate limits: no snapshots returned",
|
||||
));
|
||||
}
|
||||
|
||||
let rate_limits_by_limit_id: HashMap<_, _> = response
|
||||
.rate_limits
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|snapshot| {
|
||||
let limit_id = snapshot
|
||||
.limit_id
|
||||
.clone()
|
||||
.unwrap_or_else(|| "codex".to_string());
|
||||
(limit_id, snapshot)
|
||||
})
|
||||
.collect();
|
||||
let rate_limits = response
|
||||
.rate_limits
|
||||
.iter()
|
||||
.find(|snapshot| snapshot.limit_id.as_deref() == Some("codex"))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| response.rate_limits[0].clone());
|
||||
|
||||
let rate_limit_reset_credits = detailed_rate_limit_reset_credits.or_else(|| {
|
||||
response
|
||||
.rate_limit_reset_credits
|
||||
.map(|summary| RateLimitResetCreditsSummary {
|
||||
available_count: summary.available_count,
|
||||
credits: None,
|
||||
})
|
||||
});
|
||||
|
||||
// Match desktop's account readiness check before exposing account-bound CTA content.
|
||||
// Normal rate limits remain available when older backends omit identity or banner data.
|
||||
// Login can change while the backend read is in flight.
|
||||
let active_auth = self.auth_manager.auth().await;
|
||||
let matches_active_account = active_auth.is_some_and(|auth| {
|
||||
!auth.is_fedramp_account()
|
||||
&& response.account_id.is_some()
|
||||
&& response.account_id == auth.get_account_id()
|
||||
&& response.user_id.is_some()
|
||||
&& response.user_id == auth.get_chatgpt_user_id()
|
||||
});
|
||||
let rate_limit_upsell = response
|
||||
.rate_limit_upsell
|
||||
.filter(|_| matches_active_account);
|
||||
|
||||
Ok(GetAccountRateLimitsResponse {
|
||||
ordinary_usage_allowed: response
|
||||
.ordinary_usage_allowed
|
||||
.filter(|_| matches_active_account),
|
||||
rate_limits: rate_limits.into(),
|
||||
rate_limits_by_limit_id: Some(
|
||||
rate_limits_by_limit_id
|
||||
.into_iter()
|
||||
.map(|(limit_id, snapshot)| (limit_id, snapshot.into()))
|
||||
.collect(),
|
||||
),
|
||||
rate_limit_reset_credits,
|
||||
account_id: response.account_id,
|
||||
rate_limit_upsell,
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_account_token_usage_response(
|
||||
&self,
|
||||
params: Option<GetAccountTokenUsageParams>,
|
||||
) -> Result<GetAccountTokenUsageResponse, JSONRPCErrorError> {
|
||||
let thread_id = params
|
||||
.and_then(|params| params.thread_id)
|
||||
.map(|thread_id| {
|
||||
ThreadId::from_string(&thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))
|
||||
})
|
||||
.transpose()?;
|
||||
|
||||
let Some((auth, http_client_factory)) =
|
||||
self.auth_manager.auth_with_http_client_factory().await
|
||||
else {
|
||||
return Err(invalid_request(
|
||||
"codex account authentication required to read token usage",
|
||||
));
|
||||
};
|
||||
|
||||
if !auth.uses_codex_backend() {
|
||||
return Err(invalid_request(
|
||||
"chatgpt authentication required to read token usage",
|
||||
));
|
||||
}
|
||||
|
||||
let client = self.backend_client(&auth, http_client_factory).await?;
|
||||
if let Some(thread_id) = thread_id {
|
||||
let thread_id = thread_id.to_string();
|
||||
let usage = tokio::time::timeout(
|
||||
THREAD_USAGE_FETCH_TIMEOUT,
|
||||
client.get_thread_usage(&thread_id),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| internal_error("thread usage fetch timed out"))?;
|
||||
let thread_usage = match usage {
|
||||
Ok(usage) => Some(codex_app_server_protocol::ThreadUsage {
|
||||
thread_id: usage.thread_id,
|
||||
estimated_usage_credits_micros: usage.estimated_usage_credits_micros,
|
||||
estimated_usage_usd_micros: usage.estimated_usage_usd_micros,
|
||||
native_usage_usd_micros: usage.native_usage_usd_micros,
|
||||
groups: usage
|
||||
.groups
|
||||
.into_iter()
|
||||
.map(
|
||||
|group| codex_app_server_protocol::ThreadUsageBreakdownGroup {
|
||||
model: group.model,
|
||||
reasoning_effort: group.reasoning_effort,
|
||||
speed: group.speed,
|
||||
estimated_usage_credits_micros: group
|
||||
.estimated_usage_credits_micros,
|
||||
net_new_input_tokens: group.net_new_input_tokens,
|
||||
cached_input_tokens: group.cached_input_tokens,
|
||||
input_tokens: group.input_tokens,
|
||||
output_tokens: group.output_tokens,
|
||||
total_tokens: group.total_tokens,
|
||||
},
|
||||
)
|
||||
.collect(),
|
||||
}),
|
||||
Err(err)
|
||||
if matches!(err.status().map(|status| status.as_u16()), Some(403 | 404)) =>
|
||||
{
|
||||
None
|
||||
}
|
||||
Err(err) => {
|
||||
return Err(internal_error(format!(
|
||||
"failed to fetch thread usage: {err}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
return Ok(GetAccountTokenUsageResponse {
|
||||
summary: AccountTokenUsageSummary {
|
||||
lifetime_tokens: None,
|
||||
peak_daily_tokens: None,
|
||||
longest_running_turn_sec: None,
|
||||
current_streak_days: None,
|
||||
longest_streak_days: None,
|
||||
},
|
||||
daily_usage_buckets: None,
|
||||
thread_usage,
|
||||
});
|
||||
}
|
||||
let profile = tokio::time::timeout(
|
||||
ACCOUNT_TOKEN_USAGE_FETCH_TIMEOUT,
|
||||
client.get_token_usage_profile(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| internal_error("token usage profile fetch timed out"))?
|
||||
.map_err(|err| internal_error(format!("failed to fetch token usage profile: {err}")))?;
|
||||
Ok(Self::account_token_usage_response(profile))
|
||||
}
|
||||
|
||||
async fn get_workspace_messages_response(
|
||||
&self,
|
||||
) -> Result<GetWorkspaceMessagesResponse, JSONRPCErrorError> {
|
||||
let Some((auth, http_client_factory)) =
|
||||
self.auth_manager.auth_with_http_client_factory().await
|
||||
else {
|
||||
return Err(invalid_request(
|
||||
"codex account authentication required to read workspace messages",
|
||||
));
|
||||
};
|
||||
|
||||
if !auth.uses_codex_backend() {
|
||||
return Err(invalid_request(
|
||||
"chatgpt authentication required to read workspace messages",
|
||||
));
|
||||
}
|
||||
|
||||
let client = self.backend_client(&auth, http_client_factory).await?;
|
||||
let messages = tokio::time::timeout(
|
||||
ACCOUNT_WORKSPACE_MESSAGES_FETCH_TIMEOUT,
|
||||
client.list_workspace_messages(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| internal_error("workspace messages fetch timed out"))?;
|
||||
|
||||
match messages {
|
||||
Ok(messages) => {
|
||||
Self::workspace_messages_response(messages, /*feature_enabled*/ true)
|
||||
}
|
||||
Err(err) if workspace_messages_feature_disabled(&err) => {
|
||||
Self::workspace_messages_response(
|
||||
BackendWorkspaceMessagesResponse {
|
||||
messages: Vec::new(),
|
||||
},
|
||||
/*feature_enabled*/ false,
|
||||
)
|
||||
}
|
||||
Err(err) => Err(internal_error(format!(
|
||||
"failed to fetch workspace messages: {err}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn account_token_usage_response(profile: TokenUsageProfile) -> GetAccountTokenUsageResponse {
|
||||
let stats = profile.stats;
|
||||
GetAccountTokenUsageResponse {
|
||||
summary: AccountTokenUsageSummary {
|
||||
lifetime_tokens: stats.lifetime_tokens,
|
||||
peak_daily_tokens: stats.peak_daily_tokens,
|
||||
longest_running_turn_sec: stats.longest_running_turn_sec,
|
||||
current_streak_days: stats.current_streak_days,
|
||||
longest_streak_days: stats.longest_streak_days,
|
||||
},
|
||||
daily_usage_buckets: stats.daily_usage_buckets.map(|buckets| {
|
||||
buckets
|
||||
.into_iter()
|
||||
.map(|bucket| AccountTokenUsageDailyBucket {
|
||||
start_date: bucket.start_date,
|
||||
tokens: bucket.tokens,
|
||||
})
|
||||
.collect()
|
||||
}),
|
||||
thread_usage: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn workspace_messages_response(
|
||||
messages: BackendWorkspaceMessagesResponse,
|
||||
feature_enabled: bool,
|
||||
) -> Result<GetWorkspaceMessagesResponse, JSONRPCErrorError> {
|
||||
Ok(GetWorkspaceMessagesResponse {
|
||||
feature_enabled,
|
||||
messages: messages
|
||||
.messages
|
||||
.into_iter()
|
||||
.map(workspace_message_from_backend)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
})
|
||||
}
|
||||
|
||||
async fn send_add_credits_nudge_email_response(
|
||||
&self,
|
||||
params: SendAddCreditsNudgeEmailParams,
|
||||
) -> Result<SendAddCreditsNudgeEmailResponse, JSONRPCErrorError> {
|
||||
self.send_add_credits_nudge_email_inner(params)
|
||||
.await
|
||||
.map(|status| SendAddCreditsNudgeEmailResponse { status })
|
||||
}
|
||||
|
||||
async fn send_add_credits_nudge_email_inner(
|
||||
&self,
|
||||
params: SendAddCreditsNudgeEmailParams,
|
||||
) -> Result<AddCreditsNudgeEmailStatus, JSONRPCErrorError> {
|
||||
let Some((auth, http_client_factory)) =
|
||||
self.auth_manager.auth_with_http_client_factory().await
|
||||
else {
|
||||
return Err(invalid_request(
|
||||
"codex account authentication required to notify workspace owner",
|
||||
));
|
||||
};
|
||||
|
||||
if !auth.uses_codex_backend() {
|
||||
return Err(invalid_request(
|
||||
"chatgpt authentication required to notify workspace owner",
|
||||
));
|
||||
}
|
||||
|
||||
let client = self.backend_client(&auth, http_client_factory).await?;
|
||||
|
||||
match client
|
||||
.send_add_credits_nudge_email(Self::backend_credit_type(params.credit_type))
|
||||
.await
|
||||
{
|
||||
Ok(()) => Ok(AddCreditsNudgeEmailStatus::Sent),
|
||||
Err(err) if err.status().is_some_and(|status| status.as_u16() == 429) => {
|
||||
Ok(AddCreditsNudgeEmailStatus::CooldownActive)
|
||||
}
|
||||
Err(err) => Err(internal_error(format!(
|
||||
"failed to notify workspace owner: {err}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
|
||||
fn backend_credit_type(value: AddCreditsNudgeCreditType) -> BackendAddCreditsNudgeCreditType {
|
||||
match value {
|
||||
AddCreditsNudgeCreditType::Credits => BackendAddCreditsNudgeCreditType::Credits,
|
||||
AddCreditsNudgeCreditType::UsageLimit => BackendAddCreditsNudgeCreditType::UsageLimit,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn workspace_message_from_backend(
|
||||
message: BackendWorkspaceMessage,
|
||||
) -> Result<WorkspaceMessage, JSONRPCErrorError> {
|
||||
Ok(WorkspaceMessage {
|
||||
message_id: message.message_id,
|
||||
message_type: workspace_message_type_from_backend(message.message_type),
|
||||
message_body: message.message_body,
|
||||
created_at: workspace_message_timestamp_from_backend(message.created_at)?,
|
||||
archived_at: workspace_message_timestamp_from_backend(message.archived_at)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn workspace_message_timestamp_from_backend(
|
||||
timestamp: Option<String>,
|
||||
) -> Result<Option<i64>, JSONRPCErrorError> {
|
||||
timestamp
|
||||
.map(|timestamp| {
|
||||
DateTime::parse_from_rfc3339(×tamp)
|
||||
.map(|timestamp| timestamp.timestamp())
|
||||
.map_err(|err| {
|
||||
internal_error(format!(
|
||||
"failed to parse workspace message timestamp `{timestamp}`: {err}"
|
||||
))
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn workspace_message_type_from_backend(
|
||||
message_type: BackendWorkspaceMessageType,
|
||||
) -> WorkspaceMessageType {
|
||||
match message_type {
|
||||
BackendWorkspaceMessageType::Headline => WorkspaceMessageType::Headline,
|
||||
BackendWorkspaceMessageType::Announcement => WorkspaceMessageType::Announcement,
|
||||
BackendWorkspaceMessageType::Unknown => WorkspaceMessageType::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
fn workspace_messages_feature_disabled(err: &BackendRequestError) -> bool {
|
||||
err.status().is_some_and(|status| status.as_u16() == 404)
|
||||
}
|
||||
|
||||
/// Remove account credentials using the current account's policy, even during startup recovery.
|
||||
@@ -1616,98 +1203,3 @@ pub(crate) async fn clear_account_configuration(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use codex_backend_client::TokenUsageProfileDailyBucket;
|
||||
use codex_backend_client::TokenUsageProfileStats;
|
||||
use http::StatusCode;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn account_token_usage_response_maps_profile_stats_and_daily_buckets() {
|
||||
let response = AccountRequestProcessor::account_token_usage_response(TokenUsageProfile {
|
||||
stats: TokenUsageProfileStats {
|
||||
lifetime_tokens: Some(123),
|
||||
peak_daily_tokens: Some(45),
|
||||
longest_running_turn_sec: Some(67),
|
||||
current_streak_days: Some(8),
|
||||
longest_streak_days: Some(9),
|
||||
daily_usage_buckets: Some(vec![TokenUsageProfileDailyBucket {
|
||||
start_date: "2026-05-29".to_string(),
|
||||
tokens: 10,
|
||||
}]),
|
||||
},
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
GetAccountTokenUsageResponse {
|
||||
summary: AccountTokenUsageSummary {
|
||||
lifetime_tokens: Some(123),
|
||||
peak_daily_tokens: Some(45),
|
||||
longest_running_turn_sec: Some(67),
|
||||
current_streak_days: Some(8),
|
||||
longest_streak_days: Some(9),
|
||||
},
|
||||
daily_usage_buckets: Some(vec![AccountTokenUsageDailyBucket {
|
||||
start_date: "2026-05-29".to_string(),
|
||||
tokens: 10,
|
||||
}]),
|
||||
thread_usage: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_messages_response_maps_backend_messages() {
|
||||
let response = AccountRequestProcessor::workspace_messages_response(
|
||||
BackendWorkspaceMessagesResponse {
|
||||
messages: vec![BackendWorkspaceMessage {
|
||||
message_id: "headline-id".to_string(),
|
||||
message_type: BackendWorkspaceMessageType::Headline,
|
||||
message_body: "Headline body".to_string(),
|
||||
created_at: Some("2026-06-14T00:00:00Z".to_string()),
|
||||
archived_at: Some("2026-06-15T00:00:00Z".to_string()),
|
||||
}],
|
||||
},
|
||||
/*feature_enabled*/ true,
|
||||
)
|
||||
.expect("workspace message timestamps should parse");
|
||||
|
||||
assert_eq!(
|
||||
response,
|
||||
GetWorkspaceMessagesResponse {
|
||||
feature_enabled: true,
|
||||
messages: vec![WorkspaceMessage {
|
||||
message_id: "headline-id".to_string(),
|
||||
message_type: WorkspaceMessageType::Headline,
|
||||
message_body: "Headline body".to_string(),
|
||||
created_at: Some(1_781_395_200),
|
||||
archived_at: Some(1_781_481_600),
|
||||
}],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_messages_feature_disabled_only_for_not_found() {
|
||||
let cases = [
|
||||
(StatusCode::NOT_FOUND, true),
|
||||
(StatusCode::UNAUTHORIZED, false),
|
||||
(StatusCode::FORBIDDEN, false),
|
||||
];
|
||||
|
||||
for (status, expected) in cases {
|
||||
let err = BackendRequestError::UnexpectedStatus {
|
||||
method: "GET".to_string(),
|
||||
url: "https://example.test/api/codex/workspace-messages".to_string(),
|
||||
status,
|
||||
content_type: "application/json".to_string(),
|
||||
body: "{}".to_string(),
|
||||
identity_error_code: None,
|
||||
};
|
||||
assert_eq!(workspace_messages_feature_disabled(&err), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
//! Build account API clients from the latest config and captured account authority.
|
||||
|
||||
use super::*;
|
||||
use futures::future::BoxFuture;
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
// Keep config loading and runtime bootstrap out of request-handler future types.
|
||||
#[inline(never)]
|
||||
pub(super) fn backend_client<'a>(
|
||||
&'a self,
|
||||
auth: &'a CodexAuth,
|
||||
http_client_factory: codex_http_client::HttpClientFactory,
|
||||
) -> BoxFuture<'a, Result<BackendClient, JSONRPCErrorError>> {
|
||||
Box::pin(async move {
|
||||
let config = self.load_latest_config().await;
|
||||
let runtime = self
|
||||
.thread_manager
|
||||
.runtime_auth_for_config(&config)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
BackendClient::from_auth_with_runtime(
|
||||
config.chatgpt_base_url.clone(),
|
||||
auth,
|
||||
http_client_factory,
|
||||
runtime.as_ref(),
|
||||
/*headers*/ &Default::default(),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| internal_error(error.to_string()))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,169 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
const RATE_LIMIT_RESET_REQUEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 10);
|
||||
const RATE_LIMIT_RESET_DETAILS_REQUEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5);
|
||||
#[cfg(debug_assertions)]
|
||||
const RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR: &str =
|
||||
"CODEX_TEST_RATE_LIMIT_RESET_REQUEST_TIMEOUT_MS";
|
||||
|
||||
impl AccountRequestProcessor {
|
||||
pub(super) async fn detailed_rate_limit_reset_credits(
|
||||
client: &BackendClient,
|
||||
) -> Option<RateLimitResetCreditsSummary> {
|
||||
let details = match tokio::time::timeout(
|
||||
RATE_LIMIT_RESET_DETAILS_REQUEST_TIMEOUT,
|
||||
client.list_rate_limit_reset_credits(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(details)) => details,
|
||||
Ok(Err(err)) => {
|
||||
tracing::warn!(
|
||||
"failed to fetch rate limit reset credit details; falling back to the usage response: {err}"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::warn!(
|
||||
"rate limit reset credit detail request timed out; falling back to the usage response"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
match rate_limit_reset_credits_from_backend(details) {
|
||||
Ok(summary) => Some(summary),
|
||||
Err(err) => {
|
||||
tracing::warn!(
|
||||
"failed to parse rate limit reset credit details; falling back to the usage response: {err}"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn consume_account_rate_limit_reset_credit(
|
||||
&self,
|
||||
params: ConsumeAccountRateLimitResetCreditParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
if params.idempotency_key.is_empty() {
|
||||
return Err(invalid_request("idempotencyKey must not be empty"));
|
||||
}
|
||||
if params.credit_id.as_deref().is_some_and(str::is_empty) {
|
||||
return Err(invalid_request("creditId must not be empty"));
|
||||
}
|
||||
|
||||
let client = self.rate_limit_reset_backend_client().await?;
|
||||
let request_timeout = RATE_LIMIT_RESET_REQUEST_TIMEOUT;
|
||||
#[cfg(debug_assertions)]
|
||||
let request_timeout = std::env::var(RATE_LIMIT_RESET_REQUEST_TIMEOUT_ENV_VAR)
|
||||
.ok()
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
.map(Duration::from_millis)
|
||||
.unwrap_or(request_timeout);
|
||||
let response = tokio::time::timeout(request_timeout, async {
|
||||
match params.credit_id.as_deref() {
|
||||
Some(credit_id) => {
|
||||
client
|
||||
.consume_rate_limit_reset_credit_by_id(¶ms.idempotency_key, credit_id)
|
||||
.await
|
||||
}
|
||||
None => {
|
||||
client
|
||||
.consume_rate_limit_reset_credit(¶ms.idempotency_key)
|
||||
.await
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|_| internal_error("rate limit reset consume timed out"))?
|
||||
.map_err(|err| internal_error(format!("failed to consume rate limit reset: {err}")))?;
|
||||
let outcome = match response.code {
|
||||
BackendConsumeRateLimitResetCreditCode::Reset => {
|
||||
ConsumeAccountRateLimitResetCreditOutcome::Reset
|
||||
}
|
||||
BackendConsumeRateLimitResetCreditCode::NothingToReset => {
|
||||
ConsumeAccountRateLimitResetCreditOutcome::NothingToReset
|
||||
}
|
||||
BackendConsumeRateLimitResetCreditCode::NoCredit => {
|
||||
ConsumeAccountRateLimitResetCreditOutcome::NoCredit
|
||||
}
|
||||
BackendConsumeRateLimitResetCreditCode::AlreadyRedeemed => {
|
||||
ConsumeAccountRateLimitResetCreditOutcome::AlreadyRedeemed
|
||||
}
|
||||
};
|
||||
Ok(Some(
|
||||
ConsumeAccountRateLimitResetCreditResponse { outcome }.into(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn rate_limit_reset_backend_client(&self) -> Result<BackendClient, JSONRPCErrorError> {
|
||||
let Some((auth, http_client_factory)) =
|
||||
self.auth_manager.auth_with_http_client_factory().await
|
||||
else {
|
||||
return Err(invalid_request(
|
||||
"codex account authentication required for rate limit reset credits",
|
||||
));
|
||||
};
|
||||
if !auth.uses_codex_backend() {
|
||||
return Err(invalid_request(
|
||||
"chatgpt authentication required for rate limit reset credits",
|
||||
));
|
||||
}
|
||||
|
||||
self.backend_client(&auth, http_client_factory).await
|
||||
}
|
||||
}
|
||||
|
||||
fn rate_limit_reset_credits_from_backend(
|
||||
details: BackendRateLimitResetCreditsDetails,
|
||||
) -> Result<RateLimitResetCreditsSummary, String> {
|
||||
let credits = details
|
||||
.credits
|
||||
.into_iter()
|
||||
.map(rate_limit_reset_credit_from_backend)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(RateLimitResetCreditsSummary {
|
||||
available_count: details.available_count,
|
||||
credits: Some(credits),
|
||||
})
|
||||
}
|
||||
|
||||
fn rate_limit_reset_credit_from_backend(
|
||||
credit: BackendRateLimitResetCreditDetails,
|
||||
) -> Result<RateLimitResetCredit, String> {
|
||||
let reset_type = match credit.reset_type.as_str() {
|
||||
"codex_rate_limits" => RateLimitResetType::CodexRateLimits,
|
||||
_ => RateLimitResetType::Unknown,
|
||||
};
|
||||
let status = match credit.status.as_str() {
|
||||
"available" => RateLimitResetCreditStatus::Available,
|
||||
"redeeming" => RateLimitResetCreditStatus::Redeeming,
|
||||
"redeemed" => RateLimitResetCreditStatus::Redeemed,
|
||||
_ => RateLimitResetCreditStatus::Unknown,
|
||||
};
|
||||
let granted_at = rate_limit_reset_credit_timestamp(&credit.granted_at)
|
||||
.map_err(|err| format!("invalid granted_at for credit `{}`: {err}", credit.id))?;
|
||||
let expires_at = credit
|
||||
.expires_at
|
||||
.as_deref()
|
||||
.map(rate_limit_reset_credit_timestamp)
|
||||
.transpose()
|
||||
.map_err(|err| format!("invalid expires_at for credit `{}`: {err}", credit.id))?;
|
||||
|
||||
Ok(RateLimitResetCredit {
|
||||
id: credit.id,
|
||||
reset_type,
|
||||
status,
|
||||
granted_at,
|
||||
expires_at,
|
||||
title: credit.title,
|
||||
description: credit.description,
|
||||
})
|
||||
}
|
||||
|
||||
fn rate_limit_reset_credit_timestamp(timestamp: &str) -> Result<i64, String> {
|
||||
DateTime::parse_from_rfc3339(timestamp)
|
||||
.map(|timestamp| timestamp.timestamp())
|
||||
.map_err(|err| format!("failed to parse timestamp `{timestamp}`: {err}"))
|
||||
}
|
||||
@@ -1,497 +0,0 @@
|
||||
use super::*;
|
||||
use crate::app_info::app_info_to_api;
|
||||
use codex_connectors::AppToolPolicyEvaluator;
|
||||
|
||||
mod installed;
|
||||
mod read;
|
||||
|
||||
pub(super) use read::APP_READ_MAX_IDS;
|
||||
|
||||
pub(crate) struct AppsRequestProcessor {
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
shutdown_token: CancellationToken,
|
||||
_shutdown_drop_guard: DropGuard,
|
||||
}
|
||||
|
||||
impl AppsRequestProcessor {
|
||||
pub(crate) fn new(
|
||||
thread_manager: Arc<ThreadManager>,
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
config_manager: ConfigManager,
|
||||
shutdown_token: CancellationToken,
|
||||
) -> Self {
|
||||
let shutdown_drop_guard = shutdown_token.clone().drop_guard();
|
||||
Self {
|
||||
thread_manager,
|
||||
outgoing,
|
||||
config_manager,
|
||||
shutdown_token,
|
||||
_shutdown_drop_guard: shutdown_drop_guard,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn apps_list(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: AppsListParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
self.apps_list_inner(request_id, params)
|
||||
.await
|
||||
.map(|response| response.map(Into::into))
|
||||
}
|
||||
|
||||
async fn apps_list_inner(
|
||||
&self,
|
||||
request_id: &ConnectionRequestId,
|
||||
params: AppsListParams,
|
||||
) -> Result<Option<AppsListResponse>, JSONRPCErrorError> {
|
||||
let installed_start = Instant::now();
|
||||
let reload = params.force_refetch;
|
||||
let thread = if let Some(thread_id) = params.thread_id.as_deref() {
|
||||
let (_, loaded_thread) = self.load_thread(thread_id).await?;
|
||||
Some(loaded_thread)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let fallback_cwd = match thread.as_ref() {
|
||||
Some(thread) => Some(thread.config_snapshot().await.cwd().to_path_buf()),
|
||||
None => None,
|
||||
};
|
||||
let mut config = self.load_latest_config(fallback_cwd).await?;
|
||||
|
||||
if let Some(thread) = thread.as_ref() {
|
||||
let _ = config
|
||||
.features
|
||||
.set_enabled(Feature::Apps, thread.enabled(Feature::Apps));
|
||||
}
|
||||
|
||||
let mcp_manager = thread
|
||||
.as_ref()
|
||||
.map(|thread| thread.mcp_manager())
|
||||
.unwrap_or_else(|| self.thread_manager.mcp_manager());
|
||||
self.thread_manager
|
||||
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
let auth_manager = mcp_manager.auth_manager();
|
||||
if params.force_refetch && !auth_manager.has_external_auth() {
|
||||
auth_manager
|
||||
.reload_with_cached_auth()
|
||||
.await
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
}
|
||||
let auth = auth_manager.auth().await;
|
||||
if !config
|
||||
.features
|
||||
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend))
|
||||
{
|
||||
let response = AppsListResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
};
|
||||
record_legacy_apps_installed_duration(installed_start, reload);
|
||||
return Ok(Some(response));
|
||||
}
|
||||
|
||||
let request = request_id.clone();
|
||||
let outgoing = Arc::clone(&self.outgoing);
|
||||
let environment_manager = self.thread_manager.environment_manager();
|
||||
let plugins_manager = mcp_manager.plugins_manager();
|
||||
let shutdown_token = self.shutdown_token.child_token();
|
||||
tokio::spawn(async move {
|
||||
tokio::select! {
|
||||
_ = shutdown_token.cancelled() => {}
|
||||
_ = Self::apps_list_task(
|
||||
outgoing,
|
||||
request,
|
||||
params,
|
||||
config,
|
||||
environment_manager,
|
||||
mcp_manager,
|
||||
plugins_manager,
|
||||
installed_start,
|
||||
) => {}
|
||||
}
|
||||
});
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn shutdown(&self) {
|
||||
self.shutdown_token.cancel();
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn apps_list_task(
|
||||
outgoing: Arc<OutgoingMessageSender>,
|
||||
request_id: ConnectionRequestId,
|
||||
params: AppsListParams,
|
||||
config: Config,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
mcp_manager: Arc<McpManager>,
|
||||
plugins_manager: Arc<PluginsManager>,
|
||||
installed_start: Instant,
|
||||
) {
|
||||
let reload = params.force_refetch;
|
||||
let retry_params = params.clone();
|
||||
let retry_config = config.clone();
|
||||
let retry_environment_manager = Arc::clone(&environment_manager);
|
||||
let retry_mcp_manager = Arc::clone(&mcp_manager);
|
||||
let retry_plugins_manager = Arc::clone(&plugins_manager);
|
||||
let result = Self::apps_list_response(
|
||||
&outgoing,
|
||||
params,
|
||||
config,
|
||||
environment_manager,
|
||||
mcp_manager,
|
||||
plugins_manager,
|
||||
)
|
||||
.await;
|
||||
if result.is_ok() {
|
||||
record_legacy_apps_installed_duration(installed_start, reload);
|
||||
}
|
||||
let should_retry = result
|
||||
.as_ref()
|
||||
.is_ok_and(|(_, codex_apps_ready)| !codex_apps_ready);
|
||||
outgoing
|
||||
.send_result(request_id, result.map(|(response, _)| response))
|
||||
.await;
|
||||
|
||||
if should_retry && !retry_params.force_refetch {
|
||||
let mut retry_params = retry_params;
|
||||
retry_params.force_refetch = true;
|
||||
if let Err(err) = Self::apps_list_response(
|
||||
&outgoing,
|
||||
retry_params,
|
||||
retry_config,
|
||||
retry_environment_manager,
|
||||
retry_mcp_manager,
|
||||
retry_plugins_manager,
|
||||
)
|
||||
.await
|
||||
{
|
||||
warn!("failed to refresh app list after codex-apps readiness retry: {err:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn apps_list_response(
|
||||
outgoing: &Arc<OutgoingMessageSender>,
|
||||
params: AppsListParams,
|
||||
config: Config,
|
||||
environment_manager: Arc<EnvironmentManager>,
|
||||
mcp_manager: Arc<McpManager>,
|
||||
plugins_manager: Arc<PluginsManager>,
|
||||
) -> Result<(AppsListResponse, bool), JSONRPCErrorError> {
|
||||
let AppsListParams {
|
||||
cursor,
|
||||
limit,
|
||||
thread_id: _,
|
||||
force_refetch,
|
||||
} = params;
|
||||
let start = match cursor {
|
||||
Some(cursor) => match cursor.parse::<usize>() {
|
||||
Ok(idx) => idx,
|
||||
Err(_) => return Err(invalid_request(format!("invalid cursor: {cursor}"))),
|
||||
},
|
||||
None => 0,
|
||||
};
|
||||
|
||||
let loaded_plugins = plugins_manager
|
||||
.plugins_for_config(&config.plugins_config_input())
|
||||
.await;
|
||||
let connector_snapshot =
|
||||
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(
|
||||
loaded_plugins.capability_summaries(),
|
||||
);
|
||||
let plugin_apps = connector_snapshot.connector_ids().to_vec();
|
||||
let mut config = config;
|
||||
let auth = match mcp_manager
|
||||
.auth_manager()
|
||||
.auth_with_http_client_factory()
|
||||
.await
|
||||
{
|
||||
Some((auth, factory)) => {
|
||||
config.application_network_policy = factory.network_policy().clone();
|
||||
Some(auth)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let runtime = mcp_manager
|
||||
.runtime_auth_for_config(&config)
|
||||
.map(|(slot, mode)| {
|
||||
slot.get()
|
||||
.cloned()
|
||||
.map(|runtime| (runtime, mode))
|
||||
.ok_or_else(|| {
|
||||
internal_error("runtime authentication is not initialized".to_string())
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
let mut accessible_connectors =
|
||||
connectors::list_cached_accessible_connectors_from_mcp_tools(&config, auth.as_ref());
|
||||
let mut all_connectors =
|
||||
connectors::list_cached_all_connectors(&config, auth.as_ref(), &plugin_apps);
|
||||
let cached_all_connectors = all_connectors.clone();
|
||||
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
|
||||
let accessible_config = config.clone();
|
||||
let accessible_tx = tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager(
|
||||
&accessible_config,
|
||||
force_refetch,
|
||||
Arc::clone(&environment_manager),
|
||||
mcp_manager,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| format!("failed to load accessible apps: {err}"));
|
||||
let _ = accessible_tx.send(AppListLoadResult::Accessible(result));
|
||||
});
|
||||
|
||||
let all_config = config.clone();
|
||||
let all_plugin_apps = plugin_apps.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = connectors::list_all_connectors_with_options(
|
||||
&all_config,
|
||||
auth.as_ref(),
|
||||
runtime.as_ref(),
|
||||
force_refetch,
|
||||
&all_plugin_apps,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| format!("failed to list apps: {err}"));
|
||||
let _ = tx.send(AppListLoadResult::Directory(result));
|
||||
});
|
||||
|
||||
let app_list_deadline = tokio::time::Instant::now() + APP_LIST_LOAD_TIMEOUT;
|
||||
let mut accessible_loaded = false;
|
||||
let mut all_loaded = false;
|
||||
let mut codex_apps_ready = true;
|
||||
let mut last_notified_apps = None;
|
||||
let mut sent_app_list_update = false;
|
||||
let app_policy = AppToolPolicyEvaluator::new(&config.config_layer_stack);
|
||||
|
||||
if accessible_connectors.is_some() || all_connectors.is_some() {
|
||||
let merged = app_policy.apply_app_enabled_state(merge_loaded_apps(
|
||||
all_connectors.as_deref(),
|
||||
accessible_connectors.as_deref(),
|
||||
));
|
||||
if !force_refetch {
|
||||
last_notified_apps = Some(merged);
|
||||
} else if should_send_app_list_updated_notification(
|
||||
merged.as_slice(),
|
||||
accessible_loaded,
|
||||
all_loaded,
|
||||
) {
|
||||
send_app_list_updated_notification(outgoing, merged.clone()).await;
|
||||
last_notified_apps = Some(merged);
|
||||
sent_app_list_update = true;
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
let result = match tokio::time::timeout_at(app_list_deadline, rx.recv()).await {
|
||||
Ok(Some(result)) => result,
|
||||
Ok(None) => {
|
||||
return Err(internal_error("failed to load app lists"));
|
||||
}
|
||||
Err(_) => {
|
||||
let timeout_seconds = APP_LIST_LOAD_TIMEOUT.as_secs();
|
||||
return Err(internal_error(format!(
|
||||
"timed out waiting for app lists after {timeout_seconds} seconds"
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
match result {
|
||||
AppListLoadResult::Accessible(Ok(status)) => {
|
||||
accessible_connectors = Some(status.connectors);
|
||||
accessible_loaded = true;
|
||||
codex_apps_ready = status.codex_apps_ready;
|
||||
}
|
||||
AppListLoadResult::Accessible(Err(err)) => {
|
||||
return Err(internal_error(err));
|
||||
}
|
||||
AppListLoadResult::Directory(Ok(connectors)) => {
|
||||
all_connectors = Some(connectors);
|
||||
all_loaded = true;
|
||||
}
|
||||
AppListLoadResult::Directory(Err(err)) => {
|
||||
return Err(internal_error(err));
|
||||
}
|
||||
}
|
||||
|
||||
let showing_interim_force_refetch = force_refetch && !(accessible_loaded && all_loaded);
|
||||
let all_connectors_for_update =
|
||||
if showing_interim_force_refetch && cached_all_connectors.is_some() {
|
||||
cached_all_connectors.as_deref()
|
||||
} else {
|
||||
all_connectors.as_deref()
|
||||
};
|
||||
let accessible_connectors_for_update =
|
||||
if showing_interim_force_refetch && !accessible_loaded {
|
||||
None
|
||||
} else {
|
||||
accessible_connectors.as_deref()
|
||||
};
|
||||
let merged = app_policy.apply_app_enabled_state(merge_loaded_apps(
|
||||
all_connectors_for_update,
|
||||
accessible_connectors_for_update,
|
||||
));
|
||||
if should_send_app_list_updated_notification(
|
||||
merged.as_slice(),
|
||||
accessible_loaded,
|
||||
all_loaded,
|
||||
) && (last_notified_apps.as_ref() != Some(&merged)
|
||||
|| (!force_refetch
|
||||
&& start == 0
|
||||
&& accessible_loaded
|
||||
&& all_loaded
|
||||
&& !sent_app_list_update))
|
||||
{
|
||||
send_app_list_updated_notification(outgoing, merged.clone()).await;
|
||||
last_notified_apps = Some(merged.clone());
|
||||
sent_app_list_update = true;
|
||||
}
|
||||
|
||||
if accessible_loaded && all_loaded {
|
||||
let response = paginate_apps(merged.as_slice(), start, limit)?;
|
||||
return Ok((response, codex_apps_ready));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn load_thread(
|
||||
&self,
|
||||
thread_id: &str,
|
||||
) -> Result<(ThreadId, Arc<CodexThread>), JSONRPCErrorError> {
|
||||
let thread_id = ThreadId::from_string(thread_id)
|
||||
.map_err(|err| invalid_request(format!("invalid thread id: {err}")))?;
|
||||
|
||||
let thread = self
|
||||
.thread_manager
|
||||
.get_thread(thread_id)
|
||||
.await
|
||||
.map_err(|_| invalid_request(format!("thread not found: {thread_id}")))?;
|
||||
|
||||
Ok((thread_id, thread))
|
||||
}
|
||||
|
||||
async fn load_latest_config(
|
||||
&self,
|
||||
fallback_cwd: Option<PathBuf>,
|
||||
) -> Result<Config, JSONRPCErrorError> {
|
||||
self.config_manager
|
||||
.load_latest_config(fallback_cwd)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))
|
||||
}
|
||||
|
||||
async fn load_apps_config(
|
||||
&self,
|
||||
thread_id: Option<&str>,
|
||||
) -> Result<(Config, Arc<McpManager>), JSONRPCErrorError> {
|
||||
let Some(thread_id) = thread_id else {
|
||||
let config = self.load_latest_config(/*fallback_cwd*/ None).await?;
|
||||
self.thread_manager
|
||||
.runtime_auth_for_config(&config)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
return Ok((config, self.thread_manager.mcp_manager()));
|
||||
};
|
||||
let (_, thread) = self.load_thread(thread_id).await?;
|
||||
let thread_config = thread.config().await;
|
||||
let config = self
|
||||
.config_manager
|
||||
.load_latest_config_with_session_layers(
|
||||
&thread_config.config_layer_stack,
|
||||
&thread_config.cwd,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to reload config: {err}")))?;
|
||||
let mcp_manager = thread.mcp_manager();
|
||||
self.thread_manager
|
||||
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
Ok((config, mcp_manager))
|
||||
}
|
||||
}
|
||||
|
||||
const APP_LIST_LOAD_TIMEOUT: Duration = Duration::from_secs(90);
|
||||
// `app/list` is the legacy request-path baseline for the `app/installed` endpoint;
|
||||
// `path=legacy` keeps it separate from the new snapshot-backed implementation in dashboards.
|
||||
const APPS_INSTALLED_DURATION_METRIC: &str = "codex.apps.installed.duration_ms";
|
||||
|
||||
fn record_legacy_apps_installed_duration(started_at: Instant, reload: bool) {
|
||||
let reload = if reload { "true" } else { "false" };
|
||||
if let Some(metrics) = codex_otel::global() {
|
||||
let _ = metrics.record_duration(
|
||||
APPS_INSTALLED_DURATION_METRIC,
|
||||
started_at.elapsed(),
|
||||
&[("path", "legacy"), ("reload", reload)],
|
||||
);
|
||||
}
|
||||
}
|
||||
enum AppListLoadResult {
|
||||
Accessible(Result<AccessibleConnectorsStatus, String>),
|
||||
Directory(Result<Vec<AppInfo>, String>),
|
||||
}
|
||||
|
||||
fn merge_loaded_apps(
|
||||
all_connectors: Option<&[AppInfo]>,
|
||||
accessible_connectors: Option<&[AppInfo]>,
|
||||
) -> Vec<AppInfo> {
|
||||
let all_connectors_loaded = all_connectors.is_some();
|
||||
let all = all_connectors.map_or_else(Vec::new, <[AppInfo]>::to_vec);
|
||||
let accessible = accessible_connectors.map_or_else(Vec::new, <[AppInfo]>::to_vec);
|
||||
connectors::merge_connectors_with_accessible(all, accessible, all_connectors_loaded)
|
||||
}
|
||||
|
||||
fn should_send_app_list_updated_notification(
|
||||
connectors: &[AppInfo],
|
||||
accessible_loaded: bool,
|
||||
all_loaded: bool,
|
||||
) -> bool {
|
||||
connectors.iter().any(|connector| connector.is_accessible) || (accessible_loaded && all_loaded)
|
||||
}
|
||||
|
||||
fn paginate_apps(
|
||||
connectors: &[AppInfo],
|
||||
start: usize,
|
||||
limit: Option<u32>,
|
||||
) -> Result<AppsListResponse, JSONRPCErrorError> {
|
||||
let total = connectors.len();
|
||||
if start > total {
|
||||
return Err(invalid_request(format!(
|
||||
"cursor {start} exceeds total apps {total}"
|
||||
)));
|
||||
}
|
||||
|
||||
let effective_limit = limit.unwrap_or(total as u32).max(1) as usize;
|
||||
let end = start.saturating_add(effective_limit).min(total);
|
||||
let data = connectors[start..end]
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(app_info_to_api)
|
||||
.collect();
|
||||
let next_cursor = if end < total {
|
||||
Some(end.to_string())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(AppsListResponse { data, next_cursor })
|
||||
}
|
||||
|
||||
async fn send_app_list_updated_notification(
|
||||
outgoing: &Arc<OutgoingMessageSender>,
|
||||
data: Vec<AppInfo>,
|
||||
) {
|
||||
let data = data.into_iter().map(app_info_to_api).collect();
|
||||
outgoing
|
||||
.send_server_notification(ServerNotification::AppListUpdated(
|
||||
AppListUpdatedNotification { data },
|
||||
))
|
||||
.await;
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
use codex_connectors::ConnectorRuntimeTool;
|
||||
use codex_connectors::connector_runtime_context_key;
|
||||
use codex_connectors::connector_tool_is_synthetic;
|
||||
use codex_connectors::installed_connector_runtime;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::MCP_TOOL_CODEX_APPS_META_KEY;
|
||||
use codex_mcp::McpRuntime;
|
||||
use codex_mcp::McpRuntimeInput;
|
||||
use codex_mcp::McpStartupPolicy;
|
||||
use codex_mcp::ToolInfo;
|
||||
use codex_mcp::effective_mcp_servers;
|
||||
use codex_mcp::host_owned_codex_apps_enabled;
|
||||
use codex_mcp::tool_is_model_visible;
|
||||
use codex_protocol::mcp::ClientMcpExtensions;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "installed_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
const CONNECTOR_RUNTIME_REFRESH_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const APPS_INSTALLED_SUBMIT_ID: &str = "app-installed";
|
||||
const APPS_INSTALLED_RESPONSE_BYTES_METRIC: &str = "codex.apps.installed.response_bytes";
|
||||
const APPS_INSTALLED_CONNECTOR_COUNT_METRIC: &str = "codex.apps.installed.connector_count";
|
||||
const APPS_INSTALLED_TOOL_COUNT_METRIC: &str = "codex.apps.installed.tool_count";
|
||||
const APPS_SNAPSHOT_AGE_METRIC: &str = "codex.apps.snapshot.age_ms";
|
||||
|
||||
struct AppsInstalledSnapshotMetrics {
|
||||
age: Option<Duration>,
|
||||
tool_count: usize,
|
||||
}
|
||||
|
||||
impl AppsRequestProcessor {
|
||||
pub(crate) async fn apps_installed(
|
||||
&self,
|
||||
params: AppsInstalledParams,
|
||||
) -> Result<AppsInstalledResponse, JSONRPCErrorError> {
|
||||
let started_at = Instant::now();
|
||||
let force_refresh = params.force_refresh;
|
||||
let mut retained_previous_snapshot = false;
|
||||
let mut refresh_disposition = if force_refresh {
|
||||
"not_started"
|
||||
} else {
|
||||
"not_requested"
|
||||
};
|
||||
let mut snapshot_age = None;
|
||||
let mut snapshot_tool_count = 0;
|
||||
let result = async {
|
||||
let (config, thread) = match params.thread_id.as_deref() {
|
||||
Some(thread_id) => {
|
||||
let (_, thread) = self.load_thread(thread_id).await?;
|
||||
let config = thread.config().await;
|
||||
(config.as_ref().clone(), Some(thread))
|
||||
}
|
||||
None => (
|
||||
self.load_latest_config(/*fallback_cwd*/ None).await?,
|
||||
None,
|
||||
),
|
||||
};
|
||||
let mcp_manager = thread.as_ref().map(|thread| thread.mcp_manager())
|
||||
.unwrap_or_else(|| self.thread_manager.mcp_manager());
|
||||
let auth_manager = mcp_manager.auth_manager();
|
||||
let auth = auth_manager.auth().await;
|
||||
let runtime_enabled = config
|
||||
.features
|
||||
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend));
|
||||
|
||||
let cache_key = connector_runtime_context_key(auth.as_ref());
|
||||
let previous_snapshot = mcp_manager
|
||||
.codex_apps_tools_cache()
|
||||
.current_snapshot(config.codex_home.to_path_buf(), cache_key.clone());
|
||||
let mut model_visible_tool_names = None;
|
||||
let tools = if force_refresh && runtime_enabled {
|
||||
let refresh_result = async {
|
||||
if let Some(thread) = thread {
|
||||
let snapshot = thread.refresh_codex_apps_tools().await?;
|
||||
model_visible_tool_names = Some(snapshot.model_visible_tool_names);
|
||||
snapshot_age = Some(Duration::ZERO);
|
||||
return Ok(snapshot.tools);
|
||||
}
|
||||
let mcp_config = mcp_manager.runtime_config(&config).await;
|
||||
let mut mcp_servers = effective_mcp_servers(&mcp_config, auth.as_ref());
|
||||
mcp_servers.retain(|name, _| name == CODEX_APPS_MCP_SERVER_NAME);
|
||||
let mcp_config = Arc::new(mcp_config.for_threadless_operations(&mcp_servers));
|
||||
anyhow::ensure!(
|
||||
!mcp_servers.is_empty(),
|
||||
"host-owned MCP server '{CODEX_APPS_MCP_SERVER_NAME}' is not enabled"
|
||||
);
|
||||
let startup_timeout = mcp_servers
|
||||
.get(CODEX_APPS_MCP_SERVER_NAME)
|
||||
.and_then(|server| server.config().startup_timeout_sec)
|
||||
.unwrap_or(CONNECTOR_RUNTIME_REFRESH_TIMEOUT);
|
||||
let runtime_context = McpRuntimeContext::new(
|
||||
self.thread_manager.environment_manager(),
|
||||
config.cwd.to_path_buf(),
|
||||
);
|
||||
let cancellation_token = CancellationToken::new();
|
||||
let codex_apps_auth_manager =
|
||||
host_owned_codex_apps_enabled(&mcp_config, auth.as_ref())
|
||||
.then(|| Arc::clone(&auth_manager));
|
||||
self.thread_manager.runtime_auth_for_mcp_manager(&config, &mcp_manager)?;
|
||||
let runtime = McpRuntime::new(McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
runtime_auth: mcp_manager.runtime_auth_for_config(&config),
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::clone(&mcp_config),
|
||||
plugins_available: false,
|
||||
ready_selected_capability_roots: Vec::new(),
|
||||
mcp_servers,
|
||||
submit_id: APPS_INSTALLED_SUBMIT_ID.to_string(),
|
||||
tx_event: None,
|
||||
startup_cancellation_token: cancellation_token.clone(),
|
||||
runtime_context,
|
||||
codex_apps_tools_cache: mcp_manager.codex_apps_tools_cache(),
|
||||
tool_catalog_cache: mcp_manager.tool_catalog_cache(),
|
||||
codex_apps_tools_cache_key: cache_key.clone(),
|
||||
client_mcp_extensions: ClientMcpExtensions::default(),
|
||||
auth: auth.clone(),
|
||||
auth_manager: codex_apps_auth_manager,
|
||||
elicitation_reviewer: None,
|
||||
elicitation_lifecycle: None,
|
||||
})
|
||||
.await;
|
||||
|
||||
let result = if runtime
|
||||
.latest_wait_for_server_ready(
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
startup_timeout,
|
||||
)
|
||||
.await
|
||||
{
|
||||
mcp_manager
|
||||
.codex_apps_tools_cache()
|
||||
.current_snapshot(config.codex_home.to_path_buf(), cache_key.clone())
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"hosted connector refresh completed without publishing a snapshot"
|
||||
)
|
||||
})
|
||||
} else {
|
||||
Err(anyhow::anyhow!(
|
||||
"failed to refresh tools for MCP server '{CODEX_APPS_MCP_SERVER_NAME}'"
|
||||
))
|
||||
};
|
||||
cancellation_token.cancel();
|
||||
runtime.shutdown().await;
|
||||
result.map(|snapshot| {
|
||||
snapshot_age = Some(snapshot.age());
|
||||
snapshot.tools().to_vec()
|
||||
})
|
||||
}
|
||||
.await;
|
||||
|
||||
match refresh_result {
|
||||
Ok(tools) => {
|
||||
refresh_disposition = "success";
|
||||
tools
|
||||
}
|
||||
Err(err) => {
|
||||
refresh_disposition = "error";
|
||||
retained_previous_snapshot = previous_snapshot.is_some();
|
||||
return Err(internal_error(format!(
|
||||
"failed to refresh installed connector runtime state: {err:#}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if force_refresh {
|
||||
refresh_disposition = "skipped_apps_disabled";
|
||||
retained_previous_snapshot = previous_snapshot.is_some();
|
||||
}
|
||||
previous_snapshot.map_or_else(Vec::new, |snapshot| {
|
||||
snapshot_age = Some(snapshot.age());
|
||||
snapshot.tools().to_vec()
|
||||
})
|
||||
};
|
||||
|
||||
snapshot_tool_count = tools.len();
|
||||
let apps = installed_connector_runtime(
|
||||
&config.config_layer_stack,
|
||||
tools.iter().map(|tool| {
|
||||
let mut runtime_tool = connector_runtime_tool(tool);
|
||||
if let Some(names) = &model_visible_tool_names {
|
||||
runtime_tool.model_visible &= names.contains(tool.tool.name.as_ref());
|
||||
}
|
||||
runtime_tool
|
||||
}),
|
||||
)
|
||||
.into_iter()
|
||||
.map(|app| InstalledApp {
|
||||
id: app.id,
|
||||
runtime_name: app.runtime_name,
|
||||
enabled: runtime_enabled && app.enabled,
|
||||
callable: runtime_enabled && app.callable,
|
||||
})
|
||||
.collect();
|
||||
Ok(AppsInstalledResponse { apps })
|
||||
}
|
||||
.await;
|
||||
|
||||
if let Some(metrics) = codex_otel::global() {
|
||||
record_apps_installed_metrics(
|
||||
&metrics,
|
||||
started_at,
|
||||
force_refresh,
|
||||
retained_previous_snapshot,
|
||||
refresh_disposition,
|
||||
AppsInstalledSnapshotMetrics {
|
||||
age: snapshot_age,
|
||||
tool_count: snapshot_tool_count,
|
||||
},
|
||||
result.as_ref().ok(),
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
fn connector_runtime_tool(tool: &ToolInfo) -> ConnectorRuntimeTool<'_> {
|
||||
let annotations = tool.tool.annotations.as_ref();
|
||||
ConnectorRuntimeTool {
|
||||
connector_id: tool.connector_id.as_deref(),
|
||||
connector_name: tool.connector_name.as_deref(),
|
||||
tool_name: &tool.tool.name,
|
||||
tool_title: tool.tool.title.as_deref(),
|
||||
destructive_hint: annotations.and_then(|annotations| annotations.destructive_hint),
|
||||
open_world_hint: annotations.and_then(|annotations| annotations.open_world_hint),
|
||||
synthetic: connector_tool_is_synthetic(
|
||||
tool.tool
|
||||
.meta
|
||||
.as_deref()
|
||||
.and_then(|meta| meta.get(MCP_TOOL_CODEX_APPS_META_KEY)),
|
||||
),
|
||||
model_visible: tool_is_model_visible(tool),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_apps_installed_metrics(
|
||||
metrics: &codex_otel::MetricsClient,
|
||||
started_at: Instant,
|
||||
force_refresh: bool,
|
||||
retained_previous_snapshot: bool,
|
||||
refresh_disposition: &'static str,
|
||||
snapshot_metrics: AppsInstalledSnapshotMetrics,
|
||||
response: Option<&AppsInstalledResponse>,
|
||||
) {
|
||||
let Some(response) = response else {
|
||||
return;
|
||||
};
|
||||
let force_refresh = if force_refresh { "true" } else { "false" };
|
||||
let retained_previous_snapshot = if retained_previous_snapshot {
|
||||
"true"
|
||||
} else {
|
||||
"false"
|
||||
};
|
||||
let _ = metrics.record_duration(
|
||||
APPS_INSTALLED_DURATION_METRIC,
|
||||
started_at.elapsed(),
|
||||
&[
|
||||
("path", "installed"),
|
||||
("reload", force_refresh),
|
||||
("force_refresh", force_refresh),
|
||||
("refresh", refresh_disposition),
|
||||
("outcome", "success"),
|
||||
("retained_previous_snapshot", retained_previous_snapshot),
|
||||
],
|
||||
);
|
||||
if let Ok(bytes) = serde_json::to_vec(response) {
|
||||
let _ = metrics.histogram(
|
||||
APPS_INSTALLED_RESPONSE_BYTES_METRIC,
|
||||
i64::try_from(bytes.len()).unwrap_or(i64::MAX),
|
||||
&[("path", "new")],
|
||||
);
|
||||
}
|
||||
let _ = metrics.histogram(
|
||||
APPS_INSTALLED_CONNECTOR_COUNT_METRIC,
|
||||
i64::try_from(response.apps.len()).unwrap_or(i64::MAX),
|
||||
&[("path", "new")],
|
||||
);
|
||||
let _ = metrics.histogram(
|
||||
APPS_INSTALLED_TOOL_COUNT_METRIC,
|
||||
i64::try_from(snapshot_metrics.tool_count).unwrap_or(i64::MAX),
|
||||
&[("path", "new")],
|
||||
);
|
||||
if let Some(snapshot_age) = snapshot_metrics.age {
|
||||
let _ = metrics.record_duration(
|
||||
APPS_SNAPSHOT_AGE_METRIC,
|
||||
snapshot_age,
|
||||
&[("path", "new"), ("observation", "installed")],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
use super::APPS_INSTALLED_DURATION_METRIC;
|
||||
use super::AppsInstalledSnapshotMetrics;
|
||||
use super::record_apps_installed_metrics;
|
||||
use anyhow::Result;
|
||||
use codex_app_server_protocol::AppsInstalledResponse;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_otel::MetricsConfig;
|
||||
use opentelemetry_sdk::metrics::InMemoryMetricExporter;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use opentelemetry_sdk::metrics::data::ScopeMetrics;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::Instant;
|
||||
|
||||
fn test_metrics() -> Result<MetricsClient> {
|
||||
Ok(MetricsClient::new(
|
||||
MetricsConfig::in_memory(
|
||||
"test",
|
||||
"codex-app-server",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
InMemoryMetricExporter::default(),
|
||||
)
|
||||
.with_runtime_reader(),
|
||||
)?)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_duration_records_one_sample_per_success_with_legacy_comparison_dimensions()
|
||||
-> Result<()> {
|
||||
let metrics = test_metrics()?;
|
||||
let response = AppsInstalledResponse { apps: Vec::new() };
|
||||
|
||||
record_apps_installed_metrics(
|
||||
&metrics,
|
||||
Instant::now(),
|
||||
/*force_refresh*/ false,
|
||||
/*retained_previous_snapshot*/ false,
|
||||
"not_requested",
|
||||
AppsInstalledSnapshotMetrics {
|
||||
age: None,
|
||||
tool_count: 0,
|
||||
},
|
||||
Some(&response),
|
||||
);
|
||||
record_apps_installed_metrics(
|
||||
&metrics,
|
||||
Instant::now(),
|
||||
/*force_refresh*/ true,
|
||||
/*retained_previous_snapshot*/ false,
|
||||
"success",
|
||||
AppsInstalledSnapshotMetrics {
|
||||
age: None,
|
||||
tool_count: 0,
|
||||
},
|
||||
Some(&response),
|
||||
);
|
||||
|
||||
let snapshot = metrics.snapshot()?;
|
||||
let metric = snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(ScopeMetrics::metrics)
|
||||
.find(|metric| metric.name() == APPS_INSTALLED_DURATION_METRIC)
|
||||
.expect("installed duration metric should be recorded");
|
||||
let mut points = match metric.data() {
|
||||
AggregatedMetrics::F64(MetricData::Histogram(histogram)) => histogram
|
||||
.data_points()
|
||||
.map(|point| {
|
||||
let attributes = point
|
||||
.attributes()
|
||||
.map(|attribute| {
|
||||
(
|
||||
attribute.key.as_str().to_string(),
|
||||
attribute.value.as_str().to_string(),
|
||||
)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
(attributes, point.count())
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
_ => panic!("installed duration should be a floating-point histogram"),
|
||||
};
|
||||
points.sort_by(|(left, _), (right, _)| left.cmp(right));
|
||||
|
||||
assert_eq!(
|
||||
points,
|
||||
vec![
|
||||
(
|
||||
BTreeMap::from([
|
||||
("force_refresh".to_string(), "false".to_string()),
|
||||
("outcome".to_string(), "success".to_string()),
|
||||
("path".to_string(), "installed".to_string()),
|
||||
("refresh".to_string(), "not_requested".to_string()),
|
||||
("reload".to_string(), "false".to_string()),
|
||||
(
|
||||
"retained_previous_snapshot".to_string(),
|
||||
"false".to_string()
|
||||
),
|
||||
]),
|
||||
1,
|
||||
),
|
||||
(
|
||||
BTreeMap::from([
|
||||
("force_refresh".to_string(), "true".to_string()),
|
||||
("outcome".to_string(), "success".to_string()),
|
||||
("path".to_string(), "installed".to_string()),
|
||||
("refresh".to_string(), "success".to_string()),
|
||||
("reload".to_string(), "true".to_string()),
|
||||
(
|
||||
"retained_previous_snapshot".to_string(),
|
||||
"false".to_string()
|
||||
),
|
||||
]),
|
||||
1,
|
||||
),
|
||||
]
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_duration_does_not_record_failed_requests() -> Result<()> {
|
||||
let metrics = test_metrics()?;
|
||||
|
||||
record_apps_installed_metrics(
|
||||
&metrics,
|
||||
Instant::now(),
|
||||
/*force_refresh*/ true,
|
||||
/*retained_previous_snapshot*/ true,
|
||||
"error",
|
||||
AppsInstalledSnapshotMetrics {
|
||||
age: None,
|
||||
tool_count: 0,
|
||||
},
|
||||
/*response*/ None,
|
||||
);
|
||||
|
||||
let snapshot = metrics.snapshot()?;
|
||||
assert!(
|
||||
snapshot
|
||||
.scope_metrics()
|
||||
.flat_map(ScopeMetrics::metrics)
|
||||
.all(|metric| metric.name() != APPS_INSTALLED_DURATION_METRIC),
|
||||
"failed installed requests must not record a successful duration sample",
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
use super::*;
|
||||
use crate::app_info::connector_metadata_to_api;
|
||||
|
||||
pub(in crate::request_processors) const APP_READ_MAX_IDS: usize = 100;
|
||||
const APPS_READ_DURATION_METRIC: &str = "codex.apps.read.duration_ms";
|
||||
|
||||
impl AppsRequestProcessor {
|
||||
pub(crate) async fn apps_read(
|
||||
&self,
|
||||
params: AppsReadParams,
|
||||
) -> Result<Option<ClientResponsePayload>, JSONRPCErrorError> {
|
||||
let started_at = Instant::now();
|
||||
let AppsReadParams {
|
||||
app_ids,
|
||||
thread_id,
|
||||
include_tools,
|
||||
} = params;
|
||||
if app_ids.len() > APP_READ_MAX_IDS {
|
||||
return Err(invalid_params(format!(
|
||||
"app/read accepts at most {APP_READ_MAX_IDS} appIds"
|
||||
)));
|
||||
}
|
||||
|
||||
let mut seen_app_ids = HashSet::new();
|
||||
let app_ids = app_ids
|
||||
.into_iter()
|
||||
.filter(|app_id| seen_app_ids.insert(app_id.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
let (mut config, mcp_manager) = self.load_apps_config(thread_id.as_deref()).await?;
|
||||
let auth = match mcp_manager
|
||||
.auth_manager()
|
||||
.auth_with_http_client_factory()
|
||||
.await
|
||||
{
|
||||
Some((auth, factory)) => {
|
||||
config.application_network_policy = factory.network_policy().clone();
|
||||
Some(auth)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let runtime = self
|
||||
.thread_manager
|
||||
.runtime_auth_for_mcp_manager(&config, &mcp_manager)
|
||||
.map_err(|error| internal_error(error.to_string()))?;
|
||||
if !config
|
||||
.features
|
||||
.apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::uses_codex_backend))
|
||||
{
|
||||
let response = AppsReadResponse {
|
||||
apps: Vec::new(),
|
||||
missing_app_ids: app_ids,
|
||||
};
|
||||
record_apps_read_duration(started_at, include_tools);
|
||||
return Ok(Some(response.into()));
|
||||
}
|
||||
let auth = auth
|
||||
.as_ref()
|
||||
.ok_or_else(|| internal_error("app/read requires ChatGPT auth".to_string()))?;
|
||||
|
||||
let connectors::ConnectorMetadataReadResult {
|
||||
apps,
|
||||
missing_app_ids,
|
||||
} = connectors::read_connector_metadata(
|
||||
&config,
|
||||
auth,
|
||||
runtime.as_ref(),
|
||||
&app_ids,
|
||||
include_tools,
|
||||
)
|
||||
.await
|
||||
.map_err(|err| internal_error(format!("failed to read app metadata: {err}")))?;
|
||||
let loaded_plugins = mcp_manager
|
||||
.plugins_manager()
|
||||
.plugins_for_config(&config.plugins_config_input())
|
||||
.await;
|
||||
let connector_snapshot =
|
||||
codex_connectors::ConnectorSnapshot::from_plugin_capability_summaries(
|
||||
loaded_plugins.capability_summaries(),
|
||||
);
|
||||
let apps = apps
|
||||
.into_iter()
|
||||
.map(|metadata| {
|
||||
let mut app = connector_metadata_to_api(metadata);
|
||||
app.plugin_display_names = connector_snapshot
|
||||
.plugin_display_names_for_connector_id(app.id.as_str())
|
||||
.to_vec();
|
||||
app
|
||||
})
|
||||
.collect();
|
||||
let response = AppsReadResponse {
|
||||
apps,
|
||||
missing_app_ids,
|
||||
};
|
||||
record_apps_read_duration(started_at, include_tools);
|
||||
Ok(Some(response.into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn record_apps_read_duration(started_at: Instant, include_tools: bool) {
|
||||
let include_tools = if include_tools { "true" } else { "false" };
|
||||
if let Some(metrics) = codex_otel::global() {
|
||||
let _ = metrics.record_duration(
|
||||
APPS_READ_DURATION_METRIC,
|
||||
started_at.elapsed(),
|
||||
&[("include_tools", include_tools)],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::apps_processor::APP_READ_MAX_IDS;
|
||||
use super::config_processor::reload_user_config;
|
||||
use super::*;
|
||||
use crate::error_code::internal_error;
|
||||
use crate::error_code::invalid_request;
|
||||
use crate::error_code::method_not_found;
|
||||
use codex_analytics::PluginInstallSource;
|
||||
use codex_app_server_protocol::PluginAvailability;
|
||||
use codex_app_server_protocol::PluginSharePrincipalRole;
|
||||
@@ -1831,78 +1831,15 @@ impl PluginRequestProcessor {
|
||||
);
|
||||
}
|
||||
|
||||
/// ChatGPT apps never need auth in aKode: the hosted apps MCP server is never used.
|
||||
async fn plugin_apps_needing_auth_for_install(
|
||||
&self,
|
||||
config: &Config,
|
||||
auth: Option<&CodexAuth>,
|
||||
plugin_id: &str,
|
||||
plugin_app_declarations: &[codex_plugin::AppDeclaration],
|
||||
_config: &Config,
|
||||
_auth: Option<&CodexAuth>,
|
||||
_plugin_id: &str,
|
||||
_plugin_app_declarations: &[codex_plugin::AppDeclaration],
|
||||
) -> Vec<AppSummary> {
|
||||
if plugin_app_declarations.is_empty()
|
||||
|| !config
|
||||
.features
|
||||
.apps_enabled_for_auth(auth.is_some_and(CodexAuth::is_chatgpt_auth))
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let plugin_apps =
|
||||
codex_plugin::app_connector_ids_from_declarations(plugin_app_declarations);
|
||||
let app_category_by_id = plugin_app_declarations
|
||||
.iter()
|
||||
.filter_map(|app| {
|
||||
app.category
|
||||
.as_ref()
|
||||
.map(|category| (app.connector_id.0.clone(), category.clone()))
|
||||
})
|
||||
.collect();
|
||||
let environment_manager = self.thread_manager.environment_manager();
|
||||
let (app_summaries, accessible_connectors_result) = tokio::join!(
|
||||
load_plugin_app_summaries(
|
||||
&self.thread_manager,
|
||||
config,
|
||||
auth,
|
||||
&plugin_apps,
|
||||
&app_category_by_id
|
||||
),
|
||||
connectors::list_accessible_connectors_from_mcp_tools_with_mcp_manager(
|
||||
config,
|
||||
/*force_refetch*/ true,
|
||||
Arc::clone(&environment_manager),
|
||||
self.thread_manager.mcp_manager(),
|
||||
),
|
||||
);
|
||||
|
||||
let (accessible_connectors, codex_apps_ready) = match accessible_connectors_result {
|
||||
Ok(status) => (status.connectors, status.codex_apps_ready),
|
||||
Err(err) => {
|
||||
warn!(
|
||||
plugin = plugin_id,
|
||||
"failed to load accessible apps after plugin install: {err:#}"
|
||||
);
|
||||
(
|
||||
connectors::list_cached_accessible_connectors_from_mcp_tools(config, auth)
|
||||
.unwrap_or_default(),
|
||||
false,
|
||||
)
|
||||
}
|
||||
};
|
||||
if !codex_apps_ready {
|
||||
warn!(
|
||||
plugin = plugin_id,
|
||||
"codex_apps MCP not ready after plugin install; skipping appsNeedingAuth check"
|
||||
);
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let accessible_ids = accessible_connectors
|
||||
.iter()
|
||||
.map(|connector| connector.id.as_str())
|
||||
.collect::<HashSet<_>>();
|
||||
app_summaries
|
||||
.into_iter()
|
||||
.filter(|app| !accessible_ids.contains(app.id.as_str()))
|
||||
.collect()
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
async fn start_plugin_mcp_oauth_logins(
|
||||
@@ -2182,79 +2119,25 @@ impl PluginRequestProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
/// Summarizes plugin app declarations locally; aKode never fetches ChatGPT app metadata.
|
||||
async fn load_plugin_app_summaries(
|
||||
thread_manager: &ThreadManager,
|
||||
config: &Config,
|
||||
auth: Option<&CodexAuth>,
|
||||
_thread_manager: &ThreadManager,
|
||||
_config: &Config,
|
||||
_auth: Option<&CodexAuth>,
|
||||
plugin_apps: &[codex_plugin::AppConnectorId],
|
||||
app_category_by_id: &HashMap<String, String>,
|
||||
) -> Vec<AppSummary> {
|
||||
let mut seen_app_ids = HashSet::new();
|
||||
let app_ids = plugin_apps
|
||||
plugin_apps
|
||||
.iter()
|
||||
.map(|app| app.0.clone())
|
||||
.filter(|app_id| seen_app_ids.insert(app_id.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
let mut metadata_by_id = HashMap::new();
|
||||
if let Some(auth) = auth.filter(|auth| {
|
||||
config
|
||||
.features
|
||||
.apps_enabled_for_auth(auth.uses_codex_backend())
|
||||
}) {
|
||||
metadata_by_id.extend(
|
||||
codex_connectors::ConnectorMetadataStore::new(
|
||||
config.chatgpt_base_url.clone(),
|
||||
auth.get_account_id(),
|
||||
auth.get_chatgpt_user_id(),
|
||||
auth.is_workspace_account(),
|
||||
)
|
||||
.fresh_records(&app_ids, /*include_tools*/ false),
|
||||
);
|
||||
let runtime = thread_manager.runtime_auth_for_config(config);
|
||||
for app_ids in app_ids.chunks(APP_READ_MAX_IDS) {
|
||||
let runtime = match &runtime {
|
||||
Ok(runtime) => runtime.as_ref(),
|
||||
Err(error) => {
|
||||
warn!("failed to initialize app metadata authentication: {error}");
|
||||
break;
|
||||
}
|
||||
};
|
||||
match connectors::read_connector_metadata(
|
||||
config, auth, runtime, app_ids, /*include_tools*/ false,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(result) => metadata_by_id.extend(
|
||||
result
|
||||
.apps
|
||||
.into_iter()
|
||||
.map(|metadata| (metadata.id.clone(), metadata)),
|
||||
),
|
||||
Err(err) => {
|
||||
warn!("failed to load app metadata for plugin: {err:#}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
app_ids
|
||||
.into_iter()
|
||||
.map(|app_id| {
|
||||
let (name, description) = metadata_by_id
|
||||
.remove(&app_id)
|
||||
.map(|metadata| (metadata.name, metadata.description))
|
||||
.unwrap_or_else(|| (app_id.clone(), None));
|
||||
let category = app_category_by_id.get(&app_id).cloned();
|
||||
AppSummary {
|
||||
install_url: Some(codex_connectors::metadata::connector_install_url(
|
||||
&name, &app_id,
|
||||
)),
|
||||
id: app_id,
|
||||
name,
|
||||
description,
|
||||
category,
|
||||
}
|
||||
.map(|app_id| AppSummary {
|
||||
install_url: None,
|
||||
name: app_id.clone(),
|
||||
description: None,
|
||||
category: app_category_by_id.get(&app_id).cloned(),
|
||||
id: app_id,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -2425,6 +2308,7 @@ fn remote_plugin_detail_to_info(
|
||||
|
||||
fn remote_plugin_catalog_error_type(err: &RemotePluginCatalogError) -> &'static str {
|
||||
match err {
|
||||
RemotePluginCatalogError::Unavailable => "remote_catalog_unavailable",
|
||||
RemotePluginCatalogError::AuthRequired => "remote_catalog_auth_required",
|
||||
RemotePluginCatalogError::UnsupportedAuthMode => "remote_catalog_unsupported_auth_mode",
|
||||
RemotePluginCatalogError::AuthToken(_) => "remote_catalog_auth_token",
|
||||
@@ -2459,6 +2343,7 @@ fn remote_plugin_catalog_error_type(err: &RemotePluginCatalogError) -> &'static
|
||||
|
||||
fn remote_plugin_bundle_install_error_type(err: &RemotePluginBundleInstallError) -> &'static str {
|
||||
match err {
|
||||
RemotePluginBundleInstallError::Unavailable => "remote_bundle_unavailable",
|
||||
RemotePluginBundleInstallError::MissingReleaseVersion { .. } => {
|
||||
"remote_bundle_missing_release_version"
|
||||
}
|
||||
@@ -2499,6 +2384,7 @@ fn remote_plugin_catalog_error_to_jsonrpc(
|
||||
) -> JSONRPCErrorError {
|
||||
let message = format!("{context}: {err}");
|
||||
match &err {
|
||||
RemotePluginCatalogError::Unavailable => method_not_found(message),
|
||||
RemotePluginCatalogError::AuthRequired | RemotePluginCatalogError::UnsupportedAuthMode => {
|
||||
invalid_request(message)
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ pub(super) struct ListenerTaskContext {
|
||||
pub(super) thread_watch_manager: ThreadWatchManager,
|
||||
pub(super) codex_home: PathBuf,
|
||||
pub(super) skills_watcher: Arc<SkillsWatcher>,
|
||||
pub(super) turn_cost_worker: Option<crate::turn_cost_worker::TurnCostWorkerHandle>,
|
||||
}
|
||||
|
||||
struct UnloadingState {
|
||||
@@ -500,7 +499,6 @@ async fn start_listener(
|
||||
pending_thread_unloads,
|
||||
thread_watch_manager,
|
||||
codex_home,
|
||||
turn_cost_worker,
|
||||
..
|
||||
} = listener_task_context;
|
||||
let outgoing_for_task = Arc::clone(&outgoing);
|
||||
@@ -538,15 +536,6 @@ async fn start_listener(
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(worker) = &turn_cost_worker {
|
||||
worker.observe_event(
|
||||
conversation_id,
|
||||
config.as_ref(),
|
||||
&event,
|
||||
|| conversation.session_telemetry(),
|
||||
);
|
||||
}
|
||||
|
||||
// Track the event before emitting any typed translations
|
||||
// so thread-local state such as raw event opt-in stays
|
||||
// synchronized with the conversation.
|
||||
@@ -751,7 +740,6 @@ async fn start_listener(
|
||||
drop(conversation);
|
||||
drop(config);
|
||||
drop(thread_manager);
|
||||
drop(turn_cost_worker);
|
||||
|
||||
if shutdown_complete {
|
||||
drained_tx.send_replace(true);
|
||||
|
||||
@@ -90,7 +90,6 @@ async fn listener_shutdown_releases_runtime_and_preserves_other_subscribers(
|
||||
/*state_db*/ None,
|
||||
/*log_db*/ None,
|
||||
skills_watcher.clone(),
|
||||
/*turn_cost_worker*/ None,
|
||||
Vec::new(),
|
||||
Arc::new(SampleResponseRegistry::default()),
|
||||
);
|
||||
|
||||
@@ -518,7 +518,6 @@ pub(crate) struct ThreadRequestProcessor {
|
||||
pub(super) background_tasks: TaskTracker,
|
||||
pub(super) sample_responses: Arc<crate::thread_sample::SampleResponseRegistry>,
|
||||
pub(super) skills_watcher: Arc<SkillsWatcher>,
|
||||
pub(super) turn_cost_worker: Option<crate::turn_cost_worker::TurnCostWorkerHandle>,
|
||||
pub(super) initial_config_warnings: Arc<Vec<ConfigWarningNotification>>,
|
||||
}
|
||||
|
||||
@@ -557,7 +556,6 @@ impl ThreadRequestProcessor {
|
||||
state_db: Option<StateDbHandle>,
|
||||
log_db: Option<LogDbLayer>,
|
||||
skills_watcher: Arc<SkillsWatcher>,
|
||||
turn_cost_worker: Option<crate::turn_cost_worker::TurnCostWorkerHandle>,
|
||||
initial_config_warnings: Vec<ConfigWarningNotification>,
|
||||
sample_responses: Arc<crate::thread_sample::SampleResponseRegistry>,
|
||||
) -> Self {
|
||||
@@ -579,7 +577,6 @@ impl ThreadRequestProcessor {
|
||||
background_tasks: TaskTracker::new(),
|
||||
sample_responses,
|
||||
skills_watcher,
|
||||
turn_cost_worker,
|
||||
initial_config_warnings: Arc::new(initial_config_warnings),
|
||||
}
|
||||
}
|
||||
@@ -1231,7 +1228,6 @@ impl ThreadRequestProcessor {
|
||||
thread_watch_manager: self.thread_watch_manager.clone(),
|
||||
codex_home: self.config.codex_home.to_path_buf(),
|
||||
skills_watcher: Arc::clone(&self.skills_watcher),
|
||||
turn_cost_worker: self.turn_cost_worker.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1361,7 +1357,6 @@ impl ThreadRequestProcessor {
|
||||
thread_watch_manager: self.thread_watch_manager.clone(),
|
||||
codex_home: self.config.codex_home.to_path_buf(),
|
||||
skills_watcher: Arc::clone(&self.skills_watcher),
|
||||
turn_cost_worker: self.turn_cost_worker.clone(),
|
||||
};
|
||||
let request_trace = request_context.request_trace();
|
||||
let config_manager = self.config_manager.clone();
|
||||
|
||||
@@ -89,7 +89,6 @@ pub(crate) struct TurnRequestProcessor {
|
||||
thread_state_manager: ThreadStateManager,
|
||||
thread_watch_manager: ThreadWatchManager,
|
||||
skills_watcher: Arc<SkillsWatcher>,
|
||||
turn_cost_worker: Option<crate::turn_cost_worker::TurnCostWorkerHandle>,
|
||||
}
|
||||
|
||||
fn map_additional_context(
|
||||
@@ -147,7 +146,6 @@ impl TurnRequestProcessor {
|
||||
thread_state_manager: ThreadStateManager,
|
||||
thread_watch_manager: ThreadWatchManager,
|
||||
skills_watcher: Arc<SkillsWatcher>,
|
||||
turn_cost_worker: Option<crate::turn_cost_worker::TurnCostWorkerHandle>,
|
||||
) -> Self {
|
||||
Self {
|
||||
thread_manager,
|
||||
@@ -159,7 +157,6 @@ impl TurnRequestProcessor {
|
||||
thread_state_manager,
|
||||
thread_watch_manager,
|
||||
skills_watcher,
|
||||
turn_cost_worker,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1543,7 +1540,6 @@ impl TurnRequestProcessor {
|
||||
thread_watch_manager: self.thread_watch_manager.clone(),
|
||||
codex_home: self.config.codex_home.to_path_buf(),
|
||||
skills_watcher: Arc::clone(&self.skills_watcher),
|
||||
turn_cost_worker: self.turn_cost_worker.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,555 +0,0 @@
|
||||
use codex_backend_client::ApiKeyTurnCost;
|
||||
use codex_backend_client::ApiKeyTurnCostStatus;
|
||||
use codex_backend_client::Client as BackendClient;
|
||||
use codex_backend_client::RequestError;
|
||||
use codex_config::types::OtelExporterKind;
|
||||
use codex_core::config::Config;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_login::AuthManager;
|
||||
use codex_model_provider::SharedModelProvider;
|
||||
use codex_otel::SessionTelemetry;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::auth::AuthMode;
|
||||
use codex_protocol::protocol::Event;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tracing::warn;
|
||||
|
||||
const POLL_INTERVAL: Duration = Duration::from_secs(150);
|
||||
const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
const OBSERVATION_CHANNEL_CAPACITY: usize = 16_384;
|
||||
const MAX_TRACKED_TURNS: usize = 4_096;
|
||||
const MAX_QUERY_TURNS: usize = 100;
|
||||
const MAX_TRACKED_RESPONSES_PER_TURN: usize = 4_096;
|
||||
const MAX_STALLED_POLL_ATTEMPTS: u8 = 5;
|
||||
|
||||
pub(crate) struct TurnCostWorker {
|
||||
handle: TurnCostWorkerHandle,
|
||||
shutdown: CancellationToken,
|
||||
_task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct TurnCostWorkerHandle {
|
||||
sender: mpsc::Sender<TurnCostObservation>,
|
||||
backend: TurnCostBackend,
|
||||
config: Arc<Config>,
|
||||
}
|
||||
|
||||
enum TurnCostObservationKind {
|
||||
Started {
|
||||
session_telemetry: Box<SessionTelemetry>,
|
||||
},
|
||||
ResponseCompleted {
|
||||
response_id: String,
|
||||
},
|
||||
Finished {
|
||||
interrupted: bool,
|
||||
},
|
||||
}
|
||||
|
||||
struct TurnCostObservation {
|
||||
thread_id: ThreadId,
|
||||
turn_id: String,
|
||||
kind: TurnCostObservationKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum TurnCostStatus {
|
||||
Running,
|
||||
Completed,
|
||||
Interrupted,
|
||||
}
|
||||
|
||||
struct TurnCostEntry {
|
||||
thread_id: ThreadId,
|
||||
session_telemetry: SessionTelemetry,
|
||||
expected_response_ids: HashSet<String>,
|
||||
status: TurnCostStatus,
|
||||
next_poll_at: Instant,
|
||||
attempt_count: u8,
|
||||
}
|
||||
|
||||
struct WorkerRuntime {
|
||||
config: Arc<Config>,
|
||||
backend: TurnCostBackend,
|
||||
turns: HashMap<String, TurnCostEntry>,
|
||||
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum TurnCostBackend {
|
||||
OpenAi(Arc<AuthManager>),
|
||||
ModelProvider(SharedModelProvider),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum BackendAvailability {
|
||||
AwaitingAuthChange,
|
||||
RetryProbe,
|
||||
Ready,
|
||||
Disabled,
|
||||
}
|
||||
|
||||
impl TurnCostWorker {
|
||||
pub(crate) fn spawn(
|
||||
config: Arc<Config>,
|
||||
auth_manager: Arc<AuthManager>,
|
||||
runtime_auth: Option<(Arc<RuntimeAuthManager>, RuntimeAuthMode)>,
|
||||
) -> Option<Self> {
|
||||
let has_otel_log_exporter = matches!(
|
||||
config.otel.exporter,
|
||||
OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. }
|
||||
);
|
||||
let has_otel_metrics_exporter = matches!(
|
||||
config.otel.metrics_exporter,
|
||||
OtelExporterKind::OtlpHttp { .. } | OtelExporterKind::OtlpGrpc { .. }
|
||||
);
|
||||
if !(has_otel_log_exporter || has_otel_metrics_exporter)
|
||||
|| config.model_provider.is_amazon_bedrock()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let is_openai = config.model_provider.is_openai();
|
||||
let backend = if is_openai {
|
||||
TurnCostBackend::OpenAi(Arc::clone(&auth_manager))
|
||||
} else {
|
||||
TurnCostBackend::ModelProvider(
|
||||
codex_model_provider::ProviderAuthContext {
|
||||
credentials: Arc::clone(&auth_manager),
|
||||
runtime_auth: runtime_auth.clone(),
|
||||
}
|
||||
.model_provider(config.model_provider.clone()),
|
||||
)
|
||||
};
|
||||
let (sender, receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY);
|
||||
let shutdown = CancellationToken::new();
|
||||
let runtime = WorkerRuntime {
|
||||
config: Arc::clone(&config),
|
||||
backend: backend.clone(),
|
||||
turns: HashMap::new(),
|
||||
runtime_auth,
|
||||
};
|
||||
let worker_shutdown = shutdown.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
runtime.run(receiver, worker_shutdown).await;
|
||||
});
|
||||
Some(Self {
|
||||
handle: TurnCostWorkerHandle {
|
||||
sender,
|
||||
backend,
|
||||
config,
|
||||
},
|
||||
shutdown,
|
||||
_task: task,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn handle(&self) -> TurnCostWorkerHandle {
|
||||
self.handle.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn shutdown(&self) {
|
||||
self.shutdown.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TurnCostWorker {
|
||||
fn drop(&mut self) {
|
||||
self.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
impl TurnCostWorkerHandle {
|
||||
pub(crate) fn observe_event(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
thread_config: &Config,
|
||||
event: &Event,
|
||||
session_telemetry: impl FnOnce() -> SessionTelemetry,
|
||||
) {
|
||||
if thread_config.model_provider != self.config.model_provider {
|
||||
return;
|
||||
}
|
||||
if let TurnCostBackend::OpenAi(auth_manager) = &self.backend {
|
||||
let Some(auth) = auth_manager.auth_cached() else {
|
||||
return;
|
||||
};
|
||||
if !auth.is_api_key_auth() && !auth.is_chatgpt_auth() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let kind = match &event.msg {
|
||||
EventMsg::TurnStarted(_) => TurnCostObservationKind::Started {
|
||||
session_telemetry: Box::new(session_telemetry()),
|
||||
},
|
||||
EventMsg::RawResponseCompleted(event) => TurnCostObservationKind::ResponseCompleted {
|
||||
response_id: event.response_id.clone(),
|
||||
},
|
||||
EventMsg::TurnComplete(_) => TurnCostObservationKind::Finished { interrupted: false },
|
||||
EventMsg::TurnAborted(_) => TurnCostObservationKind::Finished { interrupted: true },
|
||||
_ => return,
|
||||
};
|
||||
let _ = self.sender.try_send(TurnCostObservation {
|
||||
thread_id,
|
||||
turn_id: event.id.clone(),
|
||||
kind,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl WorkerRuntime {
|
||||
async fn run(self, receiver: mpsc::Receiver<TurnCostObservation>, shutdown: CancellationToken) {
|
||||
let auth_changes = match &self.backend {
|
||||
TurnCostBackend::OpenAi(auth_manager) => Some(auth_manager.auth_change_receiver()),
|
||||
TurnCostBackend::ModelProvider(_) => None,
|
||||
};
|
||||
let backend_availability = self.probe_backend().await;
|
||||
self.run_with_backend_availability(receiver, shutdown, auth_changes, backend_availability)
|
||||
.await;
|
||||
}
|
||||
|
||||
async fn run_with_backend_availability(
|
||||
mut self,
|
||||
mut receiver: mpsc::Receiver<TurnCostObservation>,
|
||||
shutdown: CancellationToken,
|
||||
mut auth_changes: Option<tokio::sync::watch::Receiver<u64>>,
|
||||
mut backend_availability: BackendAvailability,
|
||||
) {
|
||||
let mut ticker = tokio::time::interval(POLL_INTERVAL);
|
||||
ticker.tick().await;
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.cancelled() => break,
|
||||
changed = async {
|
||||
match auth_changes.as_mut() {
|
||||
Some(auth_changes) => auth_changes.changed().await,
|
||||
None => std::future::pending().await,
|
||||
}
|
||||
} => {
|
||||
if changed.is_err() {
|
||||
break;
|
||||
}
|
||||
// Cost telemetry is best effort: auth changes may drop pending turns.
|
||||
// Callers can query the cost API directly to reconcile missing telemetry.
|
||||
self.turns.clear();
|
||||
while receiver.try_recv().is_ok() {}
|
||||
backend_availability = self.probe_backend().await;
|
||||
}
|
||||
observation = receiver.recv() => {
|
||||
let Some(observation) = observation else {
|
||||
break;
|
||||
};
|
||||
if !matches!(
|
||||
backend_availability,
|
||||
BackendAvailability::Ready | BackendAvailability::RetryProbe
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
self.record_observation(observation);
|
||||
}
|
||||
_ = ticker.tick() => {
|
||||
match backend_availability {
|
||||
BackendAvailability::Ready => self.poll_due().await,
|
||||
BackendAvailability::RetryProbe => {
|
||||
backend_availability = self.probe_backend().await;
|
||||
}
|
||||
BackendAvailability::AwaitingAuthChange
|
||||
| BackendAvailability::Disabled => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn probe_backend(&self) -> BackendAvailability {
|
||||
let probe_turn_ids = [uuid::Uuid::new_v4().to_string()];
|
||||
match tokio::time::timeout(REQUEST_TIMEOUT, self.query_turn_costs(&probe_turn_ids)).await {
|
||||
Ok(Ok(Some(_))) => BackendAvailability::Ready,
|
||||
Ok(Ok(None)) => match self.backend {
|
||||
TurnCostBackend::OpenAi(_) => BackendAvailability::AwaitingAuthChange,
|
||||
TurnCostBackend::ModelProvider(_) => BackendAvailability::Disabled,
|
||||
},
|
||||
Ok(Err(error)) => match error.status().map(|status| status.as_u16()) {
|
||||
Some(401 | 403) if matches!(self.backend, TurnCostBackend::OpenAi(_)) => {
|
||||
tracing::debug!(
|
||||
status = error.status().map(|status| status.as_u16()),
|
||||
"turn cost worker waiting for auth change after backend availability check"
|
||||
);
|
||||
BackendAvailability::AwaitingAuthChange
|
||||
}
|
||||
Some(401 | 403 | 429) => BackendAvailability::RetryProbe,
|
||||
Some(400..=499) => {
|
||||
tracing::debug!(
|
||||
status = error.status().map(|status| status.as_u16()),
|
||||
"turn cost worker disabled by backend availability check"
|
||||
);
|
||||
BackendAvailability::Disabled
|
||||
}
|
||||
_ => {
|
||||
tracing::debug!(
|
||||
status = error.status().map(|status| status.as_u16()),
|
||||
"turn cost worker backend availability check failed temporarily"
|
||||
);
|
||||
BackendAvailability::RetryProbe
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
tracing::debug!(
|
||||
"turn cost worker backend availability check timed out; will retry"
|
||||
);
|
||||
BackendAvailability::RetryProbe
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn record_observation(&mut self, observation: TurnCostObservation) {
|
||||
match observation.kind {
|
||||
TurnCostObservationKind::Started { session_telemetry } => {
|
||||
if self.turns.len() < MAX_TRACKED_TURNS {
|
||||
self.turns
|
||||
.entry(observation.turn_id)
|
||||
.or_insert(TurnCostEntry {
|
||||
thread_id: observation.thread_id,
|
||||
session_telemetry: *session_telemetry,
|
||||
expected_response_ids: HashSet::new(),
|
||||
status: TurnCostStatus::Running,
|
||||
next_poll_at: Instant::now(),
|
||||
attempt_count: 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
TurnCostObservationKind::ResponseCompleted { response_id } => {
|
||||
if let Some(entry) = self.turns.get_mut(&observation.turn_id)
|
||||
&& entry.status == TurnCostStatus::Running
|
||||
{
|
||||
if entry.expected_response_ids.len() >= MAX_TRACKED_RESPONSES_PER_TURN {
|
||||
self.turns.remove(&observation.turn_id);
|
||||
return;
|
||||
}
|
||||
entry.expected_response_ids.insert(response_id);
|
||||
}
|
||||
}
|
||||
TurnCostObservationKind::Finished { interrupted } => {
|
||||
let Some(entry) = self.turns.get_mut(&observation.turn_id) else {
|
||||
return;
|
||||
};
|
||||
if entry.status != TurnCostStatus::Running {
|
||||
return;
|
||||
}
|
||||
entry.status = if interrupted {
|
||||
TurnCostStatus::Interrupted
|
||||
} else {
|
||||
TurnCostStatus::Completed
|
||||
};
|
||||
entry.next_poll_at = Instant::now();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn poll_due(&mut self) {
|
||||
let now = Instant::now();
|
||||
let due_turn_ids: Vec<String> = self
|
||||
.turns
|
||||
.iter()
|
||||
.filter(|(_, entry)| {
|
||||
entry.status != TurnCostStatus::Running && entry.next_poll_at <= now
|
||||
})
|
||||
.take(MAX_QUERY_TURNS)
|
||||
.map(|(turn_id, _)| turn_id.clone())
|
||||
.collect();
|
||||
if !due_turn_ids.is_empty() {
|
||||
self.poll_entries(&due_turn_ids).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn poll_entries(&mut self, turn_ids: &[String]) {
|
||||
let costs =
|
||||
match tokio::time::timeout(REQUEST_TIMEOUT, self.query_turn_costs(turn_ids)).await {
|
||||
Ok(Ok(Some(costs))) => costs,
|
||||
Ok(Ok(None)) => return,
|
||||
Ok(Err(error)) => {
|
||||
warn!(
|
||||
status = error.status().map(|status| status.as_u16()),
|
||||
"failed to query turn costs"
|
||||
);
|
||||
self.retry_entries(turn_ids);
|
||||
return;
|
||||
}
|
||||
Err(_) => {
|
||||
warn!("timed out querying turn costs");
|
||||
self.retry_entries(turn_ids);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let costs_by_turn: HashMap<String, ApiKeyTurnCost> = costs
|
||||
.into_iter()
|
||||
.map(|cost| (cost.turn_id.clone(), cost))
|
||||
.collect();
|
||||
for turn_id in turn_ids {
|
||||
let Some(cost) = costs_by_turn.get(turn_id) else {
|
||||
self.retry_entry(turn_id);
|
||||
continue;
|
||||
};
|
||||
self.process_turn_cost(turn_id, cost);
|
||||
}
|
||||
}
|
||||
|
||||
async fn query_turn_costs(
|
||||
&self,
|
||||
turn_ids: &[String],
|
||||
) -> Result<Option<Vec<ApiKeyTurnCost>>, RequestError> {
|
||||
match &self.backend {
|
||||
TurnCostBackend::OpenAi(auth_manager) => {
|
||||
let Some((auth, captured_factory)) =
|
||||
auth_manager.auth_with_http_client_factory().await
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
let http_client_factory = self
|
||||
.config
|
||||
.http_client_factory()
|
||||
.with_network_policy(captured_factory.network_policy().clone());
|
||||
if auth.is_chatgpt_auth() {
|
||||
return self
|
||||
.query_chatgpt_turn_costs(&auth, http_client_factory, turn_ids)
|
||||
.await
|
||||
.map(Some);
|
||||
}
|
||||
if !auth.is_api_key_auth() {
|
||||
return Ok(None);
|
||||
}
|
||||
let provider = self
|
||||
.config
|
||||
.model_provider
|
||||
.to_api_provider(Some(AuthMode::ApiKey))
|
||||
.map_err(|error| RequestError::Other(error.into()))?;
|
||||
let client = BackendClient::from_auth_with_runtime(
|
||||
self.config.chatgpt_backend_url().resolve(&auth),
|
||||
&auth,
|
||||
http_client_factory,
|
||||
self.runtime_auth.as_ref(),
|
||||
&provider.headers,
|
||||
)
|
||||
.await
|
||||
.map_err(RequestError::Other)?;
|
||||
client
|
||||
.query_api_key_turn_costs(turn_ids, &provider.headers)
|
||||
.await
|
||||
.map(Some)
|
||||
}
|
||||
TurnCostBackend::ModelProvider(model_provider) => {
|
||||
let http_client_factory = self.config.http_client_factory().with_network_policy(
|
||||
self.config
|
||||
.application_network_policy
|
||||
.clone()
|
||||
.for_current_account(),
|
||||
);
|
||||
if model_provider.info().requires_openai_auth {
|
||||
let Some(auth) = model_provider.auth().await else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !auth.is_api_key_auth() {
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
let resolved = codex_model_provider::resolve_request(
|
||||
model_provider.as_ref(),
|
||||
/*scope*/ None,
|
||||
/*routing*/ None,
|
||||
http_client_factory,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| RequestError::Other(error.into()))?;
|
||||
let provider = resolved.api_provider;
|
||||
let endpoint = provider.url_for_path("analytics/codex/turn-costs");
|
||||
let client =
|
||||
BackendClient::new(provider.base_url.clone(), resolved.http_client_factory)
|
||||
.with_auth_provider(resolved.api_auth)
|
||||
.map_err(RequestError::Other)?;
|
||||
client
|
||||
.query_api_key_turn_costs_at(&endpoint, turn_ids, &provider.headers)
|
||||
.await
|
||||
.map(Some)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn process_turn_cost(&mut self, turn_id: &str, cost: &ApiKeyTurnCost) {
|
||||
if cost.status != ApiKeyTurnCostStatus::Priced {
|
||||
self.retry_entry(turn_id);
|
||||
return;
|
||||
}
|
||||
let response_count = cost
|
||||
.responses
|
||||
.as_ref()
|
||||
.map(|responses| responses.len() as u64)
|
||||
.or(cost.event_count);
|
||||
let (Some(total_usd), Some(response_count)) = (cost.total_usd.as_deref(), response_count)
|
||||
else {
|
||||
self.retry_entry(turn_id);
|
||||
return;
|
||||
};
|
||||
let Some(entry) = self.turns.get(turn_id) else {
|
||||
return;
|
||||
};
|
||||
if response_count < entry.expected_response_ids.len() as u64 {
|
||||
self.retry_entry(turn_id);
|
||||
return;
|
||||
}
|
||||
let mut session_telemetry = entry.session_telemetry.clone();
|
||||
if let Some(model) = cost.model.as_deref() {
|
||||
session_telemetry = session_telemetry.with_model(model, model);
|
||||
}
|
||||
let Some(entry) = self.turns.remove(turn_id) else {
|
||||
return;
|
||||
};
|
||||
session_telemetry.record_turn_cost(
|
||||
turn_id,
|
||||
total_usd,
|
||||
entry.status == TurnCostStatus::Interrupted,
|
||||
cost.speed.as_deref(),
|
||||
cost.reasoning_effort.as_deref(),
|
||||
);
|
||||
}
|
||||
|
||||
fn retry_entries(&mut self, turn_ids: &[String]) {
|
||||
for turn_id in turn_ids {
|
||||
self.retry_entry(turn_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn retry_entry(&mut self, turn_id: &str) {
|
||||
let Some(entry) = self.turns.get_mut(turn_id) else {
|
||||
return;
|
||||
};
|
||||
entry.attempt_count = entry.attempt_count.saturating_add(1);
|
||||
if entry.attempt_count >= MAX_STALLED_POLL_ATTEMPTS {
|
||||
warn!(
|
||||
thread_id = %entry.thread_id,
|
||||
turn_id,
|
||||
attempts = MAX_STALLED_POLL_ATTEMPTS,
|
||||
"dropping turn cost event after repeated unsuccessful polls"
|
||||
);
|
||||
self.turns.remove(turn_id);
|
||||
return;
|
||||
}
|
||||
entry.next_poll_at = Instant::now() + POLL_INTERVAL;
|
||||
}
|
||||
}
|
||||
|
||||
#[path = "turn_cost_worker_chatgpt.rs"]
|
||||
mod chatgpt;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "turn_cost_worker_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,86 +0,0 @@
|
||||
//! Adapts workspace-visible SiWC estimates to the shared turn-cost emission path.
|
||||
//! Emit only nonnegative, visible amounts covering every observed completed response;
|
||||
//! missing amounts/settlement data must never be interpreted as a zero-cost turn.
|
||||
|
||||
use super::ApiKeyTurnCost;
|
||||
use super::ApiKeyTurnCostStatus;
|
||||
use super::BackendClient;
|
||||
use super::RequestError;
|
||||
use super::WorkerRuntime;
|
||||
use codex_login::CodexAuth;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
impl WorkerRuntime {
|
||||
pub(super) async fn query_chatgpt_turn_costs(
|
||||
&self,
|
||||
auth: &CodexAuth,
|
||||
http_client_factory: codex_http_client::HttpClientFactory,
|
||||
turn_ids: &[String],
|
||||
) -> Result<Vec<ApiKeyTurnCost>, RequestError> {
|
||||
let mut threads: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
for turn_id in turn_ids {
|
||||
// Availability probes use an untracked, random thread/turn pair.
|
||||
let thread_id = self
|
||||
.turns
|
||||
.get(turn_id)
|
||||
.map(|entry| entry.thread_id)
|
||||
.unwrap_or_default();
|
||||
threads
|
||||
.entry(thread_id.to_string())
|
||||
.or_default()
|
||||
.push(turn_id.clone());
|
||||
}
|
||||
let client = BackendClient::from_auth_with_runtime(
|
||||
self.config.chatgpt_base_url.clone(),
|
||||
auth,
|
||||
http_client_factory,
|
||||
self.runtime_auth.as_ref(),
|
||||
/*headers*/ &Default::default(),
|
||||
)
|
||||
.await
|
||||
.map_err(RequestError::Other)?;
|
||||
let costs = client.query_chatgpt_turn_costs(&threads).await?;
|
||||
let mut settled_costs = Vec::new();
|
||||
for thread in costs {
|
||||
let Some(requested_turns) = threads.get(&thread.thread_id) else {
|
||||
continue;
|
||||
};
|
||||
for cost in thread.turns {
|
||||
if !requested_turns.contains(&cost.turn_id) {
|
||||
continue;
|
||||
}
|
||||
let Some(entry) = self.turns.get(&cost.turn_id) else {
|
||||
continue;
|
||||
};
|
||||
let (Some(micros), Some(settled_ids)) =
|
||||
(cost.estimated_usage_usd_micros, cost.settled_response_ids)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// Missing/hidden dollars are not zero. A projection can appear before
|
||||
// all responses settle, so require every locally observed response.
|
||||
if micros < 0
|
||||
|| entry.expected_response_ids.is_empty()
|
||||
|| !entry
|
||||
.expected_response_ids
|
||||
.iter()
|
||||
.all(|id| settled_ids.contains(id))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// Reuse the existing emission path without a floating-point conversion.
|
||||
settled_costs.push(ApiKeyTurnCost {
|
||||
turn_id: cost.turn_id,
|
||||
status: ApiKeyTurnCostStatus::Priced,
|
||||
total_usd: Some(format!("{}.{:06}", micros / 1_000_000, micros % 1_000_000)),
|
||||
event_count: Some(settled_ids.len() as u64),
|
||||
responses: None,
|
||||
model: cost.model,
|
||||
speed: None,
|
||||
reasoning_effort: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(settled_costs)
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
//! Checks unusable SiWC estimates and exact conversion; public app-server/OTLP coverage lives in turn_cost_otel.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use test_case::test_case;
|
||||
|
||||
#[test_case(json!(null), json!(["resp-one", "resp-two"]), None; "hidden or incomplete amount")]
|
||||
#[test_case(json!(-1), json!(["resp-one", "resp-two"]), None; "negative amount")]
|
||||
#[test_case(json!(1), json!(null), None; "missing settlement")]
|
||||
#[test_case(json!(1), json!([]), None; "unsettled")]
|
||||
#[test_case(json!(1), json!(["unrelated"]), None; "wrong response")]
|
||||
#[test_case(json!(1), json!(["resp-one"]), None; "only one response settled")]
|
||||
#[test_case(json!(0), json!(["resp-one", "resp-two"]), Some("0.000000"); "zero")]
|
||||
#[test_case(json!(i64::MAX), json!(["resp-one", "resp-two"]), Some("9223372036854.775807"); "integer precision")]
|
||||
#[tokio::test]
|
||||
async fn chatgpt_cost_requires_visible_amount_and_matching_settlement(
|
||||
micros: Value,
|
||||
settled_ids: Value,
|
||||
expected: Option<&str>,
|
||||
) {
|
||||
let server = MockServer::start().await;
|
||||
let mut runtime = test_runtime(
|
||||
&server,
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing()),
|
||||
)
|
||||
.await;
|
||||
let thread_id = ThreadId::new();
|
||||
runtime.turns.insert(
|
||||
"turn-1".to_string(),
|
||||
TurnCostEntry {
|
||||
thread_id,
|
||||
session_telemetry: test_session_telemetry(thread_id),
|
||||
expected_response_ids: HashSet::from(["resp-one".to_string(), "resp-two".to_string()]),
|
||||
status: TurnCostStatus::Completed,
|
||||
next_poll_at: Instant::now(),
|
||||
attempt_count: 0,
|
||||
},
|
||||
);
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/api/codex/usage/thread-estimates/query"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_json(json!({"threads": [{
|
||||
"thread_id": thread_id, "turns": [{"turn_id": "turn-1",
|
||||
"estimated_usage_usd_micros": micros, "settled_response_ids": settled_ids}]
|
||||
}]})),
|
||||
)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let costs = runtime
|
||||
.query_turn_costs(&["turn-1".to_string()])
|
||||
.await
|
||||
.expect("query")
|
||||
.expect("SiWC enabled");
|
||||
assert_eq!(
|
||||
costs,
|
||||
expected
|
||||
.map(|amount| ApiKeyTurnCost {
|
||||
turn_id: "turn-1".to_string(),
|
||||
status: ApiKeyTurnCostStatus::Priced,
|
||||
total_usd: Some(amount.to_string()),
|
||||
event_count: Some(2),
|
||||
responses: None,
|
||||
model: None,
|
||||
speed: None,
|
||||
reasoning_effort: None,
|
||||
})
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
//! Exercise runtime-authenticated turn-cost requests through OpenAI and provider aliases.
|
||||
|
||||
use super::*;
|
||||
use codex_features::RuntimeAuthMode;
|
||||
use codex_runtime_agent_instance::AgentHostAuthorization;
|
||||
use codex_runtime_agent_instance::RuntimeAuthManager;
|
||||
use codex_runtime_agent_instance::RuntimeRegistrationMetadata;
|
||||
use codex_runtime_agent_instance::RuntimeRole;
|
||||
use pretty_assertions::assert_eq;
|
||||
use test_case::test_case;
|
||||
use wiremock::matchers::body_partial_json;
|
||||
|
||||
#[test_case(false; "default OpenAI provider")]
|
||||
#[test_case(true; "OpenAI alias")]
|
||||
#[tokio::test]
|
||||
async fn turn_costs_register_with_requested_organization(openai_alias: bool) {
|
||||
for mode in [RuntimeAuthMode::DualHeader, RuntimeAuthMode::AssertionOnly] {
|
||||
let server = MockServer::start().await;
|
||||
let registration = if openai_alias {
|
||||
ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"runtime_agent_instance_id": "runtime-telemetry", "agent_host_id": "host-a",
|
||||
"actor": {"kind": "platform", "user_id": "user-a", "organization_id": "org-a", "project_id": null},
|
||||
}))
|
||||
} else {
|
||||
// Inspect registration without sending a request to the real OpenAI destination.
|
||||
ResponseTemplate::new(403)
|
||||
};
|
||||
Mock::given(path("/agent/register"))
|
||||
.and(body_partial_json(serde_json::json!({
|
||||
"actor_auth": {"organization_id": "org-a"},
|
||||
})))
|
||||
.respond_with(registration)
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(path(TURN_COST_PATH))
|
||||
.and(header("openai-organization", "org-a"))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(200).set_body_json(serde_json::json!({"turns": []})),
|
||||
)
|
||||
.expect(if openai_alias { 2 } else { 0 })
|
||||
.mount(&server)
|
||||
.await;
|
||||
let credentials = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("key-a"));
|
||||
let mut worker = test_runtime(&server, credentials.clone()).await;
|
||||
let owner = Arc::new(RuntimeAuthManager::new(
|
||||
credentials.clone(),
|
||||
AgentHostAuthorization::InstallationId {
|
||||
installation_id: uuid::Uuid::nil(),
|
||||
},
|
||||
RuntimeRegistrationMetadata {
|
||||
harness: Some("codex".into()),
|
||||
harness_version: None,
|
||||
role: RuntimeRole::Orchestrator,
|
||||
},
|
||||
format!("{}/agent/register", server.uri()).parse().unwrap(),
|
||||
));
|
||||
let mut info = codex_model_provider_info::ModelProviderInfo::create_openai_provider(Some(
|
||||
format!("{}/v1", server.uri()),
|
||||
));
|
||||
info.name = "OpenAI alias".to_string();
|
||||
info.http_headers = Some(HashMap::from([(
|
||||
"OpenAI-Organization".to_string(),
|
||||
"org-a".into(),
|
||||
)]));
|
||||
if openai_alias {
|
||||
worker.backend = TurnCostBackend::ModelProvider(
|
||||
codex_model_provider::test_support::runtime_model_provider(
|
||||
info,
|
||||
credentials,
|
||||
(owner, mode),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
let config = Arc::make_mut(&mut worker.config);
|
||||
config.model_provider = info;
|
||||
config.chatgpt_base_url = "https://chatgpt.com".to_string();
|
||||
worker.runtime_auth = Some((owner, mode));
|
||||
worker
|
||||
.query_turn_costs(&[])
|
||||
.await
|
||||
.expect_err("registration denial must stop the cost request");
|
||||
server.verify().await;
|
||||
continue;
|
||||
}
|
||||
for _ in 0..2 {
|
||||
assert!(
|
||||
worker
|
||||
.query_turn_costs(&[])
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
let requests = server.received_requests().await.unwrap();
|
||||
let proofs: Vec<_> = requests
|
||||
.iter()
|
||||
.filter(|r| r.url.path() != "/agent/register")
|
||||
.map(|r| {
|
||||
let authorization = r.headers["authorization"].to_str().unwrap();
|
||||
match mode {
|
||||
RuntimeAuthMode::DualHeader => {
|
||||
assert_eq!(authorization, "Bearer key-a");
|
||||
r.headers["x-openai-agent-assertion"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
}
|
||||
RuntimeAuthMode::AssertionOnly => {
|
||||
assert!(!r.headers.contains_key("x-openai-agent-assertion"));
|
||||
authorization
|
||||
.strip_prefix("AgentAssertion ")
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(proofs.len(), 2);
|
||||
assert_eq!(proofs.iter().collect::<HashSet<_>>().len(), 2);
|
||||
server.verify().await;
|
||||
}
|
||||
}
|
||||
@@ -1,507 +0,0 @@
|
||||
use super::*;
|
||||
use codex_backend_client::ApiKeyResponseCost;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_login::AuthCredentialsStoreMode;
|
||||
use codex_login::AuthKeyringBackendKind;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::login_with_api_key;
|
||||
use codex_model_provider::create_model_provider;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_otel::TelemetryAuthMode;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::TurnStartedEvent;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use test_case::test_case;
|
||||
use tokio::time::timeout;
|
||||
use tracing::instrument::WithSubscriber;
|
||||
use tracing_subscriber::layer::SubscriberExt;
|
||||
use wiremock::Mock;
|
||||
use wiremock::MockServer;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::header;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
const TURN_COST_PATH: &str = "/v1/analytics/codex/turn-costs";
|
||||
|
||||
#[path = "turn_cost_worker_chatgpt_tests.rs"]
|
||||
mod chatgpt;
|
||||
|
||||
#[tokio::test]
|
||||
async fn worker_starts_with_otlp_metrics_exporter_without_log_exporter() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path(TURN_COST_PATH))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"turns": []
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let codex_home = TempDir::new().expect("temporary Codex home");
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.expect("test config");
|
||||
config.chatgpt_base_url = server.uri();
|
||||
config.otel.exporter = OtelExporterKind::None;
|
||||
config.otel.metrics_exporter = OtelExporterKind::OtlpGrpc {
|
||||
endpoint: server.uri(),
|
||||
headers: HashMap::new(),
|
||||
tls: None,
|
||||
};
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test"));
|
||||
|
||||
let worker = TurnCostWorker::spawn(Arc::new(config), auth_manager, /*runtime_auth*/ None)
|
||||
.expect("OTLP metrics exporter should enable turn-cost collection");
|
||||
wait_for_request_count(&server, /*expected*/ 1).await;
|
||||
worker.shutdown();
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn handle_observes_only_matching_model_provider() {
|
||||
let codex_home = TempDir::new().expect("temporary Codex home");
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.expect("test config");
|
||||
let model_provider = ModelProviderInfo {
|
||||
name: "provider-a".to_string(),
|
||||
base_url: Some("https://provider-a.example/v1".to_string()),
|
||||
..Default::default()
|
||||
};
|
||||
config.model_provider = model_provider.clone();
|
||||
let config = Arc::new(config);
|
||||
let (sender, mut receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY);
|
||||
let handle = TurnCostWorkerHandle {
|
||||
sender,
|
||||
backend: TurnCostBackend::ModelProvider(create_model_provider(
|
||||
model_provider.clone(),
|
||||
/*auth_manager*/ None,
|
||||
)),
|
||||
config: Arc::clone(&config),
|
||||
};
|
||||
let thread_id = ThreadId::new();
|
||||
let event = Event {
|
||||
id: "turn-1".to_string(),
|
||||
msg: EventMsg::TurnStarted(TurnStartedEvent {
|
||||
turn_attribution: None,
|
||||
turn_id: "turn-1".to_string(),
|
||||
root_turn_id: None,
|
||||
trace_id: None,
|
||||
started_at: None,
|
||||
model_context_window: None,
|
||||
collaboration_mode_kind: Default::default(),
|
||||
}),
|
||||
};
|
||||
let mut mismatched_config = config.as_ref().clone();
|
||||
mismatched_config.model_provider = ModelProviderInfo {
|
||||
base_url: Some("https://provider-b.example/v1".to_string()),
|
||||
..model_provider
|
||||
};
|
||||
|
||||
handle.observe_event(thread_id, &mismatched_config, &event, || {
|
||||
panic!("telemetry should not be captured for a mismatched provider")
|
||||
});
|
||||
assert!(receiver.try_recv().is_err());
|
||||
|
||||
handle.observe_event(thread_id, config.as_ref(), &event, || {
|
||||
test_session_telemetry(thread_id)
|
||||
});
|
||||
let observation = receiver.recv().await.expect("matching observation");
|
||||
assert_eq!(observation.thread_id, thread_id);
|
||||
assert_eq!(observation.turn_id, "turn-1");
|
||||
assert!(matches!(
|
||||
observation.kind,
|
||||
TurnCostObservationKind::Started { .. }
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn worker_waits_for_late_api_key_login() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path(TURN_COST_PATH))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"turns": []
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let auth_home = TempDir::new().expect("temporary auth home");
|
||||
let auth_manager = auth_manager_at(auth_home.path()).await;
|
||||
let runtime = test_runtime(&server, Arc::clone(&auth_manager)).await;
|
||||
let (_sender, receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY);
|
||||
let shutdown = CancellationToken::new();
|
||||
let mut task = tokio::spawn(runtime.run(receiver, shutdown.clone()));
|
||||
|
||||
assert!(
|
||||
timeout(Duration::from_millis(/*millis*/ 50), &mut task)
|
||||
.await
|
||||
.is_err(),
|
||||
"worker exited while waiting for login"
|
||||
);
|
||||
login_with_api_key(
|
||||
auth_home.path(),
|
||||
"sk-test",
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("write API-key auth");
|
||||
assert!(auth_manager.reload().await);
|
||||
wait_for_request_count(&server, /*expected*/ 1).await;
|
||||
|
||||
shutdown.cancel();
|
||||
task.await.expect("worker task");
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_provider_auth_failure_retries_without_auth_changes() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/analytics/codex/turn-costs"))
|
||||
.and(header("authorization", "Bearer sk-old"))
|
||||
.respond_with(ResponseTemplate::new(401))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/analytics/codex/turn-costs"))
|
||||
.and(header("authorization", "Bearer sk-new-token"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
|
||||
"turns": []
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let provider_auth_home = TempDir::new().expect("temporary provider auth home");
|
||||
login_with_api_key(
|
||||
provider_auth_home.path(),
|
||||
"sk-old",
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("write initial provider auth");
|
||||
let provider_auth_manager = auth_manager_at(provider_auth_home.path()).await;
|
||||
let codex_home = TempDir::new().expect("temporary Codex home");
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.expect("test config");
|
||||
config.model_provider = ModelProviderInfo {
|
||||
name: "custom-provider".to_string(),
|
||||
base_url: Some(server.uri()),
|
||||
requires_openai_auth: true,
|
||||
..Default::default()
|
||||
};
|
||||
let backend = TurnCostBackend::ModelProvider(create_model_provider(
|
||||
config.model_provider.clone(),
|
||||
Some(Arc::clone(&provider_auth_manager)),
|
||||
));
|
||||
let runtime = WorkerRuntime {
|
||||
config: Arc::new(config),
|
||||
backend,
|
||||
turns: HashMap::new(),
|
||||
runtime_auth: None,
|
||||
};
|
||||
assert_eq!(
|
||||
runtime.probe_backend().await,
|
||||
BackendAvailability::RetryProbe
|
||||
);
|
||||
login_with_api_key(
|
||||
provider_auth_home.path(),
|
||||
"sk-new-token",
|
||||
AuthCredentialsStoreMode::File,
|
||||
AuthKeyringBackendKind::default(),
|
||||
)
|
||||
.expect("update provider auth");
|
||||
provider_auth_manager.reload().await;
|
||||
assert_eq!(runtime.probe_backend().await, BackendAvailability::Ready);
|
||||
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_provider_does_not_send_chatgpt_auth_for_turn_costs() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/analytics/codex/turn-costs"))
|
||||
.respond_with(ResponseTemplate::new(500))
|
||||
.mount(&server)
|
||||
.await;
|
||||
let auth_manager =
|
||||
AuthManager::from_auth_for_testing(CodexAuth::create_dummy_chatgpt_auth_for_testing());
|
||||
let codex_home = TempDir::new().expect("temporary Codex home");
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.expect("test config");
|
||||
config.model_provider = ModelProviderInfo {
|
||||
name: "custom-provider".to_string(),
|
||||
base_url: Some(server.uri()),
|
||||
requires_openai_auth: true,
|
||||
..Default::default()
|
||||
};
|
||||
let backend = TurnCostBackend::ModelProvider(create_model_provider(
|
||||
config.model_provider.clone(),
|
||||
Some(Arc::clone(&auth_manager)),
|
||||
));
|
||||
let runtime = WorkerRuntime {
|
||||
config: Arc::new(config),
|
||||
backend,
|
||||
turns: HashMap::new(),
|
||||
runtime_auth: None,
|
||||
};
|
||||
|
||||
assert_eq!(runtime.probe_backend().await, BackendAvailability::Disabled);
|
||||
let requests = server.received_requests().await.expect("received requests");
|
||||
assert!(requests.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn transient_probe_failure_keeps_worker_alive() {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path(TURN_COST_PATH))
|
||||
.respond_with(ResponseTemplate::new(500).set_body_string("temporary failure"))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test"));
|
||||
let runtime = test_runtime(&server, Arc::clone(&auth_manager)).await;
|
||||
let backend_availability = runtime.probe_backend().await;
|
||||
assert_eq!(backend_availability, BackendAvailability::RetryProbe);
|
||||
let (_sender, receiver) = mpsc::channel(OBSERVATION_CHANNEL_CAPACITY);
|
||||
let shutdown = CancellationToken::new();
|
||||
let auth_changes = Some(auth_manager.auth_change_receiver());
|
||||
let mut task = tokio::spawn(runtime.run_with_backend_availability(
|
||||
receiver,
|
||||
shutdown.clone(),
|
||||
auth_changes,
|
||||
backend_availability,
|
||||
));
|
||||
|
||||
assert!(
|
||||
timeout(Duration::from_millis(/*millis*/ 50), &mut task)
|
||||
.await
|
||||
.is_err(),
|
||||
"worker exited after a transient probe failure"
|
||||
);
|
||||
|
||||
shutdown.cancel();
|
||||
task.await.expect("worker task");
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn priced_cost_uses_telemetry_captured_before_thread_removal() {
|
||||
let server = MockServer::start().await;
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test"));
|
||||
let mut runtime = test_runtime(&server, auth_manager).await;
|
||||
let thread_id = ThreadId::new();
|
||||
let turn_id = "turn-1";
|
||||
|
||||
runtime.record_observation(TurnCostObservation {
|
||||
thread_id,
|
||||
turn_id: turn_id.to_string(),
|
||||
kind: TurnCostObservationKind::Started {
|
||||
session_telemetry: Box::new(test_session_telemetry(thread_id)),
|
||||
},
|
||||
});
|
||||
runtime.record_observation(TurnCostObservation {
|
||||
thread_id,
|
||||
turn_id: turn_id.to_string(),
|
||||
kind: TurnCostObservationKind::ResponseCompleted {
|
||||
response_id: "resp-one".to_string(),
|
||||
},
|
||||
});
|
||||
runtime.record_observation(TurnCostObservation {
|
||||
thread_id,
|
||||
turn_id: turn_id.to_string(),
|
||||
kind: TurnCostObservationKind::Finished { interrupted: false },
|
||||
});
|
||||
|
||||
runtime.process_turn_cost(
|
||||
turn_id,
|
||||
&ApiKeyTurnCost {
|
||||
turn_id: turn_id.to_string(),
|
||||
status: ApiKeyTurnCostStatus::Priced,
|
||||
total_usd: Some("1.25".to_string()),
|
||||
event_count: Some(1),
|
||||
responses: None,
|
||||
model: Some("gpt-5.6".to_string()),
|
||||
speed: Some("fast".to_string()),
|
||||
reasoning_effort: Some("high".to_string()),
|
||||
},
|
||||
);
|
||||
|
||||
assert_eq!(runtime.turns.len(), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn priced_cost_waits_for_every_response_when_response_costs_are_available() {
|
||||
let server = MockServer::start().await;
|
||||
let auth_manager = AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test"));
|
||||
let mut runtime = test_runtime(&server, auth_manager).await;
|
||||
let thread_id = ThreadId::new();
|
||||
let turn_id = "turn-1";
|
||||
|
||||
runtime.turns.insert(
|
||||
turn_id.to_string(),
|
||||
TurnCostEntry {
|
||||
thread_id,
|
||||
session_telemetry: test_session_telemetry(thread_id),
|
||||
expected_response_ids: HashSet::from(["resp-one".to_string(), "resp-two".to_string()]),
|
||||
status: TurnCostStatus::Completed,
|
||||
next_poll_at: Instant::now(),
|
||||
attempt_count: 0,
|
||||
},
|
||||
);
|
||||
|
||||
let mut cost = ApiKeyTurnCost {
|
||||
turn_id: turn_id.to_string(),
|
||||
status: ApiKeyTurnCostStatus::Priced,
|
||||
total_usd: Some("1.25".to_string()),
|
||||
event_count: Some(2),
|
||||
responses: Some(vec![ApiKeyResponseCost {
|
||||
response_id: "resp-one".to_string(),
|
||||
total_usd: "1.25".to_string(),
|
||||
}]),
|
||||
model: Some("gpt-5.6".to_string()),
|
||||
speed: Some("fast".to_string()),
|
||||
reasoning_effort: Some("high".to_string()),
|
||||
};
|
||||
runtime.process_turn_cost(turn_id, &cost);
|
||||
|
||||
let entry = runtime.turns.get(turn_id).expect("turn remains tracked");
|
||||
assert_eq!(entry.attempt_count, 1);
|
||||
|
||||
cost.event_count = None;
|
||||
cost.responses
|
||||
.as_mut()
|
||||
.expect("response costs")
|
||||
.push(ApiKeyResponseCost {
|
||||
response_id: "resp-two".to_string(),
|
||||
total_usd: "0.50".to_string(),
|
||||
});
|
||||
runtime.process_turn_cost(turn_id, &cost);
|
||||
|
||||
assert_eq!(runtime.turns.len(), 0);
|
||||
}
|
||||
|
||||
async fn test_runtime(server: &MockServer, auth_manager: Arc<AuthManager>) -> WorkerRuntime {
|
||||
let codex_home = TempDir::new().expect("temporary Codex home");
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.build()
|
||||
.await
|
||||
.expect("test config");
|
||||
config.chatgpt_base_url = server.uri();
|
||||
let backend = TurnCostBackend::OpenAi(Arc::clone(&auth_manager));
|
||||
WorkerRuntime {
|
||||
config: Arc::new(config),
|
||||
backend,
|
||||
turns: HashMap::new(),
|
||||
runtime_auth: None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn auth_manager_at(codex_home: &std::path::Path) -> Arc<AuthManager> {
|
||||
Arc::new(
|
||||
AuthManager::new(
|
||||
codex_home.to_path_buf(),
|
||||
/*enable_codex_api_key_env*/ false,
|
||||
AuthCredentialsStoreMode::File,
|
||||
/*forced_chatgpt_workspace_id*/ None,
|
||||
/*chatgpt_base_url*/ None,
|
||||
AuthKeyringBackendKind::default(),
|
||||
codex_login::test_support::transport_default_auth_route_config(),
|
||||
)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
fn test_session_telemetry(thread_id: ThreadId) -> SessionTelemetry {
|
||||
SessionTelemetry::new(
|
||||
thread_id,
|
||||
"gpt-5.6",
|
||||
"gpt-5.6",
|
||||
/*account_id*/ None,
|
||||
/*account_email*/ None,
|
||||
Some(TelemetryAuthMode::ApiKey),
|
||||
"test".to_string(),
|
||||
/*log_user_prompts*/ false,
|
||||
"test".to_string(),
|
||||
SessionSource::Cli,
|
||||
)
|
||||
}
|
||||
|
||||
async fn wait_for_request_count(server: &MockServer, expected: usize) {
|
||||
timeout(Duration::from_secs(/*secs*/ 15), async {
|
||||
loop {
|
||||
let requests = server.received_requests().await.unwrap_or_default();
|
||||
if requests.len() >= expected {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("timed out waiting for turn-cost request");
|
||||
}
|
||||
|
||||
#[test_case(500; "HTTP failure")]
|
||||
#[test_case(200; "decode failure")]
|
||||
#[tokio::test]
|
||||
async fn turn_cost_failures_do_not_log_response_bodies(status: u16) {
|
||||
let server = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path(TURN_COST_PATH))
|
||||
.respond_with(
|
||||
ResponseTemplate::new(status).set_body_string("private-workspace-response-marker"),
|
||||
)
|
||||
.expect(2)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let mut runtime = test_runtime(
|
||||
&server,
|
||||
AuthManager::from_auth_for_testing(CodexAuth::from_api_key("sk-test")),
|
||||
)
|
||||
.await;
|
||||
let capture = tempfile::NamedTempFile::new().expect("log capture");
|
||||
let subscriber = tracing_subscriber::fmt()
|
||||
.with_ansi(false)
|
||||
.with_max_level(tracing::Level::DEBUG)
|
||||
.with_writer(Arc::new(capture.reopen().expect("log writer")))
|
||||
.finish();
|
||||
// A parallel test can first register this callsite without a subscriber.
|
||||
// Keep two dispatchers alive so it cannot globally disable our log capture.
|
||||
let _parallel_dispatch = tracing::Dispatch::new(
|
||||
tracing_subscriber::registry().with(tracing_subscriber::filter::LevelFilter::OFF),
|
||||
);
|
||||
async {
|
||||
assert_eq!(
|
||||
runtime.probe_backend().await,
|
||||
BackendAvailability::RetryProbe
|
||||
);
|
||||
runtime.poll_entries(&["turn-1".to_string()]).await;
|
||||
}
|
||||
.with_subscriber(subscriber)
|
||||
.await;
|
||||
let logs = std::fs::read_to_string(capture.path()).expect("captured logs");
|
||||
assert!(logs.contains("backend availability check failed temporarily"));
|
||||
assert!(logs.contains("failed to query turn costs"));
|
||||
assert!(!logs.contains("private-workspace-response-marker"));
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[path = "turn_cost_worker_runtime_auth_tests.rs"]
|
||||
mod runtime_auth;
|
||||
@@ -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
@@ -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))
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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(())
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user