WIP fase 2b-3: rimozione sottosistemi solo-ChatGPT (plugin remoti, image gen, daybreak, cyber, attestation, cloud config, app/connettori) - test in corso
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -17,7 +17,6 @@ anyhow = { workspace = true }
|
||||
codex-core = { workspace = true }
|
||||
codex-core-plugins = { workspace = true }
|
||||
codex-config = { workspace = true }
|
||||
codex-connectors = { workspace = true }
|
||||
codex-exec-server = { workspace = true }
|
||||
codex-extension-api = { workspace = true }
|
||||
codex-features = { workspace = true }
|
||||
|
||||
@@ -1,249 +0,0 @@
|
||||
//! Refreshes cloud plugins each turn and after auth changes.
|
||||
|
||||
use crate::PluginListQuery;
|
||||
use crate::PluginsThreadState;
|
||||
use crate::plugin_contributor::PluginContributor;
|
||||
use codex_core::config::Config;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_extension_api::CatalogRefreshBackoff;
|
||||
use codex_extension_api::CatalogRefreshInput;
|
||||
use codex_extension_api::ConfigContributor;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::McpServerContribution;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_extension_api::TurnLifecycleContributor;
|
||||
use codex_extension_api::TurnStartInput;
|
||||
use codex_extension_api::TurnStartPhase;
|
||||
use codex_features::Feature;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_mcp::McpResourceClientAuthKey;
|
||||
use std::collections::HashSet;
|
||||
|
||||
const MAX_PROJECTED_CLOUD_PLUGINS: usize = 100;
|
||||
pub(crate) const MAX_PLUGIN_DISPLAY_NAME_CHARS: usize = 64;
|
||||
pub(crate) const MAX_CONNECTOR_IDS_PER_PLUGIN: usize = 64;
|
||||
|
||||
/// Auth scope of the latest catalog accepted for this turn.
|
||||
struct LatestCloudPluginAuth(Option<McpResourceClientAuthKey>);
|
||||
|
||||
impl PluginContributor {
|
||||
#[expect(
|
||||
clippy::await_holding_invalid_type,
|
||||
reason = "cloud discovery must remain serialized through fetching and catalog publication"
|
||||
)]
|
||||
async fn refresh_cloud_catalog(&self, input: CatalogRefreshInput<'_>) -> bool {
|
||||
let Some(provider) = &self.providers.cloud else {
|
||||
return false;
|
||||
};
|
||||
let Some(state) = input.thread_store.get::<PluginsThreadState>() else {
|
||||
return false;
|
||||
};
|
||||
// Wait without holding catalog state or the MCP runtime permit, then recheck the cache.
|
||||
let (mut refresh_succeeded, waited) = match state.cloud_refresh_lock.try_lock() {
|
||||
Ok(guard) => (guard, false),
|
||||
Err(_) => (state.cloud_refresh_lock.lock().await, true),
|
||||
};
|
||||
let query = PluginListQuery {
|
||||
thread_id: input.thread_store.level_id().to_string(),
|
||||
turn_id: input.turn_id.to_string(),
|
||||
mcp_resources: input.session_store.get::<McpResourceClient>(),
|
||||
snapshots: Vec::new(),
|
||||
};
|
||||
let (auth_cache_key, resource_cache_key, catalog_cleared) =
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
if !state.plugins_enabled {
|
||||
return false;
|
||||
}
|
||||
let auth = query
|
||||
.mcp_resources
|
||||
.as_ref()
|
||||
.map(|client| client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME));
|
||||
let resource_cache_key = query
|
||||
.mcp_resources
|
||||
.as_ref()
|
||||
.and_then(|client| client.server_cache_key(CODEX_APPS_MCP_SERVER_NAME));
|
||||
if ((waited && *refresh_succeeded)
|
||||
|| input
|
||||
.turn_store
|
||||
.get::<LatestCloudPluginAuth>()
|
||||
.is_some_and(|previous| previous.0 == auth))
|
||||
&& state
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.is_some_and(|generation| generation.auth_cache_key == auth)
|
||||
&& state.cloud_catalog().is_some()
|
||||
{
|
||||
input.turn_store.insert(LatestCloudPluginAuth(auth));
|
||||
return false;
|
||||
}
|
||||
if state.cloud_retry.as_ref().is_some_and(|retry| {
|
||||
retry.is_pending(auth.as_ref(), resource_cache_key.as_ref())
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
// Waiting callers must not reuse a failed or cancelled refresh.
|
||||
*refresh_succeeded = false;
|
||||
input.turn_store.remove::<LatestCloudPluginAuth>();
|
||||
let previous_catalog_auth = state
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.filter(|generation| generation.catalog.is_some())
|
||||
.map(|generation| generation.auth_cache_key.clone());
|
||||
let auth_cache_key =
|
||||
state.prepare_cloud_generation(query.mcp_resources.as_deref().cloned());
|
||||
let catalog_cleared =
|
||||
previous_catalog_auth.is_some_and(|previous| previous != auth_cache_key);
|
||||
(auth_cache_key, resource_cache_key, catalog_cleared)
|
||||
};
|
||||
let result = provider.list(query).await;
|
||||
let mut state = state.contributor_state();
|
||||
let catalog_published = match result {
|
||||
Ok(catalog) => {
|
||||
let published = state.publish_cloud_catalog(auth_cache_key.as_ref(), catalog);
|
||||
if published {
|
||||
state.cloud_retry = None;
|
||||
input
|
||||
.turn_store
|
||||
.insert(LatestCloudPluginAuth(auth_cache_key));
|
||||
*refresh_succeeded = true;
|
||||
} else {
|
||||
tracing::debug!("cloud plugin discovery finished after auth changed");
|
||||
}
|
||||
published
|
||||
}
|
||||
Err(_) => {
|
||||
if state.cloud_generation.as_ref().is_some_and(|generation| {
|
||||
generation.auth_cache_key == auth_cache_key && generation.is_auth_current()
|
||||
}) {
|
||||
state.cloud_retry = Some(CatalogRefreshBackoff::after_failure(
|
||||
auth_cache_key,
|
||||
resource_cache_key,
|
||||
state.cloud_retry.as_ref(),
|
||||
));
|
||||
}
|
||||
tracing::warn!("cloud plugin discovery failed");
|
||||
false
|
||||
}
|
||||
};
|
||||
catalog_cleared || catalog_published
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadLifecycleContributor<Config> for PluginContributor {
|
||||
fn on_thread_start<'a>(
|
||||
&'a self,
|
||||
input: ThreadStartInput<'a, Config>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let state = input.thread_store.get_or_init(PluginsThreadState::default);
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
state.plugins_enabled = input.config.features.enabled(Feature::Plugins);
|
||||
state.extension_metrics = input.extension_metrics;
|
||||
}
|
||||
if let Some(resources) = &input.mcp_resource_client {
|
||||
input.session_store.insert(resources.as_ref().clone());
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigContributor<Config> for PluginContributor {
|
||||
fn on_config_changed(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
_previous_config: &Config,
|
||||
new_config: &Config,
|
||||
) {
|
||||
let plugins_enabled = new_config.features.enabled(Feature::Plugins);
|
||||
let state = thread_store.get_or_init(PluginsThreadState::default);
|
||||
let mut state = state.contributor_state();
|
||||
if state.plugins_enabled != plugins_enabled {
|
||||
state.cloud_retry = None;
|
||||
}
|
||||
state.plugins_enabled = plugins_enabled;
|
||||
if self.providers.cloud.is_none() || !plugins_enabled {
|
||||
state.cloud_generation = None;
|
||||
state.cloud_retry = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TurnLifecycleContributor for PluginContributor {
|
||||
fn turn_start_phase(&self, thread_store: &ExtensionData) -> TurnStartPhase {
|
||||
if self.providers.cloud.is_some()
|
||||
&& thread_store
|
||||
.get::<PluginsThreadState>()
|
||||
.is_some_and(|state| state.contributor_state().plugins_enabled)
|
||||
{
|
||||
TurnStartPhase::RegularTaskStart
|
||||
} else {
|
||||
TurnStartPhase::BeforeTaskRegistration
|
||||
}
|
||||
}
|
||||
|
||||
fn requires_mcp_runtime(&self, thread_store: &ExtensionData) -> bool {
|
||||
self.turn_start_phase(thread_store) == TurnStartPhase::RegularTaskStart
|
||||
}
|
||||
|
||||
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
input.turn_store.remove::<LatestCloudPluginAuth>();
|
||||
self.refresh_cloud_catalog(CatalogRefreshInput {
|
||||
turn_id: input.turn_id,
|
||||
session_store: input.session_store,
|
||||
thread_store: input.thread_store,
|
||||
turn_store: input.turn_store,
|
||||
})
|
||||
.await;
|
||||
})
|
||||
}
|
||||
|
||||
fn refresh_catalog_for_step<'a>(
|
||||
&'a self,
|
||||
input: CatalogRefreshInput<'a>,
|
||||
) -> ExtensionFuture<'a, bool> {
|
||||
Box::pin(self.refresh_cloud_catalog(input))
|
||||
}
|
||||
}
|
||||
|
||||
/// Cloud packages contribute Apps attribution, never executor MCP declarations.
|
||||
pub(crate) fn hosted_plugin_connectors(catalog: &PluginCatalog) -> Vec<McpServerContribution> {
|
||||
catalog
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|entry| entry.enabled)
|
||||
.filter_map(|entry| {
|
||||
let PluginIdentity::Remote { remote_plugin_id } = &entry.id else {
|
||||
return None;
|
||||
};
|
||||
let mut seen_connector_ids = HashSet::new();
|
||||
Some(McpServerContribution::HostedPluginConnectors {
|
||||
plugin_id: remote_plugin_id.clone(),
|
||||
plugin_display_name: entry
|
||||
.display_name
|
||||
.chars()
|
||||
.take(MAX_PLUGIN_DISPLAY_NAME_CHARS)
|
||||
.collect(),
|
||||
connector_ids: entry
|
||||
.connector_ids
|
||||
.iter()
|
||||
.filter(|connector_id| seen_connector_ids.insert((*connector_id).clone()))
|
||||
.take(MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.cloned()
|
||||
.collect(),
|
||||
})
|
||||
})
|
||||
.take(MAX_PROJECTED_CLOUD_PLUGINS)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "cloud_plugin_tests.rs"]
|
||||
mod tests;
|
||||
@@ -1,406 +0,0 @@
|
||||
//! Tests per-turn cloud plugin discovery, auth recovery, tool calls, and plugin policy.
|
||||
|
||||
use super::*;
|
||||
use crate::PluginProvider;
|
||||
use crate::PluginProviderError;
|
||||
use crate::PluginProviderFuture;
|
||||
use crate::PluginProviders;
|
||||
use crate::PluginsThreadState;
|
||||
use crate::install_plugin_providers;
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginCatalogEntry;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_extension_api::ExtensionRegistryBuilder;
|
||||
use codex_extension_api::McpServerContributionContext;
|
||||
use codex_extension_api::McpServerContributor;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_protocol::config_types::CollaborationMode;
|
||||
use codex_protocol::config_types::ModeKind;
|
||||
use codex_protocol::config_types::Settings;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
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 tokio::sync::Notify;
|
||||
|
||||
#[tokio::test]
|
||||
async fn cloud_discovery_selects_regular_task_phase() {
|
||||
struct ExistingContributor;
|
||||
impl TurnLifecycleContributor for ExistingContributor {}
|
||||
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
builder.turn_lifecycle_contributor(Arc::new(ExistingContributor));
|
||||
let executor = Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
)));
|
||||
install_plugin_providers(&mut builder, PluginProviders::new(executor.clone()));
|
||||
install_plugin_providers(
|
||||
&mut builder,
|
||||
PluginProviders::new(executor).with_cloud_provider(Arc::new(CloudProvider::default())),
|
||||
);
|
||||
let registry = builder.build();
|
||||
let thread = ExtensionData::new("thread");
|
||||
for plugins_enabled in [false, true] {
|
||||
thread
|
||||
.get_or_init(PluginsThreadState::default)
|
||||
.contributor_state()
|
||||
.plugins_enabled = plugins_enabled;
|
||||
let dependencies = registry
|
||||
.turn_lifecycle_contributors()
|
||||
.iter()
|
||||
.map(|contributor| contributor.requires_mcp_runtime(&thread))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(dependencies, vec![false, false, plugins_enabled]);
|
||||
let phases = registry
|
||||
.turn_lifecycle_contributors()
|
||||
.iter()
|
||||
.map(|contributor| contributor.turn_start_phase(&thread))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
phases,
|
||||
vec![
|
||||
TurnStartPhase::BeforeTaskRegistration,
|
||||
TurnStartPhase::BeforeTaskRegistration,
|
||||
if plugins_enabled {
|
||||
TurnStartPhase::RegularTaskStart
|
||||
} else {
|
||||
TurnStartPhase::BeforeTaskRegistration
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabling_plugins_clears_cloud_catalog_and_skips_discovery() -> anyhow::Result<()> {
|
||||
let config_home = tempfile::tempdir()?;
|
||||
let mut config = codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(config_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(config_home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
let mode = CollaborationMode {
|
||||
mode: ModeKind::Default,
|
||||
settings: Settings {
|
||||
model: "test".to_string(),
|
||||
reasoning_effort: None,
|
||||
developer_instructions: None,
|
||||
},
|
||||
};
|
||||
let provider = Arc::new(CloudProvider::default());
|
||||
let mut builder = ExtensionRegistryBuilder::new();
|
||||
let providers = PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
))))
|
||||
.with_cloud_provider(provider.clone());
|
||||
install_plugin_providers(&mut builder, providers);
|
||||
let registry = builder.build();
|
||||
let session = ExtensionData::new("session");
|
||||
let thread = ExtensionData::new("thread");
|
||||
let thread_init = codex_extension_api::ExtensionDataInit::default();
|
||||
for (turn_id, plugins_enabled, reply) in [
|
||||
("off", false, Ok(cloud_catalog())),
|
||||
("on", true, Ok(cloud_catalog())),
|
||||
("plugins-off", false, Ok(cloud_catalog())),
|
||||
(
|
||||
"re-enabled-failed",
|
||||
true,
|
||||
Err("discovery unavailable".to_string()),
|
||||
),
|
||||
("failed-plugins-off", false, Ok(cloud_catalog())),
|
||||
("re-enabled", true, Ok(cloud_catalog())),
|
||||
] {
|
||||
let expected_catalog = if plugins_enabled {
|
||||
reply.clone().ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let previous_discoveries = provider.calls.load(Ordering::SeqCst);
|
||||
provider.set_reply(reply);
|
||||
let previous = config.clone();
|
||||
config
|
||||
.features
|
||||
.set_enabled(Feature::Plugins, plugins_enabled)?;
|
||||
for contributor in registry.config_contributors() {
|
||||
contributor.on_config_changed(&session, &thread, &previous, &config);
|
||||
}
|
||||
if !plugins_enabled && let Some(state) = thread.get::<PluginsThreadState>() {
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
}
|
||||
for contributor in registry.turn_lifecycle_contributors() {
|
||||
contributor
|
||||
.on_turn_start(TurnStartInput {
|
||||
turn_id,
|
||||
collaboration_mode: &mode,
|
||||
token_usage_at_turn_start: None,
|
||||
session_store: &session,
|
||||
thread_store: &thread,
|
||||
turn_store: &ExtensionData::new(turn_id),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
registry.mcp_server_contributors()[0]
|
||||
.contribute(codex_extension_api::McpServerContributionContext::for_step(
|
||||
&config,
|
||||
&thread_init,
|
||||
&thread,
|
||||
"test",
|
||||
&[],
|
||||
/*executor_capability_discovery*/ None,
|
||||
/*executor_capability_discovery_v2*/ None,
|
||||
))
|
||||
.await;
|
||||
if let Some(state) = thread.get::<PluginsThreadState>() {
|
||||
assert_eq!(state.cloud_catalog(), expected_catalog, "turn {turn_id}");
|
||||
}
|
||||
assert_eq!(
|
||||
provider.calls.load(Ordering::SeqCst),
|
||||
previous_discoveries + usize::from(plugins_enabled),
|
||||
"turn {turn_id}",
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn account_change_clears_hosted_plugins_before_waiting_for_executor() -> anyhow::Result<()> {
|
||||
struct UnreadyExecutor;
|
||||
impl codex_exec_server::NoiseRendezvousConnectProvider for UnreadyExecutor {
|
||||
fn connect_bundle(
|
||||
&self,
|
||||
_: codex_exec_server::NoiseChannelPublicKey,
|
||||
) -> futures::future::BoxFuture<
|
||||
'_,
|
||||
Result<
|
||||
codex_exec_server::NoiseRendezvousConnectBundle,
|
||||
codex_exec_server::ExecServerError,
|
||||
>,
|
||||
> {
|
||||
Box::pin(futures::future::pending())
|
||||
}
|
||||
}
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let mut config = codex_core::config::ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.fallback_cwd(Some(home.path().to_path_buf()))
|
||||
.build()
|
||||
.await?;
|
||||
config.features.enable(Feature::Plugins)?;
|
||||
let manager = Arc::new(EnvironmentManager::default_for_tests());
|
||||
manager
|
||||
.materialize_pending_noise_environment("unready".to_string(), Arc::new(UnreadyExecutor))?;
|
||||
let contributor = PluginContributor {
|
||||
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(manager)))
|
||||
.with_cloud_provider(Arc::new(CloudProvider::default())),
|
||||
};
|
||||
let thread = ExtensionData::new("thread");
|
||||
let state = thread.get_or_init(PluginsThreadState::default);
|
||||
let old_auth = state
|
||||
.contributor_state()
|
||||
.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
assert!(
|
||||
state
|
||||
.contributor_state()
|
||||
.publish_cloud_catalog(old_auth.as_ref(), cloud_catalog())
|
||||
);
|
||||
let roots = [SelectedCapabilityRoot {
|
||||
id: "plugin".to_string(),
|
||||
location: CapabilityRootLocation::Environment {
|
||||
environment_id: "unready".to_string(),
|
||||
path: PathUri::parse("file:///plugins/demo")?,
|
||||
},
|
||||
}];
|
||||
let init = codex_extension_api::ExtensionDataInit::default();
|
||||
let context = McpServerContributionContext::for_step(
|
||||
&config, &init, &thread, "test", &roots, /*executor_capability_discovery*/ None,
|
||||
/*executor_capability_discovery_v2*/ None,
|
||||
)
|
||||
.with_auth_changed(/*auth_changed*/ true);
|
||||
let mut loading = std::pin::pin!(contributor.selected_plugins(context, &config.plugins));
|
||||
assert!(futures::poll!(&mut loading).is_pending());
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn cloud_refresh_serializes_waiters_and_retries() {
|
||||
let new_catalog = PluginCatalog::default();
|
||||
for (reply, cancelled) in [
|
||||
(Ok(cloud_catalog()), false),
|
||||
(Err("discovery failed".to_string()), false),
|
||||
(Ok(cloud_catalog()), true),
|
||||
] {
|
||||
let succeeded = reply.is_ok() && !cancelled;
|
||||
let expected_catalog = if succeeded {
|
||||
cloud_catalog()
|
||||
} else {
|
||||
new_catalog.clone()
|
||||
};
|
||||
let provider = Arc::new(CloudProvider::default());
|
||||
provider.set_reply(reply);
|
||||
let contributor = PluginContributor {
|
||||
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
))))
|
||||
.with_cloud_provider(provider.clone()),
|
||||
};
|
||||
let session = ExtensionData::new("session");
|
||||
let thread = ExtensionData::new("thread");
|
||||
let turn = ExtensionData::new("turn");
|
||||
let prewarm_turn = ExtensionData::new("prewarm");
|
||||
let input = CatalogRefreshInput {
|
||||
turn_id: "turn",
|
||||
session_store: &session,
|
||||
thread_store: &thread,
|
||||
turn_store: &turn,
|
||||
};
|
||||
let state = thread.get_or_init(PluginsThreadState::default);
|
||||
state.contributor_state().plugins_enabled = true;
|
||||
|
||||
// A delayed prewarm waits without superseding the real turn's request.
|
||||
provider.pause_discovery.store(true, Ordering::SeqCst);
|
||||
let mut turn_start = contributor.refresh_catalog_for_step(input);
|
||||
assert!(futures::poll!(&mut turn_start).is_pending());
|
||||
let prewarm_input = CatalogRefreshInput {
|
||||
turn_id: "prewarm",
|
||||
turn_store: &prewarm_turn,
|
||||
..input
|
||||
};
|
||||
let mut prewarm = contributor.refresh_catalog_for_step(prewarm_input);
|
||||
assert!(futures::poll!(&mut prewarm).is_pending());
|
||||
let mut cancelled_waiter = contributor.refresh_catalog_for_step(prewarm_input);
|
||||
assert!(futures::poll!(&mut cancelled_waiter).is_pending());
|
||||
drop(cancelled_waiter);
|
||||
assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
|
||||
|
||||
provider.set_reply(Ok(new_catalog.clone()));
|
||||
if cancelled {
|
||||
drop(turn_start);
|
||||
} else {
|
||||
provider.resume_discovery.notify_one();
|
||||
assert_eq!(turn_start.await, succeeded);
|
||||
}
|
||||
// Waiting turns share failure cooldowns; cancellation still allows immediate retry.
|
||||
assert_eq!(
|
||||
tokio::time::timeout(Duration::from_secs(5), prewarm)
|
||||
.await
|
||||
.expect("waiting discovery should complete after its predecessor stops"),
|
||||
cancelled,
|
||||
);
|
||||
if !succeeded && !cancelled {
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
assert!(contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
}
|
||||
assert_eq!(state.cloud_catalog(), Some(expected_catalog.clone()));
|
||||
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
assert_eq!(
|
||||
provider.calls.load(Ordering::SeqCst),
|
||||
1 + usize::from(!succeeded),
|
||||
);
|
||||
|
||||
// Retained catalogs do not need MCP rebuilding after failed retries.
|
||||
prewarm_turn.remove::<LatestCloudPluginAuth>();
|
||||
provider.set_reply(Err("discovery failed".to_string()));
|
||||
let previous_calls = provider.calls.load(Ordering::SeqCst);
|
||||
for _ in 0..2 {
|
||||
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
assert_eq!(state.cloud_catalog(), Some(expected_catalog.clone()));
|
||||
}
|
||||
assert_eq!(provider.calls.load(Ordering::SeqCst), previous_calls + 1);
|
||||
|
||||
// Clearing an old auth scope still requires rebuilding, even on failure.
|
||||
session.insert(McpResourceClient::new(Arc::new(
|
||||
codex_mcp::McpRuntime::empty(/*prefix_mcp_tool_names*/ false),
|
||||
)));
|
||||
assert!(contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
assert_eq!(state.cloud_catalog(), None);
|
||||
assert!(!contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
provider.set_reply(Ok(new_catalog.clone()));
|
||||
tokio::time::advance(Duration::from_secs(30)).await;
|
||||
assert!(contributor.refresh_catalog_for_step(prewarm_input).await);
|
||||
}
|
||||
}
|
||||
|
||||
struct CloudProvider {
|
||||
reply: Mutex<Result<PluginCatalog, String>>,
|
||||
calls: AtomicUsize,
|
||||
resources: Mutex<Option<Arc<McpResourceClient>>>,
|
||||
pause_discovery: AtomicBool,
|
||||
discovery_started: Notify,
|
||||
resume_discovery: Notify,
|
||||
}
|
||||
|
||||
impl Default for CloudProvider {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
reply: Mutex::new(Ok(PluginCatalog::default())),
|
||||
calls: AtomicUsize::new(0),
|
||||
resources: Mutex::new(None),
|
||||
pause_discovery: AtomicBool::new(false),
|
||||
discovery_started: Notify::new(),
|
||||
resume_discovery: Notify::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CloudProvider {
|
||||
fn set_reply(&self, reply: Result<PluginCatalog, String>) {
|
||||
*self
|
||||
.reply
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = reply;
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginProvider for CloudProvider {
|
||||
fn list(&self, query: PluginListQuery) -> PluginProviderFuture<'_, PluginCatalog> {
|
||||
*self
|
||||
.resources
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = query.mcp_resources;
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
let reply = self
|
||||
.reply
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clone();
|
||||
let pause = self.pause_discovery.swap(false, Ordering::SeqCst);
|
||||
Box::pin(async move {
|
||||
if pause {
|
||||
self.discovery_started.notify_one();
|
||||
self.resume_discovery.notified().await;
|
||||
}
|
||||
reply.map_err(PluginProviderError::Message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn cloud_catalog() -> PluginCatalog {
|
||||
PluginCatalog {
|
||||
entries: vec![PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: "plugin_remote".to_string(),
|
||||
},
|
||||
display_name: "Cloud Demo".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
mcp_servers: Default::default(),
|
||||
connector_ids: vec!["calendar".to_string()],
|
||||
locations: vec![codex_core_plugins::PluginSourceLocation::Cloud {
|
||||
resource_uri: "plugin://plugin_remote".to_string(),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -1,612 +0,0 @@
|
||||
//! Exercises independent event connections through the real MCP HTTP transport.
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::convert::Infallible;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use axum::Json;
|
||||
use axum::Router;
|
||||
use axum::http::HeaderMap;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::response::sse::Event;
|
||||
use axum::response::sse::Sse;
|
||||
use axum::routing::post;
|
||||
use codex_config::McpServerTransportConfig;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::plugins_manager_for_config;
|
||||
use codex_exec_server_test_support::environment_manager_without_environments;
|
||||
use codex_login::AuthManager;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_login::ExternalAuth;
|
||||
use codex_login::ExternalAuthFuture;
|
||||
use codex_login::ExternalAuthRefreshContext;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::CodexAppsResourceListParams;
|
||||
use codex_mcp::EffectiveMcpServer;
|
||||
use codex_mcp::McpEventNotification;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_mcp::McpRuntime;
|
||||
use codex_mcp::McpRuntimeContext;
|
||||
use codex_mcp::McpRuntimeInput;
|
||||
use codex_mcp::McpServerRegistration;
|
||||
use codex_mcp::McpStartupPolicy;
|
||||
use codex_mcp::ResolvedMcpCatalog;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::Value;
|
||||
use serde_json::json;
|
||||
use tokio::sync::Notify;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::timeout;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub(super) const WAIT: Duration = Duration::from_secs(/*secs*/ 5);
|
||||
|
||||
pub(super) struct TestStream {
|
||||
pub request: Value,
|
||||
pub headers: HeaderMap,
|
||||
pub notifications: mpsc::UnboundedSender<Value>,
|
||||
}
|
||||
|
||||
impl TestStream {
|
||||
pub fn notify(&self, method: &str) -> McpEventNotification {
|
||||
let params = json!({
|
||||
"data": {"text": "hello"},
|
||||
"_meta": {"io.modelcontextprotocol/subscriptionId": self.request["id"], "connector": "test"},
|
||||
});
|
||||
self.notifications
|
||||
.send(json!({"jsonrpc": "2.0", "method": method, "params": params}))
|
||||
.unwrap();
|
||||
McpEventNotification {
|
||||
method: method.into(),
|
||||
params: Some(params),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct BlockedTools {
|
||||
started: Notify,
|
||||
release: Notify,
|
||||
handshakes: AtomicUsize,
|
||||
inventories: AtomicUsize,
|
||||
inventory_returned: AtomicBool,
|
||||
inventory_error: Option<&'static str>,
|
||||
stalled_initialize_timeout: Option<Duration>,
|
||||
modern_with_sharing: bool,
|
||||
held_mime_type: Option<&'static str>,
|
||||
session_id: Option<&'static str>,
|
||||
resource_started: Notify,
|
||||
release_resource: Notify,
|
||||
}
|
||||
|
||||
pub(super) struct Fixture {
|
||||
_home: tempfile::TempDir,
|
||||
_server: tokio_util::task::AbortOnDropHandle<std::io::Result<()>>,
|
||||
pub runtime: Arc<McpRuntime>,
|
||||
pub runtime_input: McpRuntimeInput,
|
||||
pub auth: Arc<AuthManager>,
|
||||
pub opened: mpsc::UnboundedReceiver<TestStream>,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
pub async fn new() -> Result<Self> {
|
||||
let fixture = Self::start(/*blocked_tools*/ None, /*early_resources*/ false).await?;
|
||||
assert!(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT)
|
||||
.await
|
||||
);
|
||||
Ok(fixture)
|
||||
}
|
||||
|
||||
async fn start(
|
||||
blocked_tools: Option<Arc<BlockedTools>>,
|
||||
early_resources: bool,
|
||||
) -> Result<Self> {
|
||||
let (opened_tx, opened) = mpsc::unbounded_channel();
|
||||
let modern_with_sharing = blocked_tools
|
||||
.as_ref()
|
||||
.is_some_and(|blocked| blocked.modern_with_sharing);
|
||||
let stalled_initialize_timeout = blocked_tools
|
||||
.as_ref()
|
||||
.and_then(|blocked| blocked.stalled_initialize_timeout);
|
||||
let router = Router::new().fallback(post(
|
||||
move |headers: HeaderMap, Json(request): Json<Value>| {
|
||||
let opened = opened_tx.clone();
|
||||
let blocked_tools = blocked_tools.clone();
|
||||
async move {
|
||||
let method = request["method"].as_str();
|
||||
let session_id = blocked_tools.as_ref().and_then(|blocked| blocked.session_id);
|
||||
if let Some(session_id) = session_id && method != Some("initialize") {
|
||||
assert_eq!(headers["mcp-session-id"], session_id);
|
||||
}
|
||||
let mut result = match method {
|
||||
Some("server/discover") if modern_with_sharing => {
|
||||
blocked_tools.as_ref().unwrap().handshakes.fetch_add(1, Ordering::SeqCst);
|
||||
json!({
|
||||
"supportedVersions": ["2026-07-28"],
|
||||
"capabilities": {"tools": {}, "resources": {}},
|
||||
"_meta": {"io.modelcontextprotocol/serverInfo": {"name": "test", "version": "1"}},
|
||||
"ttlMs": 0, "cacheScope": "private",
|
||||
})
|
||||
}
|
||||
Some("initialize") if !modern_with_sharing => {
|
||||
if let Some(blocked) = &blocked_tools {
|
||||
blocked.handshakes.fetch_add(1, Ordering::SeqCst);
|
||||
if stalled_initialize_timeout.is_some() {
|
||||
blocked.started.notify_one();
|
||||
blocked.release.notified().await;
|
||||
}
|
||||
}
|
||||
json!({
|
||||
"protocolVersion": "2025-06-18", "capabilities": {"tools": {}, "resources": {}},
|
||||
"serverInfo": {"name": "test", "version": "1"},
|
||||
})
|
||||
}
|
||||
Some("tools/list") => {
|
||||
if let Some(blocked) = &blocked_tools {
|
||||
blocked.inventories.fetch_add(1, Ordering::SeqCst);
|
||||
blocked.started.notify_one();
|
||||
blocked.release.notified().await;
|
||||
blocked.inventory_returned.store(true, Ordering::SeqCst);
|
||||
if let Some(message) = blocked.inventory_error {
|
||||
return Json(json!({
|
||||
"jsonrpc": "2.0", "id": request["id"],
|
||||
"error": {"code": -32603, "message": message}
|
||||
})).into_response();
|
||||
}
|
||||
}
|
||||
json!({"tools": []})
|
||||
}
|
||||
Some("resources/list") => {
|
||||
if let Some(blocked) = &blocked_tools {
|
||||
assert_eq!(blocked.inventory_returned.load(Ordering::SeqCst), !early_resources,
|
||||
"unexpected catalog request ordering relative to the initial inventory");
|
||||
}
|
||||
let mime_type = request["params"]["mimeType"].as_str().unwrap();
|
||||
let cursor = match mime_type {
|
||||
"mcp/plugin" => "plugin-page-two",
|
||||
"mcp/skill" => "skill-page-two",
|
||||
other => panic!("unexpected resource type: {other}"),
|
||||
};
|
||||
if let Some(blocked) = &blocked_tools && blocked.held_mime_type == Some(mime_type) {
|
||||
blocked.resource_started.notify_one();
|
||||
blocked.release_resource.notified().await;
|
||||
}
|
||||
json!({"resources": [], "nextCursor": cursor})
|
||||
}
|
||||
Some("notifications/initialized") => {
|
||||
return StatusCode::ACCEPTED.into_response();
|
||||
}
|
||||
Some("events/stream") => {
|
||||
let (notifications, receive) = mpsc::unbounded_channel();
|
||||
opened
|
||||
.send(TestStream {
|
||||
request,
|
||||
headers,
|
||||
notifications,
|
||||
})
|
||||
.unwrap();
|
||||
let events = futures::stream::unfold(receive, |mut receive| async {
|
||||
receive.recv().await.map(|value| (value, receive))
|
||||
})
|
||||
.map(|value: Value| {
|
||||
Ok::<_, Infallible>(
|
||||
Event::default().event("message").data(value.to_string()),
|
||||
)
|
||||
});
|
||||
return Sse::new(events).into_response();
|
||||
}
|
||||
method => panic!("unexpected request: {method:?}"),
|
||||
};
|
||||
if modern_with_sharing {
|
||||
result["resultType"] = "complete".into();
|
||||
}
|
||||
let response = Json(json!({"jsonrpc": "2.0", "id": request["id"], "result": result}));
|
||||
if method == Some("initialize") && let Some(session_id) = session_id {
|
||||
return ([("mcp-session-id", session_id)], response).into_response();
|
||||
}
|
||||
response.into_response()
|
||||
}
|
||||
},
|
||||
));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||
let url = format!("http://{}", listener.local_addr()?);
|
||||
let server = tokio::spawn(async move { axum::serve(listener, router).await });
|
||||
let home = tempfile::tempdir()?;
|
||||
let auth_value = CodexAuth::from_api_key("Test API Key");
|
||||
let auth =
|
||||
AuthManager::from_auth_for_testing_with_home(auth_value.clone(), home.path().into());
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().into())
|
||||
.fallback_cwd(Some(home.path().into()))
|
||||
.cli_overrides(vec![
|
||||
(
|
||||
"features.apps_early_resource_discovery".into(),
|
||||
early_resources.into(),
|
||||
),
|
||||
(
|
||||
"features.mcp_connection_sharing".into(),
|
||||
modern_with_sharing.into(),
|
||||
),
|
||||
(
|
||||
"features.codex_apps_mcp_2026_07_28".into(),
|
||||
modern_with_sharing.into(),
|
||||
),
|
||||
])
|
||||
.build()
|
||||
.await?;
|
||||
let plugins = plugins_manager_for_config(&config, Arc::clone(&auth));
|
||||
let mut config = config.to_mcp_config(&plugins).await;
|
||||
let mut server_config = codex_mcp::hosted_plugin_runtime_mcp_server_config(
|
||||
&url, /*apps_mcp_product_sku*/ None, /*originator*/ None,
|
||||
);
|
||||
let McpServerTransportConfig::StreamableHttp {
|
||||
bearer_token_env_var,
|
||||
..
|
||||
} = &mut server_config.transport
|
||||
else {
|
||||
panic!("HTTP server");
|
||||
};
|
||||
*bearer_token_env_var = None;
|
||||
if let Some(timeout) = stalled_initialize_timeout {
|
||||
server_config.startup_timeout_sec = Some(timeout);
|
||||
}
|
||||
let mut catalog = ResolvedMcpCatalog::builder();
|
||||
catalog.register(McpServerRegistration::from_hosted_apps(
|
||||
"test",
|
||||
/*contribution_order*/ 0,
|
||||
server_config.clone(),
|
||||
));
|
||||
config.mcp_server_catalog = catalog.build();
|
||||
let config = Arc::new(config);
|
||||
let startup_cancellation_token = CancellationToken::new();
|
||||
let runtime_input = || McpRuntimeInput {
|
||||
network_policy_metadata: None,
|
||||
startup_policy: McpStartupPolicy::Eager,
|
||||
config: Arc::clone(&config),
|
||||
plugins_available: false,
|
||||
ready_selected_capability_roots: Vec::new(),
|
||||
mcp_servers: HashMap::from([(
|
||||
CODEX_APPS_MCP_SERVER_NAME.into(),
|
||||
EffectiveMcpServer::from_host_config(server_config.clone()),
|
||||
)]),
|
||||
submit_id: "test".into(),
|
||||
tx_event: None,
|
||||
startup_cancellation_token: startup_cancellation_token.clone(),
|
||||
runtime_context: McpRuntimeContext::new(
|
||||
Arc::new(environment_manager_without_environments()),
|
||||
home.path().into(),
|
||||
)
|
||||
.with_connection_pool(Default::default()),
|
||||
codex_apps_tools_cache: Default::default(),
|
||||
tool_catalog_cache: Default::default(),
|
||||
codex_apps_tools_cache_key: codex_mcp::codex_apps_tools_cache_key(Some(&auth_value)),
|
||||
client_mcp_extensions: Default::default(),
|
||||
auth: Some(auth_value.clone()),
|
||||
auth_manager: Some(Arc::clone(&auth)),
|
||||
elicitation_reviewer: None,
|
||||
elicitation_lifecycle: None,
|
||||
};
|
||||
let runtime = Arc::new(McpRuntime::new(runtime_input()).await);
|
||||
let runtime_input = runtime_input();
|
||||
Ok(Self {
|
||||
_home: home,
|
||||
_server: tokio_util::task::AbortOnDropHandle::new(server),
|
||||
runtime,
|
||||
runtime_input,
|
||||
auth,
|
||||
opened,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_during_initial_tools_list() -> Result<()> {
|
||||
for (early_resources, modern_with_sharing) in [(false, false), (true, false), (true, true)] {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
modern_with_sharing,
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), early_resources).await?;
|
||||
timeout(WAIT, blocked.started.notified())
|
||||
.await
|
||||
.context("initial tools/list did not start")?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
if early_resources {
|
||||
assert_eq!(
|
||||
timeout(WAIT, &mut page)
|
||||
.await
|
||||
.context("gated catalog read waited for the blocked inventory")??
|
||||
.next_cursor
|
||||
.as_deref(),
|
||||
Some("plugin-page-two")
|
||||
);
|
||||
} else {
|
||||
assert!(futures::poll!(&mut page).is_pending());
|
||||
// A read already using the early client would now fail its generation check.
|
||||
// A read waiting for startup can still fetch the page after inventory returns.
|
||||
fixture.runtime.invalidate_resource_caches();
|
||||
}
|
||||
let mut ready = Box::pin(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT),
|
||||
);
|
||||
assert!(futures::poll!(&mut ready).is_pending());
|
||||
blocked.release.notify_one();
|
||||
assert!(ready.await);
|
||||
if !early_resources {
|
||||
assert_eq!(
|
||||
timeout(WAIT, page).await??.next_cursor.as_deref(),
|
||||
Some("plugin-page-two")
|
||||
);
|
||||
}
|
||||
assert_eq!(blocked.handshakes.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(blocked.inventories.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_times_out_during_stalled_initialization() -> Result<()> {
|
||||
let startup_timeout = Duration::from_secs(/*secs*/ 1);
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
stalled_initialize_timeout: Some(startup_timeout),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
assert!(futures::poll!(&mut page).is_pending());
|
||||
timeout(WAIT, blocked.started.notified())
|
||||
.await
|
||||
.context("initialize did not reach the server")?;
|
||||
let error = timeout(WAIT, page)
|
||||
.await
|
||||
.context("reader outlived its startup deadline")?
|
||||
.unwrap_err();
|
||||
// The handshake and early borrow each enforce the configured startup timeout.
|
||||
let message = format!("{error:#}");
|
||||
assert!(message.contains("timed out"), "{message}");
|
||||
assert_eq!(blocked.inventories.load(Ordering::SeqCst), 0);
|
||||
blocked.release.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_multiplexes_catalogs_while_tools_list_is_pending() -> Result<()> {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/plugin"),
|
||||
session_id: Some("apps-session"),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let plugin_reader = reader.clone();
|
||||
let plugin = tokio::spawn(async move {
|
||||
plugin_reader
|
||||
.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
})
|
||||
.await
|
||||
});
|
||||
timeout(WAIT, blocked.resource_started.notified())
|
||||
.await
|
||||
.context("plugin request did not reach the server while tools/list was pending")?;
|
||||
let skill = timeout(
|
||||
WAIT,
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/skill".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.context("skill request queued behind the pending plugin or inventory request")??;
|
||||
assert_eq!(skill.next_cursor.as_deref(), Some("skill-page-two"));
|
||||
assert!(!plugin.is_finished());
|
||||
|
||||
blocked.release_resource.notify_one();
|
||||
let plugin = timeout(WAIT, plugin).await???;
|
||||
assert_eq!(plugin.next_cursor.as_deref(), Some("plugin-page-two"));
|
||||
|
||||
let mut ready = Box::pin(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT),
|
||||
);
|
||||
assert!(futures::poll!(&mut ready).is_pending());
|
||||
blocked.release.notify_one();
|
||||
assert!(ready.await);
|
||||
assert_eq!(blocked.handshakes.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(blocked.inventories.load(Ordering::SeqCst), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_propagates_initial_tools_list_failure() -> Result<()> {
|
||||
const INVENTORY_ERROR: &str = "initial inventory unavailable";
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/plugin"),
|
||||
inventory_error: Some(INVENTORY_ERROR),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
tokio::select! {
|
||||
result = &mut page => panic!("catalog returned before inventory failed: {result:?}"),
|
||||
result = timeout(WAIT, blocked.resource_started.notified()) => result?,
|
||||
}
|
||||
|
||||
blocked.release.notify_one();
|
||||
let error = timeout(WAIT, page)
|
||||
.await
|
||||
.context("catalog reader kept waiting after tools/list failed")?
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(error.starts_with("MCP startup failed:"), "{error}");
|
||||
assert!(error.contains(INVENTORY_ERROR), "{error}");
|
||||
assert!(
|
||||
!fixture
|
||||
.runtime_input
|
||||
.startup_cancellation_token
|
||||
.is_cancelled()
|
||||
);
|
||||
blocked.release_resource.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_observes_cancellation_after_inventory_finishes() -> Result<()> {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/plugin"),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/plugin".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
tokio::select! {
|
||||
result = &mut page => panic!("catalog returned before release: {result:?}"),
|
||||
result = timeout(WAIT, blocked.resource_started.notified()) => result?,
|
||||
}
|
||||
blocked.release.notify_one();
|
||||
assert!(
|
||||
fixture
|
||||
.runtime
|
||||
.latest_wait_for_server_ready(CODEX_APPS_MCP_SERVER_NAME, WAIT)
|
||||
.await
|
||||
);
|
||||
assert!(futures::poll!(&mut page).is_pending());
|
||||
fixture.runtime_input.startup_cancellation_token.cancel();
|
||||
let error = timeout(WAIT, page)
|
||||
.await
|
||||
.context("catalog ignored cancellation after startup")?
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().to_lowercase().contains("cancel"));
|
||||
blocked.release_resource.notify_one();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_discards_invalidated_page() -> Result<()> {
|
||||
for cancel_startup in [false, true] {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/skill"),
|
||||
..Default::default()
|
||||
});
|
||||
let fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let page = tokio::spawn(async move {
|
||||
reader
|
||||
.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/skill".into(),
|
||||
cursor: None,
|
||||
})
|
||||
.await
|
||||
});
|
||||
timeout(WAIT, blocked.resource_started.notified()).await?;
|
||||
let expected = if cancel_startup {
|
||||
fixture.runtime.cancel_startup();
|
||||
"cancel"
|
||||
} else {
|
||||
fixture.runtime.invalidate_resource_caches();
|
||||
blocked.release_resource.notify_one();
|
||||
"changed during catalog discovery"
|
||||
};
|
||||
let error = timeout(WAIT, page).await??.unwrap_err();
|
||||
assert!(error.to_string().to_lowercase().contains(expected));
|
||||
blocked.release.notify_one();
|
||||
blocked.release_resource.notify_one();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn apps_resource_discovery_discards_page_after_account_switch() -> Result<()> {
|
||||
let blocked = Arc::new(BlockedTools {
|
||||
held_mime_type: Some("mcp/skill"),
|
||||
..Default::default()
|
||||
});
|
||||
let mut fixture = Fixture::start(Some(Arc::clone(&blocked)), /*early_resources*/ true).await?;
|
||||
timeout(WAIT, blocked.started.notified()).await?;
|
||||
let reader = McpResourceClient::new(Arc::clone(&fixture.runtime));
|
||||
let mut page = Box::pin(
|
||||
reader.list_codex_apps_resources(CodexAppsResourceListParams {
|
||||
mime_type: "mcp/skill".into(),
|
||||
cursor: None,
|
||||
}),
|
||||
);
|
||||
tokio::select! {
|
||||
result = &mut page => panic!("catalog returned before account switch: {result:?}"),
|
||||
result = timeout(WAIT, blocked.resource_started.notified()) => result?,
|
||||
}
|
||||
|
||||
let previous_auth = reader.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME);
|
||||
let next_auth = CodexAuth::from_api_key("second-account-key");
|
||||
fixture
|
||||
.auth
|
||||
.set_external_auth(Arc::new(StaticAuth(next_auth.clone())))
|
||||
.await?;
|
||||
fixture.runtime_input.codex_apps_tools_cache_key =
|
||||
codex_mcp::codex_apps_tools_cache_key(Some(&next_auth));
|
||||
fixture.runtime_input.auth = Some(next_auth);
|
||||
timeout(WAIT, fixture.runtime.replace(fixture.runtime_input)).await?;
|
||||
assert!(previous_auth != reader.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME));
|
||||
blocked.release_resource.notify_one();
|
||||
let error = timeout(WAIT, page).await?.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"Apps connection changed during catalog discovery"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) struct StaticAuth(pub CodexAuth);
|
||||
|
||||
impl ExternalAuth for StaticAuth {
|
||||
fn resolve(&self) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
fn refresh(&self, _: ExternalAuthRefreshContext) -> ExternalAuthFuture<'_, CodexAuth> {
|
||||
self.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
mod catalog_observability;
|
||||
mod cloud_plugin;
|
||||
mod plugin;
|
||||
mod plugin_contributor;
|
||||
mod plugin_contributor_state;
|
||||
mod plugin_lifecycle;
|
||||
mod plugin_providers;
|
||||
mod stream_manager;
|
||||
|
||||
pub use codex_core_plugins::PluginListQuery;
|
||||
pub use codex_core_plugins::PluginProvider;
|
||||
@@ -15,6 +14,4 @@ pub use plugin_contributor::install_plugin_providers;
|
||||
pub use plugin_contributor::install_plugins;
|
||||
pub use plugin_contributor_state::PluginsThreadState;
|
||||
pub use plugin_providers::PluginProviders;
|
||||
pub use stream_manager::McpEventStreamManager;
|
||||
pub use stream_manager::McpEventStreamUpdate;
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ use std::collections::HashMap;
|
||||
|
||||
use self::provider::PluginMcpProvider;
|
||||
use crate::PluginsThreadState;
|
||||
use crate::cloud_plugin::hosted_plugin_connectors;
|
||||
use crate::plugin_contributor::PluginContributor;
|
||||
use crate::plugin_contributor_state::CachedPluginMetadata;
|
||||
use crate::plugin_contributor_state::CachedSelectedRoot;
|
||||
@@ -133,14 +132,12 @@ impl PluginContributor {
|
||||
);
|
||||
Vec::new()
|
||||
});
|
||||
let connector_ids = Vec::new();
|
||||
let CapabilityRootLocation::Environment { environment_id, .. } =
|
||||
&selected_root.location;
|
||||
Some(SelectedPluginContribution {
|
||||
plugin_display_name: plugin.plugin().manifest().display_name().to_string(),
|
||||
source_environment_id: environment_id.clone(),
|
||||
servers,
|
||||
connector_ids,
|
||||
})
|
||||
}
|
||||
None => None,
|
||||
@@ -174,56 +171,9 @@ impl McpServerContributor<Config> for PluginContributor {
|
||||
|
||||
fn contribute<'a>(
|
||||
&'a self,
|
||||
context: McpServerContributionContext<'a, Config>,
|
||||
_context: McpServerContributionContext<'a, Config>,
|
||||
) -> ExtensionFuture<'a, Vec<McpServerContribution>> {
|
||||
Box::pin(async move {
|
||||
let Some(thread_store) = context.thread_store() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let cloud_plugins_enabled = self.providers.cloud.is_some()
|
||||
&& context.config().features.enabled(Feature::Plugins);
|
||||
let state = thread_store.get_or_init(PluginsThreadState::default);
|
||||
if !cloud_plugins_enabled {
|
||||
state.contributor_state().cloud_generation = None;
|
||||
return Vec::new();
|
||||
}
|
||||
// Core reads hosted connectors after finishing the executor registrations.
|
||||
state
|
||||
.cloud_catalog()
|
||||
.as_ref()
|
||||
.map(hosted_plugin_connectors)
|
||||
.unwrap_or_default()
|
||||
})
|
||||
}
|
||||
|
||||
fn hosted_plugin_ids(&self, context: McpServerContributionContext<'_, Config>) -> Vec<String> {
|
||||
if self.providers.cloud.is_none() || !context.config().features.enabled(Feature::Plugins) {
|
||||
return Vec::new();
|
||||
}
|
||||
let Some(state) = context
|
||||
.thread_store()
|
||||
.and_then(codex_extension_api::ExtensionData::get::<PluginsThreadState>)
|
||||
else {
|
||||
return Vec::new();
|
||||
};
|
||||
state
|
||||
.contributor_state()
|
||||
.cloud_catalog()
|
||||
.map(|catalog| {
|
||||
hosted_plugin_connectors(catalog)
|
||||
.into_iter()
|
||||
.filter_map(|contribution| {
|
||||
if let McpServerContribution::HostedPluginConnectors { plugin_id, .. } =
|
||||
contribution
|
||||
{
|
||||
Some(plugin_id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
Box::pin(async { Vec::new() })
|
||||
}
|
||||
|
||||
fn selected_plugins<'a>(
|
||||
@@ -236,10 +186,6 @@ impl McpServerContributor<Config> for PluginContributor {
|
||||
return Vec::new();
|
||||
};
|
||||
let state = thread_store.get_or_init(PluginsThreadState::default);
|
||||
if context.auth_changed() {
|
||||
// Clear the old account before executor loading can yield to other work.
|
||||
state.contributor_state().cloud_generation = None;
|
||||
}
|
||||
let selected_roots = context
|
||||
.ready_selected_capability_roots()
|
||||
.unwrap_or_default();
|
||||
@@ -248,11 +194,7 @@ impl McpServerContributor<Config> for PluginContributor {
|
||||
let merged = {
|
||||
let mut cache = state.contributor_state();
|
||||
cache.update_executor_catalog(snapshots);
|
||||
let cloud = (self.providers.cloud.is_some()
|
||||
&& context.config().features.enabled(Feature::Plugins))
|
||||
.then(|| cache.cloud_catalog())
|
||||
.flatten();
|
||||
merge_catalogs(cache.executor_catalog.as_ref(), cloud)
|
||||
merge_catalogs(cache.executor_catalog.as_ref(), /*cloud*/ None)
|
||||
};
|
||||
for warning in &merged.warnings {
|
||||
tracing::warn!(%warning, "plugin catalog merge reported a warning");
|
||||
@@ -292,7 +234,6 @@ impl McpServerContributor<Config> for PluginContributor {
|
||||
plugin_display_name: metadata.plugin_display_name,
|
||||
source_environment_id: environment_id,
|
||||
servers: metadata.servers,
|
||||
connector_ids: metadata.connector_ids,
|
||||
};
|
||||
project_metadata(
|
||||
context.config(),
|
||||
@@ -418,7 +359,6 @@ fn denied_plugin(selected_root: &SelectedCapabilityRoot) -> SelectedPlugin<'stat
|
||||
plugin_display_name: selected_root.id.clone(),
|
||||
source_environment_id: environment_id.clone(),
|
||||
servers: Vec::new(),
|
||||
connector_ids: Vec::new(),
|
||||
};
|
||||
SelectedPlugin {
|
||||
selected_root_id: selected_root.id.clone(),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use crate::cloud_plugin::MAX_CONNECTOR_IDS_PER_PLUGIN;
|
||||
use crate::cloud_plugin::MAX_PLUGIN_DISPLAY_NAME_CHARS;
|
||||
/// Bounds the plugin display name projected into MCP tool attribution.
|
||||
const MAX_PLUGIN_DISPLAY_NAME_CHARS: usize = 64;
|
||||
use crate::plugin_contributor_state::SelectedPluginMetadata;
|
||||
use codex_connectors::parse_plugin_app_config;
|
||||
use codex_core_plugins::PluginCatalogEntry;
|
||||
use codex_core_plugins::PluginSourceLocation;
|
||||
use codex_core_plugins::manifest::UriPluginManifest;
|
||||
@@ -15,7 +14,6 @@ use codex_mcp::parse_executor_plugin_mcp_config;
|
||||
use codex_plugin::manifest::PluginManifestMcpServers;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(super) fn manifest_from_discovery<'a>(
|
||||
selected_root: &SelectedCapabilityRoot,
|
||||
@@ -99,46 +97,10 @@ pub(super) fn metadata_from_discovery(
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
let connector_ids = manifest
|
||||
.paths
|
||||
.apps
|
||||
.as_ref()
|
||||
.and_then(|path| {
|
||||
plugin_files
|
||||
.apps_config
|
||||
.as_ref()
|
||||
.filter(|file| file.path == *path)
|
||||
.or_else(|| {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
path = %path,
|
||||
"exec-server capability bundle omitted declared connector config"
|
||||
);
|
||||
None
|
||||
})
|
||||
})
|
||||
.and_then(|file| match parse_plugin_app_config(&file.contents) {
|
||||
Ok(declarations) => Some(declarations),
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
selected_root = selected_root.id,
|
||||
path = %file.path,
|
||||
%error,
|
||||
"failed to parse exec-server-discovered connector config"
|
||||
);
|
||||
None
|
||||
}
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|declaration| declaration.connector_id.0)
|
||||
.collect();
|
||||
|
||||
SelectedPluginContribution {
|
||||
plugin_display_name: manifest.display_name().to_string(),
|
||||
source_environment_id: environment_id.clone(),
|
||||
servers,
|
||||
connector_ids,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,14 +112,6 @@ pub(super) fn v2_metadata_from_catalog(
|
||||
.chars()
|
||||
.take(MAX_PLUGIN_DISPLAY_NAME_CHARS)
|
||||
.collect();
|
||||
let mut seen_connector_ids = HashSet::new();
|
||||
let connector_ids: Vec<String> = entry
|
||||
.connector_ids
|
||||
.iter()
|
||||
.filter(|id| seen_connector_ids.insert(id.as_str()))
|
||||
.take(MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.cloned()
|
||||
.collect();
|
||||
let installations = entry
|
||||
.locations
|
||||
.iter()
|
||||
@@ -186,24 +140,9 @@ pub(super) fn v2_metadata_from_catalog(
|
||||
let metadata = SelectedPluginMetadata {
|
||||
plugin_display_name: plugin_display_name.clone(),
|
||||
servers,
|
||||
connector_ids: connector_ids.clone(),
|
||||
};
|
||||
projections.push((root_id, metadata));
|
||||
}
|
||||
if entry
|
||||
.locations
|
||||
.iter()
|
||||
.any(|location| matches!(location, PluginSourceLocation::Cloud { .. }))
|
||||
{
|
||||
projections.push((
|
||||
format!("cloud:{}", entry.id.as_str()),
|
||||
SelectedPluginMetadata {
|
||||
plugin_display_name,
|
||||
servers: Vec::new(),
|
||||
connector_ids,
|
||||
},
|
||||
));
|
||||
}
|
||||
projections
|
||||
}
|
||||
|
||||
|
||||
@@ -29,19 +29,14 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command":"node","args":["server.js"],"cwd":"mcp"}),
|
||||
)]),
|
||||
connector_ids: vec!["connector_example".to_string()],
|
||||
locations: vec![PluginSourceLocation::Cloud {
|
||||
resource_uri: "plugin://plugin_example".to_string(),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
};
|
||||
// Cloud locations no longer project hosted metadata.
|
||||
let projections = v2_metadata_from_catalog(&entry);
|
||||
let [(root_id, metadata)] = projections.as_slice() else {
|
||||
panic!("one cloud projection expected");
|
||||
};
|
||||
assert_eq!(root_id, "cloud:plugin_example");
|
||||
assert!(metadata.servers.is_empty());
|
||||
assert_eq!(metadata.connector_ids, vec!["connector_example"]);
|
||||
assert!(projections.is_empty());
|
||||
|
||||
// Attribution keeps the installation key; server configs distinguish the executors.
|
||||
let installations = [
|
||||
@@ -57,7 +52,7 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
|
||||
});
|
||||
}
|
||||
let projections = v2_metadata_from_catalog(&entry);
|
||||
assert_eq!(projections.len(), installations.len() + 1);
|
||||
assert_eq!(projections.len(), installations.len());
|
||||
for (index, ((root_id, metadata), (environment_id, plugin_id, root))) in
|
||||
projections.iter().zip(installations).enumerate()
|
||||
{
|
||||
@@ -70,10 +65,8 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
|
||||
plugin_display_name: metadata.plugin_display_name.clone(),
|
||||
source_environment_id: environment_id.to_string(),
|
||||
servers: metadata.servers.clone(),
|
||||
connector_ids: metadata.connector_ids.clone(),
|
||||
},
|
||||
);
|
||||
assert_eq!(contribution.connector_ids, entry.connector_ids);
|
||||
if index != 0 {
|
||||
assert!(contribution.servers.is_empty());
|
||||
continue;
|
||||
@@ -94,22 +87,11 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
|
||||
);
|
||||
}
|
||||
|
||||
let (root_id, metadata) = &projections[installations.len()];
|
||||
assert_eq!(root_id, "cloud:plugin_example");
|
||||
assert!(metadata.servers.is_empty());
|
||||
assert_eq!(metadata.connector_ids, vec!["connector_example"]);
|
||||
|
||||
// Bound projected metadata without mutating the source catalog or losing installations.
|
||||
entry.display_name = "界".repeat(MAX_PLUGIN_DISPLAY_NAME_CHARS + 1);
|
||||
entry.connector_ids = (0..=MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.flat_map(|index| vec![format!("connector_{index}"); 2])
|
||||
.collect();
|
||||
let expected_connectors = (0..MAX_CONNECTOR_IDS_PER_PLUGIN)
|
||||
.map(|index| format!("connector_{index}"))
|
||||
.collect::<Vec<_>>();
|
||||
entry.mcp_servers.clear();
|
||||
let projections = v2_metadata_from_catalog(&entry);
|
||||
assert_eq!(projections.len(), installations.len() + 1);
|
||||
assert_eq!(projections.len(), installations.len());
|
||||
assert!(
|
||||
projections
|
||||
.iter()
|
||||
@@ -120,15 +102,10 @@ async fn merged_mcp_declarations_require_an_executor_location() -> anyhow::Resul
|
||||
metadata.plugin_display_name,
|
||||
"界".repeat(MAX_PLUGIN_DISPLAY_NAME_CHARS)
|
||||
);
|
||||
assert_eq!(metadata.connector_ids, expected_connectors);
|
||||
}
|
||||
assert_eq!(
|
||||
entry.display_name.chars().count(),
|
||||
MAX_PLUGIN_DISPLAY_NAME_CHARS + 1
|
||||
);
|
||||
assert_eq!(
|
||||
entry.connector_ids.len(),
|
||||
(MAX_CONNECTOR_IDS_PER_PLUGIN + 1) * 2
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -431,7 +431,6 @@ fn resolved_plugin(
|
||||
onboarding_skill: None,
|
||||
skills: Vec::new(),
|
||||
mcp_servers,
|
||||
apps: None,
|
||||
hooks: None,
|
||||
},
|
||||
interface: None,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Coordinates cloud turn refreshes and executor MCP contributions with thread-owned catalogs.
|
||||
//! Coordinates executor MCP contributions with thread-owned catalogs.
|
||||
//!
|
||||
//! One contributor is registered for both lifecycles. Provider instances are shared, while
|
||||
//! catalogs and executor metadata live together in thread extension data.
|
||||
//! Provider instances are shared, while catalogs and executor metadata live in thread extension
|
||||
//! data.
|
||||
|
||||
use crate::PluginProviders;
|
||||
use codex_core::config::Config;
|
||||
@@ -14,9 +14,7 @@ pub(crate) struct PluginContributor {
|
||||
pub(crate) providers: PluginProviders,
|
||||
}
|
||||
|
||||
/// Installs one coordinator for cloud turn-start and executor MCP callbacks.
|
||||
/// The optional cloud provider never disables executor plugins, and Core's plugin policy applies
|
||||
/// to both paths.
|
||||
/// Installs one coordinator for executor MCP callbacks; Core's plugin policy applies to it.
|
||||
pub fn install_plugin_providers(
|
||||
builder: &mut ExtensionRegistryBuilder<Config>,
|
||||
providers: PluginProviders,
|
||||
@@ -24,7 +22,6 @@ pub fn install_plugin_providers(
|
||||
let contributor = Arc::new(PluginContributor { providers });
|
||||
builder.thread_lifecycle_contributor(contributor.clone());
|
||||
builder.config_contributor(contributor.clone());
|
||||
builder.turn_lifecycle_contributor(contributor.clone());
|
||||
builder.mcp_server_contributor(contributor);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Thread-owned cloud catalog and stable selected-root metadata, guarded by a short-lived mutex.
|
||||
//! Thread-owned executor plugin catalog and stable selected-root metadata, guarded by a short-lived mutex.
|
||||
|
||||
use crate::catalog_observability::record_catalog;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
@@ -6,33 +6,22 @@ use codex_core_plugins::PluginRootOwnership;
|
||||
use codex_core_plugins::catalog_from_snapshots;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryV2Snapshot;
|
||||
use codex_exec_server::FileSystemSandboxContext;
|
||||
use codex_extension_api::CatalogRefreshBackoff;
|
||||
use codex_extension_api::ExtensionMetrics;
|
||||
use codex_extension_api::SelectedPluginContribution;
|
||||
use codex_mcp::CODEX_APPS_MCP_SERVER_NAME;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_mcp::McpResourceClientAuthKey;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::MutexGuard;
|
||||
use tokio::sync::Mutex as AsyncMutex;
|
||||
|
||||
/// Plugin configuration and caches owned by one thread; mutable state stays extension-private.
|
||||
#[derive(Default)]
|
||||
pub struct PluginsThreadState {
|
||||
/// Serializes discovery; true only when the last refresh published successfully.
|
||||
pub(crate) cloud_refresh_lock: AsyncMutex<bool>,
|
||||
state: Mutex<PluginContributorState>,
|
||||
}
|
||||
|
||||
impl PluginsThreadState {
|
||||
/// Returns an owned cloud snapshot only while its auth generation is current.
|
||||
pub fn cloud_catalog(&self) -> Option<PluginCatalog> {
|
||||
self.contributor_state().cloud_catalog().cloned()
|
||||
}
|
||||
|
||||
/// Locks the thread's contributor state, recovering it if a holder panicked.
|
||||
pub(crate) fn contributor_state(&self) -> MutexGuard<'_, PluginContributorState> {
|
||||
self.state
|
||||
.lock()
|
||||
@@ -45,30 +34,11 @@ impl PluginsThreadState {
|
||||
pub(crate) struct PluginContributorState {
|
||||
pub(crate) extension_metrics: Option<Arc<dyn ExtensionMetrics>>,
|
||||
pub(crate) plugins_enabled: bool,
|
||||
pub(crate) cloud_generation: Option<CloudPluginGeneration>,
|
||||
pub(crate) cloud_retry: Option<CatalogRefreshBackoff>,
|
||||
pub(crate) executor_catalog: Option<PluginCatalog>,
|
||||
executor_snapshots: Vec<ExecutorCapabilityDiscoveryV2Snapshot>,
|
||||
pub(crate) executor_cache: Vec<CachedSelectedRoot>,
|
||||
}
|
||||
|
||||
/// Keeps cloud plugin metadata within one published auth scope and Apps availability state.
|
||||
pub(crate) struct CloudPluginGeneration {
|
||||
pub(crate) auth_cache_key: Option<McpResourceClientAuthKey>,
|
||||
pub(crate) mcp_resources: Option<McpResourceClient>,
|
||||
pub(crate) catalog: Option<PluginCatalog>,
|
||||
}
|
||||
|
||||
impl CloudPluginGeneration {
|
||||
pub(crate) fn is_auth_current(&self) -> bool {
|
||||
self.auth_cache_key
|
||||
== self
|
||||
.mcp_resources
|
||||
.as_ref()
|
||||
.map(|client| client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME))
|
||||
}
|
||||
}
|
||||
|
||||
impl PluginContributorState {
|
||||
/// Reuses unchanged discovery and preserves surviving installations' order on refresh.
|
||||
pub(crate) fn update_executor_catalog(
|
||||
@@ -104,67 +74,6 @@ impl PluginContributorState {
|
||||
self.executor_snapshots.clear();
|
||||
}
|
||||
|
||||
/// Returns the cloud catalog only while it belongs to the live auth generation.
|
||||
pub(crate) fn cloud_catalog(&self) -> Option<&PluginCatalog> {
|
||||
self.cloud_generation
|
||||
.as_ref()
|
||||
.filter(|generation| generation.is_auth_current())
|
||||
.and_then(|generation| generation.catalog.as_ref())
|
||||
}
|
||||
|
||||
/// Establishes the auth scope and returns the key used by that generation.
|
||||
pub(crate) fn prepare_cloud_generation(
|
||||
&mut self,
|
||||
mcp_resources: Option<McpResourceClient>,
|
||||
) -> Option<McpResourceClientAuthKey> {
|
||||
let auth_cache_key = mcp_resources
|
||||
.as_ref()
|
||||
.map(|client| client.auth_cache_key_for_server(CODEX_APPS_MCP_SERVER_NAME));
|
||||
if self
|
||||
.cloud_generation
|
||||
.as_ref()
|
||||
.is_none_or(|generation| generation.auth_cache_key != auth_cache_key)
|
||||
{
|
||||
self.cloud_generation = Some(CloudPluginGeneration {
|
||||
auth_cache_key: auth_cache_key.clone(),
|
||||
mcp_resources,
|
||||
catalog: None,
|
||||
});
|
||||
}
|
||||
auth_cache_key
|
||||
}
|
||||
|
||||
/// Accepts current-auth results, retaining prior complete entries as partial after an incomplete refresh.
|
||||
/// Returns false only when the result belongs to a stale auth generation.
|
||||
pub(crate) fn publish_cloud_catalog(
|
||||
&mut self,
|
||||
auth_cache_key: Option<&McpResourceClientAuthKey>,
|
||||
mut catalog: PluginCatalog,
|
||||
) -> bool {
|
||||
let Some(generation) = self
|
||||
.cloud_generation
|
||||
.as_mut()
|
||||
.filter(|generation| generation.auth_cache_key.as_ref() == auth_cache_key)
|
||||
.filter(|generation| generation.is_auth_current())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if catalog.is_partial
|
||||
&& let Some(previous) = generation
|
||||
.catalog
|
||||
.as_ref()
|
||||
.filter(|previous| !previous.is_partial)
|
||||
{
|
||||
catalog = previous.clone();
|
||||
catalog.is_partial = true;
|
||||
tracing::warn!(
|
||||
"cloud plugin discovery was partial; retaining prior auth-scoped entries as partial"
|
||||
);
|
||||
}
|
||||
record_catalog(self.extension_metrics.as_deref(), "cloud", &catalog);
|
||||
generation.catalog = Some(catalog);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CachedSelectedRoot {
|
||||
@@ -185,7 +94,6 @@ pub(crate) enum CachedPluginMetadata {
|
||||
pub(crate) struct SelectedPluginMetadata {
|
||||
pub(crate) plugin_display_name: String,
|
||||
pub(crate) servers: Vec<(String, codex_config::McpServerConfig)>,
|
||||
pub(crate) connector_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -5,11 +5,6 @@ use crate::PluginProviders;
|
||||
use crate::plugin_contributor::PluginContributor;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginCatalogEntry;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_core_plugins::PluginProvider;
|
||||
use codex_core_plugins::PluginSourceLocation;
|
||||
use codex_exec_server::CapabilityTextFile;
|
||||
use codex_exec_server::DiscoverV2CapabilitiesResponse;
|
||||
use codex_exec_server::DiscoveredPluginFiles;
|
||||
@@ -19,14 +14,12 @@ use codex_exec_server::ExecutorPlugin;
|
||||
use codex_exec_server::LOCAL_ENVIRONMENT_ID;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionDataInit;
|
||||
use codex_extension_api::McpServerContribution;
|
||||
use codex_extension_api::McpServerContributionContext;
|
||||
use codex_extension_api::McpServerContributor;
|
||||
use codex_features::Feature;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
async fn contribution_labels(
|
||||
@@ -49,36 +42,11 @@ async fn contribution_labels(
|
||||
);
|
||||
labels.push(plugin.selected_root_id);
|
||||
}
|
||||
for contribution in contributor.contribute(context).await {
|
||||
if let McpServerContribution::HostedPluginConnectors { plugin_id, .. } = contribution {
|
||||
labels.push(format!("cloud:{plugin_id}"));
|
||||
} else {
|
||||
panic!("unexpected contribution: {contribution:?}");
|
||||
}
|
||||
}
|
||||
// Plugins no longer contribute hosted servers outside their selected roots.
|
||||
assert!(contributor.contribute(context).await.is_empty());
|
||||
labels
|
||||
}
|
||||
|
||||
fn cloud_plugin(remote_id: &str) -> PluginCatalogEntry {
|
||||
PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: remote_id.to_string(),
|
||||
},
|
||||
display_name: "Example".to_string(),
|
||||
version: "1.0.0".to_string(),
|
||||
mcp_servers: BTreeMap::from([(
|
||||
"example".to_string(),
|
||||
serde_json::json!({"command":"node","args":["server.js"]}),
|
||||
)]),
|
||||
connector_ids: vec!["connector_example".to_string()],
|
||||
locations: vec![PluginSourceLocation::Cloud {
|
||||
resource_uri: format!("plugin://{remote_id}"),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn executor_snapshot(
|
||||
environment_id: &str,
|
||||
) -> anyhow::Result<ExecutorCapabilityDiscoveryV2Snapshot> {
|
||||
@@ -89,7 +57,6 @@ fn executor_snapshot(
|
||||
plugins: vec![ExecutorPlugin {
|
||||
id: "example@marketplace".to_string(),
|
||||
display_name: "Example".to_string(),
|
||||
remote_plugin_id: Some("plugin_a".to_string()),
|
||||
version: "1.0.0".to_string(),
|
||||
files: DiscoveredPluginFiles {
|
||||
manifest: CapabilityTextFile {
|
||||
@@ -107,39 +74,6 @@ fn executor_snapshot(
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_refresh_retains_entries_without_excluding_new_executor_plugins() -> anyhow::Result<()> {
|
||||
let mut state = PluginContributorState::default();
|
||||
let auth_key = state.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
let original = PluginCatalog {
|
||||
entries: vec![cloud_plugin("old_plugin")],
|
||||
..Default::default()
|
||||
};
|
||||
assert!(state.publish_cloud_catalog(auth_key.as_ref(), original.clone()));
|
||||
assert!(state.publish_cloud_catalog(
|
||||
auth_key.as_ref(),
|
||||
PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
is_partial: true,
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
let mut expected = original;
|
||||
expected.is_partial = true;
|
||||
assert_eq!(state.cloud_catalog(), Some(&expected));
|
||||
|
||||
state.update_executor_catalog(&[executor_snapshot("executor-a")?]);
|
||||
let merged =
|
||||
codex_core_plugins::merge_catalogs(state.executor_catalog.as_ref(), state.cloud_catalog());
|
||||
assert!(
|
||||
merged
|
||||
.entries
|
||||
.iter()
|
||||
.any(|entry| { entry.id.as_str() == "plugin_a" && entry.enabled })
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn executor_refresh_preserves_order_and_removes_stale_entries() -> anyhow::Result<()> {
|
||||
let mut state = PluginContributorState::default();
|
||||
@@ -190,9 +124,6 @@ fn executor_refresh_preserves_order_and_removes_stale_entries() -> anyhow::Resul
|
||||
|
||||
#[tokio::test]
|
||||
async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> anyhow::Result<()> {
|
||||
struct CloudProvider;
|
||||
impl PluginProvider for CloudProvider {}
|
||||
|
||||
let home = tempfile::tempdir()?;
|
||||
let root = home.path().join("legacy");
|
||||
std::fs::create_dir_all(root.join(".codex-plugin"))?;
|
||||
@@ -226,24 +157,12 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
let v1 = ExecutorCapabilityDiscoveryCache::default()
|
||||
.snapshot(&resolved_roots, &Default::default())
|
||||
.await;
|
||||
let mut contributor = PluginContributor {
|
||||
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(environments)))
|
||||
.with_cloud_provider(Arc::new(CloudProvider)),
|
||||
let contributor = PluginContributor {
|
||||
providers: PluginProviders::new(Arc::new(ExecutorPluginProvider::new(environments))),
|
||||
};
|
||||
let thread = ExtensionData::new("projection-test");
|
||||
let init = ExtensionDataInit::default();
|
||||
let state = thread.get_or_init(PluginsThreadState::default);
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
let key = state.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
assert!(state.publish_cloud_catalog(
|
||||
key.as_ref(),
|
||||
PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
..Default::default()
|
||||
}
|
||||
));
|
||||
}
|
||||
// A different environment ensures per-root filtering cannot hide a legacy fallback.
|
||||
let mut valid = [executor_snapshot("executor-a")?];
|
||||
Arc::make_mut(valid[0].result.as_mut().unwrap()).plugins[0]
|
||||
@@ -252,13 +171,10 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
path: PathUri::parse("file:///plugins/example/1.0.0/.mcp.json")?,
|
||||
contents: r#"{"executor-only":{"command":"node"}}"#.to_string(),
|
||||
});
|
||||
let mut local = [
|
||||
let local = [
|
||||
executor_snapshot("executor-a")?,
|
||||
executor_snapshot("executor-b")?,
|
||||
];
|
||||
for snapshot in &mut local {
|
||||
Arc::make_mut(snapshot.result.as_mut().unwrap()).plugins[0].remote_plugin_id = None;
|
||||
}
|
||||
let empty = [ExecutorCapabilityDiscoveryV2Snapshot {
|
||||
environment_id: "executor-a".to_string(),
|
||||
result: Ok(Arc::new(DiscoverV2CapabilitiesResponse::default())),
|
||||
@@ -272,51 +188,33 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
"snapshot selects V2 independently of the acquisition flag",
|
||||
false,
|
||||
Some(valid.as_slice()),
|
||||
vec![
|
||||
"mcp:example",
|
||||
"executor-a:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
],
|
||||
),
|
||||
(
|
||||
"legacy",
|
||||
false,
|
||||
None,
|
||||
vec!["mcp:legacy", "legacy-root", "cloud:plugin_a"],
|
||||
vec!["disabled:example@marketplace"],
|
||||
),
|
||||
("legacy", false, None, vec!["mcp:legacy", "legacy-root"]),
|
||||
(
|
||||
"no V2 snapshot",
|
||||
true,
|
||||
None,
|
||||
vec!["mcp:legacy", "legacy-root", "cloud:plugin_a"],
|
||||
vec!["mcp:legacy", "legacy-root"],
|
||||
),
|
||||
(
|
||||
"empty snapshots",
|
||||
true,
|
||||
Some([].as_slice()),
|
||||
vec!["cloud:plugin_a"],
|
||||
Vec::<&str>::new(),
|
||||
),
|
||||
(
|
||||
"empty inventory",
|
||||
true,
|
||||
Some(empty.as_slice()),
|
||||
vec!["cloud:plugin_a"],
|
||||
),
|
||||
(
|
||||
"failed",
|
||||
true,
|
||||
Some(failed.as_slice()),
|
||||
vec!["cloud:plugin_a"],
|
||||
Vec::<&str>::new(),
|
||||
),
|
||||
("failed", true, Some(failed.as_slice()), Vec::<&str>::new()),
|
||||
(
|
||||
"valid",
|
||||
true,
|
||||
Some(valid.as_slice()),
|
||||
vec![
|
||||
"mcp:example",
|
||||
"executor-a:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
],
|
||||
vec!["disabled:example@marketplace"],
|
||||
),
|
||||
(
|
||||
"unconfigured local",
|
||||
@@ -325,7 +223,6 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
vec![
|
||||
"disabled:example@marketplace",
|
||||
"disabled:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
],
|
||||
),
|
||||
] {
|
||||
@@ -375,68 +272,19 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
.features
|
||||
.enable(Feature::ExecutorCapabilityDiscoveryV2)?;
|
||||
|
||||
// Cloud counterparts control enablement without deleting the executor installation.
|
||||
let mut disabled_cloud = cloud_plugin("plugin_a");
|
||||
disabled_cloud.enabled = false;
|
||||
for (case, cloud_enabled, catalog, enabled) in [
|
||||
("no cloud provider", false, None, true),
|
||||
("no cloud catalog", true, None, true),
|
||||
("absent", true, Some(PluginCatalog::default()), false),
|
||||
// Executor installations are local and enabled by configuration alone.
|
||||
for (case, snapshots, expected) in [
|
||||
(
|
||||
"partial absent",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
is_partial: true,
|
||||
warnings: vec!["partial cloud listing".to_string()],
|
||||
..Default::default()
|
||||
}),
|
||||
true,
|
||||
"configured",
|
||||
&valid[..],
|
||||
vec!["mcp:executor-only", "executor-a:example@marketplace"],
|
||||
),
|
||||
(
|
||||
"disabled",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
entries: vec![disabled_cloud],
|
||||
..Default::default()
|
||||
}),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"re-enabled",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
..Default::default()
|
||||
}),
|
||||
true,
|
||||
),
|
||||
(
|
||||
"partial counterpart",
|
||||
true,
|
||||
Some(PluginCatalog {
|
||||
entries: vec![cloud_plugin("plugin_a")],
|
||||
is_partial: true,
|
||||
warnings: vec!["partial cloud listing".to_string()],
|
||||
}),
|
||||
true,
|
||||
"configured without MCP config",
|
||||
&local[..1],
|
||||
vec!["executor-a:example@marketplace"],
|
||||
),
|
||||
] {
|
||||
let has_cloud_counterpart = catalog
|
||||
.as_ref()
|
||||
.is_some_and(|catalog| !catalog.entries.is_empty());
|
||||
contributor.providers.cloud = if cloud_enabled {
|
||||
Some(Arc::new(CloudProvider))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
{
|
||||
let mut cache = state.contributor_state();
|
||||
cache.cloud_generation = None;
|
||||
let key = cache.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
if let Some(catalog) = catalog {
|
||||
assert!(cache.publish_cloud_catalog(key.as_ref(), catalog));
|
||||
}
|
||||
}
|
||||
let contributions = contribution_labels(
|
||||
&contributor,
|
||||
McpServerContributionContext::for_step(
|
||||
@@ -446,62 +294,16 @@ async fn projection_respects_discovery_mode_and_preserves_enabled_plugins() -> a
|
||||
case,
|
||||
&roots,
|
||||
/*executor_capability_discovery*/ None,
|
||||
Some(&valid),
|
||||
Some(snapshots),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
let expected = if enabled && !has_cloud_counterpart {
|
||||
vec!["mcp:executor-only", "executor-a:example@marketplace"]
|
||||
} else if enabled {
|
||||
vec![
|
||||
"mcp:example",
|
||||
"executor-a:example@marketplace",
|
||||
"cloud:plugin_a",
|
||||
]
|
||||
} else {
|
||||
vec!["disabled:example@marketplace"]
|
||||
};
|
||||
assert_eq!(contributions, expected, "{case}");
|
||||
assert_eq!(
|
||||
state.contributor_state().executor_catalog,
|
||||
Some(catalog_from_snapshots(&valid)),
|
||||
Some(catalog_from_snapshots(snapshots)),
|
||||
"{case}"
|
||||
);
|
||||
}
|
||||
|
||||
// A full Cloud catalog must not crowd out enabled executor-local plugins.
|
||||
let cloud_plugin_count = 100;
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
let key = state.prepare_cloud_generation(/*mcp_resources*/ None);
|
||||
let entries = (0..cloud_plugin_count)
|
||||
.map(|index| cloud_plugin(&format!("plugin_{index}")))
|
||||
.collect::<Vec<_>>();
|
||||
assert!(state.publish_cloud_catalog(
|
||||
key.as_ref(),
|
||||
PluginCatalog {
|
||||
entries,
|
||||
..Default::default()
|
||||
}
|
||||
));
|
||||
}
|
||||
let contributions = contribution_labels(
|
||||
&contributor,
|
||||
McpServerContributionContext::for_step(
|
||||
&config,
|
||||
&init,
|
||||
&thread,
|
||||
"merged",
|
||||
&roots,
|
||||
/*executor_capability_discovery*/ None,
|
||||
Some(&local[..1]),
|
||||
),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(contributions.len(), cloud_plugin_count + 1);
|
||||
assert_eq!(contributions[0], "executor-a:example@marketplace");
|
||||
for (index, contribution) in contributions[1..].iter().enumerate() {
|
||||
assert_eq!(contribution, &format!("cloud:plugin_{index}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
43
codex-rs/ext/mcp/src/plugin_lifecycle.rs
Normal file
43
codex-rs/ext/mcp/src/plugin_lifecycle.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
//! Tracks plugin enablement and shares the thread's MCP resource client.
|
||||
|
||||
use crate::PluginsThreadState;
|
||||
use crate::plugin_contributor::PluginContributor;
|
||||
use codex_core::config::Config;
|
||||
use codex_extension_api::ConfigContributor;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_features::Feature;
|
||||
|
||||
impl ThreadLifecycleContributor<Config> for PluginContributor {
|
||||
fn on_thread_start<'a>(
|
||||
&'a self,
|
||||
input: ThreadStartInput<'a, Config>,
|
||||
) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let state = input.thread_store.get_or_init(PluginsThreadState::default);
|
||||
{
|
||||
let mut state = state.contributor_state();
|
||||
state.plugins_enabled = input.config.features.enabled(Feature::Plugins);
|
||||
state.extension_metrics = input.extension_metrics;
|
||||
}
|
||||
if let Some(resources) = &input.mcp_resource_client {
|
||||
input.session_store.insert(resources.as_ref().clone());
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigContributor<Config> for PluginContributor {
|
||||
fn on_config_changed(
|
||||
&self,
|
||||
_session_store: &ExtensionData,
|
||||
thread_store: &ExtensionData,
|
||||
_previous_config: &Config,
|
||||
new_config: &Config,
|
||||
) {
|
||||
let state = thread_store.get_or_init(PluginsThreadState::default);
|
||||
state.contributor_state().plugins_enabled = new_config.features.enabled(Feature::Plugins);
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,16 @@
|
||||
//! Host-assembled plugin sources; discovery results belong to the active thread, not this registry.
|
||||
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_core_plugins::PluginProvider;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Cloud discovery is optional and never replaces executor plugin support.
|
||||
/// Plugin providers available to a host.
|
||||
pub struct PluginProviders {
|
||||
// CCA owns and supplies the cloud provider implementation.
|
||||
pub(crate) cloud: Option<Arc<dyn PluginProvider>>,
|
||||
// Keep concrete access to resolve_bound so loaders retain the exact executor filesystem.
|
||||
pub(crate) executor: Arc<ExecutorPluginProvider>,
|
||||
}
|
||||
|
||||
impl PluginProviders {
|
||||
pub fn new(executor: Arc<ExecutorPluginProvider>) -> Self {
|
||||
Self {
|
||||
cloud: None,
|
||||
executor,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_cloud_provider(mut self, provider: Arc<dyn PluginProvider>) -> Self {
|
||||
self.cloud = Some(provider);
|
||||
self
|
||||
Self { executor }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,290 +0,0 @@
|
||||
//! Owns task-scoped MCP event streams without retaining their thread or runtime.
|
||||
//! Each subscription has one worker, and cancellation never waits for output capacity.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::PoisonError;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::AtomicU64;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use codex_extension_api::ExtensionFuture;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadReadyInput;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_mcp::McpEventNotification;
|
||||
use codex_mcp::McpEventStreamOpener;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_protocol::ThreadId;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::sync::watch;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio::time::Instant;
|
||||
use tokio::time::timeout_at;
|
||||
|
||||
const EVENT_UPDATE_CAPACITY: usize = 64;
|
||||
const ACTIVATION_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 90);
|
||||
|
||||
/// A notification or stream ending, identified by task, subscription, and stream attempt.
|
||||
pub enum McpEventStreamUpdate {
|
||||
Notification {
|
||||
thread_id: ThreadId,
|
||||
subscription_id: String,
|
||||
stream_attempt_id: u64,
|
||||
notification: McpEventNotification,
|
||||
},
|
||||
Ended {
|
||||
thread_id: ThreadId,
|
||||
subscription_id: String,
|
||||
stream_attempt_id: u64,
|
||||
result: Result<()>,
|
||||
},
|
||||
}
|
||||
|
||||
struct ManagedEventStream {
|
||||
stream_attempt_id: u64,
|
||||
active: Arc<AtomicBool>,
|
||||
worker: JoinHandle<()>,
|
||||
cancel_event_streams_on_server_removal: watch::Sender<()>,
|
||||
}
|
||||
|
||||
/// Tracks event streams by thread and subscription ID.
|
||||
///
|
||||
/// Notifications and stream endings go into a queue. Cancelling a
|
||||
/// stream does not require adding an `Ended` update, so it still works when the queue is full.
|
||||
pub struct McpEventStreamManager {
|
||||
streams: Mutex<HashMap<(ThreadId, String), ManagedEventStream>>,
|
||||
next_stream_attempt_id: AtomicU64,
|
||||
updates: mpsc::Sender<McpEventStreamUpdate>,
|
||||
shutdown: AtomicBool,
|
||||
}
|
||||
|
||||
impl McpEventStreamManager {
|
||||
pub fn new() -> (Self, mpsc::Receiver<McpEventStreamUpdate>) {
|
||||
let (updates, receiver) = mpsc::channel(EVENT_UPDATE_CAPACITY);
|
||||
(
|
||||
Self {
|
||||
streams: Mutex::default(),
|
||||
next_stream_attempt_id: AtomicU64::new(/*v*/ 1),
|
||||
updates,
|
||||
shutdown: AtomicBool::new(/*v*/ false),
|
||||
},
|
||||
receiver,
|
||||
)
|
||||
}
|
||||
|
||||
/// Opens a stream and returns its attempt ID after the server confirms activation.
|
||||
pub async fn start(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
subscription_id: String,
|
||||
opener: McpEventStreamOpener,
|
||||
event_name: String,
|
||||
arguments: Value,
|
||||
request_meta: Option<Map<String, Value>>,
|
||||
) -> Result<u64> {
|
||||
let key = (thread_id, subscription_id.clone());
|
||||
let (ready_tx, ready_rx) = oneshot::channel();
|
||||
{
|
||||
let mut streams = self.streams.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if self.shutdown.load(Ordering::Acquire) {
|
||||
return Err(anyhow!("MCP event stream manager is shut down"));
|
||||
}
|
||||
streams.retain(|_, stream| !stream.worker.is_finished());
|
||||
if let Some(stream) = streams.get(&key) {
|
||||
if stream.active.load(Ordering::Acquire) {
|
||||
return Ok(stream.stream_attempt_id);
|
||||
}
|
||||
return Err(anyhow!(
|
||||
"MCP event subscription is already starting or finishing"
|
||||
));
|
||||
}
|
||||
|
||||
let stream_attempt_id = self
|
||||
.next_stream_attempt_id
|
||||
.fetch_add(/*val*/ 1, Ordering::Relaxed);
|
||||
let active = Arc::new(AtomicBool::new(/*v*/ false));
|
||||
let worker_active = Arc::clone(&active);
|
||||
let cancel_event_streams_on_server_removal = opener.event_stream_cancellation_sender();
|
||||
let updates = self.updates.clone();
|
||||
let deadline = Instant::now() + ACTIVATION_TIMEOUT;
|
||||
// Keep the stream running if the caller stops waiting for activation.
|
||||
let worker = tokio::spawn(async move {
|
||||
let mut ready = Some(ready_tx);
|
||||
let forward = async {
|
||||
let mut stream = timeout_at(
|
||||
deadline,
|
||||
opener.open(&event_name, &arguments, request_meta.as_ref()),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream activation timed out"))??;
|
||||
|
||||
loop {
|
||||
let notification = if ready.is_some() {
|
||||
timeout_at(deadline, stream.recv())
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream activation timed out"))??
|
||||
} else {
|
||||
stream.recv().await?
|
||||
};
|
||||
let Some(notification) = notification else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let activates = notification.method == "notifications/events/active";
|
||||
let terminates = notification.method == "notifications/events/terminated";
|
||||
if activates {
|
||||
worker_active.store(/*val*/ true, Ordering::Release);
|
||||
if let Some(ready) = ready.take() {
|
||||
let _ = ready.send(Ok(stream_attempt_id));
|
||||
}
|
||||
}
|
||||
|
||||
let send = updates.send(McpEventStreamUpdate::Notification {
|
||||
thread_id,
|
||||
subscription_id: subscription_id.clone(),
|
||||
stream_attempt_id,
|
||||
notification,
|
||||
});
|
||||
let sent = if ready.is_some() {
|
||||
timeout_at(deadline, send)
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream activation timed out"))?
|
||||
} else {
|
||||
send.await
|
||||
};
|
||||
sent.map_err(|_| anyhow!("MCP event stream receiver was dropped"))?;
|
||||
|
||||
if terminates {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
};
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
() = opener.wait_for_access_change() => {
|
||||
Err(anyhow!("MCP event stream access changed"))
|
||||
}
|
||||
() = updates.closed() => {
|
||||
Err(anyhow!("MCP event stream receiver was dropped"))
|
||||
}
|
||||
result = forward => result,
|
||||
};
|
||||
|
||||
worker_active.store(/*val*/ false, Ordering::Release);
|
||||
drop(opener);
|
||||
if let Some(ready) = ready {
|
||||
let error = match &result {
|
||||
Ok(()) => anyhow!("MCP event stream ended before becoming active"),
|
||||
Err(error) => anyhow!("{error:#}"),
|
||||
};
|
||||
let _ = ready.send(Err(error));
|
||||
}
|
||||
|
||||
let _ = updates
|
||||
.send(McpEventStreamUpdate::Ended {
|
||||
thread_id,
|
||||
subscription_id,
|
||||
stream_attempt_id,
|
||||
result,
|
||||
})
|
||||
.await;
|
||||
});
|
||||
streams.insert(
|
||||
key,
|
||||
ManagedEventStream {
|
||||
stream_attempt_id,
|
||||
active,
|
||||
worker,
|
||||
cancel_event_streams_on_server_removal,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
ready_rx
|
||||
.await
|
||||
.map_err(|_| anyhow!("MCP event stream ended before becoming active"))?
|
||||
}
|
||||
|
||||
/// Await cancellation before starting the same subscription again.
|
||||
pub async fn cancel(&self, thread_id: ThreadId, subscription_id: &str) {
|
||||
let stream = self
|
||||
.streams
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(&(thread_id, subscription_id.to_owned()));
|
||||
if let Some(stream) = stream {
|
||||
stream.worker.abort();
|
||||
let _ = stream.worker.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Permanently rejects new starts and waits for all current workers to release their streams.
|
||||
pub async fn shutdown(&self) {
|
||||
self.shutdown.store(/*val*/ true, Ordering::Release);
|
||||
let streams = self
|
||||
.streams
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.drain()
|
||||
.map(|(_, stream)| stream)
|
||||
.collect::<Vec<_>>();
|
||||
for stream in &streams {
|
||||
stream.worker.abort();
|
||||
}
|
||||
for stream in streams {
|
||||
let _ = stream.worker.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<C: Sync> ThreadLifecycleContributor<C> for McpEventStreamManager {
|
||||
fn on_thread_start<'a>(&'a self, input: ThreadStartInput<'a, C>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
if let Some(client) = input.mcp_resource_client {
|
||||
input.thread_store.insert(client.as_ref().clone());
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn on_thread_ready<'a>(&'a self, input: ThreadReadyInput<'a, C>) -> ExtensionFuture<'a, ()> {
|
||||
Box::pin(async move {
|
||||
let Some(client) = input.thread_store.get::<McpResourceClient>() else {
|
||||
return;
|
||||
};
|
||||
let Ok(thread_id) = ThreadId::from_string(input.thread_store.level_id()) else {
|
||||
return;
|
||||
};
|
||||
let cancellation = self
|
||||
.streams
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.iter()
|
||||
.find(|((owner, _), stream)| {
|
||||
let belongs_to_task = *owner == thread_id;
|
||||
let worker_is_running = !stream.worker.is_finished();
|
||||
belongs_to_task && worker_is_running
|
||||
})
|
||||
.map(|(_, stream)| stream.cancel_event_streams_on_server_removal.clone());
|
||||
if let Some(cancellation) = cancellation {
|
||||
client.forward_event_server_removals_to(cancellation);
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for McpEventStreamManager {
|
||||
fn drop(&mut self) {
|
||||
let mut streams = self.streams.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
for (_, stream) in streams.drain() {
|
||||
stream.worker.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,353 +0,0 @@
|
||||
//! Exercises stream activation, task ownership, and cancellation.
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_extension_api::ExtensionData;
|
||||
use codex_extension_api::ThreadLifecycleContributor;
|
||||
use codex_extension_api::ThreadReadyInput;
|
||||
use codex_extension_api::ThreadStartInput;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_mcp::McpEventStreamOpener;
|
||||
use codex_mcp::McpResourceClient;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use super::event_stream_tests::Fixture;
|
||||
use super::event_stream_tests::StaticAuth;
|
||||
use super::event_stream_tests::WAIT;
|
||||
use crate::McpEventStreamManager;
|
||||
use crate::McpEventStreamUpdate;
|
||||
|
||||
async fn start_subscription(
|
||||
manager: &McpEventStreamManager,
|
||||
opener: &McpEventStreamOpener,
|
||||
thread_id: ThreadId,
|
||||
) -> Result<u64> {
|
||||
manager
|
||||
.start(
|
||||
thread_id,
|
||||
"sub".into(),
|
||||
opener.clone(),
|
||||
"test.event".into(),
|
||||
json!({}),
|
||||
/*request_meta*/ None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn connect_loaded_task(
|
||||
manager: &McpEventStreamManager,
|
||||
thread_id: ThreadId,
|
||||
client: Arc<McpResourceClient>,
|
||||
) {
|
||||
let session_store = ExtensionData::new("test");
|
||||
let thread_store = ExtensionData::new(thread_id.to_string());
|
||||
manager
|
||||
.on_thread_start(ThreadStartInput {
|
||||
config: &(),
|
||||
session_source: &SessionSource::Exec,
|
||||
persistent_thread_state_available: false,
|
||||
environments: &[],
|
||||
mcp_resource_client: Some(client),
|
||||
extension_metrics: None,
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
})
|
||||
.await;
|
||||
manager
|
||||
.on_thread_ready(ThreadReadyInput {
|
||||
config: &(),
|
||||
session_source: &SessionSource::Exec,
|
||||
session_store: &session_store,
|
||||
thread_store: &thread_store,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reloaded_tasks_can_cancel_surviving_streams() -> Result<()> {
|
||||
for removed_before_ready in [false, true] {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let (result, stream) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
result?;
|
||||
timeout(WAIT, updates.recv()).await?.unwrap();
|
||||
fixture.runtime.shutdown().await;
|
||||
drop(fixture.runtime);
|
||||
|
||||
let mut replacement = Fixture::new().await?;
|
||||
let client = Arc::new(McpResourceClient::new(Arc::clone(&replacement.runtime)));
|
||||
replacement.runtime_input.mcp_servers.clear();
|
||||
if removed_before_ready {
|
||||
replacement.runtime.replace(replacement.runtime_input).await;
|
||||
connect_loaded_task(&manager, thread_id, client).await;
|
||||
} else {
|
||||
connect_loaded_task(&manager, thread_id, client).await;
|
||||
let expected = stream.notify("notifications/events/event");
|
||||
let McpEventStreamUpdate::Notification { notification, .. } =
|
||||
timeout(WAIT, updates.recv()).await?.unwrap()
|
||||
else {
|
||||
panic!("event expected after task reload");
|
||||
};
|
||||
assert_eq!(notification, expected);
|
||||
replacement.runtime.replace(replacement.runtime_input).await;
|
||||
}
|
||||
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
let McpEventStreamUpdate::Ended { result, .. } =
|
||||
timeout(WAIT, updates.recv()).await?.unwrap()
|
||||
else {
|
||||
panic!("stream should end after the event server is removed");
|
||||
};
|
||||
assert!(result.is_err());
|
||||
manager.shutdown().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn streams_outlive_tasks_and_activate_with_full_output() -> Result<()> {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let first_thread = ThreadId::new();
|
||||
let second_thread = ThreadId::new();
|
||||
let mut streams = Vec::new();
|
||||
for thread_id in [first_thread, second_thread] {
|
||||
let start = manager.start(
|
||||
thread_id,
|
||||
"sub".into(),
|
||||
opener.clone(),
|
||||
"test.event".into(),
|
||||
json!({"resource_id": "resource-123"}),
|
||||
Some(serde_json::Map::from_iter([(
|
||||
"saved_id".into(),
|
||||
json!("sub"),
|
||||
)])),
|
||||
);
|
||||
tokio::pin!(start);
|
||||
let stream = tokio::select! {
|
||||
result = &mut start => panic!("start returned before activation: {result:?}"),
|
||||
stream = timeout(WAIT, fixture.opened.recv()) => stream?.unwrap(),
|
||||
};
|
||||
let mut params = stream.request["params"].clone();
|
||||
params["_meta"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("progressToken");
|
||||
assert_eq!(
|
||||
params,
|
||||
json!({"name": "test.event", "arguments": {"resource_id": "resource-123"}, "_meta": {"saved_id": "sub"}})
|
||||
);
|
||||
stream.notify("notifications/events/active");
|
||||
timeout(WAIT, start).await??;
|
||||
timeout(WAIT, updates.recv()).await?.unwrap();
|
||||
streams.push(stream);
|
||||
}
|
||||
start_subscription(&manager, &opener, first_thread).await?;
|
||||
assert!(fixture.opened.try_recv().is_err());
|
||||
|
||||
fixture.runtime.shutdown().await;
|
||||
let expected = streams[1].notify("notifications/events/event");
|
||||
let McpEventStreamUpdate::Notification {
|
||||
thread_id,
|
||||
subscription_id,
|
||||
notification,
|
||||
..
|
||||
} = timeout(WAIT, updates.recv()).await?.unwrap()
|
||||
else {
|
||||
panic!("event expected");
|
||||
};
|
||||
assert_eq!(
|
||||
(thread_id, subscription_id, notification),
|
||||
(second_thread, "sub".into(), expected)
|
||||
);
|
||||
for _ in 0..=updates.max_capacity() {
|
||||
streams[0].notify("notifications/events/event");
|
||||
}
|
||||
timeout(WAIT, async {
|
||||
while updates.capacity() != 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
|
||||
let third_thread = ThreadId::new();
|
||||
let (started, stream) = tokio::join!(
|
||||
timeout(WAIT, start_subscription(&manager, &opener, third_thread)),
|
||||
async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
}
|
||||
);
|
||||
started??;
|
||||
assert_eq!(updates.capacity(), 0);
|
||||
manager.cancel(third_thread, "sub").await;
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
|
||||
manager.cancel(first_thread, "sub").await;
|
||||
timeout(WAIT, streams[0].notifications.closed()).await?;
|
||||
manager.shutdown().await;
|
||||
timeout(WAIT, streams[1].notifications.closed()).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queued_updates_keep_their_stream_attempt_after_replacement() -> Result<()> {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let (first_attempt, stream) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
let first_attempt = first_attempt?;
|
||||
assert_eq!(
|
||||
start_subscription(&manager, &opener, thread_id).await?,
|
||||
first_attempt
|
||||
);
|
||||
|
||||
stream.notify("notifications/events/terminated");
|
||||
// Leave activation, termination, and the ending queued while opening a replacement.
|
||||
timeout(WAIT, async {
|
||||
while updates.len() < 3 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
manager.cancel(thread_id, "sub").await;
|
||||
|
||||
let (second_attempt, replacement) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
let second_attempt = second_attempt?;
|
||||
assert_ne!(first_attempt, second_attempt);
|
||||
|
||||
let mut queued_attempts = Vec::new();
|
||||
for _ in 0..4 {
|
||||
let stream_attempt_id = match timeout(WAIT, updates.recv()).await?.unwrap() {
|
||||
McpEventStreamUpdate::Notification {
|
||||
stream_attempt_id, ..
|
||||
} => stream_attempt_id,
|
||||
McpEventStreamUpdate::Ended {
|
||||
stream_attempt_id,
|
||||
result,
|
||||
..
|
||||
} => {
|
||||
result?;
|
||||
assert_eq!(stream_attempt_id, first_attempt);
|
||||
stream_attempt_id
|
||||
}
|
||||
};
|
||||
queued_attempts.push(stream_attempt_id);
|
||||
}
|
||||
assert_eq!(
|
||||
queued_attempts,
|
||||
vec![first_attempt, first_attempt, first_attempt, second_attempt]
|
||||
);
|
||||
manager.shutdown().await;
|
||||
timeout(WAIT, replacement.notifications.closed()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_before_activation_releases_the_subscription_id() -> Result<()> {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, _updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let start = start_subscription(&manager, &opener, thread_id);
|
||||
tokio::pin!(start);
|
||||
let stream = tokio::select! {
|
||||
result = &mut start => panic!("start returned before activation: {result:?}"),
|
||||
stream = timeout(WAIT, fixture.opened.recv()) => stream?.unwrap(),
|
||||
};
|
||||
manager.cancel(thread_id, "sub").await;
|
||||
assert!(timeout(WAIT, start).await?.is_err());
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
let (result, replacement) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
result?;
|
||||
manager.shutdown().await;
|
||||
timeout(WAIT, replacement.notifications.closed()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn access_changes_cancel_streams_with_full_output() -> Result<()> {
|
||||
for remove_server in [false, true] {
|
||||
let mut fixture = Fixture::new().await?;
|
||||
let opener = McpResourceClient::new(Arc::clone(&fixture.runtime)).event_stream_opener()?;
|
||||
let (manager, mut updates) = McpEventStreamManager::new();
|
||||
let thread_id = ThreadId::new();
|
||||
let (result, stream) =
|
||||
tokio::join!(start_subscription(&manager, &opener, thread_id), async {
|
||||
let stream = timeout(WAIT, fixture.opened.recv()).await.unwrap().unwrap();
|
||||
stream.notify("notifications/events/active");
|
||||
stream
|
||||
});
|
||||
result?;
|
||||
timeout(WAIT, updates.recv()).await?.unwrap();
|
||||
for _ in 0..=updates.max_capacity() {
|
||||
stream.notify("notifications/events/event");
|
||||
}
|
||||
timeout(WAIT, async {
|
||||
while updates.capacity() != 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
if remove_server {
|
||||
fixture.runtime_input.mcp_servers.clear();
|
||||
fixture.runtime.replace(fixture.runtime_input).await;
|
||||
} else {
|
||||
fixture
|
||||
.auth
|
||||
.set_external_auth(Arc::new(StaticAuth(CodexAuth::from_api_key(
|
||||
"other-account-key",
|
||||
))))
|
||||
.await?;
|
||||
}
|
||||
// Access changes close the stream even while its output is blocked.
|
||||
timeout(WAIT, stream.notifications.closed()).await?;
|
||||
let result = timeout(WAIT, async {
|
||||
loop {
|
||||
if let McpEventStreamUpdate::Ended { result, .. } = updates.recv().await.unwrap() {
|
||||
break result;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await?;
|
||||
assert!(result.is_err());
|
||||
assert!(
|
||||
opener
|
||||
.open("test.event", &json!({}), /*request_meta*/ None)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,20 +1,12 @@
|
||||
use anyhow::Context;
|
||||
use codex_config::AppToolApproval;
|
||||
use codex_config::McpServerToolConfig;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_config::test_support::ManagedConfigFixture;
|
||||
use codex_core::EnvironmentConfig;
|
||||
use codex_core::config::Config;
|
||||
use codex_core::config::ConfigBuilder;
|
||||
use codex_core::windows_sandbox::WindowsSandboxLevelExt;
|
||||
use codex_core_plugins::ExecutorPluginProvider;
|
||||
use codex_core_plugins::PluginCatalog;
|
||||
use codex_core_plugins::PluginCatalogEntry;
|
||||
use codex_core_plugins::PluginIdentity;
|
||||
use codex_core_plugins::PluginListQuery;
|
||||
use codex_core_plugins::PluginProvider;
|
||||
use codex_core_plugins::PluginProviderError;
|
||||
use codex_core_plugins::PluginProviderFuture;
|
||||
use codex_core_plugins::PluginSourceLocation;
|
||||
use codex_exec_server::CapabilityRootDiscovery;
|
||||
use codex_exec_server::EnvironmentManager;
|
||||
use codex_exec_server::ExecutorCapabilityDiscoveryCache;
|
||||
@@ -29,15 +21,14 @@ use codex_extension_api::SelectedPluginContribution;
|
||||
use codex_features::Feature;
|
||||
use codex_login::CodexAuth;
|
||||
use codex_mcp_extension::PluginProviders;
|
||||
use codex_mcp_extension::PluginsThreadState;
|
||||
use codex_mcp_extension::install_plugin_providers;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use codex_protocol::config_types::WindowsSandboxLevel;
|
||||
use codex_protocol::models::PermissionProfileSnapshot;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use core_test_support::apps_test_server::AppsTestServer;
|
||||
use core_test_support::apps_test_server::recorded_apps_tool_calls;
|
||||
use core_test_support::mcp_test_server::McpTestServer;
|
||||
use core_test_support::mcp_test_server::recorded_mcp_tool_calls;
|
||||
use core_test_support::responses::ev_assistant_message;
|
||||
use core_test_support::responses::ev_completed;
|
||||
use core_test_support::responses::ev_function_call_with_namespace;
|
||||
@@ -53,8 +44,6 @@ use serde_json::json;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
type TestResult = Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
@@ -73,7 +62,6 @@ struct PackageSummary {
|
||||
plugin_id: String,
|
||||
plugin_display_name: String,
|
||||
source_environment_id: String,
|
||||
connector_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -102,8 +90,8 @@ async fn selected_plugin_servers_use_managed_requirements_for_the_selected_root_
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.cloud_config_bundle(
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement(
|
||||
.loader_overrides(
|
||||
(ManagedConfigFixture::requirements(
|
||||
r#"
|
||||
[plugins."selected-root".mcp_servers.allowed.identity]
|
||||
command = "allowed-command"
|
||||
@@ -111,7 +99,9 @@ command = "allowed-command"
|
||||
[plugins."selected-root".mcp_servers.mismatched.identity]
|
||||
command = "expected-command"
|
||||
"#,
|
||||
),
|
||||
))
|
||||
.loader_overrides_for_tests(codex_home.path())
|
||||
.expect("write managed config fixture"),
|
||||
)
|
||||
.build()
|
||||
.await?;
|
||||
@@ -151,7 +141,7 @@ command = "expected-command"
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn selected_plugin_package_is_contributed_without_servers_or_connectors() -> TestResult {
|
||||
async fn selected_plugin_package_is_contributed_without_servers() -> TestResult {
|
||||
let codex_home = tempfile::tempdir()?;
|
||||
let plugin_root = tempfile::tempdir()?;
|
||||
std::fs::create_dir_all(plugin_root.path().join(".codex-plugin"))?;
|
||||
@@ -178,7 +168,6 @@ async fn selected_plugin_package_is_contributed_without_servers_or_connectors()
|
||||
plugin_id,
|
||||
plugin_display_name: contribution.plugin_display_name,
|
||||
source_environment_id: contribution.source_environment_id,
|
||||
connector_ids: contribution.connector_ids,
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
@@ -187,7 +176,6 @@ async fn selected_plugin_package_is_contributed_without_servers_or_connectors()
|
||||
plugin_id: "selected-root".to_string(),
|
||||
plugin_display_name: "Skill Only".to_string(),
|
||||
source_environment_id: LOCAL_ENVIRONMENT_ID.to_string(),
|
||||
connector_ids: Vec::new(),
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
@@ -235,7 +223,6 @@ async fn denied_malformed_plugin_retains_identity_without_capabilities() -> Test
|
||||
vec![(
|
||||
("selected-root".to_string(), "selected-root".to_string()),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
)]
|
||||
} else {
|
||||
Vec::new()
|
||||
@@ -248,7 +235,6 @@ async fn denied_malformed_plugin_retains_identity_without_capabilities() -> Test
|
||||
.map(|(root_id, plugin_id, contribution)| (
|
||||
(root_id, plugin_id),
|
||||
contribution.servers,
|
||||
contribution.connector_ids,
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
expected
|
||||
@@ -395,7 +381,6 @@ async fn selected_root_ownership_retries_errors_and_caches_success() -> TestResu
|
||||
.into_iter()
|
||||
.map(|(name, _)| name)
|
||||
.collect::<Vec<_>>(),
|
||||
contribution.connector_ids,
|
||||
));
|
||||
}
|
||||
assert_eq!(
|
||||
@@ -405,7 +390,6 @@ async fn selected_root_ownership_retries_errors_and_caches_success() -> TestResu
|
||||
.map(|(id, servers)| (
|
||||
id.to_string(),
|
||||
servers.into_iter().map(str::to_string).collect::<Vec<_>>(),
|
||||
Vec::new(),
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
"phase {phase}",
|
||||
@@ -430,13 +414,15 @@ async fn managed_plugins_requirement_disables_selected_plugin_capabilities() ->
|
||||
let mut config = ConfigBuilder::default()
|
||||
.codex_home(codex_home.path().to_path_buf())
|
||||
.fallback_cwd(Some(codex_home.path().to_path_buf()))
|
||||
.cloud_config_bundle(
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement(
|
||||
.loader_overrides(
|
||||
(ManagedConfigFixture::requirements(
|
||||
r#"
|
||||
[features]
|
||||
plugins = false
|
||||
"#,
|
||||
),
|
||||
))
|
||||
.loader_overrides_for_tests(codex_home.path())
|
||||
.expect("write managed config fixture"),
|
||||
)
|
||||
.build()
|
||||
.await?;
|
||||
@@ -692,43 +678,22 @@ async fn raw_selected_plugin_contributions(
|
||||
Ok(contributions)
|
||||
}
|
||||
|
||||
struct CloudCatalogFixture {
|
||||
reply: Result<PluginCatalog, String>,
|
||||
calls: AtomicUsize,
|
||||
}
|
||||
|
||||
impl PluginProvider for CloudCatalogFixture {
|
||||
fn list(&self, _query: PluginListQuery) -> PluginProviderFuture<'_, PluginCatalog> {
|
||||
Box::pin(async {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
self.reply.clone().map_err(PluginProviderError::Message)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloud_plugins_append_apps_without_changing_executor_tools() -> anyhow::Result<()> {
|
||||
fn installed_executor_plugin_exposes_and_calls_its_mcp_tools() -> anyhow::Result<()> {
|
||||
run_test_with_large_stack(
|
||||
"cloud-plugin-projection",
|
||||
run_cloud_plugin_projection_scenarios,
|
||||
"executor-plugin-projection",
|
||||
run_executor_plugin_projection_scenarios,
|
||||
)
|
||||
}
|
||||
|
||||
async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
async fn run_executor_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
core_test_support::skip_if_remote!(Ok(()), "V1 plugin fixtures use host-local files");
|
||||
// Fresh sessions keep unavailable-cloud fallback independent of a previously cached catalog.
|
||||
for (case, installed, cloud_enabled, cloud_available, cloud_empty) in [
|
||||
("cloud_only", false, true, true, false),
|
||||
("cloud_and_executor", true, true, true, false),
|
||||
("unavailable_cloud", true, true, false, false),
|
||||
("rollout_disabled", true, false, true, false),
|
||||
("empty_cloud", true, true, true, true),
|
||||
] {
|
||||
// Uninstalled plugins must not start MCPs; installed ones expose and run their tools.
|
||||
for (case, installed) in [("not_installed", false), ("installed", true)] {
|
||||
let server = start_mock_server().await;
|
||||
let apps = AppsTestServer::mount(&server).await?;
|
||||
let plugin_server = start_mock_server().await;
|
||||
let plugin_mcp = AppsTestServer::mount_with_tools(
|
||||
let plugin_mcp = McpTestServer::mount_with_tools(
|
||||
&plugin_server,
|
||||
Arc::new(std::sync::Mutex::new(vec![json!({
|
||||
"name": "echo", "description": "Echo a note.",
|
||||
@@ -749,41 +714,11 @@ async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
})
|
||||
.with_priority(1)
|
||||
.mount(&plugin_server).await;
|
||||
let declaration =
|
||||
json!({"url": format!("{}/api/codex/ps/mcp", plugin_mcp.chatgpt_base_url)});
|
||||
let cloud = Arc::new(CloudCatalogFixture {
|
||||
reply: if cloud_empty {
|
||||
Ok(PluginCatalog::default())
|
||||
} else if cloud_available {
|
||||
Ok(PluginCatalog {
|
||||
entries: vec![PluginCatalogEntry {
|
||||
enabled: true,
|
||||
id: PluginIdentity::Remote {
|
||||
remote_plugin_id: "plugin_notes".into(),
|
||||
},
|
||||
display_name: "Cloud Notes".into(),
|
||||
version: "1".into(),
|
||||
mcp_servers: [("notes".into(), declaration.clone())].into(),
|
||||
connector_ids: vec!["calendar".into()],
|
||||
locations: vec![PluginSourceLocation::Cloud {
|
||||
resource_uri: "plugin://plugin_notes".into(),
|
||||
bundle_uri: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
})
|
||||
} else {
|
||||
Err("plugin-service unavailable".into())
|
||||
},
|
||||
calls: AtomicUsize::new(0),
|
||||
});
|
||||
let declaration = json!({"url": plugin_mcp.mcp_url()});
|
||||
let mut extensions = ExtensionRegistryBuilder::new();
|
||||
let mut providers = PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
let providers = PluginProviders::new(Arc::new(ExecutorPluginProvider::new(Arc::new(
|
||||
EnvironmentManager::default_for_tests(),
|
||||
))));
|
||||
if cloud_enabled {
|
||||
providers = providers.with_cloud_provider(cloud.clone());
|
||||
}
|
||||
install_plugin_providers(&mut extensions, providers);
|
||||
let mut builder = test_codex()
|
||||
.with_extensions(Arc::new(extensions.build()))
|
||||
@@ -791,14 +726,12 @@ async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
.with_model_info_override("gpt-5.5", |model| model.supports_search_tool = false)
|
||||
.with_config(move |config| {
|
||||
assert!(config.features.enable(Feature::Plugins).is_ok());
|
||||
assert!(config.features.enable(Feature::Apps).is_ok());
|
||||
assert!(
|
||||
config
|
||||
.features
|
||||
.enable(Feature::ExecutorCapabilityDiscovery)
|
||||
.is_ok()
|
||||
);
|
||||
config.chatgpt_base_url = apps.chatgpt_base_url;
|
||||
});
|
||||
let test = builder.build(&server).await?;
|
||||
if installed {
|
||||
@@ -887,7 +820,7 @@ async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
"{case}: {output}"
|
||||
);
|
||||
}
|
||||
let calls = recorded_apps_tool_calls(&plugin_server).await;
|
||||
let calls = recorded_mcp_tool_calls(&plugin_server).await;
|
||||
assert_eq!(calls.len(), usize::from(installed), "{case}");
|
||||
if installed {
|
||||
assert_eq!(calls[0]["params"]["name"], "echo");
|
||||
@@ -907,34 +840,7 @@ async fn run_cloud_plugin_projection_scenarios() -> anyhow::Result<()> {
|
||||
});
|
||||
assert_eq!(
|
||||
initialized, installed,
|
||||
"{case}: cloud-only declarations must not start MCPs"
|
||||
);
|
||||
// Failed discovery stays in cooldown across both model steps.
|
||||
assert_eq!(
|
||||
cloud.calls.load(Ordering::SeqCst),
|
||||
usize::from(cloud_enabled),
|
||||
"{case}"
|
||||
);
|
||||
let state = test
|
||||
.codex
|
||||
.thread_extension_data()
|
||||
.get::<PluginsThreadState>()
|
||||
.context("plugin state missing")?;
|
||||
assert_eq!(
|
||||
state.cloud_catalog().is_some(),
|
||||
cloud_enabled && cloud_available,
|
||||
"{case}"
|
||||
);
|
||||
let calendar = requests[0]
|
||||
.tool_by_name("mcp__codex_apps__calendar", "_list_events")
|
||||
.context("Calendar tool missing")?;
|
||||
assert_eq!(
|
||||
calendar["description"]
|
||||
.as_str()
|
||||
.context("Apps description missing")?
|
||||
.contains("Cloud Notes"),
|
||||
cloud_enabled && cloud_available && !cloud_empty,
|
||||
"{case}"
|
||||
"{case}: uninstalled declarations must not start MCPs"
|
||||
);
|
||||
test.codex.shutdown_and_wait().await?;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user