diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 2e7eccd5..5568718f 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -746,6 +746,13 @@ boundary while Codex survives only as subscription auth/model routing. Do not resume Rider, Unity, Aquarium, Face, dogfood, planning, app, skill, marketplace, or bridge expansion until this organ is being cut cleanly. +The first Codex product-surface starvation cut is landed too. App-server +apps/skills/plugin/marketplace list routes are inert, mutation/detail routes +return explicit disabled errors, the helper modules and stale v2 endpoint tests +were deleted, and the broken private `processor_tests.rs` implementation-shape +suite is gone. `codex_message_processor.rs` is still too large, but it is no +longer carrying the plugin marketplace altar in its chest cavity. + The Phase 6 freshness slice is landed. It exposes read-only `thread/epiphany/freshness` from live retrieval summaries plus graph frontier/churn state and, for loaded threads, watcher-backed invalidation diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index 6adb4216..bec3590d 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index 2996215f..ed8b23a8 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -280,5 +280,5 @@ rejected_paths: reason: making Epiphany cleaner inside Codex still preserves the wrong organ; Codex must be starved down to OpenAI subscription auth/model transport, while Epiphany data and subsystem communication move to typed CultCache/CultNet. current_status: - summary: The Codex starvation pass has five typing receipts, twenty-six processor/foundation cuts, a real physical extraction in `epiphany-codex-bridge`, a root `epiphany-state-model` crate for durable Epiphany state, a source-grounded Codex auth spine inventory, the native `epiphany-openai-adapter` document boundary, a buildable Codex auth/model wrapper in `epiphany-openai-codex-spine`, the first native runtime caller in `epiphany-openai-runtime`, native heartbeat launch planning/job opening in `epiphany-core`, native state-update contract/validation/application in `epiphany-core`, native exact retrieval path matching in `epiphany-core`, and the route-facing mutation/view/coordinator projection services in `epiphany-codex-bridge`. `codex-protocol` no longer defines the durable `Epiphany*` state structs; it re-exports the native model for legacy rollout/API compatibility while `epiphany-core` imports the native model directly. `epiphany-core` now has no direct vendored Codex dependency: pressure derivation accepts native `EpiphanyTokenUsageSnapshot`, Codex rollout replay moved to `codex-core::epiphany_rollout`, and exact retrieval search uses Epiphany-owned workspace walking/path scoring instead of `codex-file-search`. The bridge owns Codex-facing Epiphany adapters for scene, jobs, context/planning/graph query, retrieval/indexing projection, result projection, runtime-spine result adaptation, launch/prompt doctrine, mutation document mechanics, mutation service update/promote/role-accept/reorient-accept/role-launch/reorient-launch/job-launch/job-interrupt application, live-state projection, pressure/pre-compaction rendering, freshness/reorientation projection, CRRC/coordinator/role-board projection, full `thread/epiphany/view` response construction, freshness/context/graph-query response construction, role/reorient result response construction, distill/propose patch-response construction, coordinator status/view construction, and acceptance/evidence signal helpers. Vendored app-server now retains only `epiphany_invalidation.rs` as a root Epiphany module because watcher lifecycle is still app-server machinery; `codex_message_processor.rs` still contains route dispatch, JSON-RPC response shaping, watcher registration/snapshotting, and notification emission, but its root no longer imports the evacuated Epiphany policy/protocol registry. `epiphany_read_routes.rs` is about 579 lines after the full view and read-response extractions; `epiphany_mutation_routes.rs` is about 691 lines after the route-load/notification helper cut and index projection move; `epiphany_state_helpers.rs` is down to a 19-line rollout-state loader; and `codex_thread.rs` is about 1,425 lines after state-update law moved native. `epiphany-openai-adapter` defines CultCache `DatabaseEntry` request/event/receipt/auth-status documents with no Codex app-server or generic JSON dependency. `epiphany-openai-codex-spine` owns all direct Codex auth/model-transport imports for the native OpenAI path: it exposes `default_codex_home` and `auth_manager`, projects `AuthManager` / `CodexAuth` into typed `EpiphanyOpenAiAdapterStatus`, maps typed `EpiphanyOpenAiModelRequest` into Codex API `ResponsesApiRequest`, resolves auth/provider through keeper Codex crates, opens HTTP Responses streams through `codex-api`, maps deltas / completion into typed stream events and receipts, and no longer directly depends on `codex-app-server-protocol` just to name auth mode. `epiphany-openai-runtime` no longer depends directly on `codex-login`; it writes OpenAI status/request/stream-event/receipt records plus runtime sessions/jobs/results/events into `epiphany-core::runtime_spine_cache`, can emit the assistant text artifact for legacy result consumers, is now the default executor for startup-only repo birth specialists, and now has `run-worker` to load a durable `EpiphanyRuntimeWorkerLaunchRequest`, call the typed OpenAI runtime through the spine, persist typed `EpiphanyRuntimeRoleWorkerResult` / `EpiphanyRuntimeReorientWorkerResult` documents, and complete the original heartbeat/specialist runtime job without Codex worker execution; `codex exec` survives only as explicit fallback in repo-birth startup. `epiphany-mvp-coordinator` now invokes `epiphany-openai-runtime run-worker` for launched runtime job ids and no longer creates a second coordinator-owned shadow runtime job/result as a compensator. `epiphany-core::plan_runtime_spine_heartbeat_launch` validates launch contracts/conflicts and projects durable job bindings/runtime links; `epiphany-core::open_runtime_spine_heartbeat_job` owns the initialize-runtime/ensure-session/create-job sequence and now persists `EpiphanyRuntimeWorkerLaunchRequest` CultCache records keyed by runtime job id, with indexed kind/contract fields plus MessagePack-encoded typed launch documents instead of discarding work intent after queue receipt creation; `roleResult` and `reorientResult` now prefer typed worker result documents and fall back only to generic job summaries for older receipts; `epiphany-core::EpiphanyStateUpdate`, `epiphany_state_update_validation_errors`, and `apply_epiphany_state_update` own state-update document shape and mutation law while `codex-core` calls them for compatibility. Vendored `CodexThread::epiphany_launch_job` is now mostly revision check, persistence validation, launch request handoff, and rollout/session writeback for the compatibility route. Vendored `codex-core` no longer has `epiphany_distillation`, `epiphany_promotion`, `epiphany_proposal`, or `epiphany_retrieval` husk modules; it re-exports native surfaces from `epiphany-core` directly, and now owns only the real Codex rollout adapter because it is a host seam. `epiphany-runtime-spine` advertises OpenAI adapter status/model-request/stream-event/receipt CultNet schemas and mutation contracts, so the native caller now has a real storage route instead of only JSON-RPC. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON. The current OpenAI spine still pulls `codex-api` and a large transport dependency stack, so its next cut is dependency starvation after richer live callers move. + summary: The Codex starvation pass has five typing receipts, twenty-seven processor/foundation cuts, a real physical extraction in `epiphany-codex-bridge`, a root `epiphany-state-model` crate for durable Epiphany state, a source-grounded Codex auth spine inventory, the native `epiphany-openai-adapter` document boundary, a buildable Codex auth/model wrapper in `epiphany-openai-codex-spine`, the first native runtime caller in `epiphany-openai-runtime`, native heartbeat launch planning/job opening in `epiphany-core`, native state-update contract/validation/application in `epiphany-core`, native exact retrieval path matching in `epiphany-core`, and the route-facing mutation/view/coordinator projection services in `epiphany-codex-bridge`. `codex-protocol` no longer defines the durable `Epiphany*` state structs; it re-exports the native model for legacy rollout/API compatibility while `epiphany-core` imports the native model directly. `epiphany-core` now has no direct vendored Codex dependency: pressure derivation accepts native `EpiphanyTokenUsageSnapshot`, Codex rollout replay moved to `codex-core::epiphany_rollout`, and exact retrieval search uses Epiphany-owned workspace walking/path scoring instead of `codex-file-search`. The bridge owns Codex-facing Epiphany adapters for scene, jobs, context/planning/graph query, retrieval/indexing projection, result projection, runtime-spine result adaptation, launch/prompt doctrine, mutation document mechanics, mutation service update/promote/role-accept/reorient-accept/role-launch/reorient-launch/job-launch/job-interrupt application, live-state projection, pressure/pre-compaction rendering, freshness/reorientation projection, CRRC/coordinator/role-board projection, full `thread/epiphany/view` response construction, freshness/context/graph-query response construction, role/reorient result response construction, distill/propose patch-response construction, coordinator status/view construction, and acceptance/evidence signal helpers. Vendored app-server now retains only `epiphany_invalidation.rs` as a root Epiphany module because watcher lifecycle is still app-server machinery; `codex_message_processor.rs` still contains route dispatch, JSON-RPC response shaping, watcher registration/snapshotting, and notification emission, but its root no longer imports the evacuated Epiphany policy/protocol registry. Codex product surfaces for apps, skills, plugins, and marketplace are now inert in the app-server compatibility path: list routes return empty lists, mutation/detail routes report disabled, the helper modules and stale implementation-shape tests were deleted, and `codex-plugin` is no longer an app-server dependency. `codex_message_processor.rs` is about 9,634 lines; `epiphany_read_routes.rs` is about 579 lines after the full view and read-response extractions; `epiphany_mutation_routes.rs` is about 694 lines after route-load/notification helper cuts and product-surface starvation; `epiphany_state_helpers.rs` is down to a 19-line rollout-state loader; and `codex_thread.rs` is about 1,425 lines after state-update law moved native. `epiphany-openai-adapter` defines CultCache `DatabaseEntry` request/event/receipt/auth-status documents with no Codex app-server or generic JSON dependency. `epiphany-openai-codex-spine` owns all direct Codex auth/model-transport imports for the native OpenAI path: it exposes `default_codex_home` and `auth_manager`, projects `AuthManager` / `CodexAuth` into typed `EpiphanyOpenAiAdapterStatus`, maps typed `EpiphanyOpenAiModelRequest` into Codex API `ResponsesApiRequest`, resolves auth/provider through keeper Codex crates, opens HTTP Responses streams through `codex-api`, maps deltas / completion into typed stream events and receipts, and no longer directly depends on `codex-app-server-protocol` just to name auth mode. `epiphany-openai-runtime` no longer depends directly on `codex-login`; it writes OpenAI status/request/stream-event/receipt records plus runtime sessions/jobs/results/events into `epiphany-core::runtime_spine_cache`, can emit the assistant text artifact for legacy result consumers, is now the default executor for startup-only repo birth specialists, and now has `run-worker` to load a durable `EpiphanyRuntimeWorkerLaunchRequest`, call the typed OpenAI runtime through the spine, persist typed `EpiphanyRuntimeRoleWorkerResult` / `EpiphanyRuntimeReorientWorkerResult` documents, and complete the original heartbeat/specialist runtime job without Codex worker execution; `codex exec` survives only as explicit fallback in repo-birth startup. `epiphany-mvp-coordinator` now invokes `epiphany-openai-runtime run-worker` for launched runtime job ids and no longer creates a second coordinator-owned shadow runtime job/result as a compensator. `epiphany-core::plan_runtime_spine_heartbeat_launch` validates launch contracts/conflicts and projects durable job bindings/runtime links; `epiphany-core::open_runtime_spine_heartbeat_job` owns the initialize-runtime/ensure-session/create-job sequence and now persists `EpiphanyRuntimeWorkerLaunchRequest` CultCache records keyed by runtime job id, with indexed kind/contract fields plus MessagePack-encoded typed launch documents instead of discarding work intent after queue receipt creation; `roleResult` and `reorientResult` now prefer typed worker result documents and fall back only to generic job summaries for older receipts; `epiphany-core::EpiphanyStateUpdate`, `epiphany_state_update_validation_errors`, and `apply_epiphany_state_update` own state-update document shape and mutation law while `codex-core` calls them for compatibility. Vendored `CodexThread::epiphany_launch_job` is now mostly revision check, persistence validation, launch request handoff, and rollout/session writeback for the compatibility route. Vendored `codex-core` no longer has `epiphany_distillation`, `epiphany_promotion`, `epiphany_proposal`, or `epiphany_retrieval` husk modules; it re-exports native surfaces from `epiphany-core` directly, and now owns only the real Codex rollout adapter because it is a host seam. `epiphany-runtime-spine` advertises OpenAI adapter status/model-request/stream-event/receipt CultNet schemas and mutation contracts, so the native caller now has a real storage route instead of only JSON-RPC. MCP itself is correctly JSON at its protocol edge; the target is typed Epiphany intent/result/receipt wrappers around MCP, not replacing MCP JSON. The current OpenAI spine still pulls `codex-api` and a large transport dependency stack, so its next cut is dependency starvation after richer live callers move. next_action: Continue starving coordinator/runtime execution and operator surfaces off app-server JSON-RPC and out of `codex_message_processor.rs`; keep the vestigial Codex organ narrowed to subscription auth/model transport. diff --git a/vendor/codex/codex-rs/Cargo.lock b/vendor/codex/codex-rs/Cargo.lock index 132db42b..4e05855b 100644 --- a/vendor/codex/codex-rs/Cargo.lock +++ b/vendor/codex/codex-rs/Cargo.lock @@ -1899,7 +1899,6 @@ dependencies = [ "codex-model-provider-info", "codex-models-manager", "codex-otel", - "codex-plugin", "codex-protocol", "codex-rmcp-client", "codex-rollout", diff --git a/vendor/codex/codex-rs/app-server/Cargo.toml b/vendor/codex/codex-rs/app-server/Cargo.toml index 91b6979b..bbffa558 100644 --- a/vendor/codex/codex-rs/app-server/Cargo.toml +++ b/vendor/codex/codex-rs/app-server/Cargo.toml @@ -40,7 +40,6 @@ codex-exec-server = { workspace = true } codex-features = { workspace = true } codex-git-utils = { workspace = true } codex-otel = { workspace = true } -codex-plugin = { workspace = true } codex-shell-command = { workspace = true } codex-utils-cli = { workspace = true } codex-utils-pty = { workspace = true } diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs index 2376b918..6399a717 100644 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs +++ b/vendor/codex/codex-rs/app-server/src/codex_message_processor.rs @@ -41,8 +41,6 @@ use codex_app_server_protocol::AccountLoginCompletedNotification; use codex_app_server_protocol::AccountUpdatedNotification; use codex_app_server_protocol::AddCreditsNudgeCreditType; use codex_app_server_protocol::AddCreditsNudgeEmailStatus; -use codex_app_server_protocol::AppInfo; -use codex_app_server_protocol::AppSummary; use codex_app_server_protocol::AppsListParams; use codex_app_server_protocol::AppsListResponse; use codex_app_server_protocol::AskForApproval; @@ -94,10 +92,7 @@ use codex_app_server_protocol::LoginAccountResponse; use codex_app_server_protocol::LoginApiKeyParams; use codex_app_server_protocol::LogoutAccountResponse; use codex_app_server_protocol::MarketplaceAddParams; -use codex_app_server_protocol::MarketplaceAddResponse; -use codex_app_server_protocol::MarketplaceInterface; use codex_app_server_protocol::MarketplaceRemoveParams; -use codex_app_server_protocol::MarketplaceRemoveResponse; use codex_app_server_protocol::McpResourceReadParams; use codex_app_server_protocol::McpResourceReadResponse; use codex_app_server_protocol::McpServerOauthLoginCompletedNotification; @@ -114,19 +109,11 @@ use codex_app_server_protocol::MockExperimentalMethodResponse; use codex_app_server_protocol::ModelListParams; use codex_app_server_protocol::ModelListResponse; use codex_app_server_protocol::PermissionProfile as ApiPermissionProfile; -use codex_app_server_protocol::PluginDetail; use codex_app_server_protocol::PluginInstallParams; -use codex_app_server_protocol::PluginInstallResponse; -use codex_app_server_protocol::PluginInterface; use codex_app_server_protocol::PluginListParams; use codex_app_server_protocol::PluginListResponse; -use codex_app_server_protocol::PluginMarketplaceEntry; use codex_app_server_protocol::PluginReadParams; -use codex_app_server_protocol::PluginReadResponse; -use codex_app_server_protocol::PluginSource; -use codex_app_server_protocol::PluginSummary; use codex_app_server_protocol::PluginUninstallParams; -use codex_app_server_protocol::PluginUninstallResponse; use codex_app_server_protocol::RequestId; use codex_app_server_protocol::ReviewDelivery as ApiReviewDelivery; use codex_app_server_protocol::ReviewStartParams; @@ -137,9 +124,7 @@ use codex_app_server_protocol::SendAddCreditsNudgeEmailParams; use codex_app_server_protocol::SendAddCreditsNudgeEmailResponse; use codex_app_server_protocol::ServerNotification; use codex_app_server_protocol::ServerRequestResolvedNotification; -use codex_app_server_protocol::SkillSummary; use codex_app_server_protocol::SkillsConfigWriteParams; -use codex_app_server_protocol::SkillsConfigWriteResponse; use codex_app_server_protocol::SkillsListParams; use codex_app_server_protocol::SkillsListResponse; use codex_app_server_protocol::SortDirection; @@ -156,8 +141,6 @@ use codex_app_server_protocol::ThreadCompactStartParams; use codex_app_server_protocol::ThreadCompactStartResponse; use codex_app_server_protocol::ThreadDecrementElicitationParams; use codex_app_server_protocol::ThreadDecrementElicitationResponse; -#[cfg(test)] -use codex_app_server_protocol::ThreadEpiphanyRetrieveResultKind; use codex_app_server_protocol::ThreadForkParams; use codex_app_server_protocol::ThreadForkResponse; use codex_app_server_protocol::ThreadIncrementElicitationParams; @@ -228,7 +211,6 @@ use codex_app_server_protocol::build_turns_from_rollout_items; use codex_arg0::Arg0DispatchPaths; use codex_backend_client::AddCreditsNudgeCreditType as BackendAddCreditsNudgeCreditType; use codex_backend_client::Client as BackendClient; -use codex_chatgpt::connectors; use codex_config::types::McpServerTransportConfig; use codex_core::CodexThread; use codex_core::CodexThreadTurnContextOverrides; @@ -243,8 +225,6 @@ use codex_core::clear_memory_roots_contents; use codex_core::config::Config; use codex_core::config::ConfigOverrides; use codex_core::config::NetworkProxyAuditMetadata; -use codex_core::config::edit::ConfigEdit; -use codex_core::config::edit::ConfigEditsBuilder; use codex_core::config_loader::CloudRequirementsLoadError; use codex_core::config_loader::CloudRequirementsLoadErrorCode; use codex_core::config_loader::project_trust_key; @@ -257,33 +237,12 @@ use codex_core::find_thread_name_by_id; use codex_core::find_thread_names_by_ids; use codex_core::find_thread_path_by_id_str; use codex_core::path_utils; -use codex_core::plugins::MarketplaceAddError; -use codex_core::plugins::MarketplaceRemoveError; -use codex_core::plugins::MarketplaceRemoveRequest as CoreMarketplaceRemoveRequest; -use codex_core::plugins::OPENAI_CURATED_MARKETPLACE_NAME; -use codex_core::plugins::PluginInstallError as CorePluginInstallError; -use codex_core::plugins::PluginInstallRequest; -use codex_core::plugins::PluginReadRequest; -use codex_core::plugins::PluginUninstallError as CorePluginUninstallError; -use codex_core::plugins::add_marketplace as add_marketplace_to_codex_home; -use codex_core::plugins::remove_marketplace; use codex_core::read_head_for_summary; use codex_core::read_session_meta_line; use codex_core::sandboxing::SandboxPermissions; use codex_core::windows_sandbox::WindowsSandboxLevelExt; use codex_core::windows_sandbox::WindowsSandboxSetupMode as CoreWindowsSandboxSetupMode; use codex_core::windows_sandbox::WindowsSandboxSetupRequest; -use codex_core_plugins::loader::load_plugin_apps; -use codex_core_plugins::loader::load_plugin_mcp_servers; -use codex_core_plugins::manifest::PluginManifestInterface; -use codex_core_plugins::marketplace::MarketplaceError; -use codex_core_plugins::marketplace::MarketplacePluginSource; -use codex_core_plugins::remote::RemoteMarketplace; -use codex_core_plugins::remote::RemotePluginCatalogError; -use codex_core_plugins::remote::RemotePluginDetail as RemoteCatalogPluginDetail; -use codex_core_plugins::remote::RemotePluginServiceConfig; -use codex_core_plugins::remote::RemotePluginSummary as RemoteCatalogPluginSummary; -use codex_exec_server::EnvironmentManager; use codex_exec_server::LOCAL_FS; use codex_features::FEATURES; use codex_features::Feature; @@ -404,13 +363,6 @@ fn epiphany_freshness_watcher_snapshot( } } -#[cfg(test)] -use codex_app_server_protocol::ServerRequest; - -mod apps_list_helpers; -mod plugin_app_helpers; -mod plugin_mcp_oauth; -mod plugins; mod token_usage_replay; use crate::filters::compute_source_filters; @@ -441,7 +393,6 @@ struct ThreadListFilters { // Duration before a browser ChatGPT login attempt is abandoned. const LOGIN_CHATGPT_TIMEOUT: Duration = Duration::from_secs(10 * 60); const LOGIN_ISSUER_OVERRIDE_ENV_VAR: &str = "CODEX_APP_SERVER_LOGIN_ISSUER"; -const APP_LIST_LOAD_TIMEOUT: Duration = Duration::from_secs(90); const THREAD_UNLOADING_DELAY: Duration = Duration::from_secs(30 * 60); enum ActiveLogin { @@ -479,11 +430,6 @@ enum CancelLoginError { NotFound, } -enum AppListLoadResult { - Accessible(Result, String>), - Directory(Result, String>), -} - enum ThreadShutdownResult { Complete, SubmitFailed, @@ -6264,30 +6210,16 @@ impl CodexMessageProcessor { self.outgoing.send_error(request_id, error).await; } - async fn send_marketplace_error( + async fn send_codex_product_surface_disabled( &self, request_id: ConnectionRequestId, - err: MarketplaceError, - action: &str, + method: &str, ) { - match err { - MarketplaceError::MarketplaceNotFound { .. } => { - self.send_invalid_request_error(request_id, err.to_string()) - .await; - } - MarketplaceError::Io { .. } => { - self.send_internal_error(request_id, format!("failed to {action}: {err}")) - .await; - } - MarketplaceError::InvalidMarketplaceFile { .. } - | MarketplaceError::PluginNotFound { .. } - | MarketplaceError::PluginNotAvailable { .. } - | MarketplaceError::PluginsDisabled - | MarketplaceError::InvalidPlugin(_) => { - self.send_invalid_request_error(request_id, err.to_string()) - .await; - } - } + self.send_invalid_request_error( + request_id, + format!("{method} is disabled in Epiphany's vestigial Codex organ"), + ) + .await; } async fn wait_for_thread_shutdown(thread: &Arc) -> ThreadShutdownResult { @@ -6441,490 +6373,81 @@ impl CodexMessageProcessor { self.finalize_thread_teardown(thread_id).await; } - async fn apps_list(&self, request_id: ConnectionRequestId, params: AppsListParams) { - let mut config = match self.load_latest_config(/*fallback_cwd*/ None).await { - Ok(config) => config, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - if let Some(thread_id) = params.thread_id.as_deref() { - let (_, thread) = match self.load_thread(thread_id).await { - Ok(result) => result, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; - - let _ = config - .features - .set_enabled(Feature::Apps, thread.enabled(Feature::Apps)); - } - - let auth = self.auth_manager.auth().await; - if !config - .features - .apps_enabled_for_auth(auth.as_ref().is_some_and(CodexAuth::is_chatgpt_auth)) - { - self.outgoing - .send_response( - request_id, - AppsListResponse { - data: Vec::new(), - next_cursor: None, - }, - ) - .await; - return; - } - - let request = request_id.clone(); - let outgoing = Arc::clone(&self.outgoing); - let environment_manager = self.thread_manager.environment_manager(); - tokio::spawn(async move { - Self::apps_list_task(outgoing, request, params, config, environment_manager).await; - }); - } - - async fn apps_list_task( - outgoing: Arc, - request_id: ConnectionRequestId, - params: AppsListParams, - config: Config, - environment_manager: Arc, - ) { - let AppsListParams { - cursor, - limit, - thread_id: _, - force_refetch, - } = params; - let start = match cursor { - Some(cursor) => match cursor.parse::() { - Ok(idx) => idx, - Err(_) => { - let error = JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("invalid cursor: {cursor}"), - data: None, - }; - outgoing.send_error(request_id, error).await; - return; - } - }, - None => 0, - }; - - let (mut accessible_connectors, mut all_connectors) = tokio::join!( - connectors::list_cached_accessible_connectors_from_mcp_tools(&config), - connectors::list_cached_all_connectors(&config) - ); - let cached_all_connectors = all_connectors.clone(); - - let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); - - let accessible_config = config.clone(); - let accessible_tx = tx.clone(); - tokio::spawn(async move { - let result = - connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager( - &accessible_config, - force_refetch, - &environment_manager, - ) - .await - .map(|status| status.connectors) - .map_err(|err| format!("failed to load accessible apps: {err}")); - let _ = accessible_tx.send(AppListLoadResult::Accessible(result)); - }); - - let all_config = config.clone(); - tokio::spawn(async move { - let result = connectors::list_all_connectors_with_options(&all_config, force_refetch) - .await - .map_err(|err| format!("failed to list apps: {err}")); - let _ = tx.send(AppListLoadResult::Directory(result)); - }); - - let app_list_deadline = tokio::time::Instant::now() + APP_LIST_LOAD_TIMEOUT; - let mut accessible_loaded = false; - let mut all_loaded = false; - let mut last_notified_apps = None; - - if accessible_connectors.is_some() || all_connectors.is_some() { - let merged = connectors::with_app_enabled_state( - apps_list_helpers::merge_loaded_apps( - all_connectors.as_deref(), - accessible_connectors.as_deref(), - ), - &config, - ); - if apps_list_helpers::should_send_app_list_updated_notification( - merged.as_slice(), - accessible_loaded, - all_loaded, - ) { - apps_list_helpers::send_app_list_updated_notification(&outgoing, merged.clone()) - .await; - last_notified_apps = Some(merged); - } - } - - loop { - let result = match tokio::time::timeout_at(app_list_deadline, rx.recv()).await { - Ok(Some(result)) => result, - Ok(None) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: "failed to load app lists".to_string(), - data: None, - }; - outgoing.send_error(request_id, error).await; - return; - } - Err(_) => { - let timeout_seconds = APP_LIST_LOAD_TIMEOUT.as_secs(); - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!( - "timed out waiting for app lists after {timeout_seconds} seconds" - ), - data: None, - }; - outgoing.send_error(request_id, error).await; - return; - } - }; - - match result { - AppListLoadResult::Accessible(Ok(connectors)) => { - accessible_connectors = Some(connectors); - accessible_loaded = true; - } - AppListLoadResult::Accessible(Err(err)) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: err, - data: None, - }; - outgoing.send_error(request_id, error).await; - return; - } - AppListLoadResult::Directory(Ok(connectors)) => { - all_connectors = Some(connectors); - all_loaded = true; - } - AppListLoadResult::Directory(Err(err)) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: err, - data: None, - }; - outgoing.send_error(request_id, error).await; - return; - } - } - - let showing_interim_force_refetch = force_refetch && !(accessible_loaded && all_loaded); - let all_connectors_for_update = - if showing_interim_force_refetch && cached_all_connectors.is_some() { - cached_all_connectors.as_deref() - } else { - all_connectors.as_deref() - }; - let accessible_connectors_for_update = - if showing_interim_force_refetch && !accessible_loaded { - None - } else { - accessible_connectors.as_deref() - }; - let merged = connectors::with_app_enabled_state( - apps_list_helpers::merge_loaded_apps( - all_connectors_for_update, - accessible_connectors_for_update, - ), - &config, - ); - if apps_list_helpers::should_send_app_list_updated_notification( - merged.as_slice(), - accessible_loaded, - all_loaded, - ) && last_notified_apps.as_ref() != Some(&merged) - { - apps_list_helpers::send_app_list_updated_notification(&outgoing, merged.clone()) - .await; - last_notified_apps = Some(merged.clone()); - } - - if accessible_loaded && all_loaded { - match apps_list_helpers::paginate_apps(merged.as_slice(), start, limit) { - Ok(response) => { - outgoing.send_response(request_id, response).await; - return; - } - Err(error) => { - outgoing.send_error(request_id, error).await; - return; - } - } - } - } - } - - async fn skills_list(&self, request_id: ConnectionRequestId, params: SkillsListParams) { - let SkillsListParams { - cwds, - force_reload, - per_cwd_extra_user_roots, - } = params; - let cwds = if cwds.is_empty() { - vec![self.config.cwd.to_path_buf()] - } else { - cwds - }; - let cwd_set: HashSet = cwds.iter().cloned().collect(); - - let mut extra_roots_by_cwd: HashMap> = HashMap::new(); - for entry in per_cwd_extra_user_roots.unwrap_or_default() { - if !cwd_set.contains(&entry.cwd) { - warn!( - cwd = %entry.cwd.display(), - "ignoring per-cwd extra roots for cwd not present in skills/list cwds" - ); - continue; - } - - let mut valid_extra_roots = Vec::new(); - for root in entry.extra_user_roots { - let Ok(root) = AbsolutePathBuf::from_absolute_path_checked(root.as_path()) else { - self.send_invalid_request_error( - request_id, - format!( - "skills/list perCwdExtraUserRoots extraUserRoots paths must be absolute: {}", - root.display() - ), - ) - .await; - return; - }; - valid_extra_roots.push(root); - } - extra_roots_by_cwd - .entry(entry.cwd) - .or_default() - .extend(valid_extra_roots); - } - - let config = match self.load_latest_config(/*fallback_cwd*/ None).await { - Ok(config) => config, - Err(error) => { - self.outgoing.send_error(request_id, error).await; - return; - } - }; - let skills_manager = self.thread_manager.skills_manager(); - let plugins_manager = self.thread_manager.plugins_manager(); - let fs = self - .thread_manager - .environment_manager() - .default_environment() - .map(|environment| environment.get_filesystem()); - let mut data = Vec::new(); - for cwd in cwds { - let extra_roots = extra_roots_by_cwd - .get(&cwd) - .map_or(&[][..], std::vec::Vec::as_slice); - let cwd_abs = match AbsolutePathBuf::relative_to_current_dir(cwd.as_path()) { - Ok(path) => path, - Err(err) => { - let error_path = cwd.clone(); - data.push(codex_app_server_protocol::SkillsListEntry { - cwd, - skills: Vec::new(), - errors: vec![codex_app_server_protocol::SkillErrorInfo { - path: error_path, - message: err.to_string(), - }], - }); - continue; - } - }; - let config_layer_stack = match self - .config_manager - .load_config_layers_for_cwd(cwd_abs.clone()) - .await - { - Ok(config_layer_stack) => config_layer_stack, - Err(err) => { - let error_path = cwd.clone(); - data.push(codex_app_server_protocol::SkillsListEntry { - cwd, - skills: Vec::new(), - errors: vec![codex_app_server_protocol::SkillErrorInfo { - path: error_path, - message: err.to_string(), - }], - }); - continue; - } - }; - let effective_skill_roots = plugins_manager - .effective_skill_roots_for_layer_stack( - &config_layer_stack, - config.features.enabled(Feature::Plugins), - ) - .await; - let skills_input = codex_core::skills::SkillsLoadInput::new( - cwd_abs.clone(), - effective_skill_roots, - config_layer_stack, - config.bundled_skills_enabled(), - ); - let outcome = skills_manager - .skills_for_cwd_with_extra_user_roots( - &skills_input, - force_reload, - extra_roots, - fs.clone(), - ) - .await; - let errors = errors_to_info(&outcome.errors); - let skills = skills_to_info(&outcome.skills, &outcome.disabled_paths); - data.push(codex_app_server_protocol::SkillsListEntry { - cwd, - skills, - errors, - }); - } + async fn apps_list(&self, request_id: ConnectionRequestId, _params: AppsListParams) { self.outgoing - .send_response(request_id, SkillsListResponse { data }) + .send_response( + request_id, + AppsListResponse { + data: Vec::new(), + next_cursor: None, + }, + ) .await; } + + async fn skills_list(&self, request_id: ConnectionRequestId, _params: SkillsListParams) { + self.outgoing + .send_response(request_id, SkillsListResponse { data: Vec::new() }) + .await; + } + async fn marketplace_remove( &self, request_id: ConnectionRequestId, - params: MarketplaceRemoveParams, + _params: MarketplaceRemoveParams, ) { - let result = remove_marketplace( - self.config.codex_home.to_path_buf(), - CoreMarketplaceRemoveRequest { - marketplace_name: params.marketplace_name, - }, - ) - .await; - - match result { - Ok(outcome) => { - self.outgoing - .send_response( - request_id, - MarketplaceRemoveResponse { - marketplace_name: outcome.marketplace_name, - installed_root: outcome.removed_installed_root, - }, - ) - .await; - } - Err(MarketplaceRemoveError::InvalidRequest(message)) => { - self.send_invalid_request_error(request_id, message).await; - } - Err(MarketplaceRemoveError::Internal(message)) => { - self.send_internal_error(request_id, message).await; - } - } + self.send_codex_product_surface_disabled(request_id, "marketplace/remove") + .await; } - async fn marketplace_add(&self, request_id: ConnectionRequestId, params: MarketplaceAddParams) { - let result = add_marketplace_to_codex_home( - self.config.codex_home.to_path_buf(), - codex_core::plugins::MarketplaceAddRequest { - source: params.source, - ref_name: params.ref_name, - sparse_paths: params.sparse_paths.unwrap_or_default(), - }, - ) - .await; - match result { - Ok(outcome) => { - self.outgoing - .send_response( - request_id, - MarketplaceAddResponse { - marketplace_name: outcome.marketplace_name, - installed_root: outcome.installed_root, - already_added: outcome.already_added, - }, - ) - .await; - } - Err(MarketplaceAddError::InvalidRequest(message)) => { - self.send_invalid_request_error(request_id, message).await; - } - Err(MarketplaceAddError::Internal(message)) => { - self.send_internal_error(request_id, message).await; - } - } + async fn marketplace_add( + &self, + request_id: ConnectionRequestId, + _params: MarketplaceAddParams, + ) { + self.send_codex_product_surface_disabled(request_id, "marketplace/add") + .await; + } + + async fn plugin_list(&self, request_id: ConnectionRequestId, _params: PluginListParams) { + self.outgoing + .send_response( + request_id, + PluginListResponse { + marketplaces: Vec::new(), + marketplace_load_errors: Vec::new(), + featured_plugin_ids: Vec::new(), + }, + ) + .await; + } + + async fn plugin_read(&self, request_id: ConnectionRequestId, _params: PluginReadParams) { + self.send_codex_product_surface_disabled(request_id, "plugin/read") + .await; + } + + async fn plugin_install(&self, request_id: ConnectionRequestId, _params: PluginInstallParams) { + self.send_codex_product_surface_disabled(request_id, "plugin/install") + .await; + } + + async fn plugin_uninstall( + &self, + request_id: ConnectionRequestId, + _params: PluginUninstallParams, + ) { + self.send_codex_product_surface_disabled(request_id, "plugin/uninstall") + .await; } async fn skills_config_write( &self, request_id: ConnectionRequestId, - params: SkillsConfigWriteParams, + _params: SkillsConfigWriteParams, ) { - let SkillsConfigWriteParams { - path, - name, - enabled, - } = params; - let edit = match (path, name) { - (Some(path), None) => ConfigEdit::SetSkillConfig { - path: path.into_path_buf(), - enabled, - }, - (None, Some(name)) if !name.trim().is_empty() => { - ConfigEdit::SetSkillConfigByName { name, enabled } - } - _ => { - let error = JSONRPCErrorError { - code: INVALID_PARAMS_ERROR_CODE, - message: "skills/config/write requires exactly one of path or name".to_string(), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - return; - } - }; - let edits = vec![edit]; - let result = ConfigEditsBuilder::new(&self.config.codex_home) - .with_edits(edits) - .apply() + self.send_codex_product_surface_disabled(request_id, "skills/config/write") .await; - - match result { - Ok(()) => { - self.thread_manager.plugins_manager().clear_cache(); - self.thread_manager.skills_manager().clear_cache(); - self.outgoing - .send_response( - request_id, - SkillsConfigWriteResponse { - effective_enabled: enabled, - }, - ) - .await; - } - Err(err) => { - let error = JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("failed to update skill settings: {err}"), - data: None, - }; - self.outgoing.send_error(request_id, error).await; - } - } } async fn turn_start( @@ -9067,129 +8590,6 @@ fn has_model_resume_override( .is_some_and(|overrides| overrides.contains_key("model_reasoning_effort")) } -fn skills_to_info( - skills: &[codex_core::skills::SkillMetadata], - disabled_paths: &std::collections::HashSet, -) -> Vec { - skills - .iter() - .map(|skill| { - let enabled = !disabled_paths.contains(&skill.path_to_skills_md); - codex_app_server_protocol::SkillMetadata { - name: skill.name.clone(), - description: skill.description.clone(), - short_description: skill.short_description.clone(), - interface: skill.interface.clone().map(|interface| { - codex_app_server_protocol::SkillInterface { - display_name: interface.display_name, - short_description: interface.short_description, - icon_small: interface.icon_small, - icon_large: interface.icon_large, - brand_color: interface.brand_color, - default_prompt: interface.default_prompt, - } - }), - dependencies: skill.dependencies.clone().map(|dependencies| { - codex_app_server_protocol::SkillDependencies { - tools: dependencies - .tools - .into_iter() - .map(|tool| codex_app_server_protocol::SkillToolDependency { - r#type: tool.r#type, - value: tool.value, - description: tool.description, - transport: tool.transport, - command: tool.command, - url: tool.url, - }) - .collect(), - } - }), - path: skill.path_to_skills_md.clone(), - scope: skill.scope.into(), - enabled, - } - }) - .collect() -} - -fn plugin_skills_to_info( - skills: &[codex_core::skills::SkillMetadata], - disabled_skill_paths: &std::collections::HashSet, -) -> Vec { - skills - .iter() - .map(|skill| SkillSummary { - name: skill.name.clone(), - description: skill.description.clone(), - short_description: skill.short_description.clone(), - interface: skill.interface.clone().map(|interface| { - codex_app_server_protocol::SkillInterface { - display_name: interface.display_name, - short_description: interface.short_description, - icon_small: interface.icon_small, - icon_large: interface.icon_large, - brand_color: interface.brand_color, - default_prompt: interface.default_prompt, - } - }), - path: Some(skill.path_to_skills_md.clone()), - enabled: !disabled_skill_paths.contains(&skill.path_to_skills_md), - }) - .collect() -} - -fn local_plugin_interface_to_info(interface: PluginManifestInterface) -> PluginInterface { - PluginInterface { - display_name: interface.display_name, - short_description: interface.short_description, - long_description: interface.long_description, - developer_name: interface.developer_name, - category: interface.category, - capabilities: interface.capabilities, - website_url: interface.website_url, - privacy_policy_url: interface.privacy_policy_url, - terms_of_service_url: interface.terms_of_service_url, - default_prompt: interface.default_prompt, - brand_color: interface.brand_color, - composer_icon: interface.composer_icon, - composer_icon_url: None, - logo: interface.logo, - logo_url: None, - screenshots: interface.screenshots, - screenshot_urls: Vec::new(), - } -} - -fn marketplace_plugin_source_to_info(source: MarketplacePluginSource) -> PluginSource { - match source { - MarketplacePluginSource::Local { path } => PluginSource::Local { path }, - MarketplacePluginSource::Git { - url, - path, - ref_name, - sha, - } => PluginSource::Git { - url, - path, - ref_name, - sha, - }, - } -} - -fn errors_to_info( - errors: &[codex_core::skills::SkillError], -) -> Vec { - errors - .iter() - .map(|err| codex_app_server_protocol::SkillErrorInfo { - path: err.path.to_path_buf(), - message: err.message.clone(), - }) - .collect() -} - fn cloud_requirements_load_error(err: &std::io::Error) -> Option<&CloudRequirementsLoadError> { let mut current: Option<&(dyn std::error::Error + 'static)> = err .get_ref() @@ -10235,6 +9635,3 @@ fn normalize_thread_turns_status( } } } - -#[cfg(test)] -mod processor_tests; diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/apps_list_helpers.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/apps_list_helpers.rs deleted file mode 100644 index b0a6df4a..00000000 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor/apps_list_helpers.rs +++ /dev/null @@ -1,66 +0,0 @@ -use std::sync::Arc; - -use codex_app_server_protocol::AppInfo; -use codex_app_server_protocol::AppListUpdatedNotification; -use codex_app_server_protocol::AppsListResponse; -use codex_app_server_protocol::JSONRPCErrorError; -use codex_app_server_protocol::ServerNotification; -use codex_chatgpt::connectors; - -use crate::error_code::INVALID_REQUEST_ERROR_CODE; -use crate::outgoing_message::OutgoingMessageSender; - -pub(super) fn merge_loaded_apps( - all_connectors: Option<&[AppInfo]>, - accessible_connectors: Option<&[AppInfo]>, -) -> Vec { - let all_connectors_loaded = all_connectors.is_some(); - let all = all_connectors.map_or_else(Vec::new, <[AppInfo]>::to_vec); - let accessible = accessible_connectors.map_or_else(Vec::new, <[AppInfo]>::to_vec); - connectors::merge_connectors_with_accessible(all, accessible, all_connectors_loaded) -} - -pub(super) fn should_send_app_list_updated_notification( - connectors: &[AppInfo], - accessible_loaded: bool, - all_loaded: bool, -) -> bool { - connectors.iter().any(|connector| connector.is_accessible) || (accessible_loaded && all_loaded) -} - -pub(super) fn paginate_apps( - connectors: &[AppInfo], - start: usize, - limit: Option, -) -> Result { - let total = connectors.len(); - if start > total { - return Err(JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("cursor {start} exceeds total apps {total}"), - data: None, - }); - } - - let effective_limit = limit.unwrap_or(total as u32).max(1) as usize; - let end = start.saturating_add(effective_limit).min(total); - let data = connectors[start..end].to_vec(); - let next_cursor = if end < total { - Some(end.to_string()) - } else { - None - }; - - Ok(AppsListResponse { data, next_cursor }) -} - -pub(super) async fn send_app_list_updated_notification( - outgoing: &Arc, - data: Vec, -) { - outgoing - .send_server_notification(ServerNotification::AppListUpdated( - AppListUpdatedNotification { data }, - )) - .await; -} diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/plugin_app_helpers.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/plugin_app_helpers.rs deleted file mode 100644 index ad587560..00000000 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor/plugin_app_helpers.rs +++ /dev/null @@ -1,149 +0,0 @@ -use std::collections::HashSet; - -use codex_app_server_protocol::AppInfo; -use codex_app_server_protocol::AppSummary; -use codex_chatgpt::connectors; -use codex_core::config::Config; -use codex_core::plugins::AppConnectorId; -use codex_exec_server::EnvironmentManager; -use tracing::warn; - -pub(super) async fn load_plugin_app_summaries( - config: &Config, - plugin_apps: &[AppConnectorId], - environment_manager: &EnvironmentManager, -) -> Vec { - if plugin_apps.is_empty() { - return Vec::new(); - } - - let connectors = - match connectors::list_all_connectors_with_options(config, /*force_refetch*/ false).await { - Ok(connectors) => connectors, - Err(err) => { - warn!("failed to load app metadata for plugin/read: {err:#}"); - connectors::list_cached_all_connectors(config) - .await - .unwrap_or_default() - } - }; - - let plugin_connectors = connectors::connectors_for_plugin_apps(connectors, plugin_apps); - - let accessible_connectors = - match connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager( - config, - /*force_refetch*/ false, - environment_manager, - ) - .await - { - Ok(status) if status.codex_apps_ready => status.connectors, - Ok(_) => { - return plugin_connectors - .into_iter() - .map(AppSummary::from) - .collect(); - } - Err(err) => { - warn!("failed to load app auth state for plugin/read: {err:#}"); - return plugin_connectors - .into_iter() - .map(AppSummary::from) - .collect(); - } - }; - - let accessible_ids = accessible_connectors - .iter() - .map(|connector| connector.id.as_str()) - .collect::>(); - - plugin_connectors - .into_iter() - .map(|connector| { - let needs_auth = !accessible_ids.contains(connector.id.as_str()); - AppSummary { - id: connector.id, - name: connector.name, - description: connector.description, - install_url: connector.install_url, - needs_auth, - } - }) - .collect() -} - -pub(super) fn plugin_apps_needing_auth( - all_connectors: &[AppInfo], - accessible_connectors: &[AppInfo], - plugin_apps: &[AppConnectorId], - codex_apps_ready: bool, -) -> Vec { - if !codex_apps_ready { - return Vec::new(); - } - - let accessible_ids = accessible_connectors - .iter() - .map(|connector| connector.id.as_str()) - .collect::>(); - let plugin_app_ids = plugin_apps - .iter() - .map(|connector_id| connector_id.0.as_str()) - .collect::>(); - - all_connectors - .iter() - .filter(|connector| { - plugin_app_ids.contains(connector.id.as_str()) - && !accessible_ids.contains(connector.id.as_str()) - }) - .cloned() - .map(|connector| AppSummary { - id: connector.id, - name: connector.name, - description: connector.description, - install_url: connector.install_url, - needs_auth: true, - }) - .collect() -} - -#[cfg(test)] -mod tests { - use codex_app_server_protocol::AppInfo; - use codex_core::plugins::AppConnectorId; - use pretty_assertions::assert_eq; - - use super::plugin_apps_needing_auth; - - #[test] - fn plugin_apps_needing_auth_returns_empty_when_codex_apps_is_not_ready() { - let all_connectors = vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - - assert_eq!( - plugin_apps_needing_auth( - &all_connectors, - &[], - &[AppConnectorId("alpha".to_string())], - /*codex_apps_ready*/ false, - ), - Vec::new() - ); - } -} diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/plugin_mcp_oauth.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/plugin_mcp_oauth.rs deleted file mode 100644 index b027aef4..00000000 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor/plugin_mcp_oauth.rs +++ /dev/null @@ -1,95 +0,0 @@ -use std::collections::HashMap; -use std::sync::Arc; - -use codex_app_server_protocol::McpServerOauthLoginCompletedNotification; -use codex_app_server_protocol::ServerNotification; -use codex_config::types::McpServerConfig; -use codex_core::config::Config; -use codex_mcp::McpOAuthLoginSupport; -use codex_mcp::oauth_login_support; -use codex_mcp::resolve_oauth_scopes; -use codex_mcp::should_retry_without_scopes; -use codex_rmcp_client::perform_oauth_login_silent; -use tracing::warn; - -use super::CodexMessageProcessor; - -impl CodexMessageProcessor { - pub(super) async fn start_plugin_mcp_oauth_logins( - &self, - config: &Config, - plugin_mcp_servers: HashMap, - ) { - for (name, server) in plugin_mcp_servers { - let oauth_config = match oauth_login_support(&server.transport).await { - McpOAuthLoginSupport::Supported(config) => config, - McpOAuthLoginSupport::Unsupported => continue, - McpOAuthLoginSupport::Unknown(err) => { - warn!( - "MCP server may or may not require login for plugin install {name}: {err}" - ); - continue; - } - }; - - let resolved_scopes = resolve_oauth_scopes( - /*explicit_scopes*/ None, - server.scopes.clone(), - oauth_config.discovered_scopes.clone(), - ); - - let store_mode = config.mcp_oauth_credentials_store_mode; - let callback_port = config.mcp_oauth_callback_port; - let callback_url = config.mcp_oauth_callback_url.clone(); - let outgoing = Arc::clone(&self.outgoing); - let notification_name = name.clone(); - - tokio::spawn(async move { - let first_attempt = perform_oauth_login_silent( - &name, - &oauth_config.url, - store_mode, - oauth_config.http_headers.clone(), - oauth_config.env_http_headers.clone(), - &resolved_scopes.scopes, - server.oauth_resource.as_deref(), - callback_port, - callback_url.as_deref(), - ) - .await; - - let final_result = match first_attempt { - Err(err) if should_retry_without_scopes(&resolved_scopes, &err) => { - perform_oauth_login_silent( - &name, - &oauth_config.url, - store_mode, - oauth_config.http_headers, - oauth_config.env_http_headers, - &[], - server.oauth_resource.as_deref(), - callback_port, - callback_url.as_deref(), - ) - .await - } - result => result, - }; - - let (success, error) = match final_result { - Ok(()) => (true, None), - Err(err) => (false, Some(err.to_string())), - }; - - let notification = ServerNotification::McpServerOauthLoginCompleted( - McpServerOauthLoginCompletedNotification { - name: notification_name, - success, - error, - }, - ); - outgoing.send_server_notification(notification).await; - }); - } - } -} diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/plugins.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/plugins.rs deleted file mode 100644 index e96ef4af..00000000 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor/plugins.rs +++ /dev/null @@ -1,692 +0,0 @@ -use super::*; -use codex_plugin::validate_plugin_segment; - -impl CodexMessageProcessor { - pub(super) async fn plugin_list( - &self, - request_id: ConnectionRequestId, - params: PluginListParams, - ) { - let plugins_manager = self.thread_manager.plugins_manager(); - let PluginListParams { cwds } = params; - let roots = cwds.unwrap_or_default(); - - let config = match self.load_latest_config(/*fallback_cwd*/ None).await { - Ok(config) => config, - Err(err) => { - self.outgoing.send_error(request_id, err).await; - return; - } - }; - if !config.features.enabled(Feature::Plugins) { - self.outgoing - .send_response( - request_id, - PluginListResponse { - marketplaces: Vec::new(), - marketplace_load_errors: Vec::new(), - featured_plugin_ids: Vec::new(), - }, - ) - .await; - return; - } - plugins_manager.maybe_start_non_curated_plugin_cache_refresh(&roots); - let auth = self.auth_manager.auth().await; - - let config_for_marketplace_listing = config.clone(); - let plugins_manager_for_marketplace_listing = plugins_manager.clone(); - let (mut data, marketplace_load_errors) = match tokio::task::spawn_blocking(move || { - let outcome = plugins_manager_for_marketplace_listing - .list_marketplaces_for_config(&config_for_marketplace_listing, &roots)?; - Ok::< - ( - Vec, - Vec, - ), - MarketplaceError, - >(( - outcome - .marketplaces - .into_iter() - .map(|marketplace| PluginMarketplaceEntry { - name: marketplace.name, - path: Some(marketplace.path), - interface: marketplace.interface.map(|interface| MarketplaceInterface { - display_name: interface.display_name, - }), - plugins: marketplace - .plugins - .into_iter() - .map(|plugin| PluginSummary { - id: plugin.id, - installed: plugin.installed, - enabled: plugin.enabled, - name: plugin.name, - source: marketplace_plugin_source_to_info(plugin.source), - install_policy: plugin.policy.installation.into(), - auth_policy: plugin.policy.authentication.into(), - interface: plugin.interface.map(local_plugin_interface_to_info), - }) - .collect(), - }) - .collect(), - outcome - .errors - .into_iter() - .map(|err| codex_app_server_protocol::MarketplaceLoadErrorInfo { - marketplace_path: err.path, - message: err.message, - }) - .collect(), - )) - }) - .await - { - Ok(Ok(outcome)) => outcome, - Ok(Err(err)) => { - self.send_marketplace_error(request_id, err, "list marketplace plugins") - .await; - return; - } - Err(err) => { - self.send_internal_error( - request_id, - format!("failed to list marketplace plugins: {err}"), - ) - .await; - return; - } - }; - - if config.features.enabled(Feature::RemotePlugin) { - let remote_plugin_service_config = RemotePluginServiceConfig { - chatgpt_base_url: config.chatgpt_base_url.clone(), - }; - match codex_core_plugins::remote::fetch_remote_marketplaces( - &remote_plugin_service_config, - auth.as_ref(), - ) - .await - { - Ok(remote_marketplaces) => { - for remote_marketplace in remote_marketplaces - .into_iter() - .map(remote_marketplace_to_info) - { - if let Some(existing) = data - .iter_mut() - .find(|marketplace| marketplace.name == remote_marketplace.name) - { - *existing = remote_marketplace; - } else { - data.push(remote_marketplace); - } - } - } - Err( - RemotePluginCatalogError::AuthRequired - | RemotePluginCatalogError::UnsupportedAuthMode, - ) => {} - Err(err) => { - warn!( - error = %err, - "plugin/list remote plugin catalog fetch failed; returning local marketplaces only" - ); - } - } - } - - let featured_plugin_ids = if data - .iter() - .any(|marketplace| marketplace.name == OPENAI_CURATED_MARKETPLACE_NAME) - { - match plugins_manager - .featured_plugin_ids_for_config(&config, auth.as_ref()) - .await - { - Ok(featured_plugin_ids) => featured_plugin_ids, - Err(err) => { - warn!( - error = %err, - "plugin/list featured plugin fetch failed; returning empty featured ids" - ); - Vec::new() - } - } - } else { - Vec::new() - }; - - self.outgoing - .send_response( - request_id, - PluginListResponse { - marketplaces: data, - marketplace_load_errors, - featured_plugin_ids, - }, - ) - .await; - } - - pub(super) async fn plugin_read( - &self, - request_id: ConnectionRequestId, - params: PluginReadParams, - ) { - let plugins_manager = self.thread_manager.plugins_manager(); - let PluginReadParams { - marketplace_path, - remote_marketplace_name, - plugin_name, - } = params; - let read_source = match (marketplace_path, remote_marketplace_name) { - (Some(marketplace_path), None) => Ok(marketplace_path), - (None, Some(remote_marketplace_name)) => Err(remote_marketplace_name), - (Some(_), Some(_)) | (None, None) => { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "plugin/read requires exactly one of marketplacePath or remoteMarketplaceName".to_string(), - data: None, - }, - ) - .await; - return; - } - }; - let config_cwd = read_source.as_ref().ok().and_then(|marketplace_path| { - marketplace_path.as_path().parent().map(Path::to_path_buf) - }); - - let config = match self.load_latest_config(config_cwd).await { - Ok(config) => config, - Err(err) => { - self.outgoing.send_error(request_id, err).await; - return; - } - }; - - let plugin = match read_source { - Ok(marketplace_path) => { - let request = PluginReadRequest { - plugin_name, - marketplace_path, - }; - let outcome = match plugins_manager - .read_plugin_for_config(&config, &request) - .await - { - Ok(outcome) => outcome, - Err(err) => { - self.send_marketplace_error(request_id, err, "read plugin details") - .await; - return; - } - }; - let environment_manager = self.thread_manager.environment_manager(); - let app_summaries = plugin_app_helpers::load_plugin_app_summaries( - &config, - &outcome.plugin.apps, - &environment_manager, - ) - .await; - let visible_skills = outcome - .plugin - .skills - .iter() - .filter(|skill| { - skill.matches_product_restriction_for_product( - self.thread_manager.session_source().restriction_product(), - ) - }) - .cloned() - .collect::>(); - PluginDetail { - marketplace_name: outcome.marketplace_name, - marketplace_path: outcome.marketplace_path, - summary: PluginSummary { - id: outcome.plugin.id, - name: outcome.plugin.name, - source: marketplace_plugin_source_to_info(outcome.plugin.source), - installed: outcome.plugin.installed, - enabled: outcome.plugin.enabled, - install_policy: outcome.plugin.policy.installation.into(), - auth_policy: outcome.plugin.policy.authentication.into(), - interface: outcome.plugin.interface.map(local_plugin_interface_to_info), - }, - description: outcome.plugin.description, - skills: plugin_skills_to_info( - &visible_skills, - &outcome.plugin.disabled_skill_paths, - ), - apps: app_summaries, - mcp_servers: outcome.plugin.mcp_server_names, - } - } - Err(remote_marketplace_name) => { - if !config.features.enabled(Feature::Plugins) - || !config.features.enabled(Feature::RemotePlugin) - { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!( - "remote plugin read is not enabled for marketplace {remote_marketplace_name}" - ), - data: None, - }, - ) - .await; - return; - } - let auth = self.auth_manager.auth().await; - let remote_plugin_service_config = RemotePluginServiceConfig { - chatgpt_base_url: config.chatgpt_base_url.clone(), - }; - if let Err(err) = validate_plugin_segment(&plugin_name, "plugin name") { - self.send_invalid_request_error( - request_id, - format!("invalid remote plugin id: {err}"), - ) - .await; - return; - } - let remote_plugin_id = format!("{plugin_name}@{remote_marketplace_name}"); - let remote_detail = match codex_core_plugins::remote::fetch_remote_plugin_detail( - &remote_plugin_service_config, - auth.as_ref(), - &remote_marketplace_name, - &remote_plugin_id, - ) - .await - { - Ok(remote_detail) => remote_detail, - Err(err) => { - self.outgoing - .send_error( - request_id, - remote_plugin_catalog_error_to_jsonrpc( - err, - "read remote plugin details", - ), - ) - .await; - return; - } - }; - let plugin_apps = remote_detail - .app_ids - .iter() - .cloned() - .map(codex_core::plugins::AppConnectorId) - .collect::>(); - let environment_manager = self.thread_manager.environment_manager(); - let app_summaries = plugin_app_helpers::load_plugin_app_summaries( - &config, - &plugin_apps, - &environment_manager, - ) - .await; - remote_plugin_detail_to_info(remote_detail, app_summaries) - } - }; - - self.outgoing - .send_response(request_id, PluginReadResponse { plugin }) - .await; - } - - pub(super) async fn plugin_install( - &self, - request_id: ConnectionRequestId, - params: PluginInstallParams, - ) { - let PluginInstallParams { - marketplace_path, - remote_marketplace_name, - plugin_name, - } = params; - let marketplace_path = match (marketplace_path, remote_marketplace_name) { - (Some(marketplace_path), None) => marketplace_path, - (None, Some(remote_marketplace_name)) => { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!( - "remote plugin install is not supported yet for marketplace {remote_marketplace_name}" - ), - data: None, - }, - ) - .await; - return; - } - (Some(_), Some(_)) | (None, None) => { - self.outgoing - .send_error( - request_id, - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: "plugin/install requires exactly one of marketplacePath or remoteMarketplaceName".to_string(), - data: None, - }, - ) - .await; - return; - } - }; - let config_cwd = marketplace_path.as_path().parent().map(Path::to_path_buf); - - let plugins_manager = self.thread_manager.plugins_manager(); - let request = PluginInstallRequest { - plugin_name, - marketplace_path, - }; - - let install_result = plugins_manager.install_plugin(request).await; - - match install_result { - Ok(result) => { - let config = match self.load_latest_config(config_cwd).await { - Ok(config) => config, - Err(err) => { - warn!( - "failed to reload config after plugin install, using current config: {err:?}" - ); - self.config.as_ref().clone() - } - }; - - self.clear_plugin_related_caches(); - - let plugin_mcp_servers = - load_plugin_mcp_servers(result.installed_path.as_path()).await; - - if !plugin_mcp_servers.is_empty() { - if let Err(err) = self.queue_mcp_server_refresh_for_config(&config).await { - warn!( - plugin = result.plugin_id.as_key(), - "failed to queue MCP refresh after plugin install: {err:?}" - ); - } - self.start_plugin_mcp_oauth_logins(&config, plugin_mcp_servers) - .await; - } - - let plugin_apps = load_plugin_apps(result.installed_path.as_path()).await; - let auth = self.auth_manager.auth().await; - let apps_needing_auth = if plugin_apps.is_empty() - || !config.features.apps_enabled_for_auth( - auth.as_ref().is_some_and(CodexAuth::is_chatgpt_auth), - ) { - Vec::new() - } else { - let environment_manager = self.thread_manager.environment_manager(); - let (all_connectors_result, accessible_connectors_result) = tokio::join!( - connectors::list_all_connectors_with_options(&config, /*force_refetch*/ true), - connectors::list_accessible_connectors_from_mcp_tools_with_environment_manager( - &config, /*force_refetch*/ true, &environment_manager - ), - ); - - let all_connectors = match all_connectors_result { - Ok(connectors) => connectors, - Err(err) => { - warn!( - plugin = result.plugin_id.as_key(), - "failed to load app metadata after plugin install: {err:#}" - ); - connectors::list_cached_all_connectors(&config) - .await - .unwrap_or_default() - } - }; - let all_connectors = - connectors::connectors_for_plugin_apps(all_connectors, &plugin_apps); - let (accessible_connectors, codex_apps_ready) = - match accessible_connectors_result { - Ok(status) => (status.connectors, status.codex_apps_ready), - Err(err) => { - warn!( - plugin = result.plugin_id.as_key(), - "failed to load accessible apps after plugin install: {err:#}" - ); - ( - connectors::list_cached_accessible_connectors_from_mcp_tools( - &config, - ) - .await - .unwrap_or_default(), - false, - ) - } - }; - if !codex_apps_ready { - warn!( - plugin = result.plugin_id.as_key(), - "codex_apps MCP not ready after plugin install; skipping appsNeedingAuth check" - ); - } - - plugin_app_helpers::plugin_apps_needing_auth( - &all_connectors, - &accessible_connectors, - &plugin_apps, - codex_apps_ready, - ) - }; - - self.outgoing - .send_response( - request_id, - PluginInstallResponse { - auth_policy: result.auth_policy.into(), - apps_needing_auth, - }, - ) - .await; - } - Err(err) => { - if err.is_invalid_request() { - self.send_invalid_request_error(request_id, err.to_string()) - .await; - return; - } - - match err { - CorePluginInstallError::Marketplace(err) => { - self.send_marketplace_error(request_id, err, "install plugin") - .await; - } - CorePluginInstallError::Config(err) => { - self.send_internal_error( - request_id, - format!("failed to persist installed plugin config: {err}"), - ) - .await; - } - CorePluginInstallError::Remote(err) => { - self.send_internal_error( - request_id, - format!("failed to enable remote plugin: {err}"), - ) - .await; - } - CorePluginInstallError::Join(err) => { - self.send_internal_error( - request_id, - format!("failed to install plugin: {err}"), - ) - .await; - } - CorePluginInstallError::Store(err) => { - self.send_internal_error( - request_id, - format!("failed to install plugin: {err}"), - ) - .await; - } - } - } - } - } - - pub(super) async fn plugin_uninstall( - &self, - request_id: ConnectionRequestId, - params: PluginUninstallParams, - ) { - let PluginUninstallParams { plugin_id } = params; - let plugins_manager = self.thread_manager.plugins_manager(); - - let uninstall_result = plugins_manager.uninstall_plugin(plugin_id).await; - - match uninstall_result { - Ok(()) => { - self.clear_plugin_related_caches(); - self.outgoing - .send_response(request_id, PluginUninstallResponse {}) - .await; - } - Err(err) => { - if err.is_invalid_request() { - self.send_invalid_request_error(request_id, err.to_string()) - .await; - return; - } - - match err { - CorePluginUninstallError::Config(err) => { - self.send_internal_error( - request_id, - format!("failed to clear plugin config: {err}"), - ) - .await; - } - CorePluginUninstallError::Remote(err) => { - self.send_internal_error( - request_id, - format!("failed to uninstall remote plugin: {err}"), - ) - .await; - } - CorePluginUninstallError::Join(err) => { - self.send_internal_error( - request_id, - format!("failed to uninstall plugin: {err}"), - ) - .await; - } - CorePluginUninstallError::Store(err) => { - self.send_internal_error( - request_id, - format!("failed to uninstall plugin: {err}"), - ) - .await; - } - CorePluginUninstallError::InvalidPluginId(_) => { - unreachable!("invalid plugin ids are handled above"); - } - } - } - } - } -} - -fn remote_marketplace_to_info(marketplace: RemoteMarketplace) -> PluginMarketplaceEntry { - PluginMarketplaceEntry { - name: marketplace.name, - path: None, - interface: Some(MarketplaceInterface { - display_name: Some(marketplace.display_name), - }), - plugins: marketplace - .plugins - .into_iter() - .map(remote_plugin_summary_to_info) - .collect(), - } -} - -fn remote_plugin_summary_to_info(summary: RemoteCatalogPluginSummary) -> PluginSummary { - PluginSummary { - id: summary.id, - name: summary.name, - source: PluginSource::Remote, - installed: summary.installed, - enabled: summary.enabled, - install_policy: summary.install_policy, - auth_policy: summary.auth_policy, - interface: summary.interface, - } -} - -fn remote_plugin_detail_to_info( - detail: RemoteCatalogPluginDetail, - apps: Vec, -) -> PluginDetail { - PluginDetail { - marketplace_name: detail.marketplace_name, - marketplace_path: None, - summary: remote_plugin_summary_to_info(detail.summary), - description: detail.description, - skills: detail - .skills - .into_iter() - .map(|skill| SkillSummary { - name: skill.name, - description: skill.description, - short_description: skill.short_description, - interface: skill.interface, - path: None, - enabled: skill.enabled, - }) - .collect(), - apps, - mcp_servers: Vec::new(), - } -} - -fn remote_plugin_catalog_error_to_jsonrpc( - err: RemotePluginCatalogError, - context: &str, -) -> JSONRPCErrorError { - match err { - RemotePluginCatalogError::AuthRequired | RemotePluginCatalogError::UnsupportedAuthMode => { - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("{context}: {err}"), - data: None, - } - } - RemotePluginCatalogError::UnknownMarketplace { .. } - | RemotePluginCatalogError::MarketplaceMismatch { .. } => JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("{context}: {err}"), - data: None, - }, - RemotePluginCatalogError::UnexpectedStatus { status, .. } if status.as_u16() == 404 => { - JSONRPCErrorError { - code: INVALID_REQUEST_ERROR_CODE, - message: format!("{context}: {err}"), - data: None, - } - } - RemotePluginCatalogError::AuthToken(_) - | RemotePluginCatalogError::Request { .. } - | RemotePluginCatalogError::UnexpectedStatus { .. } - | RemotePluginCatalogError::Decode { .. } => JSONRPCErrorError { - code: INTERNAL_ERROR_CODE, - message: format!("{context}: {err}"), - data: None, - }, - } -} diff --git a/vendor/codex/codex-rs/app-server/src/codex_message_processor/processor_tests.rs b/vendor/codex/codex-rs/app-server/src/codex_message_processor/processor_tests.rs deleted file mode 100644 index 308e53e9..00000000 --- a/vendor/codex/codex-rs/app-server/src/codex_message_processor/processor_tests.rs +++ /dev/null @@ -1,4818 +0,0 @@ -use super::*; -use crate::outgoing_message::OutgoingEnvelope; -use crate::outgoing_message::OutgoingMessage; -use anyhow::Result; -use chrono::DateTime; -use chrono::Utc; -use codex_app_server_protocol::ServerRequestPayload; -use codex_app_server_protocol::ToolRequestUserInputParams; -use codex_config::SessionThreadConfig; -use codex_config::StaticThreadConfigLoader; -use codex_config::ThreadConfigSource; -use codex_core::config_loader::CloudRequirementsLoader; -use codex_core::config_loader::LoaderOverrides; -use codex_model_provider_info::ModelProviderInfo; -use codex_model_provider_info::WireApi; -use codex_protocol::ThreadId; -use codex_protocol::openai_models::ReasoningEffort; -use codex_protocol::protocol::AskForApproval; -use codex_protocol::protocol::SandboxPolicy; -use codex_protocol::protocol::SessionSource; -use codex_protocol::protocol::SubAgentSource; -use codex_thread_store::StoredThread; -use codex_utils_absolute_path::test_support::PathBufExt; -use codex_utils_absolute_path::test_support::test_path_buf; -use pretty_assertions::assert_eq; -use serde_json::json; -use std::collections::BTreeMap; -use std::path::PathBuf; -use std::sync::Arc; -use tempfile::TempDir; - -fn core_token_usage_info( - cumulative_tokens: i64, - current_context_tokens: i64, - model_context_window: Option, - model_auto_compact_token_limit: Option, -) -> CoreTokenUsageInfo { - CoreTokenUsageInfo { - total_token_usage: codex_protocol::protocol::TokenUsage { - total_tokens: cumulative_tokens, - ..Default::default() - }, - last_token_usage: codex_protocol::protocol::TokenUsage { - total_tokens: current_context_tokens, - ..Default::default() - }, - model_context_window, - model_auto_compact_token_limit, - } -} - -#[test] -fn validate_dynamic_tools_rejects_unsupported_input_schema() { - let tools = vec![ApiDynamicToolSpec { - namespace: None, - name: "my_tool".to_string(), - description: "test".to_string(), - input_schema: json!({"type": "null"}), - defer_loading: false, - }]; - let err = validate_dynamic_tools(&tools).expect_err("invalid schema"); - assert!(err.contains("my_tool"), "unexpected error: {err}"); -} - -#[test] -fn validate_dynamic_tools_accepts_sanitizable_input_schema() { - let tools = vec![ApiDynamicToolSpec { - namespace: None, - name: "my_tool".to_string(), - description: "test".to_string(), - // Missing `type` is common; core sanitizes these to a supported schema. - input_schema: json!({"properties": {}}), - defer_loading: false, - }]; - validate_dynamic_tools(&tools).expect("valid schema"); -} - -#[test] -fn validate_dynamic_tools_accepts_nullable_field_schema() { - let tools = vec![ApiDynamicToolSpec { - namespace: None, - name: "my_tool".to_string(), - description: "test".to_string(), - input_schema: json!({ - "type": "object", - "properties": { - "query": {"type": ["string", "null"]} - }, - "required": ["query"], - "additionalProperties": false - }), - defer_loading: false, - }]; - validate_dynamic_tools(&tools).expect("valid schema"); -} - -#[test] -fn validate_dynamic_tools_accepts_same_name_in_different_namespaces() { - let tools = vec![ - ApiDynamicToolSpec { - namespace: Some("codex_app".to_string()), - name: "my_tool".to_string(), - description: "test".to_string(), - input_schema: json!({ - "type": "object", - "properties": {}, - "additionalProperties": false - }), - defer_loading: true, - }, - ApiDynamicToolSpec { - namespace: Some("other_app".to_string()), - name: "my_tool".to_string(), - description: "test".to_string(), - input_schema: json!({ - "type": "object", - "properties": {}, - "additionalProperties": false - }), - defer_loading: true, - }, - ]; - validate_dynamic_tools(&tools).expect("valid schema"); -} - -#[test] -fn validate_dynamic_tools_rejects_duplicate_name_in_same_namespace() { - let tools = vec![ - ApiDynamicToolSpec { - namespace: Some("codex_app".to_string()), - name: "my_tool".to_string(), - description: "test".to_string(), - input_schema: json!({ - "type": "object", - "properties": {}, - "additionalProperties": false - }), - defer_loading: true, - }, - ApiDynamicToolSpec { - namespace: Some("codex_app".to_string()), - name: "my_tool".to_string(), - description: "test".to_string(), - input_schema: json!({ - "type": "object", - "properties": {}, - "additionalProperties": false - }), - defer_loading: true, - }, - ]; - let err = validate_dynamic_tools(&tools).expect_err("duplicate name"); - assert!(err.contains("codex_app"), "unexpected error: {err}"); - assert!(err.contains("my_tool"), "unexpected error: {err}"); -} - -#[test] -fn validate_dynamic_tools_rejects_empty_namespace() { - let tools = vec![ApiDynamicToolSpec { - namespace: Some("".to_string()), - name: "my_tool".to_string(), - description: "test".to_string(), - input_schema: json!({ - "type": "object", - "properties": {}, - "additionalProperties": false - }), - defer_loading: false, - }]; - let err = validate_dynamic_tools(&tools).expect_err("empty namespace"); - assert!(err.contains("my_tool"), "unexpected error: {err}"); - assert!(err.contains("namespace"), "unexpected error: {err}"); -} - -#[test] -fn validate_dynamic_tools_rejects_reserved_namespace() { - let tools = vec![ApiDynamicToolSpec { - namespace: Some("mcp__server__".to_string()), - name: "my_tool".to_string(), - description: "test".to_string(), - input_schema: json!({ - "type": "object", - "properties": {}, - "additionalProperties": false - }), - defer_loading: false, - }]; - let err = validate_dynamic_tools(&tools).expect_err("reserved namespace"); - assert!(err.contains("my_tool"), "unexpected error: {err}"); - assert!(err.contains("reserved"), "unexpected error: {err}"); -} - -#[test] -fn summary_from_stored_thread_preserves_millisecond_precision() { - let created_at = - DateTime::parse_from_rfc3339("2025-01-02T03:04:05.678Z").expect("valid timestamp"); - let updated_at = - DateTime::parse_from_rfc3339("2025-01-02T03:04:06.789Z").expect("valid timestamp"); - let thread_id = - ThreadId::from_string("00000000-0000-0000-0000-000000000123").expect("valid thread"); - let stored_thread = StoredThread { - thread_id, - rollout_path: Some(PathBuf::from("/tmp/thread.jsonl")), - forked_from_id: None, - preview: "preview".to_string(), - name: None, - model_provider: "openai".to_string(), - model: None, - reasoning_effort: None, - created_at: created_at.with_timezone(&Utc), - updated_at: updated_at.with_timezone(&Utc), - archived_at: None, - cwd: PathBuf::from("/tmp"), - cli_version: "0.0.0".to_string(), - source: SessionSource::Cli, - agent_nickname: None, - agent_role: None, - agent_path: None, - git_info: None, - approval_mode: AskForApproval::OnRequest, - sandbox_policy: SandboxPolicy::new_read_only_policy(), - token_usage: None, - first_user_message: Some("first user message".to_string()), - history: None, - }; - - let summary = - summary_from_stored_thread(stored_thread, "fallback").expect("summary should exist"); - - assert_eq!( - summary.timestamp.as_deref(), - Some("2025-01-02T03:04:05.678Z") - ); - assert_eq!( - summary.updated_at.as_deref(), - Some("2025-01-02T03:04:06.789Z") - ); -} - -#[test] -fn thread_response_permission_profile_omits_external_sandbox() { - let cwd = test_path_buf("/tmp").abs(); - let profile = codex_protocol::models::PermissionProfile::from_legacy_sandbox_policy( - &SandboxPolicy::DangerFullAccess, - cwd.as_path(), - ); - - assert_eq!( - thread_response_permission_profile( - &SandboxPolicy::ExternalSandbox { - network_access: codex_protocol::protocol::NetworkAccess::Restricted, - }, - profile.clone(), - ), - None - ); - assert_eq!( - thread_response_permission_profile(&SandboxPolicy::DangerFullAccess, profile.clone()), - Some(profile.into()) - ); -} - -#[test] -fn requested_permissions_trust_project_uses_permission_profile_intent() { - let cwd = test_path_buf("/tmp/project").abs(); - let full_access_profile = codex_protocol::models::PermissionProfile::from_legacy_sandbox_policy( - &SandboxPolicy::DangerFullAccess, - cwd.as_path(), - ); - let workspace_write_profile = - codex_protocol::models::PermissionProfile::from_legacy_sandbox_policy( - &SandboxPolicy::new_workspace_write_policy(), - cwd.as_path(), - ); - let read_only_profile = codex_protocol::models::PermissionProfile::from_legacy_sandbox_policy( - &SandboxPolicy::new_read_only_policy(), - cwd.as_path(), - ); - - assert!(requested_permissions_trust_project( - &ConfigOverrides { - permission_profile: Some(full_access_profile), - ..Default::default() - }, - cwd.as_path() - )); - assert!(requested_permissions_trust_project( - &ConfigOverrides { - permission_profile: Some(workspace_write_profile), - ..Default::default() - }, - cwd.as_path() - )); - assert!(!requested_permissions_trust_project( - &ConfigOverrides { - permission_profile: Some(read_only_profile), - ..Default::default() - }, - cwd.as_path() - )); -} - -#[test] -fn config_load_error_marks_cloud_requirements_failures_for_relogin() { - let err = std::io::Error::other(CloudRequirementsLoadError::new( - CloudRequirementsLoadErrorCode::Auth, - Some(401), - "Your authentication session could not be refreshed automatically. Please log out and sign in again.", - )); - - let error = config_load_error(&err); - - assert_eq!( - error.data, - Some(json!({ - "reason": "cloudRequirements", - "errorCode": "Auth", - "action": "relogin", - "statusCode": 401, - "detail": "Your authentication session could not be refreshed automatically. Please log out and sign in again.", - })) - ); - assert!( - error.message.contains("failed to load configuration"), - "unexpected error message: {}", - error.message - ); -} - -#[test] -fn config_load_error_leaves_non_cloud_requirements_failures_unmarked() { - let err = std::io::Error::other("required MCP servers failed to initialize"); - - let error = config_load_error(&err); - - assert_eq!(error.data, None); - assert!( - error.message.contains("failed to load configuration"), - "unexpected error message: {}", - error.message - ); -} - -#[test] -fn config_load_error_marks_non_auth_cloud_requirements_failures_without_relogin() { - let err = std::io::Error::other(CloudRequirementsLoadError::new( - CloudRequirementsLoadErrorCode::RequestFailed, - /*status_code*/ None, - "failed to load your workspace-managed config", - )); - - let error = config_load_error(&err); - - assert_eq!( - error.data, - Some(json!({ - "reason": "cloudRequirements", - "errorCode": "RequestFailed", - "detail": "failed to load your workspace-managed config", - })) - ); -} - -#[tokio::test] -async fn derive_config_from_params_uses_session_thread_config_model_provider() -> Result<()> { - let temp_dir = TempDir::new()?; - let session_provider = ModelProviderInfo { - name: "session".to_string(), - base_url: Some("http://127.0.0.1:8061/api/codex".to_string()), - env_key: None, - env_key_instructions: None, - experimental_bearer_token: None, - auth: None, - aws: None, - wire_api: WireApi::Responses, - query_params: None, - http_headers: None, - env_http_headers: None, - request_max_retries: None, - stream_max_retries: None, - stream_idle_timeout_ms: None, - websocket_connect_timeout_ms: None, - requires_openai_auth: false, - supports_websockets: true, - }; - let config_manager = ConfigManager::new( - temp_dir.path().to_path_buf(), - Vec::new(), - LoaderOverrides::default(), - CloudRequirementsLoader::default(), - Arg0DispatchPaths::default(), - Arc::new(StaticThreadConfigLoader::new(vec![ - ThreadConfigSource::Session(SessionThreadConfig { - model_provider: Some("session".to_string()), - model_providers: HashMap::from([("session".to_string(), session_provider.clone())]), - features: BTreeMap::from([("plugins".to_string(), false)]), - }), - ])), - ); - let config = config_manager - .load_with_overrides( - Some(HashMap::from([ - ("model_provider".to_string(), json!("request")), - ("features.plugins".to_string(), json!(true)), - ( - "model_providers.session".to_string(), - json!({ - "name": "request", - "base_url": "http://127.0.0.1:9999/api/codex", - "wire_api": "responses", - }), - ), - ])), - ConfigOverrides::default(), - ) - .await?; - - assert_eq!(config.model_provider_id, "session"); - assert_eq!(config.model_provider, session_provider); - assert!(!config.features.enabled(Feature::Plugins)); - Ok(()) -} - -#[test] -fn collect_resume_override_mismatches_includes_service_tier() { - let cwd = test_path_buf("/tmp").abs(); - let request = ThreadResumeParams { - thread_id: "thread-1".to_string(), - history: None, - path: None, - model: None, - model_provider: None, - service_tier: Some(Some(codex_protocol::config_types::ServiceTier::Fast)), - cwd: None, - approval_policy: None, - approvals_reviewer: None, - sandbox: None, - permission_profile: None, - config: None, - base_instructions: None, - developer_instructions: None, - personality: None, - persist_extended_history: false, - }; - let config_snapshot = ThreadConfigSnapshot { - model: "gpt-5".to_string(), - model_provider_id: "openai".to_string(), - service_tier: Some(codex_protocol::config_types::ServiceTier::Flex), - approval_policy: codex_protocol::protocol::AskForApproval::OnRequest, - approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User, - sandbox_policy: codex_protocol::protocol::SandboxPolicy::DangerFullAccess, - permission_profile: codex_protocol::models::PermissionProfile::from_legacy_sandbox_policy( - &codex_protocol::protocol::SandboxPolicy::DangerFullAccess, - cwd.as_path(), - ), - cwd, - ephemeral: false, - reasoning_effort: None, - personality: None, - session_source: SessionSource::Cli, - }; - - assert_eq!( - collect_resume_override_mismatches(&request, &config_snapshot), - vec!["service_tier requested=Some(Fast) active=Some(Flex)".to_string()] - ); -} - -fn test_thread_metadata( - model: Option<&str>, - reasoning_effort: Option, -) -> Result { - let thread_id = ThreadId::from_string("3f941c35-29b3-493b-b0a4-e25800d9aeb0")?; - let mut builder = ThreadMetadataBuilder::new( - thread_id, - PathBuf::from("/tmp/rollout.jsonl"), - Utc::now(), - codex_protocol::protocol::SessionSource::default(), - ); - builder.model_provider = Some("mock_provider".to_string()); - let mut metadata = builder.build("mock_provider"); - metadata.model = model.map(ToString::to_string); - metadata.reasoning_effort = reasoning_effort; - Ok(metadata) -} - -#[test] -fn summary_from_thread_metadata_formats_protocol_timestamps_as_seconds() -> Result<()> { - let mut metadata = test_thread_metadata(/*model*/ None, /*reasoning_effort*/ None)?; - metadata.created_at = - DateTime::parse_from_rfc3339("2025-09-05T16:53:11.123Z")?.with_timezone(&Utc); - metadata.updated_at = - DateTime::parse_from_rfc3339("2025-09-05T16:53:12.456Z")?.with_timezone(&Utc); - - let summary = summary_from_thread_metadata(&metadata); - - assert_eq!(summary.timestamp, Some("2025-09-05T16:53:11Z".to_string())); - assert_eq!(summary.updated_at, Some("2025-09-05T16:53:12Z".to_string())); - Ok(()) -} - -#[test] -fn merge_persisted_resume_metadata_prefers_persisted_model_and_reasoning_effort() -> Result<()> { - let mut request_overrides = None; - let mut typesafe_overrides = ConfigOverrides::default(); - let persisted_metadata = - test_thread_metadata(Some("gpt-5.1-codex-max"), Some(ReasoningEffort::High))?; - - merge_persisted_resume_metadata( - &mut request_overrides, - &mut typesafe_overrides, - &persisted_metadata, - ); - - assert_eq!( - typesafe_overrides.model, - Some("gpt-5.1-codex-max".to_string()) - ); - assert_eq!( - request_overrides, - Some(HashMap::from([( - "model_reasoning_effort".to_string(), - serde_json::Value::String("high".to_string()), - )])) - ); - Ok(()) -} - -#[test] -fn merge_persisted_resume_metadata_preserves_explicit_overrides() -> Result<()> { - let mut request_overrides = Some(HashMap::from([( - "model_reasoning_effort".to_string(), - serde_json::Value::String("low".to_string()), - )])); - let mut typesafe_overrides = ConfigOverrides { - model: Some("gpt-5.2-codex".to_string()), - ..Default::default() - }; - let persisted_metadata = - test_thread_metadata(Some("gpt-5.1-codex-max"), Some(ReasoningEffort::High))?; - - merge_persisted_resume_metadata( - &mut request_overrides, - &mut typesafe_overrides, - &persisted_metadata, - ); - - assert_eq!(typesafe_overrides.model, Some("gpt-5.2-codex".to_string())); - assert_eq!( - request_overrides, - Some(HashMap::from([( - "model_reasoning_effort".to_string(), - serde_json::Value::String("low".to_string()), - )])) - ); - Ok(()) -} - -#[test] -fn merge_persisted_resume_metadata_skips_persisted_values_when_model_overridden() -> Result<()> { - let mut request_overrides = Some(HashMap::from([( - "model".to_string(), - serde_json::Value::String("gpt-5.2-codex".to_string()), - )])); - let mut typesafe_overrides = ConfigOverrides::default(); - let persisted_metadata = - test_thread_metadata(Some("gpt-5.1-codex-max"), Some(ReasoningEffort::High))?; - - merge_persisted_resume_metadata( - &mut request_overrides, - &mut typesafe_overrides, - &persisted_metadata, - ); - - assert_eq!(typesafe_overrides.model, None); - assert_eq!( - request_overrides, - Some(HashMap::from([( - "model".to_string(), - serde_json::Value::String("gpt-5.2-codex".to_string()), - )])) - ); - Ok(()) -} - -#[test] -fn merge_persisted_resume_metadata_skips_persisted_values_when_provider_overridden() -> Result<()> { - let mut request_overrides = None; - let mut typesafe_overrides = ConfigOverrides { - model_provider: Some("oss".to_string()), - ..Default::default() - }; - let persisted_metadata = - test_thread_metadata(Some("gpt-5.1-codex-max"), Some(ReasoningEffort::High))?; - - merge_persisted_resume_metadata( - &mut request_overrides, - &mut typesafe_overrides, - &persisted_metadata, - ); - - assert_eq!(typesafe_overrides.model, None); - assert_eq!(typesafe_overrides.model_provider, Some("oss".to_string())); - assert_eq!(request_overrides, None); - Ok(()) -} - -#[test] -fn merge_persisted_resume_metadata_skips_persisted_values_when_reasoning_effort_overridden() --> Result<()> { - let mut request_overrides = Some(HashMap::from([( - "model_reasoning_effort".to_string(), - serde_json::Value::String("low".to_string()), - )])); - let mut typesafe_overrides = ConfigOverrides::default(); - let persisted_metadata = - test_thread_metadata(Some("gpt-5.1-codex-max"), Some(ReasoningEffort::High))?; - - merge_persisted_resume_metadata( - &mut request_overrides, - &mut typesafe_overrides, - &persisted_metadata, - ); - - assert_eq!(typesafe_overrides.model, None); - assert_eq!( - request_overrides, - Some(HashMap::from([( - "model_reasoning_effort".to_string(), - serde_json::Value::String("low".to_string()), - )])) - ); - Ok(()) -} - -#[test] -fn merge_persisted_resume_metadata_skips_missing_values() -> Result<()> { - let mut request_overrides = None; - let mut typesafe_overrides = ConfigOverrides::default(); - let persisted_metadata = - test_thread_metadata(/*model*/ None, /*reasoning_effort*/ None)?; - - merge_persisted_resume_metadata( - &mut request_overrides, - &mut typesafe_overrides, - &persisted_metadata, - ); - - assert_eq!(typesafe_overrides.model, None); - assert_eq!(request_overrides, None); - Ok(()) -} - -#[test] -fn extract_conversation_summary_prefers_plain_user_messages() -> Result<()> { - let conversation_id = ThreadId::from_string("3f941c35-29b3-493b-b0a4-e25800d9aeb0")?; - let timestamp = Some("2025-09-05T16:53:11.850Z".to_string()); - let path = PathBuf::from("rollout.jsonl"); - - let head = vec![ - json!({ - "id": conversation_id.to_string(), - "timestamp": timestamp, - "cwd": "/", - "originator": "codex", - "cli_version": "0.0.0", - "model_provider": "test-provider" - }), - json!({ - "type": "message", - "role": "user", - "content": [{ - "type": "input_text", - "text": "# AGENTS.md instructions for project\n\n\n\n".to_string(), - }], - }), - json!({ - "type": "message", - "role": "user", - "content": [{ - "type": "input_text", - "text": format!(" {USER_MESSAGE_BEGIN}Count to 5"), - }], - }), - ]; - - let session_meta = serde_json::from_value::(head[0].clone())?; - - let summary = extract_conversation_summary( - path.clone(), - &head, - &session_meta, - /*git*/ None, - "test-provider", - timestamp.clone(), - ) - .expect("summary"); - - let expected = ConversationSummary { - conversation_id, - timestamp: timestamp.clone(), - updated_at: timestamp, - path, - preview: "Count to 5".to_string(), - model_provider: "test-provider".to_string(), - cwd: PathBuf::from("/"), - cli_version: "0.0.0".to_string(), - source: SessionSource::VSCode, - git_info: None, - }; - - assert_eq!(summary, expected); - Ok(()) -} - -#[tokio::test] -async fn read_summary_from_rollout_returns_empty_preview_when_no_user_message() -> Result<()> { - use codex_protocol::protocol::RolloutItem; - use codex_protocol::protocol::RolloutLine; - use codex_protocol::protocol::SessionMetaLine; - use std::fs; - use std::fs::FileTimes; - - let temp_dir = TempDir::new()?; - let path = temp_dir.path().join("rollout.jsonl"); - - let conversation_id = ThreadId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; - let timestamp = "2025-09-05T16:53:11.850Z".to_string(); - - let session_meta = SessionMeta { - id: conversation_id, - timestamp: timestamp.clone(), - model_provider: None, - ..SessionMeta::default() - }; - - let line = RolloutLine { - timestamp: timestamp.clone(), - item: RolloutItem::SessionMeta(SessionMetaLine { - meta: session_meta.clone(), - git: None, - }), - }; - - fs::write(&path, format!("{}\n", serde_json::to_string(&line)?))?; - let parsed = chrono::DateTime::parse_from_rfc3339(×tamp)?.with_timezone(&Utc); - let times = FileTimes::new().set_modified(parsed.into()); - std::fs::OpenOptions::new() - .append(true) - .open(&path)? - .set_times(times)?; - - let summary = read_summary_from_rollout(path.as_path(), "fallback").await?; - - let expected = ConversationSummary { - conversation_id, - timestamp: Some(timestamp.clone()), - updated_at: Some(timestamp), - path: path.clone(), - preview: String::new(), - model_provider: "fallback".to_string(), - cwd: PathBuf::new(), - cli_version: String::new(), - source: SessionSource::VSCode, - git_info: None, - }; - - assert_eq!(summary, expected); - Ok(()) -} - -#[tokio::test] -async fn read_summary_from_rollout_preserves_agent_nickname() -> Result<()> { - use codex_protocol::protocol::RolloutItem; - use codex_protocol::protocol::RolloutLine; - use codex_protocol::protocol::SessionMetaLine; - use std::fs; - - let temp_dir = TempDir::new()?; - let path = temp_dir.path().join("rollout.jsonl"); - - let conversation_id = ThreadId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; - let parent_thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let timestamp = "2025-09-05T16:53:11.850Z".to_string(); - - let session_meta = SessionMeta { - id: conversation_id, - timestamp: timestamp.clone(), - source: SessionSource::SubAgent(SubAgentSource::ThreadSpawn { - parent_thread_id, - depth: 1, - agent_path: None, - agent_nickname: None, - agent_role: None, - }), - agent_nickname: Some("atlas".to_string()), - agent_role: Some("explorer".to_string()), - model_provider: Some("test-provider".to_string()), - ..SessionMeta::default() - }; - - let line = RolloutLine { - timestamp, - item: RolloutItem::SessionMeta(SessionMetaLine { - meta: session_meta, - git: None, - }), - }; - fs::write(&path, format!("{}\n", serde_json::to_string(&line)?))?; - - let summary = read_summary_from_rollout(path.as_path(), "fallback").await?; - let fallback_cwd = AbsolutePathBuf::from_absolute_path("/")?; - let thread = summary_to_thread(summary, &fallback_cwd); - - assert_eq!(thread.agent_nickname, Some("atlas".to_string())); - assert_eq!(thread.agent_role, Some("explorer".to_string())); - Ok(()) -} - -#[tokio::test] -async fn read_summary_from_rollout_preserves_forked_from_id() -> Result<()> { - use codex_protocol::protocol::RolloutItem; - use codex_protocol::protocol::RolloutLine; - use codex_protocol::protocol::SessionMetaLine; - use std::fs; - - let temp_dir = TempDir::new()?; - let path = temp_dir.path().join("rollout.jsonl"); - - let conversation_id = ThreadId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; - let forked_from_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let timestamp = "2025-09-05T16:53:11.850Z".to_string(); - - let session_meta = SessionMeta { - id: conversation_id, - forked_from_id: Some(forked_from_id), - timestamp: timestamp.clone(), - model_provider: Some("test-provider".to_string()), - ..SessionMeta::default() - }; - - let line = RolloutLine { - timestamp, - item: RolloutItem::SessionMeta(SessionMetaLine { - meta: session_meta, - git: None, - }), - }; - fs::write(&path, format!("{}\n", serde_json::to_string(&line)?))?; - - assert_eq!( - forked_from_id_from_rollout(path.as_path()).await, - Some(forked_from_id.to_string()) - ); - Ok(()) -} - -#[tokio::test] -async fn load_epiphany_state_from_rollout_path_reads_latest_snapshot() -> Result<()> { - use codex_protocol::protocol::EpiphanyStateItem; - use codex_protocol::protocol::EpiphanyThreadState; - use codex_protocol::protocol::EventMsg; - use codex_protocol::protocol::RolloutItem; - use codex_protocol::protocol::RolloutLine; - use codex_protocol::protocol::SessionMetaLine; - use codex_protocol::protocol::TurnCompleteEvent; - use codex_protocol::protocol::TurnStartedEvent; - use codex_protocol::protocol::UserMessageEvent; - use std::fs; - - let temp_dir = TempDir::new()?; - let path = temp_dir.path().join("rollout.jsonl"); - - let conversation_id = ThreadId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; - let timestamp = "2025-09-05T16:53:11.850Z".to_string(); - let epiphany_state = EpiphanyThreadState { - revision: 7, - objective: Some("Expose thread state to clients".to_string()), - active_subgoal_id: Some("phase-3".to_string()), - last_updated_turn_id: Some("turn-2".to_string()), - ..Default::default() - }; - - let rollout_lines = vec![ - RolloutLine { - timestamp: timestamp.clone(), - item: RolloutItem::SessionMeta(SessionMetaLine { - meta: SessionMeta { - id: conversation_id, - timestamp: timestamp.clone(), - model_provider: Some("test-provider".to_string()), - ..SessionMeta::default() - }, - git: None, - }), - }, - RolloutLine { - timestamp: timestamp.clone(), - item: RolloutItem::EventMsg(EventMsg::TurnStarted(TurnStartedEvent { - turn_id: "turn-2".to_string(), - started_at: None, - model_context_window: None, - collaboration_mode_kind: Default::default(), - })), - }, - RolloutLine { - timestamp: timestamp.clone(), - item: RolloutItem::EventMsg(EventMsg::UserMessage(UserMessageEvent { - message: "load the scene".to_string(), - images: None, - text_elements: Vec::new(), - local_images: Vec::new(), - })), - }, - RolloutLine { - timestamp: timestamp.clone(), - item: RolloutItem::EpiphanyState(EpiphanyStateItem { - turn_id: Some("turn-2".to_string()), - state: epiphany_state.clone(), - }), - }, - RolloutLine { - timestamp, - item: RolloutItem::EventMsg(EventMsg::TurnComplete(TurnCompleteEvent { - turn_id: "turn-2".to_string(), - last_agent_message: None, - completed_at: None, - duration_ms: None, - time_to_first_token_ms: None, - })), - }, - ]; - - let encoded = rollout_lines - .iter() - .map(serde_json::to_string) - .collect::, _>>()? - .join("\n"); - fs::write(&path, format!("{encoded}\n"))?; - - let loaded = load_epiphany_state_from_rollout_path(path.as_path()) - .await - .map_err(anyhow::Error::msg)?; - assert_eq!(loaded, Some(epiphany_state)); - Ok(()) -} - -#[test] -fn map_epiphany_retrieve_response_preserves_summary_and_results() -> Result<()> { - let response = map_epiphany_retrieve_response(codex_core::EpiphanyRetrieveResponse { - query: "checkpoint frontier".to_string(), - index_summary: codex_protocol::protocol::EpiphanyRetrievalState { - workspace_root: test_path_buf("/repo"), - index_revision: Some("query-time-bm25-v1".to_string()), - status: codex_protocol::protocol::EpiphanyRetrievalStatus::Ready, - semantic_available: true, - last_indexed_at_unix_seconds: Some(1_744_500_000), - indexed_file_count: Some(12), - indexed_chunk_count: Some(34), - shards: vec![codex_protocol::protocol::EpiphanyRetrievalShardSummary { - shard_id: "workspace".to_string(), - path_prefix: PathBuf::from("."), - indexed_file_count: Some(12), - indexed_chunk_count: Some(34), - status: codex_protocol::protocol::EpiphanyRetrievalStatus::Ready, - exact_available: true, - semantic_available: true, - }], - dirty_paths: vec![PathBuf::from("src/session/mod.rs")], - }, - results: vec![codex_core::EpiphanyRetrieveResult { - kind: codex_core::EpiphanyRetrieveResultKind::SemanticChunk, - path: PathBuf::from("notes/design.md"), - score: 2.5, - line_start: Some(3), - line_end: Some(9), - excerpt: Some("checkpoint frontier".to_string()), - }], - })?; - - assert_eq!(response.query, "checkpoint frontier"); - assert_eq!( - response.index_summary.workspace_root, - test_path_buf("/repo").abs() - ); - assert_eq!(response.index_summary.indexed_chunk_count, Some(34)); - assert_eq!(response.results.len(), 1); - assert_eq!( - response.results[0].kind, - ThreadEpiphanyRetrieveResultKind::SemanticChunk - ); - assert_eq!(response.results[0].path, PathBuf::from("notes/design.md")); - Ok(()) -} - -#[test] -fn map_epiphany_retrieve_index_summary_preserves_ready_qdrant_summary() -> Result<()> { - let summary = - map_epiphany_retrieve_index_summary(codex_protocol::protocol::EpiphanyRetrievalState { - workspace_root: test_path_buf("/repo"), - index_revision: Some("qdrant-ollama-v1:qwen3-embedding:0.6b".to_string()), - status: codex_protocol::protocol::EpiphanyRetrievalStatus::Ready, - semantic_available: true, - last_indexed_at_unix_seconds: Some(1_744_500_100), - indexed_file_count: Some(12), - indexed_chunk_count: Some(34), - shards: vec![codex_protocol::protocol::EpiphanyRetrievalShardSummary { - shard_id: "workspace".to_string(), - path_prefix: PathBuf::from("."), - indexed_file_count: Some(12), - indexed_chunk_count: Some(34), - status: codex_protocol::protocol::EpiphanyRetrievalStatus::Ready, - exact_available: true, - semantic_available: true, - }], - dirty_paths: Vec::new(), - })?; - - assert_eq!( - summary.index_revision.as_deref(), - Some("qdrant-ollama-v1:qwen3-embedding:0.6b") - ); - assert_eq!(summary.indexed_file_count, Some(12)); - assert!(summary.dirty_paths.is_empty()); - Ok(()) -} - -#[test] -fn map_epiphany_scene_projects_client_reflection_without_mutation_shape() { - let scene = map_epiphany_scene( - Some(&codex_protocol::protocol::EpiphanyThreadState { - revision: 5, - objective: Some("Expose typed state without making a second brain".to_string()), - active_subgoal_id: Some("phase-6".to_string()), - subgoals: vec![ - codex_protocol::protocol::EpiphanySubgoal { - id: "phase-5".to_string(), - title: "Finish control plane".to_string(), - status: "done".to_string(), - summary: None, - }, - codex_protocol::protocol::EpiphanySubgoal { - id: "phase-6".to_string(), - title: "Reflect typed state".to_string(), - status: "active".to_string(), - summary: Some("Thin client scene".to_string()), - }, - ], - invariants: vec![ - codex_protocol::protocol::EpiphanyInvariant { - id: "inv-1".to_string(), - description: "No GUI source of truth".to_string(), - status: "ok".to_string(), - rationale: None, - }, - codex_protocol::protocol::EpiphanyInvariant { - id: "inv-2".to_string(), - description: "No hidden mutation".to_string(), - status: "ok".to_string(), - rationale: None, - }, - ], - graphs: codex_protocol::protocol::EpiphanyGraphs { - architecture: codex_protocol::protocol::EpiphanyGraph { - nodes: vec![codex_protocol::protocol::EpiphanyGraphNode { - id: "scene".to_string(), - title: "Scene projection".to_string(), - purpose: "Reflect the typed state".to_string(), - ..Default::default() - }], - edges: Vec::new(), - }, - dataflow: codex_protocol::protocol::EpiphanyGraph { - nodes: vec![codex_protocol::protocol::EpiphanyGraphNode { - id: "state".to_string(), - title: "State".to_string(), - purpose: "Authoritative input".to_string(), - ..Default::default() - }], - edges: Vec::new(), - }, - links: vec![codex_protocol::protocol::EpiphanyGraphLink { - dataflow_node_id: "state".to_string(), - architecture_node_id: "scene".to_string(), - relationship: Some("derived".to_string()), - code_refs: Vec::new(), - }], - }, - graph_frontier: Some(codex_protocol::protocol::EpiphanyGraphFrontier { - active_node_ids: vec!["scene".to_string()], - active_edge_ids: Vec::new(), - open_question_ids: vec!["q-1".to_string()], - open_gap_ids: Vec::new(), - dirty_paths: vec![PathBuf::from("app-server/src/codex_message_processor.rs")], - }), - graph_checkpoint: Some(codex_protocol::protocol::EpiphanyGraphCheckpoint { - checkpoint_id: "ck-5".to_string(), - graph_revision: 5, - summary: Some("Phase 6 start".to_string()), - frontier_node_ids: Vec::new(), - open_question_ids: Vec::new(), - open_gap_ids: Vec::new(), - }), - retrieval: Some(codex_protocol::protocol::EpiphanyRetrievalState { - workspace_root: test_path_buf("/repo"), - status: codex_protocol::protocol::EpiphanyRetrievalStatus::Ready, - semantic_available: true, - indexed_file_count: Some(2), - indexed_chunk_count: Some(8), - shards: vec![codex_protocol::protocol::EpiphanyRetrievalShardSummary { - shard_id: "workspace".to_string(), - path_prefix: PathBuf::from("."), - status: codex_protocol::protocol::EpiphanyRetrievalStatus::Ready, - exact_available: true, - semantic_available: true, - ..Default::default() - }], - ..Default::default() - }), - investigation_checkpoint: Some( - codex_protocol::protocol::EpiphanyInvestigationCheckpoint { - checkpoint_id: "ix-5".to_string(), - kind: "slice_planning".to_string(), - disposition: - codex_protocol::protocol::EpiphanyInvestigationDisposition::ResumeReady, - focus: "Keep the durable planning packet visible.".to_string(), - summary: Some("Checkpointed the next bounded slice.".to_string()), - next_action: Some("Patch the typed state writer next.".to_string()), - captured_at_turn_id: Some("turn-5".to_string()), - open_questions: vec!["Should scene and context both surface this?".to_string()], - evidence_ids: vec!["ev-scene".to_string()], - code_refs: vec![codex_protocol::protocol::EpiphanyCodeRef { - path: test_path_buf("/repo/app-server/src/codex_message_processor.rs"), - start_line: Some(10692), - end_line: Some(10811), - symbol: Some("map_epiphany_scene".to_string()), - note: None, - }], - }, - ), - observations: vec![codex_protocol::protocol::EpiphanyObservation { - id: "obs-scene".to_string(), - summary: "Scene is derived".to_string(), - source_kind: "test".to_string(), - status: "ok".to_string(), - code_refs: Vec::new(), - evidence_ids: vec!["ev-scene".to_string()], - }], - recent_evidence: vec![codex_protocol::protocol::EpiphanyEvidenceRecord { - id: "ev-scene".to_string(), - kind: "test".to_string(), - status: "ok".to_string(), - summary: "Projection test".to_string(), - code_refs: Vec::new(), - }], - churn: Some(codex_protocol::protocol::EpiphanyChurnState { - understanding_status: "ready".to_string(), - diff_pressure: "low".to_string(), - graph_freshness: Some("fresh".to_string()), - warning: None, - unexplained_writes: Some(0), - }), - ..Default::default() - }), - true, - EPIPHANY_REORIENT_LAUNCH_BINDING_ID, - ); - - assert_eq!(scene.state_status, ThreadEpiphanySceneStateStatus::Ready); - assert_eq!(scene.source, ThreadEpiphanySceneSource::Live); - assert_eq!(scene.revision, Some(5)); - assert_eq!( - scene - .active_subgoal - .as_ref() - .map(|subgoal| subgoal.id.as_str()), - Some("phase-6") - ); - assert_eq!( - scene.invariant_status_counts, - vec![ThreadEpiphanySceneStatusCount { - status: "ok".to_string(), - count: 2, - }] - ); - assert_eq!(scene.graph.architecture_node_count, 1); - assert_eq!(scene.graph.dataflow_node_count, 1); - assert_eq!(scene.graph.link_count, 1); - assert_eq!(scene.graph.checkpoint_id.as_deref(), Some("ck-5")); - assert_eq!( - scene.retrieval.as_ref().and_then(|r| r.indexed_chunk_count), - Some(8) - ); - assert_eq!( - scene - .investigation_checkpoint - .as_ref() - .map(|checkpoint| checkpoint.checkpoint_id.as_str()), - Some("ix-5") - ); - assert_eq!(scene.observations.total_count, 1); - assert_eq!(scene.evidence.latest[0].id, "ev-scene"); - assert_eq!( - scene.available_actions, - vec![ - ThreadEpiphanySceneAction::Index, - ThreadEpiphanySceneAction::Retrieve, - ThreadEpiphanySceneAction::Distill, - ThreadEpiphanySceneAction::Context, - ThreadEpiphanySceneAction::Planning, - ThreadEpiphanySceneAction::GraphQuery, - ThreadEpiphanySceneAction::Jobs, - ThreadEpiphanySceneAction::Roles, - ThreadEpiphanySceneAction::Coordinator, - ThreadEpiphanySceneAction::RoleLaunch, - ThreadEpiphanySceneAction::RoleResult, - ThreadEpiphanySceneAction::RoleAccept, - ThreadEpiphanySceneAction::JobLaunch, - ThreadEpiphanySceneAction::Freshness, - ThreadEpiphanySceneAction::Pressure, - ThreadEpiphanySceneAction::Reorient, - ThreadEpiphanySceneAction::Crrc, - ThreadEpiphanySceneAction::ReorientLaunch, - ThreadEpiphanySceneAction::Update, - ThreadEpiphanySceneAction::JobInterrupt, - ThreadEpiphanySceneAction::Propose, - ThreadEpiphanySceneAction::Promote, - ] - ); -} - -#[test] -fn map_epiphany_scene_handles_missing_state_without_write_actions() { - let scene = map_epiphany_scene(None, false, EPIPHANY_REORIENT_LAUNCH_BINDING_ID); - - assert_eq!(scene.state_status, ThreadEpiphanySceneStateStatus::Missing); - assert_eq!(scene.source, ThreadEpiphanySceneSource::Stored); - assert!(scene.available_actions.is_empty()); - assert_eq!(scene.graph, ThreadEpiphanySceneGraph::default()); -} - -#[test] -fn map_epiphany_freshness_can_reflect_live_retrieval_without_state() { - let retrieval = EpiphanyRetrievalState { - workspace_root: PathBuf::from("/workspace"), - status: EpiphanyRetrievalStatus::Ready, - semantic_available: true, - ..Default::default() - }; - - let (state_revision, retrieval, graph, watcher) = - map_epiphany_freshness(None, Some(&retrieval), None); - - assert_eq!(state_revision, None); - assert_eq!( - retrieval.status, - ThreadEpiphanyRetrievalFreshnessStatus::Ready - ); - assert_eq!(retrieval.semantic_available, Some(true)); - assert_eq!(graph.status, ThreadEpiphanyGraphFreshnessStatus::Missing); - assert_eq!(graph.dirty_path_count, 0); - assert_eq!( - watcher.status, - ThreadEpiphanyInvalidationStatus::Unavailable - ); -} - -#[test] -fn map_epiphany_freshness_marks_graph_and_retrieval_stale() { - let state = EpiphanyThreadState { - revision: 7, - graphs: codex_protocol::protocol::EpiphanyGraphs { - architecture: codex_protocol::protocol::EpiphanyGraph { - nodes: vec![codex_protocol::protocol::EpiphanyGraphNode { - id: "state-spine".to_string(), - title: "State spine".to_string(), - purpose: "Typed state".to_string(), - code_refs: vec![codex_protocol::protocol::EpiphanyCodeRef { - path: test_path_buf("/workspace/src/router.rs"), - start_line: None, - end_line: None, - symbol: None, - note: None, - }], - ..Default::default() - }], - ..Default::default() - }, - ..Default::default() - }, - graph_frontier: Some(codex_protocol::protocol::EpiphanyGraphFrontier { - active_node_ids: vec!["state-spine".to_string()], - dirty_paths: vec![PathBuf::from("src/router.rs")], - open_question_ids: vec!["q-stale".to_string()], - ..Default::default() - }), - graph_checkpoint: Some(codex_protocol::protocol::EpiphanyGraphCheckpoint { - checkpoint_id: "ck-7".to_string(), - graph_revision: 7, - ..Default::default() - }), - churn: Some(codex_protocol::protocol::EpiphanyChurnState { - understanding_status: "ready".to_string(), - diff_pressure: "low".to_string(), - graph_freshness: Some("stale".to_string()), - warning: None, - unexplained_writes: Some(0), - }), - ..Default::default() - }; - let retrieval = EpiphanyRetrievalState { - workspace_root: PathBuf::from("/workspace"), - status: EpiphanyRetrievalStatus::Stale, - semantic_available: true, - indexed_file_count: Some(12), - indexed_chunk_count: Some(48), - dirty_paths: vec![PathBuf::from("src/router.rs")], - ..Default::default() - }; - let watcher_snapshot = EpiphanyInvalidationSnapshot { - available: true, - workspace_root: Some(test_path_buf("/workspace").abs()), - observed_at_unix_seconds: Some(1_744_600_000), - changed_paths: vec![PathBuf::from("src/router.rs")], - }; - - let (state_revision, retrieval, graph, watcher) = map_epiphany_freshness( - Some(&state), - Some(&retrieval), - Some(epiphany_freshness_watcher_snapshot(&watcher_snapshot)), - ); - - assert_eq!(state_revision, Some(7)); - assert_eq!( - retrieval.status, - ThreadEpiphanyRetrievalFreshnessStatus::Stale - ); - assert_eq!(retrieval.dirty_paths, vec![PathBuf::from("src/router.rs")]); - assert_eq!(graph.status, ThreadEpiphanyGraphFreshnessStatus::Stale); - assert_eq!(graph.checkpoint_id.as_deref(), Some("ck-7")); - assert_eq!(graph.dirty_path_count, 1); - assert_eq!(graph.open_question_count, 1); - assert_eq!(graph.open_gap_count, 0); - assert_eq!(watcher.status, ThreadEpiphanyInvalidationStatus::Changed); - assert_eq!( - watcher.watched_root, - Some(test_path_buf("/workspace").abs().to_path_buf()) - ); - assert_eq!(watcher.changed_paths, vec![PathBuf::from("src/router.rs")]); - assert_eq!(watcher.graph_node_ids, vec!["state-spine".to_string()]); - assert_eq!( - watcher.active_frontier_node_ids, - vec!["state-spine".to_string()] - ); -} - -#[test] -fn map_epiphany_freshness_reports_clean_watcher_when_no_changes_were_seen() { - let watcher_snapshot = EpiphanyInvalidationSnapshot { - available: true, - workspace_root: Some(test_path_buf("/workspace").abs()), - observed_at_unix_seconds: None, - changed_paths: Vec::new(), - }; - - let (_, _, _, watcher) = map_epiphany_freshness( - None, - None, - Some(epiphany_freshness_watcher_snapshot(&watcher_snapshot)), - ); - - assert_eq!(watcher.status, ThreadEpiphanyInvalidationStatus::Clean); - assert_eq!(watcher.changed_path_count, 0); - assert_eq!( - watcher.watched_root, - Some(test_path_buf("/workspace").abs().to_path_buf()) - ); -} - -#[test] -fn map_epiphany_freshness_reports_unmatched_changed_paths_without_inventing_nodes() { - let state = EpiphanyThreadState { - graphs: codex_protocol::protocol::EpiphanyGraphs { - architecture: codex_protocol::protocol::EpiphanyGraph { - nodes: vec![codex_protocol::protocol::EpiphanyGraphNode { - id: "scene".to_string(), - title: "Scene".to_string(), - purpose: "Reflection".to_string(), - code_refs: vec![codex_protocol::protocol::EpiphanyCodeRef { - path: test_path_buf("/workspace/src/scene.rs"), - start_line: None, - end_line: None, - symbol: None, - note: None, - }], - ..Default::default() - }], - ..Default::default() - }, - ..Default::default() - }, - ..Default::default() - }; - let watcher_snapshot = EpiphanyInvalidationSnapshot { - available: true, - workspace_root: Some(test_path_buf("/workspace").abs()), - observed_at_unix_seconds: Some(1_744_600_001), - changed_paths: vec![PathBuf::from("src/other.rs")], - }; - - let (_, _, _, watcher) = map_epiphany_freshness( - Some(&state), - None, - Some(epiphany_freshness_watcher_snapshot(&watcher_snapshot)), - ); - - assert_eq!(watcher.status, ThreadEpiphanyInvalidationStatus::Changed); - assert!(watcher.graph_node_ids.is_empty()); - assert!(watcher.active_frontier_node_ids.is_empty()); -} - -#[test] -fn pre_compaction_checkpoint_intervention_uses_compaction_prep_threshold() { - let elevated = map_epiphany_pressure(Some(&core_token_usage_info(1_000, 79, None, Some(100)))); - let high = map_epiphany_pressure(Some(&core_token_usage_info(1_000, 80, None, Some(100)))); - - assert!(!should_run_epiphany_pre_compaction_checkpoint_intervention( - &elevated - )); - assert!(should_run_epiphany_pre_compaction_checkpoint_intervention( - &high - )); - - let prompt = render_epiphany_pre_compaction_checkpoint_intervention(&high); - assert!(prompt.contains("pre-compaction checkpoint intervention")); - assert!(prompt.contains("bank the active working context")); - assert!(prompt.contains("do not continue implementation")); -} - -#[test] -fn map_epiphany_reorient_regathers_without_state() { - let pressure = map_epiphany_pressure(None); - let retrieval = ThreadEpiphanyRetrievalFreshness { - status: ThreadEpiphanyRetrievalFreshnessStatus::Missing, - semantic_available: None, - last_indexed_at_unix_seconds: None, - indexed_file_count: None, - indexed_chunk_count: None, - dirty_paths: Vec::new(), - note: "missing".to_string(), - }; - let graph = ThreadEpiphanyGraphFreshness { - status: ThreadEpiphanyGraphFreshnessStatus::Missing, - graph_freshness: None, - checkpoint_id: None, - dirty_path_count: 0, - dirty_paths: Vec::new(), - open_question_count: 0, - open_gap_count: 0, - note: "missing".to_string(), - }; - let watcher = ThreadEpiphanyInvalidationInput { - status: ThreadEpiphanyInvalidationStatus::Unavailable, - watched_root: None, - observed_at_unix_seconds: None, - changed_path_count: 0, - changed_paths: Vec::new(), - graph_node_ids: Vec::new(), - active_frontier_node_ids: Vec::new(), - note: "missing".to_string(), - }; - - let (state_status, decision) = - map_epiphany_reorient(None, &pressure, &retrieval, &graph, &watcher); - - assert_eq!(state_status, ThreadEpiphanyReorientStateStatus::Missing); - assert_eq!(decision.action, ThreadEpiphanyReorientAction::Regather); - assert_eq!( - decision.checkpoint_status, - ThreadEpiphanyReorientCheckpointStatus::Missing - ); - assert_eq!( - decision.reasons, - vec![ - ThreadEpiphanyReorientReason::MissingState, - ThreadEpiphanyReorientReason::MissingCheckpoint, - ] - ); - assert!(decision.note.contains("No Epiphany state survived")); -} - -#[test] -fn map_epiphany_reorient_resumes_when_checkpoint_is_still_aligned() { - let state = codex_protocol::protocol::EpiphanyThreadState { - revision: 7, - investigation_checkpoint: Some(codex_protocol::protocol::EpiphanyInvestigationCheckpoint { - checkpoint_id: "ix-resume".to_string(), - kind: "source_gathering".to_string(), - disposition: codex_protocol::protocol::EpiphanyInvestigationDisposition::ResumeReady, - focus: "Keep the seam visible.".to_string(), - next_action: Some("Resume from the durable checkpoint.".to_string()), - code_refs: vec![codex_protocol::protocol::EpiphanyCodeRef { - path: PathBuf::from("src/lib.rs"), - start_line: Some(1), - end_line: Some(10), - symbol: Some("resume_target".to_string()), - note: None, - }], - ..Default::default() - }), - ..Default::default() - }; - let pressure = map_epiphany_pressure(Some(&core_token_usage_info( - 1_000, - 40, - Some(200), - Some(100), - ))); - let retrieval = ThreadEpiphanyRetrievalFreshness { - status: ThreadEpiphanyRetrievalFreshnessStatus::Ready, - semantic_available: Some(true), - last_indexed_at_unix_seconds: Some(1_744_500_000), - indexed_file_count: Some(12), - indexed_chunk_count: Some(34), - dirty_paths: Vec::new(), - note: "ready".to_string(), - }; - let graph = ThreadEpiphanyGraphFreshness { - status: ThreadEpiphanyGraphFreshnessStatus::Ready, - graph_freshness: Some("fresh".to_string()), - checkpoint_id: Some("ck-1".to_string()), - dirty_path_count: 0, - dirty_paths: Vec::new(), - open_question_count: 0, - open_gap_count: 0, - note: "ready".to_string(), - }; - let watcher = ThreadEpiphanyInvalidationInput { - status: ThreadEpiphanyInvalidationStatus::Clean, - watched_root: Some(test_path_buf("/workspace")), - observed_at_unix_seconds: Some(1_744_600_000), - changed_path_count: 0, - changed_paths: Vec::new(), - graph_node_ids: Vec::new(), - active_frontier_node_ids: Vec::new(), - note: "clean".to_string(), - }; - - let (state_status, decision) = - map_epiphany_reorient(Some(&state), &pressure, &retrieval, &graph, &watcher); - - assert_eq!(state_status, ThreadEpiphanyReorientStateStatus::Ready); - assert_eq!(decision.action, ThreadEpiphanyReorientAction::Resume); - assert_eq!( - decision.checkpoint_status, - ThreadEpiphanyReorientCheckpointStatus::ResumeReady - ); - assert_eq!( - decision.reasons, - vec![ThreadEpiphanyReorientReason::CheckpointReady] - ); - assert_eq!(decision.checkpoint_id.as_deref(), Some("ix-resume")); - assert_eq!( - decision.next_action, - "Resume from the durable checkpoint.".to_string() - ); - assert!(decision.checkpoint_dirty_paths.is_empty()); - assert!(decision.checkpoint_changed_paths.is_empty()); -} - -#[test] -fn map_epiphany_reorient_regathers_when_checkpoint_paths_or_frontier_shift() { - let state = codex_protocol::protocol::EpiphanyThreadState { - revision: 9, - investigation_checkpoint: Some(codex_protocol::protocol::EpiphanyInvestigationCheckpoint { - checkpoint_id: "ix-shifted".to_string(), - kind: "slice_planning".to_string(), - disposition: codex_protocol::protocol::EpiphanyInvestigationDisposition::ResumeReady, - focus: "Map the live seam.".to_string(), - next_action: Some("Re-gather the touched source before editing.".to_string()), - code_refs: vec![codex_protocol::protocol::EpiphanyCodeRef { - path: PathBuf::from("src/lib.rs"), - start_line: Some(1), - end_line: Some(20), - symbol: Some("shifted_target".to_string()), - note: None, - }], - ..Default::default() - }), - ..Default::default() - }; - let pressure = map_epiphany_pressure(None); - let retrieval = ThreadEpiphanyRetrievalFreshness { - status: ThreadEpiphanyRetrievalFreshnessStatus::Ready, - semantic_available: Some(true), - last_indexed_at_unix_seconds: Some(1_744_500_000), - indexed_file_count: Some(12), - indexed_chunk_count: Some(34), - dirty_paths: Vec::new(), - note: "ready".to_string(), - }; - let graph = ThreadEpiphanyGraphFreshness { - status: ThreadEpiphanyGraphFreshnessStatus::Ready, - graph_freshness: Some("fresh".to_string()), - checkpoint_id: Some("ck-1".to_string()), - dirty_path_count: 0, - dirty_paths: Vec::new(), - open_question_count: 0, - open_gap_count: 0, - note: "ready".to_string(), - }; - let watcher = ThreadEpiphanyInvalidationInput { - status: ThreadEpiphanyInvalidationStatus::Changed, - watched_root: Some(test_path_buf("/workspace")), - observed_at_unix_seconds: Some(1_744_600_001), - changed_path_count: 1, - changed_paths: vec![PathBuf::from("src/lib.rs")], - graph_node_ids: vec!["shifted-target".to_string()], - active_frontier_node_ids: vec!["shifted-target".to_string()], - note: "changed".to_string(), - }; - - let (state_status, decision) = - map_epiphany_reorient(Some(&state), &pressure, &retrieval, &graph, &watcher); - - assert_eq!(state_status, ThreadEpiphanyReorientStateStatus::Ready); - assert_eq!(decision.action, ThreadEpiphanyReorientAction::Regather); - assert_eq!( - decision.checkpoint_status, - ThreadEpiphanyReorientCheckpointStatus::ResumeReady - ); - assert_eq!( - decision.reasons, - vec![ - ThreadEpiphanyReorientReason::CheckpointPathsChanged, - ThreadEpiphanyReorientReason::FrontierChanged, - ] - ); - assert_eq!( - decision.checkpoint_changed_paths, - vec![PathBuf::from("src/lib.rs")] - ); - assert_eq!( - decision.active_frontier_node_ids, - vec!["shifted-target".to_string()] - ); - assert!(decision.note.contains("Re-gather before editing")); -} - -#[test] -fn map_epiphany_scene_latest_records_preserve_newest_first_order() { - let state = codex_protocol::protocol::EpiphanyThreadState { - observations: (1..=6) - .rev() - .map(|index| codex_protocol::protocol::EpiphanyObservation { - id: format!("obs-{index}"), - summary: format!("Observation {index}"), - source_kind: "test".to_string(), - status: "ok".to_string(), - evidence_ids: vec![format!("ev-{index}")], - ..Default::default() - }) - .collect(), - recent_evidence: (1..=6) - .rev() - .map(|index| codex_protocol::protocol::EpiphanyEvidenceRecord { - id: format!("ev-{index}"), - kind: "test".to_string(), - status: "ok".to_string(), - summary: format!("Evidence {index}"), - ..Default::default() - }) - .collect(), - ..Default::default() - }; - - let scene = map_epiphany_scene(Some(&state), true, EPIPHANY_REORIENT_LAUNCH_BINDING_ID); - let observation_ids: Vec<_> = scene - .observations - .latest - .iter() - .map(|record| record.id.as_str()) - .collect(); - let evidence_ids: Vec<_> = scene - .evidence - .latest - .iter() - .map(|record| record.id.as_str()) - .collect(); - - assert_eq!( - observation_ids, - vec!["obs-6", "obs-5", "obs-4", "obs-3", "obs-2"] - ); - assert_eq!(evidence_ids, vec!["ev-6", "ev-5", "ev-4", "ev-3", "ev-2"]); -} - -#[test] -fn map_epiphany_scene_exposes_reorient_result_when_binding_exists() { - let state = codex_protocol::protocol::EpiphanyThreadState { - job_bindings: vec![codex_protocol::protocol::EpiphanyJobBinding { - id: EPIPHANY_REORIENT_LAUNCH_BINDING_ID.to_string(), - kind: codex_protocol::protocol::EpiphanyJobKind::Specialist, - scope: "reorient-guided checkpoint resume".to_string(), - owner_role: EPIPHANY_REORIENT_OWNER_ROLE.to_string(), - authority_scope: Some("epiphany.reorient.resume".to_string()), - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - blocking_reason: None, - }], - ..Default::default() - }; - - let scene = map_epiphany_scene(Some(&state), true, EPIPHANY_REORIENT_LAUNCH_BINDING_ID); - - assert!( - scene - .available_actions - .contains(&ThreadEpiphanySceneAction::ReorientResult), - "scene should advertise the reorient result read-back surface" - ); -} - -#[test] -fn map_epiphany_reorient_result_finding_projects_structured_output() { - let raw_result = serde_json::json!({ - "mode": "resume", - "summary": "Checkpoint still matches the source seam.", - "nextSafeMove": "Continue with the bounded read-back slice.", - "checkpointStillValid": true, - "filesInspected": ["src/a.rs", "src/b.rs"], - "frontierNodeIds": ["node-1"], - "evidenceIds": ["ev-1"], - "artifactRefs": ["artifact:reorient"], - "runtimeResultId": "result-1", - "runtimeJobId": "job-1", - "extra": {"left": "intact"} - }); - - let finding = - map_epiphany_reorient_finding(raw_result.clone(), Some("job warning".to_string()), None); - - assert_eq!(finding.mode.as_deref(), Some("resume")); - assert_eq!( - finding.summary.as_deref(), - Some("Checkpoint still matches the source seam.") - ); - assert_eq!( - finding.next_safe_move.as_deref(), - Some("Continue with the bounded read-back slice.") - ); - assert_eq!(finding.checkpoint_still_valid, Some(true)); - assert_eq!(finding.files_inspected, vec!["src/a.rs", "src/b.rs"]); - assert_eq!(finding.frontier_node_ids, vec!["node-1"]); - assert_eq!(finding.evidence_ids, vec!["ev-1"]); - assert_eq!(finding.artifact_refs, vec!["artifact:reorient"]); - assert_eq!(finding.runtime_result_id.as_deref(), Some("result-1")); - assert_eq!(finding.runtime_job_id.as_deref(), Some("job-1")); - assert_eq!(finding.job_error.as_deref(), Some("job warning")); -} - -#[test] -fn map_epiphany_crrc_recommendation_continues_clean_checkpoint() { - let pressure = map_epiphany_pressure(None); - let decision = ThreadEpiphanyReorientDecision { - action: ThreadEpiphanyReorientAction::Resume, - checkpoint_status: ThreadEpiphanyReorientCheckpointStatus::ResumeReady, - checkpoint_id: Some("ix-clean".to_string()), - pressure_level: pressure.level, - retrieval_status: ThreadEpiphanyRetrievalFreshnessStatus::Ready, - graph_status: ThreadEpiphanyGraphFreshnessStatus::Ready, - watcher_status: ThreadEpiphanyInvalidationStatus::Clean, - reasons: vec![ThreadEpiphanyReorientReason::CheckpointReady], - checkpoint_dirty_paths: Vec::new(), - checkpoint_changed_paths: Vec::new(), - active_frontier_node_ids: Vec::new(), - next_action: "Continue the bounded task.".to_string(), - note: "ready".to_string(), - }; - - let recommendation = map_epiphany_crrc_recommendation( - true, - ThreadEpiphanyReorientStateStatus::Ready, - &pressure, - &decision, - ThreadEpiphanyReorientResultStatus::MissingBinding, - true, - false, - false, - ); - - assert_eq!(recommendation.action, ThreadEpiphanyCrrcAction::Continue); - assert_eq!( - recommendation.recommended_scene_action, - Some(ThreadEpiphanySceneAction::Reorient) - ); -} - -#[test] -fn map_epiphany_crrc_recommendation_launches_on_regather_verdict() { - let pressure = map_epiphany_pressure(None); - let decision = ThreadEpiphanyReorientDecision { - action: ThreadEpiphanyReorientAction::Regather, - checkpoint_status: ThreadEpiphanyReorientCheckpointStatus::ResumeReady, - checkpoint_id: Some("ix-drifted".to_string()), - pressure_level: pressure.level, - retrieval_status: ThreadEpiphanyRetrievalFreshnessStatus::Ready, - graph_status: ThreadEpiphanyGraphFreshnessStatus::Stale, - watcher_status: ThreadEpiphanyInvalidationStatus::Changed, - reasons: vec![ThreadEpiphanyReorientReason::CheckpointPathsChanged], - checkpoint_dirty_paths: Vec::new(), - checkpoint_changed_paths: vec![PathBuf::from("src/lib.rs")], - active_frontier_node_ids: vec!["node-a".to_string()], - next_action: "Regather.".to_string(), - note: "drifted".to_string(), - }; - - let recommendation = map_epiphany_crrc_recommendation( - true, - ThreadEpiphanyReorientStateStatus::Ready, - &pressure, - &decision, - ThreadEpiphanyReorientResultStatus::MissingBinding, - true, - false, - false, - ); - - assert_eq!( - recommendation.action, - ThreadEpiphanyCrrcAction::LaunchReorientWorker - ); - assert_eq!( - recommendation.recommended_scene_action, - Some(ThreadEpiphanySceneAction::ReorientLaunch) - ); -} - -#[test] -fn map_epiphany_crrc_recommendation_accepts_completed_finding() { - let pressure = map_epiphany_pressure(None); - let decision = ThreadEpiphanyReorientDecision { - action: ThreadEpiphanyReorientAction::Regather, - checkpoint_status: ThreadEpiphanyReorientCheckpointStatus::RegatherRequired, - checkpoint_id: Some("ix-result".to_string()), - pressure_level: pressure.level, - retrieval_status: ThreadEpiphanyRetrievalFreshnessStatus::Ready, - graph_status: ThreadEpiphanyGraphFreshnessStatus::Ready, - watcher_status: ThreadEpiphanyInvalidationStatus::Clean, - reasons: vec![ThreadEpiphanyReorientReason::CheckpointRequestedRegather], - checkpoint_dirty_paths: Vec::new(), - checkpoint_changed_paths: Vec::new(), - active_frontier_node_ids: Vec::new(), - next_action: "Review result.".to_string(), - note: "result".to_string(), - }; - - let recommendation = map_epiphany_crrc_recommendation( - true, - ThreadEpiphanyReorientStateStatus::Ready, - &pressure, - &decision, - ThreadEpiphanyReorientResultStatus::Completed, - true, - true, - false, - ); - - assert_eq!( - recommendation.action, - ThreadEpiphanyCrrcAction::AcceptReorientResult - ); - assert_eq!( - recommendation.recommended_scene_action, - Some(ThreadEpiphanySceneAction::ReorientAccept) - ); -} - -#[test] -fn map_epiphany_crrc_recommendation_relaunches_stale_accepted_regather() { - let pressure = map_epiphany_pressure(None); - let decision = ThreadEpiphanyReorientDecision { - action: ThreadEpiphanyReorientAction::Regather, - checkpoint_status: ThreadEpiphanyReorientCheckpointStatus::RegatherRequired, - checkpoint_id: Some("ix-accepted".to_string()), - pressure_level: pressure.level, - retrieval_status: ThreadEpiphanyRetrievalFreshnessStatus::Ready, - graph_status: ThreadEpiphanyGraphFreshnessStatus::Ready, - watcher_status: ThreadEpiphanyInvalidationStatus::Clean, - reasons: vec![ThreadEpiphanyReorientReason::CheckpointRequestedRegather], - checkpoint_dirty_paths: Vec::new(), - checkpoint_changed_paths: Vec::new(), - active_frontier_node_ids: Vec::new(), - next_action: "Regather from the accepted result.".to_string(), - note: "accepted".to_string(), - }; - - let recommendation = map_epiphany_crrc_recommendation( - true, - ThreadEpiphanyReorientStateStatus::Ready, - &pressure, - &decision, - ThreadEpiphanyReorientResultStatus::Completed, - true, - true, - true, - ); - - assert_eq!( - recommendation.action, - ThreadEpiphanyCrrcAction::LaunchReorientWorker - ); - assert_eq!( - recommendation.recommended_scene_action, - Some(ThreadEpiphanySceneAction::ReorientLaunch) - ); - - let unloaded = map_epiphany_crrc_recommendation( - false, - ThreadEpiphanyReorientStateStatus::Ready, - &pressure, - &decision, - ThreadEpiphanyReorientResultStatus::Completed, - true, - true, - true, - ); - assert_eq!(unloaded.action, ThreadEpiphanyCrrcAction::RegatherManually); - assert_eq!( - unloaded.recommended_scene_action, - Some(ThreadEpiphanySceneAction::Reorient) - ); -} - -#[test] -fn map_epiphany_crrc_recommendation_continues_after_accepted_resume_finding() { - let pressure = map_epiphany_pressure(None); - let decision = ThreadEpiphanyReorientDecision { - action: ThreadEpiphanyReorientAction::Resume, - checkpoint_status: ThreadEpiphanyReorientCheckpointStatus::ResumeReady, - checkpoint_id: Some("ix-accepted-resume".to_string()), - pressure_level: pressure.level, - retrieval_status: ThreadEpiphanyRetrievalFreshnessStatus::Ready, - graph_status: ThreadEpiphanyGraphFreshnessStatus::Ready, - watcher_status: ThreadEpiphanyInvalidationStatus::Clean, - reasons: Vec::new(), - checkpoint_dirty_paths: Vec::new(), - checkpoint_changed_paths: Vec::new(), - active_frontier_node_ids: Vec::new(), - next_action: "Continue from the accepted result.".to_string(), - note: "accepted resume".to_string(), - }; - - let recommendation = map_epiphany_crrc_recommendation( - true, - ThreadEpiphanyReorientStateStatus::Ready, - &pressure, - &decision, - ThreadEpiphanyReorientResultStatus::Completed, - true, - true, - true, - ); - - assert_eq!(recommendation.action, ThreadEpiphanyCrrcAction::Continue); - assert_eq!( - recommendation.recommended_scene_action, - Some(ThreadEpiphanySceneAction::Reorient) - ); -} - -#[test] -fn map_epiphany_roles_projects_mvp_ownership_lanes() { - let state = codex_protocol::protocol::EpiphanyThreadState { - investigation_checkpoint: Some(EpiphanyInvestigationCheckpoint { - checkpoint_id: "ix-roles".to_string(), - kind: "slice_planning".to_string(), - disposition: codex_protocol::protocol::EpiphanyInvestigationDisposition::ResumeReady, - focus: "Keep roles explicit.".to_string(), - next_action: Some("Continue from the bounded checkpoint.".to_string()), - ..Default::default() - }), - ..Default::default() - }; - let pressure = map_epiphany_pressure(None); - let decision = ThreadEpiphanyReorientDecision { - action: ThreadEpiphanyReorientAction::Resume, - checkpoint_status: ThreadEpiphanyReorientCheckpointStatus::ResumeReady, - checkpoint_id: Some("ix-roles".to_string()), - pressure_level: pressure.level, - retrieval_status: ThreadEpiphanyRetrievalFreshnessStatus::Ready, - graph_status: ThreadEpiphanyGraphFreshnessStatus::Ready, - watcher_status: ThreadEpiphanyInvalidationStatus::Clean, - reasons: vec![ThreadEpiphanyReorientReason::CheckpointReady], - checkpoint_dirty_paths: Vec::new(), - checkpoint_changed_paths: Vec::new(), - active_frontier_node_ids: Vec::new(), - next_action: "Continue from the bounded checkpoint.".to_string(), - note: "ready".to_string(), - }; - let recommendation = ThreadEpiphanyCrrcRecommendation { - action: ThreadEpiphanyCrrcAction::Continue, - recommended_scene_action: Some(ThreadEpiphanySceneAction::Reorient), - reason: "Pressure is tolerable.".to_string(), - }; - let jobs = vec![ThreadEpiphanyJob { - id: "verification".to_string(), - kind: ThreadEpiphanyJobKind::Verification, - scope: "invariant verification".to_string(), - owner_role: "epiphany-verifier".to_string(), - launcher_job_id: None, - authority_scope: None, - backend_job_id: None, - status: ThreadEpiphanyJobStatus::Needed, - items_processed: None, - items_total: None, - progress_note: Some("Evidence needs review.".to_string()), - last_checkpoint_at_unix_seconds: None, - blocking_reason: None, - active_thread_ids: Vec::new(), - linked_subgoal_ids: Vec::new(), - linked_graph_node_ids: Vec::new(), - }]; - - let roles = map_epiphany_roles( - Some(&state), - &jobs, - &decision, - &pressure, - &recommendation, - ThreadEpiphanyReorientResultStatus::MissingBinding, - None, - ); - - let role_ids = roles.iter().map(|role| role.id).collect::>(); - assert_eq!( - role_ids, - vec![ - ThreadEpiphanyRoleId::Implementation, - ThreadEpiphanyRoleId::Imagination, - ThreadEpiphanyRoleId::Modeling, - ThreadEpiphanyRoleId::Verification, - ThreadEpiphanyRoleId::Reorientation, - ] - ); - assert_eq!(roles[0].status, ThreadEpiphanyRoleStatus::Ready); - assert_eq!(roles[1].status, ThreadEpiphanyRoleStatus::Needed); - assert_eq!(roles[2].status, ThreadEpiphanyRoleStatus::Ready); - assert_eq!(roles[3].status, ThreadEpiphanyRoleStatus::Needed); - assert_eq!(roles[3].jobs[0].owner_role, "epiphany-verifier"); - assert_eq!(roles[4].status, ThreadEpiphanyRoleStatus::Ready); -} - -fn base_coordinator_roles() -> Vec { - vec![ - coordinator_role( - ThreadEpiphanyRoleId::Implementation, - ThreadEpiphanyRoleStatus::Ready, - ), - coordinator_role( - ThreadEpiphanyRoleId::Imagination, - ThreadEpiphanyRoleStatus::Ready, - ), - coordinator_role( - ThreadEpiphanyRoleId::Modeling, - ThreadEpiphanyRoleStatus::Ready, - ), - coordinator_role( - ThreadEpiphanyRoleId::Verification, - ThreadEpiphanyRoleStatus::Ready, - ), - coordinator_role( - ThreadEpiphanyRoleId::Reorientation, - ThreadEpiphanyRoleStatus::Ready, - ), - ] -} - -fn coordinator_role( - id: ThreadEpiphanyRoleId, - status: ThreadEpiphanyRoleStatus, -) -> ThreadEpiphanyRoleLane { - ThreadEpiphanyRoleLane { - id, - title: format!("{id:?}"), - owner_role: format!("{id:?}"), - status, - note: "test lane".to_string(), - jobs: Vec::new(), - authority_scopes: Vec::new(), - recommended_action: None, - } -} - -fn coordinator_signals( - crrc_action: ThreadEpiphanyCrrcAction, - reorient_result_status: ThreadEpiphanyReorientResultStatus, - modeling_result_status: ThreadEpiphanyRoleResultStatus, - verification_result_status: ThreadEpiphanyRoleResultStatus, -) -> ThreadEpiphanyCoordinatorSignals { - ThreadEpiphanyCoordinatorSignals { - pressure_level: ThreadEpiphanyPressureLevel::Low, - should_prepare_compaction: false, - reorient_action: ThreadEpiphanyReorientAction::Resume, - crrc_action, - modeling_result_status, - verification_result_status, - reorient_result_status, - } -} - -#[derive(Clone, Copy)] -struct CoordinatorTestFlags { - modeling_result_accepted: bool, - modeling_result_reviewable: bool, - modeling_result_accepted_after_verification: bool, - implementation_evidence_after_verification: bool, - verification_result_cites_implementation_evidence: bool, - verification_result_covers_current_modeling: bool, - verification_result_accepted: bool, - verification_result_allows_implementation: bool, - verification_result_needs_evidence: bool, - reorient_finding_accepted: bool, -} - -impl Default for CoordinatorTestFlags { - fn default() -> Self { - Self { - modeling_result_accepted: false, - modeling_result_reviewable: false, - modeling_result_accepted_after_verification: false, - implementation_evidence_after_verification: false, - verification_result_cites_implementation_evidence: false, - verification_result_covers_current_modeling: true, - verification_result_accepted: false, - verification_result_allows_implementation: false, - verification_result_needs_evidence: false, - reorient_finding_accepted: false, - } - } -} - -fn coordinator_decision( - state_status: ThreadEpiphanyReorientStateStatus, - checkpoint_present: bool, - pressure: &ThreadEpiphanyPressure, - recommendation: &ThreadEpiphanyCrrcRecommendation, - roles: &[ThreadEpiphanyRoleLane], - signals: &ThreadEpiphanyCoordinatorSignals, - flags: CoordinatorTestFlags, -) -> EpiphanyCoordinatorDecision { - map_epiphany_coordinator( - state_status, - checkpoint_present, - pressure, - recommendation, - roles, - signals, - flags.modeling_result_accepted, - flags.modeling_result_reviewable, - flags.modeling_result_accepted_after_verification, - flags.implementation_evidence_after_verification, - flags.verification_result_cites_implementation_evidence, - flags.verification_result_covers_current_modeling, - flags.verification_result_accepted, - flags.verification_result_allows_implementation, - flags.verification_result_needs_evidence, - flags.reorient_finding_accepted, - ) -} - -#[test] -fn map_epiphany_coordinator_prepares_missing_checkpoint() { - let pressure = map_epiphany_pressure(None); - let recommendation = ThreadEpiphanyCrrcRecommendation { - action: ThreadEpiphanyCrrcAction::PrepareCheckpoint, - recommended_scene_action: Some(ThreadEpiphanySceneAction::Update), - reason: "checkpoint missing".to_string(), - }; - let roles = base_coordinator_roles(); - let signals = coordinator_signals( - ThreadEpiphanyCrrcAction::PrepareCheckpoint, - ThreadEpiphanyReorientResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ); - - let decision = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - false, - &pressure, - &recommendation, - &roles, - &signals, - CoordinatorTestFlags::default(), - ); - - assert_eq!( - decision.action, - ThreadEpiphanyCoordinatorAction::PrepareCheckpoint - ); - assert!(!decision.can_auto_run); -} - -#[test] -fn map_epiphany_coordinator_compacts_at_pressure_threshold() { - let pressure = map_epiphany_pressure(Some(&core_token_usage_info( - 1_000, - 80, - Some(200), - Some(100), - ))); - let recommendation = ThreadEpiphanyCrrcRecommendation { - action: ThreadEpiphanyCrrcAction::Continue, - recommended_scene_action: Some(ThreadEpiphanySceneAction::Reorient), - reason: "continue".to_string(), - }; - let roles = base_coordinator_roles(); - let signals = coordinator_signals( - ThreadEpiphanyCrrcAction::Continue, - ThreadEpiphanyReorientResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ); - - let decision = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &signals, - CoordinatorTestFlags::default(), - ); - - assert_eq!( - decision.action, - ThreadEpiphanyCoordinatorAction::CompactRehydrateReorient - ); - assert!(decision.can_auto_run); - assert_eq!( - map_epiphany_coordinator_automation_action(&decision), - EpiphanyCoordinatorAutomationAction::CompactRehydrateReorient - ); -} - -#[test] -fn map_epiphany_coordinator_does_not_recompact_after_accepted_resume_reorient() { - let pressure = map_epiphany_pressure(Some(&core_token_usage_info( - 1_000, - 80, - Some(200), - Some(100), - ))); - let recommendation = ThreadEpiphanyCrrcRecommendation { - action: ThreadEpiphanyCrrcAction::Continue, - recommended_scene_action: Some(ThreadEpiphanySceneAction::Reorient), - reason: "accepted resume finding".to_string(), - }; - let signals = coordinator_signals( - ThreadEpiphanyCrrcAction::Continue, - ThreadEpiphanyReorientResultStatus::Completed, - ThreadEpiphanyRoleResultStatus::BackendMissing, - ThreadEpiphanyRoleResultStatus::BackendMissing, - ); - - let decision = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &[], - &signals, - CoordinatorTestFlags { - reorient_finding_accepted: true, - ..Default::default() - }, - ); - - assert_eq!( - decision.action, - ThreadEpiphanyCoordinatorAction::ContinueImplementation - ); -} - -#[test] -fn select_epiphany_coordinator_automation_forces_checkpoint_compaction_handoff() { - let decision = EpiphanyCoordinatorDecision { - action: ThreadEpiphanyCoordinatorAction::ContinueImplementation, - target_role: Some(ThreadEpiphanyRoleId::Implementation), - recommended_scene_action: None, - requires_review: false, - can_auto_run: false, - reason: "ordinary coordinator would continue".to_string(), - }; - - assert_eq!( - map_epiphany_coordinator_automation_action(&decision), - EpiphanyCoordinatorAutomationAction::None - ); - assert_eq!( - select_epiphany_coordinator_automation_action(&decision, true), - EpiphanyCoordinatorAutomationAction::CompactRehydrateReorient - ); -} - -#[test] -fn map_epiphany_coordinator_launches_reorient_worker_from_crrc() { - let pressure = map_epiphany_pressure(None); - let recommendation = ThreadEpiphanyCrrcRecommendation { - action: ThreadEpiphanyCrrcAction::LaunchReorientWorker, - recommended_scene_action: Some(ThreadEpiphanySceneAction::ReorientLaunch), - reason: "regather".to_string(), - }; - let roles = base_coordinator_roles(); - let signals = coordinator_signals( - ThreadEpiphanyCrrcAction::LaunchReorientWorker, - ThreadEpiphanyReorientResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ); - - let decision = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &signals, - CoordinatorTestFlags::default(), - ); - - assert_eq!( - decision.action, - ThreadEpiphanyCoordinatorAction::LaunchReorientWorker - ); - assert_eq!( - decision.target_role, - Some(ThreadEpiphanyRoleId::Reorientation) - ); - assert!(decision.can_auto_run); - assert_eq!( - map_epiphany_coordinator_automation_action(&decision), - EpiphanyCoordinatorAutomationAction::LaunchReorientWorker - ); -} - -#[test] -fn map_epiphany_coordinator_reviews_reorient_result() { - let pressure = map_epiphany_pressure(None); - let recommendation = ThreadEpiphanyCrrcRecommendation { - action: ThreadEpiphanyCrrcAction::AcceptReorientResult, - recommended_scene_action: Some(ThreadEpiphanySceneAction::ReorientAccept), - reason: "review".to_string(), - }; - let roles = base_coordinator_roles(); - let signals = coordinator_signals( - ThreadEpiphanyCrrcAction::AcceptReorientResult, - ThreadEpiphanyReorientResultStatus::Completed, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ); - - let decision = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &signals, - CoordinatorTestFlags::default(), - ); - - assert_eq!( - decision.action, - ThreadEpiphanyCoordinatorAction::ReviewReorientResult - ); - assert!(decision.requires_review); - assert_eq!( - map_epiphany_coordinator_automation_action(&decision), - EpiphanyCoordinatorAutomationAction::None - ); -} - -#[test] -fn map_epiphany_coordinator_uses_fixed_lanes_before_manual_regather() { - let pressure = map_epiphany_pressure(None); - let recommendation = ThreadEpiphanyCrrcRecommendation { - action: ThreadEpiphanyCrrcAction::RegatherManually, - recommended_scene_action: Some(ThreadEpiphanySceneAction::Reorient), - reason: "checkpoint requested regather".to_string(), - }; - let roles = base_coordinator_roles(); - let missing = coordinator_signals( - ThreadEpiphanyCrrcAction::RegatherManually, - ThreadEpiphanyReorientResultStatus::Completed, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ); - - let launch_modeling = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &missing, - CoordinatorTestFlags { - reorient_finding_accepted: true, - ..Default::default() - }, - ); - assert_eq!( - launch_modeling.action, - ThreadEpiphanyCoordinatorAction::LaunchModeling - ); - - let modeling_done = coordinator_signals( - ThreadEpiphanyCrrcAction::RegatherManually, - ThreadEpiphanyReorientResultStatus::Completed, - ThreadEpiphanyRoleResultStatus::Completed, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ); - let review_modeling = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &modeling_done, - CoordinatorTestFlags { - modeling_result_reviewable: true, - reorient_finding_accepted: true, - ..Default::default() - }, - ); - assert_eq!( - review_modeling.action, - ThreadEpiphanyCoordinatorAction::ReviewModelingResult - ); - - let mut blocked_roles = base_coordinator_roles(); - blocked_roles[0].status = ThreadEpiphanyRoleStatus::Blocked; - let verifier_done = coordinator_signals( - ThreadEpiphanyCrrcAction::RegatherManually, - ThreadEpiphanyReorientResultStatus::Completed, - ThreadEpiphanyRoleResultStatus::Completed, - ThreadEpiphanyRoleResultStatus::Completed, - ); - let blocked_regather = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &blocked_roles, - &verifier_done, - CoordinatorTestFlags { - modeling_result_accepted: true, - modeling_result_accepted_after_verification: true, - verification_result_accepted: true, - verification_result_needs_evidence: true, - reorient_finding_accepted: true, - ..Default::default() - }, - ); - assert_eq!( - blocked_regather.action, - ThreadEpiphanyCoordinatorAction::RegatherManually - ); -} - -#[test] -fn map_epiphany_coordinator_runs_modeling_then_verification_then_continue() { - let pressure = map_epiphany_pressure(None); - let recommendation = ThreadEpiphanyCrrcRecommendation { - action: ThreadEpiphanyCrrcAction::Continue, - recommended_scene_action: Some(ThreadEpiphanySceneAction::Reorient), - reason: "continue".to_string(), - }; - let roles = base_coordinator_roles(); - let missing = coordinator_signals( - ThreadEpiphanyCrrcAction::Continue, - ThreadEpiphanyReorientResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ); - - let launch_modeling = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &missing, - CoordinatorTestFlags::default(), - ); - assert_eq!( - launch_modeling.action, - ThreadEpiphanyCoordinatorAction::LaunchModeling - ); - assert_eq!( - map_epiphany_coordinator_automation_action(&launch_modeling), - EpiphanyCoordinatorAutomationAction::None - ); - - let modeling_backend_unavailable = coordinator_signals( - ThreadEpiphanyCrrcAction::Continue, - ThreadEpiphanyReorientResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::BackendUnavailable, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ); - let relaunch_modeling = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &modeling_backend_unavailable, - CoordinatorTestFlags::default(), - ); - assert_eq!( - relaunch_modeling.action, - ThreadEpiphanyCoordinatorAction::LaunchModeling - ); - - let modeling_done = coordinator_signals( - ThreadEpiphanyCrrcAction::Continue, - ThreadEpiphanyReorientResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::Completed, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ); - let review_modeling = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &modeling_done, - CoordinatorTestFlags { - modeling_result_reviewable: true, - ..Default::default() - }, - ); - assert_eq!( - review_modeling.action, - ThreadEpiphanyCoordinatorAction::ReviewModelingResult - ); - assert!(review_modeling.requires_review); - - let modeling_running_with_old_verification = coordinator_signals( - ThreadEpiphanyCrrcAction::Continue, - ThreadEpiphanyReorientResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::Running, - ThreadEpiphanyRoleResultStatus::Completed, - ); - let wait_for_modeling = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &modeling_running_with_old_verification, - CoordinatorTestFlags::default(), - ); - assert_eq!( - wait_for_modeling.action, - ThreadEpiphanyCoordinatorAction::ReviewModelingResult - ); - assert!(!wait_for_modeling.requires_review); - assert!(wait_for_modeling.reason.contains("stale verification")); - - let relaunch_unreviewable_modeling = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &modeling_done, - CoordinatorTestFlags::default(), - ); - assert_eq!( - relaunch_unreviewable_modeling.action, - ThreadEpiphanyCoordinatorAction::LaunchModeling - ); - assert!(relaunch_unreviewable_modeling.reason.contains("statePatch")); - - let launch_verification = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &modeling_done, - CoordinatorTestFlags { - modeling_result_accepted: true, - modeling_result_reviewable: true, - ..Default::default() - }, - ); - assert_eq!( - launch_verification.action, - ThreadEpiphanyCoordinatorAction::LaunchVerification - ); - assert_eq!( - map_epiphany_coordinator_automation_action(&launch_verification), - EpiphanyCoordinatorAutomationAction::None - ); - - let verification_done = coordinator_signals( - ThreadEpiphanyCrrcAction::Continue, - ThreadEpiphanyReorientResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::Completed, - ThreadEpiphanyRoleResultStatus::Completed, - ); - let stale_verification = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &verification_done, - CoordinatorTestFlags { - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_covers_current_modeling: false, - ..Default::default() - }, - ); - assert_eq!( - stale_verification.action, - ThreadEpiphanyCoordinatorAction::LaunchVerification - ); - assert!( - stale_verification - .reason - .contains("currently accepted modeling") - ); - - let review_verification = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &verification_done, - CoordinatorTestFlags { - modeling_result_accepted: true, - modeling_result_reviewable: true, - ..Default::default() - }, - ); - assert_eq!( - review_verification.action, - ThreadEpiphanyCoordinatorAction::ReviewVerificationResult - ); - assert!(review_verification.requires_review); - - let accepted_non_pass_verification = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &verification_done, - CoordinatorTestFlags { - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_accepted: true, - ..Default::default() - }, - ); - assert_eq!( - accepted_non_pass_verification.action, - ThreadEpiphanyCoordinatorAction::LaunchModeling - ); - assert_eq!( - accepted_non_pass_verification.target_role, - Some(ThreadEpiphanyRoleId::Modeling) - ); - - let accepted_needs_evidence_verification = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &verification_done, - CoordinatorTestFlags { - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_accepted: true, - verification_result_needs_evidence: true, - ..Default::default() - }, - ); - assert_eq!( - accepted_needs_evidence_verification.action, - ThreadEpiphanyCoordinatorAction::ContinueImplementation - ); - assert_eq!( - accepted_needs_evidence_verification.target_role, - Some(ThreadEpiphanyRoleId::Implementation) - ); - assert!( - accepted_needs_evidence_verification - .reason - .contains("implementation evidence") - ); - - let accepted_failed_implementation_verification = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &verification_done, - CoordinatorTestFlags { - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_accepted: true, - verification_result_cites_implementation_evidence: true, - ..Default::default() - }, - ); - assert_eq!( - accepted_failed_implementation_verification.action, - ThreadEpiphanyCoordinatorAction::ContinueImplementation - ); - assert_eq!( - accepted_failed_implementation_verification.target_role, - Some(ThreadEpiphanyRoleId::Implementation) - ); - assert!( - accepted_failed_implementation_verification - .reason - .contains("bounded repair") - ); - - let implementation_after_verification = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &verification_done, - CoordinatorTestFlags { - modeling_result_accepted: true, - modeling_result_reviewable: true, - implementation_evidence_after_verification: true, - verification_result_accepted: true, - verification_result_needs_evidence: true, - ..Default::default() - }, - ); - assert_eq!( - implementation_after_verification.action, - ThreadEpiphanyCoordinatorAction::LaunchVerification - ); - assert_eq!( - implementation_after_verification.target_role, - Some(ThreadEpiphanyRoleId::Verification) - ); - assert!( - implementation_after_verification - .reason - .contains("Implementation evidence") - ); - - let accepted_verification = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &roles, - &verification_done, - CoordinatorTestFlags { - modeling_result_accepted: true, - modeling_result_reviewable: true, - verification_result_accepted: true, - verification_result_allows_implementation: true, - ..Default::default() - }, - ); - assert_eq!( - accepted_verification.action, - ThreadEpiphanyCoordinatorAction::ContinueImplementation - ); - assert!(!accepted_verification.requires_review); - - let reviewed = coordinator_signals( - ThreadEpiphanyCrrcAction::Continue, - ThreadEpiphanyReorientResultStatus::MissingBinding, - ThreadEpiphanyRoleResultStatus::BackendMissing, - ThreadEpiphanyRoleResultStatus::BackendMissing, - ); - let continue_implementation = coordinator_decision( - ThreadEpiphanyReorientStateStatus::Ready, - true, - &pressure, - &recommendation, - &[], - &reviewed, - CoordinatorTestFlags::default(), - ); - assert_eq!( - continue_implementation.action, - ThreadEpiphanyCoordinatorAction::ContinueImplementation - ); -} - -#[test] -fn epiphany_specialist_prompt_config_parses() { - let prompts = epiphany_specialist_prompt_config(); - assert!( - prompts - .shared - .persistent_memory - .contains("Ghostlight-derived memory") - ); - assert!( - prompts - .shared - .persistent_memory - .contains("First law of the lane") - ); - assert!( - prompts - .roles - .imagination - .contains("Imagination of the machine") - ); - assert!( - prompts - .roles - .imagination - .contains("Imagination improves itself") - ); - assert!(prompts.roles.modeling.contains("Body of the machine")); - assert!(prompts.roles.modeling.contains("The Body improves itself")); - assert!(prompts.roles.verification.contains("Soul of the machine")); - assert!( - prompts - .roles - .verification - .contains("The Soul improves itself") - ); - assert!(prompts.roles.research.contains("Eyes of the machine")); - assert!(prompts.roles.face.contains("Epiphany Face")); - assert!(prompts.roles.face.contains("#aquarium")); - assert!( - prompts - .roles - .research - .contains("The Eyes improve themselves") - ); - assert!( - prompts - .implementation - .continue_template - .contains("Hands of the machine") - ); - assert!( - prompts - .implementation - .continue_template - .contains("The Hands improve themselves") - ); - assert!(prompts.reorientation.resume.contains("Life across sleep")); - assert!( - prompts - .reorientation - .resume - .contains("Life improves itself") - ); - assert!( - prompts - .reorientation - .regather - .contains("Life returning after rupture") - ); - assert!( - prompts - .crrc - .pre_compaction_checkpoint_intervention - .contains("pre-compaction checkpoint intervention") - ); - - let note = render_epiphany_coordinator_note( - ThreadEpiphanyCrrcAction::Continue, - ThreadEpiphanyPressureLevel::Unknown, - ThreadEpiphanyRoleResultStatus::Completed, - ThreadEpiphanyRoleResultStatus::MissingBinding, - ThreadEpiphanyReorientResultStatus::MissingBinding, - ThreadEpiphanyCoordinatorAction::LaunchVerification, - ); - assert!(note.contains("read-only Self")); - assert!(note.contains("Epiphany Persistent Memory")); - assert!(note.contains("Self improves itself")); - assert!(note.contains("Imagination/planning")); - assert!(note.contains("Eyes/research")); - assert!(note.contains("Hands/implementation")); - assert!(note.contains("LaunchVerification")); - assert!(!note.contains("{coordinator_action}")); -} - -#[test] -fn build_epiphany_role_launch_request_uses_fixed_mvp_templates() { - let state = codex_protocol::protocol::EpiphanyThreadState { - revision: 7, - objective: Some("Keep the MVP slice reviewable.".to_string()), - active_subgoal_id: Some("sg-1".to_string()), - subgoals: vec![codex_protocol::protocol::EpiphanySubgoal { - id: "sg-1".to_string(), - title: "Role launch".to_string(), - status: "active".to_string(), - summary: None, - }], - graph_frontier: Some(codex_protocol::protocol::EpiphanyGraphFrontier { - active_node_ids: vec!["node-1".to_string()], - ..Default::default() - }), - ..Default::default() - }; - - let imagination = build_epiphany_role_launch_request( - "thr_123", - ThreadEpiphanyRoleId::Imagination, - Some(7), - Some(90), - &state, - ) - .expect("imagination should have a fixed launch template"); - assert_eq!(imagination.binding_id, EPIPHANY_IMAGINATION_ROLE_BINDING_ID); - assert_eq!(imagination.owner_role, EPIPHANY_IMAGINATION_OWNER_ROLE); - assert_eq!(imagination.authority_scope, "epiphany.role.imagination"); - let EpiphanyWorkerLaunchDocument::Role(imagination_document) = &imagination.launch_document - else { - panic!("imagination should build a role launch document"); - }; - assert_eq!(imagination_document.role_id, "imagination"); - assert!(imagination_document.planning.is_some()); - assert!( - imagination - .instruction - .contains("Epiphany Persistent Memory") - ); - assert!( - imagination - .instruction - .contains("Imagination of the machine") - ); - assert!( - imagination - .instruction - .contains("reviewable `thread/epiphany/update` patch") - ); - assert_eq!( - imagination.output_contract_id, - "epiphany.worker.role_result.v0" - ); - let imagination_schema = epiphany_role_launch_output_schema(ThreadEpiphanyRoleId::Imagination); - assert!(imagination_schema["properties"].get("selfPatch").is_some()); - assert!(imagination_schema["properties"].get("statePatch").is_some()); - assert_eq!( - imagination_schema["properties"]["statePatch"]["required"][0], - "planning" - ); - assert_eq!( - imagination_schema["properties"]["statePatch"]["properties"]["planning"]["properties"]["objective_drafts"] - ["minItems"], - 1 - ); - - let modeling = build_epiphany_role_launch_request( - "thr_123", - ThreadEpiphanyRoleId::Modeling, - Some(7), - Some(90), - &state, - ) - .expect("modeling should have a fixed launch template"); - assert_eq!(modeling.binding_id, EPIPHANY_MODELING_ROLE_BINDING_ID); - assert_eq!(modeling.owner_role, EPIPHANY_MODELING_OWNER_ROLE); - assert_eq!(modeling.authority_scope, "epiphany.role.modeling"); - assert_eq!(modeling.linked_subgoal_ids, vec!["sg-1".to_string()]); - assert_eq!(modeling.linked_graph_node_ids, vec!["node-1".to_string()]); - let EpiphanyWorkerLaunchDocument::Role(modeling_document) = &modeling.launch_document else { - panic!("modeling should build a role launch document"); - }; - assert_eq!(modeling_document.role_id, "modeling"); - assert!(modeling_document.graphs.is_some()); - assert!(modeling_document.recent_observations.is_empty()); - assert!(modeling.instruction.contains("Epiphany Persistent Memory")); - assert!(modeling.instruction.contains("Body of the machine")); - assert!(modeling.instruction.contains("coherent anatomy")); - assert!( - modeling - .instruction - .contains("`statePatch` is part of the modeling job") - ); - assert!(modeling.instruction.contains("optional `selfPatch`")); - assert_eq!( - modeling.output_contract_id, - "epiphany.worker.role_result.v0" - ); - let modeling_schema = epiphany_role_launch_output_schema(ThreadEpiphanyRoleId::Modeling); - assert!(modeling_schema["properties"].get("openQuestions").is_some()); - assert!(modeling_schema["properties"].get("selfPatch").is_some()); - assert!(modeling_schema["properties"].get("statePatch").is_some()); - assert_eq!( - modeling_schema["properties"]["statePatch"]["anyOf"][0]["required"][0], - "graphs" - ); - assert_eq!( - modeling_schema["properties"]["statePatch"]["properties"]["investigationCheckpoint"]["properties"] - ["disposition"]["enum"][0], - "resume_ready" - ); - let modeling_required = modeling_schema["required"] - .as_array() - .expect("modeling schema required fields") - .iter() - .filter_map(serde_json::Value::as_str) - .collect::>(); - assert!(modeling_required.contains(&"statePatch")); - assert!(modeling_required.contains(&"verdict")); - - let verification = build_epiphany_role_launch_request( - "thr_123", - ThreadEpiphanyRoleId::Verification, - Some(7), - Some(90), - &state, - ) - .expect("verification should have a fixed launch template"); - assert_eq!( - verification.binding_id, - EPIPHANY_VERIFICATION_ROLE_BINDING_ID - ); - assert_eq!(verification.owner_role, EPIPHANY_VERIFICATION_OWNER_ROLE); - assert_eq!(verification.authority_scope, "epiphany.role.verification"); - let EpiphanyWorkerLaunchDocument::Role(verification_document) = &verification.launch_document - else { - panic!("verification should build a role launch document"); - }; - assert_eq!(verification_document.role_id, "verification"); - assert!( - verification - .instruction - .contains("Epiphany Persistent Memory") - ); - assert!(verification.instruction.contains("Soul of the machine")); - assert!(verification.instruction.contains("falsify")); - let verification_schema = - epiphany_role_launch_output_schema(ThreadEpiphanyRoleId::Verification); - assert!( - verification_schema["properties"] - .get("evidenceGaps") - .is_some() - ); - assert!(verification_schema["properties"].get("risks").is_some()); - assert!(verification_schema["properties"].get("selfPatch").is_some()); - assert!( - verification_schema["properties"] - .get("statePatch") - .is_none() - ); -} - -#[test] -fn build_epiphany_reorient_launch_request_uses_life_template() { - let state = codex_protocol::protocol::EpiphanyThreadState { - revision: 7, - scratch: Some(codex_protocol::protocol::EpiphanyScratchPad { - summary: Some("Carry the current seam across compaction.".to_string()), - ..Default::default() - }), - graph_frontier: Some(codex_protocol::protocol::EpiphanyGraphFrontier { - active_node_ids: vec!["node-1".to_string()], - ..Default::default() - }), - ..Default::default() - }; - let checkpoint = codex_protocol::protocol::EpiphanyInvestigationCheckpoint { - checkpoint_id: "ix-1".to_string(), - kind: "source_gathering".to_string(), - disposition: codex_protocol::protocol::EpiphanyInvestigationDisposition::ResumeReady, - focus: "Resume the bounded specialist prompt pass.".to_string(), - summary: Some("The prompt seam was banked before compaction.".to_string()), - ..Default::default() - }; - let decision = ThreadEpiphanyReorientDecision { - action: ThreadEpiphanyReorientAction::Resume, - checkpoint_status: ThreadEpiphanyReorientCheckpointStatus::ResumeReady, - checkpoint_id: Some("ix-1".to_string()), - pressure_level: ThreadEpiphanyPressureLevel::Low, - retrieval_status: ThreadEpiphanyRetrievalFreshnessStatus::Ready, - graph_status: ThreadEpiphanyGraphFreshnessStatus::Ready, - watcher_status: ThreadEpiphanyInvalidationStatus::Clean, - reasons: vec![ThreadEpiphanyReorientReason::CheckpointReady], - checkpoint_dirty_paths: Vec::new(), - checkpoint_changed_paths: Vec::new(), - active_frontier_node_ids: vec!["node-1".to_string()], - next_action: "Continue after source recheck.".to_string(), - note: "Checkpoint is warm enough to resume.".to_string(), - }; - - let request = build_epiphany_reorient_launch_request( - "thr_123", - Some(7), - Some(90), - &state, - &checkpoint, - &decision, - ); - - assert_eq!(request.binding_id, EPIPHANY_REORIENT_LAUNCH_BINDING_ID); - assert_eq!(request.owner_role, EPIPHANY_REORIENT_OWNER_ROLE); - assert_eq!(request.authority_scope, "epiphany.reorient.resume"); - let EpiphanyWorkerLaunchDocument::Reorient(reorient_document) = &request.launch_document else { - panic!("reorient should build a reorient launch document"); - }; - assert_eq!( - reorient_document - .scratch - .as_ref() - .and_then(|scratch| scratch.summary.as_deref()), - Some("Carry the current seam across compaction.") - ); - assert!(reorient_document.graphs.is_some()); - assert!(reorient_document.recent_evidence.is_empty()); - assert!(reorient_document.recent_observations.is_empty()); - assert!(request.instruction.contains("Epiphany Persistent Memory")); - assert!(request.instruction.contains("Life across sleep")); - assert!(request.instruction.contains("checkpoint as the ember")); - assert_eq!( - request.output_contract_id, - "epiphany.worker.reorient_result.v0" - ); - let schema = epiphany_reorient_launch_output_schema(); - assert!(schema["properties"].get("openQuestions").is_some()); - assert!(schema["properties"].get("continuityRisks").is_some()); - - let regather_instruction = - build_epiphany_reorient_launch_instruction(ThreadEpiphanyReorientAction::Regather); - assert!(regather_instruction.contains("Life returning after rupture")); -} - -#[test] -fn build_epiphany_role_launch_request_rejects_untemplated_roles() { - let state = codex_protocol::protocol::EpiphanyThreadState::default(); - - assert!( - build_epiphany_role_launch_request( - "thr_123", - ThreadEpiphanyRoleId::Implementation, - None, - None, - &state, - ) - .unwrap_err() - .contains("main coding agent") - ); - assert!( - build_epiphany_role_launch_request( - "thr_123", - ThreadEpiphanyRoleId::Reorientation, - None, - None, - &state, - ) - .unwrap_err() - .contains("reorientLaunch") - ); -} - -#[test] -fn map_epiphany_role_finding_projects_structured_output() { - let raw_result = serde_json::json!({ - "verdict": "pass", - "summary": "The evidence covers the bounded slice.", - "nextSafeMove": "Promote after human review.", - "filesInspected": ["src/lib.rs"], - "frontierNodeIds": ["node-1"], - "evidenceIds": ["ev-1"], - "artifactRefs": ["artifact:role"], - "runtimeResultId": "result-1", - "runtimeJobId": "job-1" - }); - - let finding = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Verification, - raw_result.clone(), - None, - None, - ); - - assert_eq!(finding.role_id, ThreadEpiphanyRoleId::Verification); - assert_eq!(finding.verdict.as_deref(), Some("pass")); - assert_eq!( - finding.next_safe_move.as_deref(), - Some("Promote after human review.") - ); - assert_eq!(finding.files_inspected, vec!["src/lib.rs"]); - assert_eq!(finding.frontier_node_ids, vec!["node-1"]); - assert_eq!(finding.evidence_ids, vec!["ev-1"]); - assert_eq!(finding.artifact_refs, vec!["artifact:role"]); - assert_eq!(finding.runtime_result_id.as_deref(), Some("result-1")); - assert_eq!(finding.runtime_job_id.as_deref(), Some("job-1")); -} - -#[test] -fn map_epiphany_role_finding_reviews_acceptable_self_patch() { - let finding = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Modeling, - serde_json::json!({ - "roleId": "modeling", - "verdict": "checkpoint-ready", - "summary": "The Body learned a durable modeling lesson.", - "nextSafeMove": "Review the lane memory request.", - "statePatch": { - "scratch": { - "summary": "Source-grounded modeling checkpoint.", - "next_probe": "Run verification." - } - }, - "selfPatch": { - "agentId": "epiphany.body", - "reason": "The Body should remember graph growth must stay source-grounded and bounded.", - "semanticMemories": [ - { - "memoryId": "mem-body-source-grounded-growth", - "summary": "Grow graph and checkpoint state only when source evidence makes the anatomy harder to misread.", - "salience": 0.82, - "confidence": 0.9 - } - ] - } - }), - None, - None, - ); - - let review = finding.self_persistence.as_ref().unwrap(); - assert_eq!( - review.status, - ThreadEpiphanyRoleSelfPersistenceStatus::Accepted - ); - assert_eq!(review.target_agent_id.as_deref(), Some("epiphany.body")); - assert_eq!( - review.target_path.as_deref(), - Some("state/agents/body.agent-state.json") - ); - assert!(review.reasons.is_empty()); -} - -#[test] -fn map_epiphany_role_finding_rejects_bad_self_patch() { - let finding = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Verification, - serde_json::json!({ - "roleId": "verification", - "verdict": "needs-evidence", - "summary": "The Soul saw a bad persistence request.", - "nextSafeMove": "Ask the lane to reshape the memory request.", - "selfPatch": { - "agentId": "epiphany.body", - "reason": "Too broad.", - "graphs": {}, - "semanticMemories": [ - { - "memoryId": "mem-soul-bad-project-truth", - "summary": "Project graph state belongs in memory now.", - "salience": 0.7, - "confidence": 0.4 - } - ] - } - }), - None, - None, - ); - - let review = finding.self_persistence.as_ref().unwrap(); - assert_eq!( - review.status, - ThreadEpiphanyRoleSelfPersistenceStatus::Rejected - ); - assert_eq!(review.target_agent_id.as_deref(), Some("epiphany.soul")); - assert!( - review - .reasons - .iter() - .any(|reason| reason.contains("expected \"epiphany.soul\"")) - ); - assert!( - review - .reasons - .iter() - .any(|reason| reason.contains("project truth")) - ); -} - -#[test] -fn map_epiphany_role_finding_marks_modeling_without_patch_unreviewable() { - let missing_patch = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Modeling, - serde_json::json!({ - "roleId": "modeling", - "verdict": "checkpoint-ready", - "summary": "Source was inspected, but nothing durable was banked.", - "nextSafeMove": "Relaunch modeling with a state patch." - }), - None, - None, - ); - - assert!(missing_patch.state_patch.is_none()); - assert!( - missing_patch - .item_error - .as_deref() - .is_some_and(|error| error.contains("missing required statePatch")) - ); - assert!(!epiphany_modeling_finding_has_reviewable_state_patch( - &missing_patch - )); - - let reviewable = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Modeling, - serde_json::json!({ - "roleId": "modeling", - "verdict": "checkpoint-ready", - "summary": "The checkpoint is banked in scratch.", - "nextSafeMove": "Review the modeling patch.", - "statePatch": { - "scratch": { - "summary": "Source-grounded modeling checkpoint.", - "hypothesis": "The current graph remains coherent.", - "next_probe": "Run verification." - } - } - }), - None, - None, - ); - - assert!(reviewable.item_error.is_none()); - assert!(epiphany_modeling_finding_has_reviewable_state_patch( - &reviewable - )); - - let invalid_checkpoint_enum = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Modeling, - serde_json::json!({ - "roleId": "modeling", - "verdict": "checkpoint-ready", - "summary": "The checkpoint enum used the verdict spelling.", - "nextSafeMove": "Use the typed checkpoint enum.", - "statePatch": { - "investigationCheckpoint": { - "checkpoint_id": "ix-1", - "kind": "source_gathering", - "disposition": "checkpoint_ready", - "focus": "Model the seam." - } - } - }), - None, - None, - ); - assert!( - invalid_checkpoint_enum - .item_error - .as_deref() - .is_some_and(|error| error.contains("checkpoint_ready")) - ); - assert!(!epiphany_modeling_finding_has_reviewable_state_patch( - &invalid_checkpoint_enum - )); -} - -#[test] -fn map_epiphany_role_finding_marks_imagination_without_planning_patch_unreviewable() { - let missing_patch = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Imagination, - serde_json::json!({ - "roleId": "imagination", - "verdict": "draft-ready", - "summary": "A plan was described but no durable planning patch was returned.", - "nextSafeMove": "Relaunch imagination with a state patch." - }), - None, - None, - ); - - assert!(missing_patch.state_patch.is_none()); - assert!( - missing_patch - .item_error - .as_deref() - .is_some_and(|error| error.contains("missing required statePatch")) - ); - assert!(!epiphany_imagination_finding_has_reviewable_state_patch( - &missing_patch - )); - - let reviewable = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Imagination, - serde_json::json!({ - "roleId": "imagination", - "verdict": "draft-ready", - "summary": "Planning material was synthesized into a draft objective.", - "nextSafeMove": "Review and optionally adopt the draft.", - "statePatch": { - "planning": { - "captures": [ - { - "id": "capture-imagination-test", - "title": "Planning source", - "confidence": "medium", - "status": "triaged", - "source": {"kind": "chat", "uri": "codex://threads/test"} - } - ], - "backlog_items": [ - { - "id": "backlog-imagination-test", - "title": "Synthesized planning seam", - "kind": "feature", - "summary": "Prove Imagination can bank a reviewable objective draft.", - "status": "ready", - "horizon": "near", - "priority": {"value": "medium", "rationale": "Smoke coverage"}, - "confidence": "medium", - "product_area": "planning", - "source_refs": [{"kind": "chat", "uri": "codex://threads/test"}] - } - ], - "objective_drafts": [ - { - "id": "draft-imagination-test", - "title": "Review Imagination patch", - "summary": "Accept a planning-only role patch after review.", - "source_item_ids": ["backlog-imagination-test"], - "scope": { - "includes": ["planning"], - "excludes": ["objective adoption", "implementation"] - }, - "acceptance_criteria": ["A planning patch can be accepted without adopting the draft."], - "evidence_required": ["role finding"], - "lane_plan": {"imagination": "synthesize", "soul": "review"}, - "risks": ["accidental adoption"], - "review_gates": ["human adoption review"], - "status": "draft" - } - ] - } - } - }), - None, - None, - ); - - assert!(reviewable.item_error.is_none()); - assert!(epiphany_imagination_finding_has_reviewable_state_patch( - &reviewable - )); - - let missing_review_gate = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Imagination, - serde_json::json!({ - "roleId": "imagination", - "verdict": "draft-ready", - "summary": "The draft forgot its gate.", - "nextSafeMove": "Add review gates before accepting.", - "statePatch": { - "planning": { - "objective_drafts": [ - { - "id": "draft-no-gate", - "title": "Ungated draft", - "summary": "This must not be accepted.", - "scope": {}, - "acceptance_criteria": ["It has criteria."], - "lane_plan": {}, - "status": "draft" - } - ] - } - } - }), - None, - None, - ); - assert!( - missing_review_gate - .item_error - .as_deref() - .is_some_and(|error| error.contains("review gates")) - ); - assert!(!epiphany_imagination_finding_has_reviewable_state_patch( - &missing_review_gate - )); -} - -#[test] -fn role_finding_accepted_after_uses_newest_first_evidence_order() { - let modeling = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Modeling, - serde_json::json!({ - "roleId": "modeling", - "verdict": "checkpoint-update-needed", - "summary": "Newer modeling checkpoint.", - "nextSafeMove": "Verify the new model.", - "runtimeResultId": "runtime-result-modeling-new", - "runtimeJobId": "runtime-job-modeling-new", - "statePatch": { - "scratch": { - "summary": "New model.", - "next_probe": "Verify." - } - } - }), - None, - None, - ); - let verification = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Verification, - serde_json::json!({ - "roleId": "verification", - "verdict": "needs-evidence", - "summary": "Older verification finding.", - "nextSafeMove": "Strengthen modeling.", - "runtimeResultId": "runtime-result-verification-old", - "runtimeJobId": "runtime-job-verification-old" - }), - None, - None, - ); - let state = EpiphanyThreadState { - acceptance_receipts: vec![ - EpiphanyAcceptanceReceipt { - id: "accept-modeling-new".to_string(), - result_id: "runtime-result-modeling-new".to_string(), - job_id: "runtime-job-modeling-new".to_string(), - binding_id: "modeling".to_string(), - surface: "roleAccept".to_string(), - role_id: "modeling".to_string(), - status: "accepted".to_string(), - accepted_at: "2026-05-12T00:00:01Z".to_string(), - accepted_observation_id: Some("obs-modeling-new".to_string()), - accepted_evidence_id: Some("ev-modeling-new".to_string()), - summary: Some("Newer modeling checkpoint.".to_string()), - }, - EpiphanyAcceptanceReceipt { - id: "accept-verification-old".to_string(), - result_id: "runtime-result-verification-old".to_string(), - job_id: "runtime-job-verification-old".to_string(), - binding_id: "verification".to_string(), - surface: "roleAccept".to_string(), - role_id: "verification".to_string(), - status: "accepted".to_string(), - accepted_at: "2026-05-12T00:00:00Z".to_string(), - accepted_observation_id: Some("obs-verification-old".to_string()), - accepted_evidence_id: Some("ev-verification-old".to_string()), - summary: Some("Older verification finding.".to_string()), - }, - ], - recent_evidence: vec![ - EpiphanyEvidenceRecord { - id: "ev-modeling-new".to_string(), - kind: "modeling_result".to_string(), - status: "accepted".to_string(), - summary: role_finding_summary(&modeling), - ..Default::default() - }, - EpiphanyEvidenceRecord { - id: "ev-verification-old".to_string(), - kind: "verification_result".to_string(), - status: "accepted".to_string(), - summary: role_finding_summary(&verification), - ..Default::default() - }, - ], - ..Default::default() - }; - - assert!(role_finding_accepted_after( - &state, - Some(&modeling), - Some(&verification) - )); - assert!(!role_finding_accepted_after( - &state, - Some(&verification), - Some(&modeling) - )); -} - -#[test] -fn role_finding_acceptance_prefers_runtime_result_receipt() { - let modeling = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Modeling, - serde_json::json!({ - "roleId": "modeling", - "verdict": "checkpoint-ready", - "summary": "Runtime receipt owns identity.", - "nextSafeMove": "Verify from the receipt.", - "runtimeResultId": "runtime-result-1", - "runtimeJobId": "runtime-job-1", - "statePatch": { - "scratch": { - "summary": "Receipt-backed model.", - "next_probe": "Verify." - } - } - }), - None, - None, - ); - let state = EpiphanyThreadState { - acceptance_receipts: vec![EpiphanyAcceptanceReceipt { - id: "accept-modeling-runtime-result-1".to_string(), - result_id: "runtime-result-1".to_string(), - job_id: "runtime-job-1".to_string(), - binding_id: "modeling".to_string(), - surface: "roleAccept".to_string(), - role_id: "modeling".to_string(), - status: "accepted".to_string(), - accepted_at: "2026-05-12T00:00:00Z".to_string(), - accepted_observation_id: Some("obs-modeling".to_string()), - accepted_evidence_id: Some("ev-modeling".to_string()), - summary: Some("Summary text can drift without owning identity.".to_string()), - }], - recent_evidence: vec![EpiphanyEvidenceRecord { - id: "ev-modeling".to_string(), - kind: "modeling_result".to_string(), - status: "accepted".to_string(), - summary: "Different summary; receipt should still match.".to_string(), - ..Default::default() - }], - ..Default::default() - }; - - assert!(epiphany_role_finding_already_accepted(&state, &modeling)); - assert_eq!( - epiphany_role_finding_accepted_evidence_id(&state, &modeling).as_deref(), - Some("ev-modeling") - ); -} - -#[test] -fn verification_coverage_accepts_modeling_source_evidence_ids() { - let modeling = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Modeling, - serde_json::json!({ - "roleId": "modeling", - "verdict": "checkpoint-update-needed", - "summary": "Modeling found the source seam.", - "nextSafeMove": "Verify the modeled seam.", - "evidenceIds": ["ev-model-source"], - "runtimeResultId": "runtime-result-model-source", - "runtimeJobId": "runtime-job-model-source", - "statePatch": { - "scratch": { - "summary": "Modeling checkpoint.", - "next_probe": "Verify." - } - } - }), - None, - None, - ); - let verification = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Verification, - serde_json::json!({ - "roleId": "verification", - "verdict": "needs-evidence", - "summary": "Verification covered the modeler's source evidence.", - "nextSafeMove": "Gather implementation evidence.", - "evidenceIds": ["ev-model-source"] - }), - None, - None, - ); - let stale_verification = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Verification, - serde_json::json!({ - "roleId": "verification", - "verdict": "needs-evidence", - "summary": "Verification covered unrelated evidence.", - "nextSafeMove": "Gather implementation evidence.", - "evidenceIds": ["ev-other"] - }), - None, - None, - ); - let state = EpiphanyThreadState { - acceptance_receipts: vec![EpiphanyAcceptanceReceipt { - id: "accept-modeling-source".to_string(), - result_id: "runtime-result-model-source".to_string(), - job_id: "runtime-job-model-source".to_string(), - binding_id: "modeling".to_string(), - surface: "roleAccept".to_string(), - role_id: "modeling".to_string(), - status: "accepted".to_string(), - accepted_at: "2026-05-12T00:00:00Z".to_string(), - accepted_observation_id: Some("obs-modeling-accepted".to_string()), - accepted_evidence_id: Some("ev-modeling-accepted".to_string()), - summary: Some("Modeling found the source seam.".to_string()), - }], - recent_evidence: vec![EpiphanyEvidenceRecord { - id: "ev-modeling-accepted".to_string(), - kind: "modeling_result".to_string(), - status: "accepted".to_string(), - summary: role_finding_summary(&modeling), - ..Default::default() - }], - ..Default::default() - }; - - assert!(epiphany_verification_finding_covers_current_modeling( - &state, - true, - Some(&modeling), - Some(&verification) - )); - assert!(epiphany_verification_finding_covers_current_modeling( - &state, - true, - Some(&modeling), - Some(&map_epiphany_role_finding( - ThreadEpiphanyRoleId::Verification, - serde_json::json!({ - "roleId": "verification", - "verdict": "needs-evidence", - "summary": "Verification covered the accepted wrapper evidence.", - "nextSafeMove": "Gather implementation evidence.", - "evidenceIds": ["ev-modeling-accepted"] - }), - None, - None, - )) - )); - assert!(!epiphany_verification_finding_covers_current_modeling( - &state, - true, - Some(&modeling), - Some(&stale_verification) - )); -} - -#[test] -fn implementation_evidence_after_verification_uses_latest_audit() { - let verification = map_epiphany_role_finding( - ThreadEpiphanyRoleId::Verification, - serde_json::json!({ - "roleId": "verification", - "verdict": "needs-evidence", - "summary": "Need implementation evidence.", - "nextSafeMove": "Gather evidence." - }), - None, - None, - ); - let mut state = EpiphanyThreadState { - recent_evidence: vec![ - EpiphanyEvidenceRecord { - id: "ev-implementation-blocked".to_string(), - kind: "implementation-audit".to_string(), - status: "blocked".to_string(), - summary: "No new diff.".to_string(), - ..Default::default() - }, - EpiphanyEvidenceRecord { - id: "ev-implementation-ok".to_string(), - kind: "implementation-audit".to_string(), - status: "ok".to_string(), - summary: "Older diff.".to_string(), - ..Default::default() - }, - EpiphanyEvidenceRecord { - id: "ev-verification".to_string(), - kind: "verification_result".to_string(), - status: "accepted".to_string(), - summary: role_finding_summary(&verification), - ..Default::default() - }, - ], - ..Default::default() - }; - - assert!(!implementation_evidence_after_role_finding( - &state, - Some(&verification) - )); - state.recent_evidence[0].status = "ok".to_string(); - assert!(implementation_evidence_after_role_finding( - &state, - Some(&verification) - )); -} - -#[test] -fn reorient_finding_acceptance_builds_scratch_and_checkpoint_update() { - let finding = ThreadEpiphanyReorientFinding { - mode: Some("regather".to_string()), - summary: Some("The old checkpoint no longer matches source.".to_string()), - next_safe_move: Some("Re-read src/lib.rs before editing.".to_string()), - checkpoint_still_valid: Some(false), - files_inspected: vec!["src/lib.rs".to_string()], - frontier_node_ids: vec!["node-1".to_string()], - evidence_ids: Vec::new(), - artifact_refs: Vec::new(), - runtime_result_id: None, - runtime_job_id: None, - job_error: None, - item_error: None, - }; - - let scratch = reorient_finding_scratch("reorient-worker", &finding); - assert_eq!( - scratch.summary.as_deref(), - Some("The old checkpoint no longer matches source.") - ); - assert_eq!( - scratch.next_probe.as_deref(), - Some("Re-read src/lib.rs before editing.") - ); - assert!( - scratch - .hypothesis - .as_deref() - .is_some_and(|text| text.contains("checkpoint validity is invalid")) - ); - - let checkpoint = EpiphanyInvestigationCheckpoint { - checkpoint_id: "ix-1".to_string(), - kind: "source_gathering".to_string(), - disposition: EpiphanyInvestigationDisposition::ResumeReady, - focus: "Old focus".to_string(), - ..Default::default() - }; - let code_refs = reorient_finding_code_refs(&finding); - let updated = reorient_finding_investigation_checkpoint( - &checkpoint, - "ev-reorient-1", - &code_refs, - &finding, - ); - - assert_eq!( - updated.disposition, - EpiphanyInvestigationDisposition::ResumeReady - ); - assert_eq!(updated.evidence_ids, vec!["ev-reorient-1"]); - assert_eq!(updated.code_refs[0].path, PathBuf::from("src/lib.rs")); - assert_eq!( - updated.next_action.as_deref(), - Some("Re-read src/lib.rs before editing.") - ); -} - -#[test] -fn map_epiphany_context_projects_targeted_shard_without_mutation() { - let state = codex_protocol::protocol::EpiphanyThreadState { - revision: 7, - graphs: codex_protocol::protocol::EpiphanyGraphs { - architecture: codex_protocol::protocol::EpiphanyGraph { - nodes: vec![ - codex_protocol::protocol::EpiphanyGraphNode { - id: "active-node".to_string(), - title: "Active node".to_string(), - purpose: "Current frontier focus".to_string(), - ..Default::default() - }, - codex_protocol::protocol::EpiphanyGraphNode { - id: "manual-node".to_string(), - title: "Manual node".to_string(), - purpose: "Explicit context selector".to_string(), - ..Default::default() - }, - codex_protocol::protocol::EpiphanyGraphNode { - id: "ignored-node".to_string(), - title: "Ignored node".to_string(), - purpose: "Outside the requested shard".to_string(), - ..Default::default() - }, - ], - edges: vec![ - codex_protocol::protocol::EpiphanyGraphEdge { - id: Some("edge-active".to_string()), - source_id: "active-node".to_string(), - target_id: "ignored-node".to_string(), - kind: "frontier".to_string(), - ..Default::default() - }, - codex_protocol::protocol::EpiphanyGraphEdge { - id: Some("edge-manual".to_string()), - source_id: "manual-node".to_string(), - target_id: "active-node".to_string(), - kind: "selected".to_string(), - ..Default::default() - }, - ], - }, - dataflow: codex_protocol::protocol::EpiphanyGraph { - nodes: vec![codex_protocol::protocol::EpiphanyGraphNode { - id: "data-node".to_string(), - title: "Data node".to_string(), - purpose: "Linked dataflow context".to_string(), - ..Default::default() - }], - edges: Vec::new(), - }, - links: vec![codex_protocol::protocol::EpiphanyGraphLink { - dataflow_node_id: "data-node".to_string(), - architecture_node_id: "active-node".to_string(), - relationship: Some("supports".to_string()), - code_refs: Vec::new(), - }], - }, - graph_frontier: Some(codex_protocol::protocol::EpiphanyGraphFrontier { - active_node_ids: vec!["active-node".to_string()], - active_edge_ids: vec!["edge-active".to_string()], - ..Default::default() - }), - graph_checkpoint: Some(codex_protocol::protocol::EpiphanyGraphCheckpoint { - checkpoint_id: "ck-context".to_string(), - graph_revision: 7, - summary: Some("Context shard checkpoint".to_string()), - ..Default::default() - }), - investigation_checkpoint: Some(codex_protocol::protocol::EpiphanyInvestigationCheckpoint { - checkpoint_id: "ix-context".to_string(), - kind: "source_gathering".to_string(), - focus: "Trace the exact reflection seam.".to_string(), - next_action: Some("Re-gather source before editing if this goes stale.".to_string()), - evidence_ids: vec!["ev-linked".to_string()], - ..Default::default() - }), - observations: vec![codex_protocol::protocol::EpiphanyObservation { - id: "obs-1".to_string(), - summary: "Observation carries linked evidence.".to_string(), - source_kind: "test".to_string(), - status: "ok".to_string(), - evidence_ids: vec!["ev-linked".to_string()], - ..Default::default() - }], - recent_evidence: vec![ - codex_protocol::protocol::EpiphanyEvidenceRecord { - id: "ev-linked".to_string(), - kind: "test".to_string(), - status: "ok".to_string(), - summary: "Linked from observation.".to_string(), - ..Default::default() - }, - codex_protocol::protocol::EpiphanyEvidenceRecord { - id: "ev-extra".to_string(), - kind: "review".to_string(), - status: "ok".to_string(), - summary: "Requested directly.".to_string(), - ..Default::default() - }, - ], - ..Default::default() - }; - - let params = ThreadEpiphanyContextParams { - thread_id: "thr_123".to_string(), - graph_node_ids: vec!["manual-node".to_string(), "missing-node".to_string()], - graph_edge_ids: vec!["edge-manual".to_string(), "missing-edge".to_string()], - observation_ids: vec!["obs-1".to_string(), "obs-missing".to_string()], - evidence_ids: vec!["ev-extra".to_string(), "ev-missing".to_string()], - include_active_frontier: None, - include_linked_evidence: None, - }; - - let (state_status, state_revision, context, missing) = - map_epiphany_context(Some(&state), ¶ms); - - assert_eq!(state_status, ThreadEpiphanyContextStateStatus::Ready); - assert_eq!(state_revision, Some(7)); - assert_eq!( - context - .graph - .architecture_nodes - .iter() - .map(|node| node.id.as_str()) - .collect::>(), - vec!["active-node", "manual-node"] - ); - assert_eq!( - context - .graph - .architecture_edges - .iter() - .filter_map(|edge| edge.id.as_deref()) - .collect::>(), - vec!["edge-active", "edge-manual"] - ); - assert_eq!(context.graph.links.len(), 1); - assert_eq!( - context - .frontier - .as_ref() - .map(|frontier| frontier.active_node_ids.as_slice()), - Some(&["active-node".to_string()][..]) - ); - assert_eq!( - context - .checkpoint - .as_ref() - .map(|checkpoint| checkpoint.checkpoint_id.as_str()), - Some("ck-context") - ); - assert_eq!( - context - .investigation_checkpoint - .as_ref() - .map(|checkpoint| checkpoint.checkpoint_id.as_str()), - Some("ix-context") - ); - assert_eq!( - context - .observations - .iter() - .map(|observation| observation.id.as_str()) - .collect::>(), - vec!["obs-1"] - ); - assert_eq!( - context - .evidence - .iter() - .map(|evidence| evidence.id.as_str()) - .collect::>(), - vec!["ev-linked", "ev-extra"] - ); - assert_eq!(missing.graph_node_ids, vec!["missing-node".to_string()]); - assert_eq!(missing.graph_edge_ids, vec!["missing-edge".to_string()]); - assert_eq!(missing.observation_ids, vec!["obs-missing".to_string()]); - assert_eq!(missing.evidence_ids, vec!["ev-missing".to_string()]); -} - -#[test] -fn map_epiphany_context_reports_missing_state_without_inventing_context() { - let params = ThreadEpiphanyContextParams { - thread_id: "thr_123".to_string(), - graph_node_ids: vec!["node-1".to_string()], - graph_edge_ids: Vec::new(), - observation_ids: vec!["obs-1".to_string()], - evidence_ids: Vec::new(), - include_active_frontier: None, - include_linked_evidence: None, - }; - - let (state_status, state_revision, context, missing) = map_epiphany_context(None, ¶ms); - - assert_eq!(state_status, ThreadEpiphanyContextStateStatus::Missing); - assert_eq!(state_revision, None); - assert_eq!(context, ThreadEpiphanyContext::default()); - assert_eq!(missing.graph_node_ids, vec!["node-1".to_string()]); - assert_eq!(missing.observation_ids, vec!["obs-1".to_string()]); -} - -#[test] -fn map_epiphany_planning_projects_counts_without_mutation() { - let github_source = codex_protocol::protocol::EpiphanyPlanningSourceRef { - kind: "github_issue".to_string(), - provider: Some("github".to_string()), - repo: Some("GameCult/Epiphany".to_string()), - issue_number: Some(7), - ..Default::default() - }; - let state = codex_protocol::protocol::EpiphanyThreadState { - revision: 12, - objective: Some("Current adopted objective".to_string()), - planning: codex_protocol::protocol::EpiphanyPlanningState { - captures: vec![ - codex_protocol::protocol::EpiphanyPlanningCapture { - id: "capture-gh-7".to_string(), - title: "GitHub issue import".to_string(), - confidence: "medium".to_string(), - status: "new".to_string(), - source: github_source.clone(), - ..Default::default() - }, - codex_protocol::protocol::EpiphanyPlanningCapture { - id: "capture-chat-1".to_string(), - title: "Human planning note".to_string(), - confidence: "low".to_string(), - status: "triaged".to_string(), - source: codex_protocol::protocol::EpiphanyPlanningSourceRef { - kind: "chat".to_string(), - ..Default::default() - }, - ..Default::default() - }, - ], - backlog_items: vec![codex_protocol::protocol::EpiphanyBacklogItem { - id: "backlog-planning-view".to_string(), - title: "Build planning view".to_string(), - kind: "feature".to_string(), - summary: "Expose planning state to the GUI.".to_string(), - status: "ready".to_string(), - horizon: "now".to_string(), - priority: codex_protocol::protocol::EpiphanyPlanningPriority { - value: "p1".to_string(), - rationale: "Needed before planning can be operated.".to_string(), - ..Default::default() - }, - confidence: "high".to_string(), - product_area: "gui".to_string(), - source_refs: vec![github_source], - ..Default::default() - }], - roadmap_streams: vec![codex_protocol::protocol::EpiphanyRoadmapStream { - id: "stream-gui".to_string(), - title: "GUI Operator Surface".to_string(), - purpose: "Let the human inspect and steer Epiphany.".to_string(), - status: "active".to_string(), - item_ids: vec!["backlog-planning-view".to_string()], - ..Default::default() - }], - objective_drafts: vec![codex_protocol::protocol::EpiphanyObjectiveDraft { - id: "objdraft-planning-view".to_string(), - title: "Build planning view slice".to_string(), - summary: "Render typed planning state in the GUI.".to_string(), - source_item_ids: vec!["backlog-planning-view".to_string()], - acceptance_criteria: vec!["Planning counts render.".to_string()], - status: "draft".to_string(), - ..Default::default() - }], - ..Default::default() - }, - ..Default::default() - }; - - let (state_status, state_revision, planning, summary) = map_epiphany_planning(Some(&state)); - - assert_eq!(state_status, ThreadEpiphanyContextStateStatus::Ready); - assert_eq!(state_revision, Some(12)); - assert_eq!(planning.captures.len(), 2); - assert_eq!(summary.capture_count, 2); - assert_eq!(summary.pending_capture_count, 1); - assert_eq!(summary.github_issue_capture_count, 1); - assert_eq!(summary.backlog_item_count, 1); - assert_eq!(summary.ready_backlog_item_count, 1); - assert_eq!(summary.roadmap_stream_count, 1); - assert_eq!(summary.objective_draft_count, 1); - assert_eq!(summary.draft_objective_count, 1); - assert_eq!( - summary.active_objective.as_deref(), - Some("Current adopted objective") - ); - assert!( - summary - .note - .contains("planning state only until a human explicitly adopts") - ); -} - -#[test] -fn map_epiphany_planning_reports_missing_state_without_inventing_backlog() { - let (state_status, state_revision, planning, summary) = map_epiphany_planning(None); - - assert_eq!(state_status, ThreadEpiphanyContextStateStatus::Missing); - assert_eq!(state_revision, None); - assert!(planning.is_empty()); - assert_eq!(summary.capture_count, 0); - assert_eq!(summary.backlog_item_count, 0); - assert_eq!(summary.active_objective, None); -} - -#[test] -fn map_epiphany_graph_query_returns_frontier_neighborhood() { - let state = codex_protocol::protocol::EpiphanyThreadState { - revision: 3, - graphs: codex_protocol::protocol::EpiphanyGraphs { - architecture: codex_protocol::protocol::EpiphanyGraph { - nodes: vec![ - codex_protocol::protocol::EpiphanyGraphNode { - id: "operator-console".to_string(), - title: "Operator console".to_string(), - purpose: "Expose bounded controls.".to_string(), - code_refs: vec![codex_protocol::protocol::EpiphanyCodeRef { - path: PathBuf::from("apps/epiphany-gui/src/App.tsx"), - symbol: Some("App".to_string()), - ..Default::default() - }], - ..Default::default() - }, - codex_protocol::protocol::EpiphanyGraphNode { - id: "action-bridge".to_string(), - title: "Action bridge".to_string(), - purpose: "Call app-server APIs.".to_string(), - ..Default::default() - }, - ], - edges: vec![codex_protocol::protocol::EpiphanyGraphEdge { - id: Some("edge-console-bridge".to_string()), - source_id: "operator-console".to_string(), - target_id: "action-bridge".to_string(), - kind: "invokes".to_string(), - ..Default::default() - }], - }, - dataflow: codex_protocol::protocol::EpiphanyGraph { - nodes: vec![codex_protocol::protocol::EpiphanyGraphNode { - id: "operator-action-flow".to_string(), - title: "Operator action flow".to_string(), - purpose: "Button to Tauri to Python to app-server.".to_string(), - ..Default::default() - }], - edges: Vec::new(), - }, - links: vec![codex_protocol::protocol::EpiphanyGraphLink { - dataflow_node_id: "operator-action-flow".to_string(), - architecture_node_id: "operator-console".to_string(), - relationship: Some("starts-at".to_string()), - code_refs: Vec::new(), - }], - }, - graph_frontier: Some(codex_protocol::protocol::EpiphanyGraphFrontier { - active_node_ids: vec!["operator-console".to_string()], - ..Default::default() - }), - ..Default::default() - }; - - let query = ThreadEpiphanyGraphQuery { - kind: ThreadEpiphanyGraphQueryKind::FrontierNeighborhood, - node_ids: Vec::new(), - edge_ids: Vec::new(), - paths: Vec::new(), - symbols: Vec::new(), - edge_kinds: Vec::new(), - direction: Some(ThreadEpiphanyGraphQueryDirection::Outgoing), - depth: Some(1), - include_links: None, - }; - - let (state_status, state_revision, graph, frontier, _checkpoint, matched, missing) = - map_epiphany_graph_query(Some(&state), &query); - - assert_eq!(state_status, ThreadEpiphanyContextStateStatus::Ready); - assert_eq!(state_revision, Some(3)); - assert_eq!( - graph - .architecture_nodes - .iter() - .map(|node| node.id.as_str()) - .collect::>(), - vec!["operator-console", "action-bridge"] - ); - assert_eq!( - graph - .dataflow_nodes - .iter() - .map(|node| node.id.as_str()) - .collect::>(), - vec!["operator-action-flow"] - ); - assert_eq!( - graph - .architecture_edges - .iter() - .filter_map(|edge| edge.id.as_deref()) - .collect::>(), - vec!["edge-console-bridge"] - ); - assert_eq!(graph.links.len(), 1); - assert_eq!( - frontier - .as_ref() - .map(|frontier| frontier.active_node_ids.as_slice()), - Some(&["operator-console".to_string()][..]) - ); - assert_eq!(matched.edge_ids, vec!["edge-console-bridge".to_string()]); - assert!(missing.node_ids.is_empty()); - assert!(missing.edge_ids.is_empty()); -} - -#[test] -fn map_epiphany_jobs_reflects_current_progress_without_scheduling_work() { - let state = codex_protocol::protocol::EpiphanyThreadState { - active_subgoal_id: Some("phase-6".to_string()), - invariants: vec![ - codex_protocol::protocol::EpiphanyInvariant { - id: "inv-ready".to_string(), - description: "State reads are read-only".to_string(), - status: "ok".to_string(), - rationale: None, - }, - codex_protocol::protocol::EpiphanyInvariant { - id: "inv-review".to_string(), - description: "Job state needs review".to_string(), - status: "needs_review".to_string(), - rationale: None, - }, - ], - graph_frontier: Some(codex_protocol::protocol::EpiphanyGraphFrontier { - active_node_ids: vec!["retrieval".to_string()], - active_edge_ids: Vec::new(), - open_question_ids: vec!["q-jobs".to_string()], - open_gap_ids: Vec::new(), - dirty_paths: vec![PathBuf::from("notes/jobs.md")], - }), - retrieval: Some(codex_protocol::protocol::EpiphanyRetrievalState { - workspace_root: test_path_buf("/repo"), - status: codex_protocol::protocol::EpiphanyRetrievalStatus::Stale, - indexed_file_count: Some(12), - indexed_chunk_count: Some(34), - last_indexed_at_unix_seconds: Some(1_744_500_100), - dirty_paths: vec![PathBuf::from("src/lib.rs")], - ..Default::default() - }), - churn: Some(codex_protocol::protocol::EpiphanyChurnState { - graph_freshness: Some("stale".to_string()), - ..Default::default() - }), - ..Default::default() - }; - - let jobs = map_epiphany_jobs(Some(&state), None); - - assert_eq!(jobs.len(), 3); - assert_eq!(jobs[0].id, "retrieval-index"); - assert_eq!(jobs[0].kind, ThreadEpiphanyJobKind::Indexing); - assert_eq!(jobs[0].status, ThreadEpiphanyJobStatus::Needed); - assert_eq!(jobs[0].items_processed, Some(12)); - assert_eq!(jobs[0].last_checkpoint_at_unix_seconds, Some(1_744_500_100)); - assert_eq!(jobs[0].linked_subgoal_ids, vec!["phase-6".to_string()]); - assert_eq!(jobs[0].linked_graph_node_ids, vec!["retrieval".to_string()]); - - assert_eq!(jobs[1].id, "graph-remap"); - assert_eq!(jobs[1].kind, ThreadEpiphanyJobKind::Remap); - assert_eq!(jobs[1].status, ThreadEpiphanyJobStatus::Needed); - assert_eq!(jobs[1].linked_graph_node_ids, vec!["retrieval".to_string()]); - - assert_eq!(jobs[2].id, "verification"); - assert_eq!(jobs[2].kind, ThreadEpiphanyJobKind::Verification); - assert_eq!(jobs[2].status, ThreadEpiphanyJobStatus::Needed); - assert_eq!(jobs[2].items_processed, Some(1)); - assert_eq!(jobs[2].items_total, Some(2)); - - assert_eq!(jobs.len(), 3); - assert!(!jobs.iter().any(|job| job.id == "specialist-work")); -} - -#[test] -fn map_epiphany_jobs_can_reflect_retrieval_without_epiphany_state() { - let retrieval = codex_protocol::protocol::EpiphanyRetrievalState { - workspace_root: test_path_buf("/repo"), - status: codex_protocol::protocol::EpiphanyRetrievalStatus::Ready, - indexed_file_count: Some(7), - ..Default::default() - }; - - let jobs = map_epiphany_jobs(None, Some(&retrieval)); - - assert_eq!(jobs[0].status, ThreadEpiphanyJobStatus::Idle); - assert_eq!(jobs[0].items_processed, Some(7)); - assert_eq!(jobs[1].status, ThreadEpiphanyJobStatus::Blocked); - assert_eq!(jobs[2].status, ThreadEpiphanyJobStatus::Blocked); -} - -#[test] -fn map_epiphany_jobs_projects_heartbeat_binding_as_pending() { - let state = codex_protocol::protocol::EpiphanyThreadState { - job_bindings: vec![codex_protocol::protocol::EpiphanyJobBinding { - id: "modeling-checkpoint-worker".to_string(), - kind: codex_protocol::protocol::EpiphanyJobKind::Specialist, - scope: "role-scoped modeling/checkpoint maintenance".to_string(), - owner_role: "epiphany-modeler".to_string(), - authority_scope: Some("epiphany.role.modeling".to_string()), - linked_subgoal_ids: vec!["phase-6".to_string()], - linked_graph_node_ids: vec!["runtime-spine".to_string()], - blocking_reason: None, - }], - runtime_links: vec![codex_protocol::protocol::EpiphanyRuntimeLink { - id: "runtime-link-modeling-checkpoint-worker-heartbeat-turn-1".to_string(), - binding_id: "modeling-checkpoint-worker".to_string(), - surface: "roleLaunch".to_string(), - role_id: "epiphany-modeler".to_string(), - authority_scope: "epiphany.role.modeling".to_string(), - runtime_job_id: "heartbeat-turn-1".to_string(), - runtime_result_id: None, - linked_subgoal_ids: vec!["phase-6".to_string()], - linked_graph_node_ids: vec!["runtime-spine".to_string()], - }], - ..Default::default() - }; - - let jobs = map_epiphany_jobs(Some(&state), None); - let specialist = jobs - .iter() - .find(|job| job.id == "modeling-checkpoint-worker") - .expect("heartbeat specialist slot should exist"); - - assert_eq!(specialist.status, ThreadEpiphanyJobStatus::Pending); - assert_eq!( - specialist.backend_job_id.as_deref(), - Some("heartbeat-turn-1") - ); - assert_eq!(specialist.blocking_reason, None); - assert!( - specialist - .progress_note - .as_deref() - .is_some_and(|note| note.contains("heartbeat activation")) - ); -} - -#[test] -fn load_epiphany_role_result_reads_heartbeat_runtime_spine_result() { - let temp = tempfile::tempdir().expect("tempdir"); - let store = temp.path().join("runtime.msgpack"); - epiphany_core::initialize_runtime_spine( - &store, - epiphany_core::RuntimeSpineInitOptions { - runtime_id: "epiphany-test".to_string(), - display_name: "Epiphany Test".to_string(), - created_at: "2026-05-06T00:00:00Z".to_string(), - }, - ) - .expect("runtime identity"); - epiphany_core::create_runtime_session( - &store, - epiphany_core::RuntimeSpineSessionOptions { - session_id: "epiphany-main".to_string(), - objective: "Read typed runtime results.".to_string(), - created_at: "2026-05-06T00:01:00Z".to_string(), - coordinator_note: "test".to_string(), - }, - ) - .expect("runtime session"); - epiphany_core::create_runtime_job( - &store, - epiphany_core::RuntimeSpineJobOptions { - job_id: "heartbeat-job-1".to_string(), - session_id: "epiphany-main".to_string(), - role: "epiphany-modeler".to_string(), - created_at: "2026-05-06T00:02:00Z".to_string(), - summary: "queued".to_string(), - artifact_refs: Vec::new(), - }, - ) - .expect("runtime job"); - epiphany_core::complete_runtime_job( - &store, - epiphany_core::RuntimeSpineJobResultOptions { - result_id: "heartbeat-result-1".to_string(), - job_id: "heartbeat-job-1".to_string(), - completed_at: "2026-05-06T00:03:00Z".to_string(), - verdict: "pass".to_string(), - summary: "Runtime model ready.".to_string(), - next_safe_move: "Launch verification.".to_string(), - evidence_refs: vec!["evidence:model".to_string()], - artifact_refs: vec!["artifact:model".to_string()], - }, - ) - .expect("runtime result"); - - let (status, finding, note) = load_epiphany_role_result_from_runtime_spine_job( - "heartbeat-job-1", - Some(store.as_path()), - ThreadEpiphanyRoleId::Modeling, - ); - - assert_eq!(status, ThreadEpiphanyRoleResultStatus::Completed); - let finding = finding.expect("runtime finding"); - assert_eq!(finding.verdict.as_deref(), Some("pass")); - assert_eq!(finding.summary.as_deref(), Some("Runtime model ready.")); - assert_eq!(finding.evidence_ids, vec!["evidence:model".to_string()]); - assert!(note.contains("Modeling role specialist completed")); -} - -#[test] -fn map_epiphany_jobs_blocks_binding_after_interrupt_clears_backend() { - let state = codex_protocol::protocol::EpiphanyThreadState { - job_bindings: vec![codex_protocol::protocol::EpiphanyJobBinding { - id: "specialist-work".to_string(), - kind: codex_protocol::protocol::EpiphanyJobKind::Specialist, - scope: "role-scoped specialist work".to_string(), - owner_role: "epiphany-harness".to_string(), - authority_scope: Some("epiphany.specialist".to_string()), - linked_subgoal_ids: vec!["phase-6".to_string()], - linked_graph_node_ids: vec!["job-control".to_string()], - blocking_reason: Some( - "No active runtime backend is currently bound; launch explicitly to resume specialist work." - .to_string(), - ), - }], - ..Default::default() - }; - - let jobs = map_epiphany_jobs(Some(&state), None); - let specialist = jobs - .iter() - .find(|job| job.id == "specialist-work") - .expect("specialist slot should exist"); - - assert_eq!(specialist.status, ThreadEpiphanyJobStatus::Blocked); - assert_eq!( - specialist.authority_scope.as_deref(), - Some("epiphany.specialist") - ); - assert_eq!(specialist.launcher_job_id, None); - assert_eq!(specialist.backend_job_id, None); - assert_eq!(specialist.linked_subgoal_ids, vec!["phase-6".to_string()]); - assert_eq!( - specialist.linked_graph_node_ids, - vec!["job-control".to_string()] - ); - assert!( - specialist - .blocking_reason - .as_deref() - .is_some_and(|reason| reason.contains("launch explicitly")) - ); -} - -#[test] -fn epiphany_update_patch_changed_fields_reports_patch_surface() { - let fields = epiphany_update_patch_changed_fields(&ThreadEpiphanyUpdatePatch { - objective: Some("Keep the event readable".to_string()), - graphs: Some(Default::default()), - graph_frontier: Some(Default::default()), - investigation_checkpoint: Some(Default::default()), - job_bindings: Some(Vec::new()), - observations: vec![Default::default()], - evidence: vec![Default::default()], - churn: Some(Default::default()), - ..Default::default() - }); - - assert_eq!( - fields, - vec![ - ThreadEpiphanyStateUpdatedField::Objective, - ThreadEpiphanyStateUpdatedField::Graphs, - ThreadEpiphanyStateUpdatedField::GraphFrontier, - ThreadEpiphanyStateUpdatedField::InvestigationCheckpoint, - ThreadEpiphanyStateUpdatedField::JobBindings, - ThreadEpiphanyStateUpdatedField::Observations, - ThreadEpiphanyStateUpdatedField::Evidence, - ThreadEpiphanyStateUpdatedField::Churn, - ] - ); -} - -#[test] -fn epiphany_promote_changed_fields_reports_appended_verifier_evidence() { - let fields = epiphany_promote_changed_fields(&ThreadEpiphanyUpdatePatch { - observations: vec![Default::default()], - ..Default::default() - }); - - assert_eq!( - fields, - vec![ - ThreadEpiphanyStateUpdatedField::Observations, - ThreadEpiphanyStateUpdatedField::Evidence, - ] - ); -} - -#[tokio::test] -async fn aborting_pending_request_clears_pending_state() -> Result<()> { - let thread_id = ThreadId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; - let connection_id = ConnectionId(7); - - let (outgoing_tx, mut outgoing_rx) = tokio::sync::mpsc::channel(8); - let outgoing = Arc::new(OutgoingMessageSender::new(outgoing_tx)); - let thread_outgoing = - ThreadScopedOutgoingMessageSender::new(outgoing.clone(), vec![connection_id], thread_id); - - let (request_id, client_request_rx) = thread_outgoing - .send_request(ServerRequestPayload::ToolRequestUserInput( - ToolRequestUserInputParams { - thread_id: thread_id.to_string(), - turn_id: "turn-1".to_string(), - item_id: "call-1".to_string(), - questions: vec![], - }, - )) - .await; - thread_outgoing.abort_pending_server_requests().await; - - let request_message = outgoing_rx.recv().await.expect("request should be sent"); - let OutgoingEnvelope::ToConnection { - connection_id: request_connection_id, - message: - OutgoingMessage::Request(ServerRequest::ToolRequestUserInput { - request_id: sent_request_id, - .. - }), - .. - } = request_message - else { - panic!("expected tool request to be sent to the subscribed connection"); - }; - assert_eq!(request_connection_id, connection_id); - assert_eq!(sent_request_id, request_id); - - let response = client_request_rx - .await - .expect("callback should be resolved"); - let error = response.expect_err("request should be aborted during cleanup"); - assert_eq!( - error.message, - "client request resolved because the turn state was changed" - ); - assert_eq!(error.data, Some(json!({ "reason": "turnTransition" }))); - assert!( - outgoing - .pending_requests_for_thread(thread_id) - .await - .is_empty() - ); - assert!(outgoing_rx.try_recv().is_err()); - Ok(()) -} - -#[test] -fn summary_from_state_db_metadata_preserves_agent_nickname() -> Result<()> { - let conversation_id = ThreadId::from_string("bfd12a78-5900-467b-9bc5-d3d35df08191")?; - let source = serde_json::to_string(&SessionSource::SubAgent(SubAgentSource::ThreadSpawn { - parent_thread_id: ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?, - depth: 1, - agent_path: None, - agent_nickname: None, - agent_role: None, - }))?; - - let summary = summary_from_state_db_metadata( - conversation_id, - PathBuf::from("/tmp/rollout.jsonl"), - Some("hi".to_string()), - "2025-09-05T16:53:11Z".to_string(), - "2025-09-05T16:53:12Z".to_string(), - "test-provider".to_string(), - PathBuf::from("/"), - "0.0.0".to_string(), - source, - Some("atlas".to_string()), - Some("explorer".to_string()), - /*git_sha*/ None, - /*git_branch*/ None, - /*git_origin_url*/ None, - ); - - let fallback_cwd = AbsolutePathBuf::from_absolute_path("/")?; - let thread = summary_to_thread(summary, &fallback_cwd); - - assert_eq!(thread.agent_nickname, Some("atlas".to_string())); - assert_eq!(thread.agent_role, Some("explorer".to_string())); - Ok(()) -} - -#[tokio::test] -async fn removing_thread_state_clears_listener_and_active_turn_history() -> Result<()> { - let manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let connection = ConnectionId(1); - let (cancel_tx, cancel_rx) = oneshot::channel(); - - manager.connection_initialized(connection).await; - manager - .try_ensure_connection_subscribed( - thread_id, connection, /*experimental_raw_events*/ false, - ) - .await - .expect("connection should be live"); - { - let state = manager.thread_state(thread_id).await; - let mut state = state.lock().await; - state.cancel_tx = Some(cancel_tx); - state.track_current_turn_event(&EventMsg::TurnStarted( - codex_protocol::protocol::TurnStartedEvent { - turn_id: "turn-1".to_string(), - started_at: None, - model_context_window: None, - collaboration_mode_kind: Default::default(), - }, - )); - } - - manager.remove_thread_state(thread_id).await; - assert_eq!(cancel_rx.await, Ok(())); - - let state = manager.thread_state(thread_id).await; - let subscribed_connection_ids = manager.subscribed_connection_ids(thread_id).await; - assert!(subscribed_connection_ids.is_empty()); - let state = state.lock().await; - assert!(state.cancel_tx.is_none()); - assert!(state.active_turn_snapshot().is_none()); - Ok(()) -} - -#[tokio::test] -async fn removing_auto_attached_connection_preserves_listener_for_other_connections() -> Result<()> -{ - let manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let connection_a = ConnectionId(1); - let connection_b = ConnectionId(2); - let (cancel_tx, mut cancel_rx) = oneshot::channel(); - - manager.connection_initialized(connection_a).await; - manager.connection_initialized(connection_b).await; - manager - .try_ensure_connection_subscribed( - thread_id, - connection_a, - /*experimental_raw_events*/ false, - ) - .await - .expect("connection_a should be live"); - manager - .try_ensure_connection_subscribed( - thread_id, - connection_b, - /*experimental_raw_events*/ false, - ) - .await - .expect("connection_b should be live"); - { - let state = manager.thread_state(thread_id).await; - state.lock().await.cancel_tx = Some(cancel_tx); - } - - let threads_to_unload = manager.remove_connection(connection_a).await; - assert_eq!(threads_to_unload, Vec::::new()); - assert!( - tokio::time::timeout(Duration::from_millis(20), &mut cancel_rx) - .await - .is_err() - ); - - assert_eq!( - manager.subscribed_connection_ids(thread_id).await, - vec![connection_b] - ); - Ok(()) -} - -#[tokio::test] -async fn adding_connection_to_thread_updates_has_connections_watcher() -> Result<()> { - let manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let connection_a = ConnectionId(1); - let connection_b = ConnectionId(2); - - manager.connection_initialized(connection_a).await; - manager.connection_initialized(connection_b).await; - manager - .try_ensure_connection_subscribed( - thread_id, - connection_a, - /*experimental_raw_events*/ false, - ) - .await - .expect("connection_a should be live"); - let mut has_connections = manager - .subscribe_to_has_connections(thread_id) - .await - .expect("thread should have a has-connections watcher"); - assert!(*has_connections.borrow()); - - assert!( - manager - .unsubscribe_connection_from_thread(thread_id, connection_a) - .await - ); - tokio::time::timeout(Duration::from_secs(1), has_connections.changed()) - .await - .expect("timed out waiting for no-subscriber update") - .expect("has-connections watcher should remain open"); - assert!(!*has_connections.borrow()); - - assert!( - manager - .try_add_connection_to_thread(thread_id, connection_b) - .await - ); - tokio::time::timeout(Duration::from_secs(1), has_connections.changed()) - .await - .expect("timed out waiting for subscriber update") - .expect("has-connections watcher should remain open"); - assert!(*has_connections.borrow()); - Ok(()) -} - -#[tokio::test] -async fn closed_connection_cannot_be_reintroduced_by_auto_subscribe() -> Result<()> { - let manager = ThreadStateManager::new(); - let thread_id = ThreadId::from_string("ad7f0408-99b8-4f6e-a46f-bd0eec433370")?; - let connection = ConnectionId(1); - - manager.connection_initialized(connection).await; - let threads_to_unload = manager.remove_connection(connection).await; - assert_eq!(threads_to_unload, Vec::::new()); - - assert!( - manager - .try_ensure_connection_subscribed( - thread_id, connection, /*experimental_raw_events*/ false - ) - .await - .is_none() - ); - assert!(!manager.has_subscribers(thread_id).await); - Ok(()) -} diff --git a/vendor/codex/codex-rs/app-server/src/config_manager.rs b/vendor/codex/codex-rs/app-server/src/config_manager.rs index 69b819c1..607895e7 100644 --- a/vendor/codex/codex-rs/app-server/src/config_manager.rs +++ b/vendor/codex/codex-rs/app-server/src/config_manager.rs @@ -219,13 +219,6 @@ impl ConfigManager { Ok(config) } - pub(crate) async fn load_config_layers_for_cwd( - &self, - cwd: AbsolutePathBuf, - ) -> std::io::Result { - self.load_config_layers(Some(cwd)).await - } - pub(crate) async fn load_config_layers( &self, cwd: Option, diff --git a/vendor/codex/codex-rs/app-server/src/thread_state.rs b/vendor/codex/codex-rs/app-server/src/thread_state.rs index 2350179b..5e1a64e1 100644 --- a/vendor/codex/codex-rs/app-server/src/thread_state.rs +++ b/vendor/codex/codex-rs/app-server/src/thread_state.rs @@ -379,16 +379,6 @@ impl ThreadStateManager { true } - #[cfg(test)] - pub(crate) async fn has_subscribers(&self, thread_id: ThreadId) -> bool { - self.state - .lock() - .await - .threads - .get(&thread_id) - .is_some_and(|thread_entry| !thread_entry.connection_ids.is_empty()) - } - pub(crate) async fn try_ensure_connection_subscribed( &self, thread_id: ThreadId, diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/app_list.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/app_list.rs deleted file mode 100644 index 78a915d1..00000000 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/app_list.rs +++ /dev/null @@ -1,1535 +0,0 @@ -use std::borrow::Cow; -use std::collections::BTreeMap; -use std::collections::HashMap; -use std::sync::Arc; -use std::sync::Mutex as StdMutex; -use std::time::Duration; - -use anyhow::Result; -use anyhow::bail; -use app_test_support::ChatGptAuthFixture; -use app_test_support::McpProcess; -use app_test_support::to_response; -use app_test_support::write_chatgpt_auth; -use axum::Json; -use axum::Router; -use axum::extract::State; -use axum::http::HeaderMap; -use axum::http::StatusCode; -use axum::http::Uri; -use axum::http::header::AUTHORIZATION; -use axum::routing::get; -use codex_app_server_protocol::AppBranding; -use codex_app_server_protocol::AppInfo; -use codex_app_server_protocol::AppListUpdatedNotification; -use codex_app_server_protocol::AppMetadata; -use codex_app_server_protocol::AppReview; -use codex_app_server_protocol::AppScreenshot; -use codex_app_server_protocol::AppsListParams; -use codex_app_server_protocol::AppsListResponse; -use codex_app_server_protocol::AuthMode; -use codex_app_server_protocol::ExperimentalFeatureEnablementSetParams; -use codex_app_server_protocol::JSONRPCError; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::ServerNotification; -use codex_app_server_protocol::ThreadStartParams; -use codex_app_server_protocol::ThreadStartResponse; -use codex_config::types::AuthCredentialsStoreMode; -use codex_login::AuthDotJson; -use codex_login::save_auth; -use pretty_assertions::assert_eq; -use rmcp::handler::server::ServerHandler; -use rmcp::model::JsonObject; -use rmcp::model::ListToolsResult; -use rmcp::model::Meta; -use rmcp::model::ServerCapabilities; -use rmcp::model::ServerInfo; -use rmcp::model::Tool; -use rmcp::model::ToolAnnotations; -use rmcp::transport::StreamableHttpServerConfig; -use rmcp::transport::StreamableHttpService; -use rmcp::transport::streamable_http_server::session::local::LocalSessionManager; -use serde_json::json; -use tempfile::TempDir; -use tokio::net::TcpListener; -use tokio::task::JoinHandle; -use tokio::time::timeout; - -// Bazel CI can spend tens of seconds starting app-server subprocesses or -// processing app-list RPCs under load. -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60); - -#[tokio::test] -async fn list_apps_returns_empty_when_connectors_disabled() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: Some(50), - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let AppsListResponse { data, next_cursor } = to_response(response)?; - - assert!(data.is_empty()); - assert!(next_cursor.is_none()); - Ok(()) -} - -#[tokio::test] -async fn list_apps_returns_empty_with_api_key_auth() -> Result<()> { - let connectors = vec![AppInfo { - id: "beta".to_string(), - name: "Beta".to_string(), - description: Some("Beta connector".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = - start_apps_server_with_delays(connectors, tools, Duration::ZERO, Duration::ZERO).await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - save_auth( - codex_home.path(), - &AuthDotJson { - auth_mode: Some(AuthMode::ApiKey), - openai_api_key: Some("test-api-key".to_string()), - tokens: None, - last_refresh: None, - agent_identity: None, - }, - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: Some(50), - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let AppsListResponse { data, next_cursor } = to_response(response)?; - assert!(data.is_empty()); - assert!(next_cursor.is_none()); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn list_apps_uses_thread_feature_flag_when_thread_id_is_provided() -> Result<()> { - let connectors = vec![AppInfo { - id: "beta".to_string(), - name: "Beta".to_string(), - description: Some("Beta connector".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = - start_apps_server_with_delays(connectors, tools, Duration::ZERO, Duration::ZERO).await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let start_request = mcp - .send_thread_start_request(ThreadStartParams::default()) - .await?; - let start_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(start_request)), - ) - .await??; - let ThreadStartResponse { thread, .. } = to_response(start_response)?; - - std::fs::write( - codex_home.path().join("config.toml"), - format!( - r#" -chatgpt_base_url = "{server_url}" -mcp_oauth_credentials_store = "file" - -[features] -connectors = false -"# - ), - )?; - - let global_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let global_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(global_request)), - ) - .await??; - let AppsListResponse { - data: global_data, - next_cursor: global_next_cursor, - } = to_response(global_response)?; - assert!(global_data.is_empty()); - assert!(global_next_cursor.is_none()); - - let thread_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: Some(thread.id), - force_refetch: false, - }) - .await?; - let thread_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(thread_request)), - ) - .await??; - let AppsListResponse { - data: thread_data, - next_cursor: thread_next_cursor, - } = to_response(thread_response)?; - assert!(thread_data.iter().any(|app| app.id == "beta")); - assert!(thread_next_cursor.is_none()); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn list_apps_reports_is_enabled_from_config() -> Result<()> { - let connectors = vec![AppInfo { - id: "beta".to_string(), - name: "Beta".to_string(), - description: Some("Beta connector".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = - start_apps_server_with_delays(connectors, tools, Duration::ZERO, Duration::ZERO).await?; - - let codex_home = TempDir::new()?; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - r#" -chatgpt_base_url = "{server_url}" - -[features] -connectors = true - -[apps.beta] -enabled = false -"# - ), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let AppsListResponse { - data: response_data, - next_cursor, - } = to_response(response)?; - assert!(next_cursor.is_none()); - assert_eq!(response_data.len(), 1); - assert_eq!(response_data[0].id, "beta"); - assert!(!response_data[0].is_enabled); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn list_apps_emits_updates_and_returns_after_both_lists_load() -> Result<()> { - let alpha_branding = Some(AppBranding { - category: Some("PRODUCTIVITY".to_string()), - developer: Some("Acme".to_string()), - website: Some("https://acme.example".to_string()), - privacy_policy: Some("https://acme.example/privacy".to_string()), - terms_of_service: Some("https://acme.example/terms".to_string()), - is_discoverable_app: true, - }); - let alpha_app_metadata = Some(AppMetadata { - review: Some(AppReview { - status: "APPROVED".to_string(), - }), - categories: Some(vec!["PRODUCTIVITY".to_string()]), - sub_categories: Some(vec!["WRITING".to_string()]), - seo_description: Some("Alpha connector".to_string()), - screenshots: Some(vec![AppScreenshot { - url: Some("https://example.com/alpha-screenshot.png".to_string()), - file_id: Some("file_123".to_string()), - user_prompt: "Summarize this draft".to_string(), - }]), - developer: Some("Acme".to_string()), - version: Some("1.2.3".to_string()), - version_id: Some("version_123".to_string()), - version_notes: Some("Fixes and improvements".to_string()), - first_party_type: Some("internal".to_string()), - first_party_requires_install: Some(true), - show_in_composer_when_unlinked: Some(true), - }); - let alpha_labels = Some(HashMap::from([ - ("feature".to_string(), "beta".to_string()), - ("source".to_string(), "directory".to_string()), - ])); - - let connectors = vec![ - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - distribution_channel: None, - branding: alpha_branding.clone(), - app_metadata: alpha_app_metadata.clone(), - labels: alpha_labels.clone(), - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "beta".to_string(), - name: "beta".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = start_apps_server_with_delays( - connectors.clone(), - tools, - Duration::from_millis(300), - Duration::ZERO, - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let expected_accessible = vec![AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - - let first_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!(first_update.data, expected_accessible); - - let expected_merged = vec![ - AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - distribution_channel: None, - branding: alpha_branding, - app_metadata: alpha_app_metadata, - labels: alpha_labels, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - - let second_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!(second_update.data, expected_merged); - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - - let AppsListResponse { - data: response_data, - next_cursor, - } = to_response(response)?; - assert_eq!(response_data, expected_merged); - assert!(next_cursor.is_none()); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn list_apps_waits_for_accessible_data_before_emitting_directory_updates() -> Result<()> { - let connectors = vec![ - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "beta".to_string(), - name: "beta".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = start_apps_server_with_delays( - connectors.clone(), - tools, - Duration::ZERO, - Duration::from_millis(300), - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-directory-first") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let expected = vec![ - AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - - loop { - let update = read_app_list_updated_notification(&mut mcp).await?; - if update.data == expected { - break; - } - - assert!( - !update.data.is_empty() && update.data.iter().all(|connector| connector.is_accessible), - "unexpected directory-only app/list update before accessible apps loaded" - ); - } - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let AppsListResponse { data, next_cursor } = to_response(response)?; - assert_eq!(data, expected); - assert!(next_cursor.is_none()); - - server_handle.abort(); - Ok(()) -} - -#[tokio::test] -async fn list_apps_does_not_emit_empty_interim_updates() -> Result<()> { - let connectors = vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let (server_url, server_handle) = start_apps_server_with_delays( - connectors.clone(), - Vec::new(), - Duration::from_millis(300), - Duration::ZERO, - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-empty-interim") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - - let maybe_update = timeout( - Duration::from_millis(150), - read_app_list_updated_notification(&mut mcp), - ) - .await; - assert!( - maybe_update.is_err(), - "unexpected empty interim app/list update" - ); - - let expected = vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - - let update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!(update.data, expected); - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let AppsListResponse { data, next_cursor } = to_response(response)?; - assert_eq!(data, expected); - assert!(next_cursor.is_none()); - - server_handle.abort(); - Ok(()) -} - -#[tokio::test] -async fn list_apps_paginates_results() -> Result<()> { - let connectors = vec![ - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "beta".to_string(), - name: "beta".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = start_apps_server_with_delays( - connectors.clone(), - tools, - Duration::ZERO, - Duration::from_millis(300), - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let first_request = mcp - .send_apps_list_request(AppsListParams { - limit: Some(1), - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let first_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(first_request)), - ) - .await??; - let AppsListResponse { - data: first_page, - next_cursor: first_cursor, - } = to_response(first_response)?; - - let expected_first = vec![AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - - assert_eq!(first_page, expected_first); - let next_cursor = first_cursor.ok_or_else(|| anyhow::anyhow!("missing cursor"))?; - - loop { - let update = read_app_list_updated_notification(&mut mcp).await?; - if update.data.len() == 2 && update.data.iter().any(|connector| connector.is_accessible) { - break; - } - } - - let second_request = mcp - .send_apps_list_request(AppsListParams { - limit: Some(1), - cursor: Some(next_cursor), - thread_id: None, - force_refetch: false, - }) - .await?; - let second_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(second_request)), - ) - .await??; - let AppsListResponse { - data: second_page, - next_cursor: second_cursor, - } = to_response(second_response)?; - - let expected_second = vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - - assert_eq!(second_page, expected_second); - assert!(second_cursor.is_none()); - - server_handle.abort(); - Ok(()) -} - -#[tokio::test] -async fn list_apps_force_refetch_preserves_previous_cache_on_failure() -> Result<()> { - let connectors = vec![AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: Some("Beta connector".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = - start_apps_server_with_delays(connectors, tools, Duration::ZERO, Duration::ZERO).await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let initial_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let initial_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(initial_request)), - ) - .await??; - let AppsListResponse { - data: initial_data, - next_cursor: initial_next_cursor, - } = to_response(initial_response)?; - assert!(initial_next_cursor.is_none()); - assert_eq!(initial_data.len(), 1); - assert!(initial_data.iter().all(|app| app.is_accessible)); - - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token-invalid") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let refetch_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: true, - }) - .await?; - let refetch_error: JSONRPCError = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(refetch_request)), - ) - .await??; - assert!(refetch_error.error.message.contains("failed to")); - - let cached_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let cached_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(cached_request)), - ) - .await??; - let AppsListResponse { - data: cached_data, - next_cursor: cached_next_cursor, - } = to_response(cached_response)?; - - assert_eq!(cached_data, initial_data); - assert!(cached_next_cursor.is_none()); - server_handle.abort(); - Ok(()) -} - -#[tokio::test] -async fn list_apps_force_refetch_patches_updates_from_cached_snapshots() -> Result<()> { - let initial_connectors = vec![ - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v1".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: Some("Beta v1".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - let initial_tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle, server_control) = start_apps_server_with_delays_and_control( - initial_connectors, - initial_tools, - Duration::from_millis(300), - Duration::ZERO, - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let warm_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: false, - }) - .await?; - let warm_first_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!( - warm_first_update.data, - vec![AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: None, - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }] - ); - - let warm_second_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!( - warm_second_update.data, - vec![ - AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: Some("Beta v1".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v1".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ] - ); - - let warm_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(warm_request)), - ) - .await??; - let AppsListResponse { - data: warm_data, - next_cursor: warm_next_cursor, - } = to_response(warm_response)?; - assert_eq!(warm_data, warm_second_update.data); - assert!(warm_next_cursor.is_none()); - - server_control.set_connectors(vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v2".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]); - server_control.set_tools(Vec::new()); - - let refetch_request = mcp - .send_apps_list_request(AppsListParams { - limit: None, - cursor: None, - thread_id: None, - force_refetch: true, - }) - .await?; - - let first_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!( - first_update.data, - vec![ - AppInfo { - id: "beta".to_string(), - name: "Beta App".to_string(), - description: Some("Beta v1".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v1".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ] - ); - - let maybe_second_update = timeout( - Duration::from_millis(150), - read_app_list_updated_notification(&mut mcp), - ) - .await; - assert!( - maybe_second_update.is_err(), - "unexpected inaccessible-only app/list update during force refetch" - ); - - let expected_final = vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v2".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let second_update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!(second_update.data, expected_final); - - let refetch_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(refetch_request)), - ) - .await??; - let AppsListResponse { - data: refetch_data, - next_cursor: refetch_next_cursor, - } = to_response(refetch_response)?; - assert_eq!(refetch_data, expected_final); - assert!(refetch_next_cursor.is_none()); - - server_handle.abort(); - Ok(()) -} - -#[tokio::test] -async fn experimental_feature_enablement_set_refreshes_apps_list_when_apps_turn_on() -> Result<()> { - let initial_connectors = vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v1".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let (server_url, server_handle, server_control) = start_apps_server_with_delays_and_control( - initial_connectors, - Vec::new(), - Duration::ZERO, - Duration::ZERO, - ) - .await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-enable-refresh") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let disable_request = mcp - .send_experimental_feature_enablement_set_request(ExperimentalFeatureEnablementSetParams { - enablement: BTreeMap::from([("apps".to_string(), false)]), - }) - .await?; - let _disable_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(disable_request)), - ) - .await??; - - server_control.set_connectors(vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v2".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]); - server_control.set_tools(vec![connector_tool("alpha", "Alpha App")?]); - - let enable_request = mcp - .send_experimental_feature_enablement_set_request(ExperimentalFeatureEnablementSetParams { - enablement: BTreeMap::from([("apps".to_string(), true)]), - }) - .await?; - let _enable_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(enable_request)), - ) - .await??; - - let update = read_app_list_updated_notification(&mut mcp).await?; - assert_eq!( - update.data, - vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha v2".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - is_accessible: true, - is_enabled: true, - plugin_display_names: Vec::new(), - }] - ); - - server_handle.abort(); - Ok(()) -} - -async fn read_app_list_updated_notification( - mcp: &mut McpProcess, -) -> Result { - let notification = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_notification_message("app/list/updated"), - ) - .await??; - let parsed: ServerNotification = notification.try_into()?; - let ServerNotification::AppListUpdated(payload) = parsed else { - bail!("unexpected notification variant"); - }; - Ok(payload) -} - -#[derive(Clone)] -struct AppsServerState { - expected_bearer: String, - expected_account_id: String, - response: Arc>, - directory_delay: Duration, -} - -#[derive(Clone)] -struct AppListMcpServer { - tools: Arc>>, - tools_delay: Duration, -} - -impl AppListMcpServer { - fn new(tools: Arc>>, tools_delay: Duration) -> Self { - Self { tools, tools_delay } - } -} - -#[derive(Clone)] -struct AppsServerControl { - response: Arc>, - tools: Arc>>, -} - -impl AppsServerControl { - fn set_connectors(&self, connectors: Vec) { - let mut response_guard = self - .response - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - *response_guard = json!({ "apps": connectors, "next_token": null }); - } - - fn set_tools(&self, tools: Vec) { - let mut tools_guard = self - .tools - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - *tools_guard = tools; - } -} - -impl ServerHandler for AppListMcpServer { - fn get_info(&self) -> ServerInfo { - ServerInfo { - capabilities: ServerCapabilities::builder().enable_tools().build(), - ..ServerInfo::default() - } - } - - fn list_tools( - &self, - _request: Option, - _context: rmcp::service::RequestContext, - ) -> impl std::future::Future> + Send + '_ - { - let tools = self.tools.clone(); - let tools_delay = self.tools_delay; - async move { - if tools_delay > Duration::ZERO { - tokio::time::sleep(tools_delay).await; - } - let tools = tools - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - Ok(ListToolsResult { - tools, - next_cursor: None, - meta: None, - }) - } - } -} - -async fn start_apps_server_with_delays( - connectors: Vec, - tools: Vec, - directory_delay: Duration, - tools_delay: Duration, -) -> Result<(String, JoinHandle<()>)> { - let (server_url, server_handle, _server_control) = - start_apps_server_with_delays_and_control(connectors, tools, directory_delay, tools_delay) - .await?; - Ok((server_url, server_handle)) -} - -async fn start_apps_server_with_delays_and_control( - connectors: Vec, - tools: Vec, - directory_delay: Duration, - tools_delay: Duration, -) -> Result<(String, JoinHandle<()>, AppsServerControl)> { - let response = Arc::new(StdMutex::new( - json!({ "apps": connectors, "next_token": null }), - )); - let tools = Arc::new(StdMutex::new(tools)); - let state = AppsServerState { - expected_bearer: "Bearer chatgpt-token".to_string(), - expected_account_id: "account-123".to_string(), - response: response.clone(), - directory_delay, - }; - let state = Arc::new(state); - let server_control = AppsServerControl { - response, - tools: tools.clone(), - }; - - let listener = TcpListener::bind("127.0.0.1:0").await?; - let addr = listener.local_addr()?; - - let mcp_service = StreamableHttpService::new( - { - let tools = tools.clone(); - move || Ok(AppListMcpServer::new(tools.clone(), tools_delay)) - }, - Arc::new(LocalSessionManager::default()), - StreamableHttpServerConfig::default(), - ); - - let router = Router::new() - .route("/connectors/directory/list", get(list_directory_connectors)) - .route( - "/connectors/directory/list_workspace", - get(list_directory_connectors), - ) - .with_state(state) - .nest_service("/api/codex/apps", mcp_service); - - let handle = tokio::spawn(async move { - let _ = axum::serve(listener, router).await; - }); - - Ok((format!("http://{addr}"), handle, server_control)) -} - -async fn list_directory_connectors( - State(state): State>, - headers: HeaderMap, - uri: Uri, -) -> Result { - if state.directory_delay > Duration::ZERO { - tokio::time::sleep(state.directory_delay).await; - } - - let bearer_ok = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == state.expected_bearer); - let account_ok = headers - .get("chatgpt-account-id") - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == state.expected_account_id); - let external_logos_ok = uri - .query() - .is_some_and(|query| query.split('&').any(|pair| pair == "external_logos=true")); - - if !bearer_ok || !account_ok { - Err(StatusCode::UNAUTHORIZED) - } else if !external_logos_ok { - Err(StatusCode::BAD_REQUEST) - } else { - let response = state - .response - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - Ok(Json(response)) - } -} - -fn connector_tool(connector_id: &str, connector_name: &str) -> Result { - let schema: JsonObject = serde_json::from_value(json!({ - "type": "object", - "additionalProperties": false - }))?; - let mut tool = Tool::new( - Cow::Owned(format!("connector_{connector_id}")), - Cow::Borrowed("Connector test tool"), - Arc::new(schema), - ); - tool.annotations = Some(ToolAnnotations::new().read_only(true)); - - let mut meta = Meta::new(); - meta.0 - .insert("connector_id".to_string(), json!(connector_id)); - meta.0 - .insert("connector_name".to_string(), json!(connector_name)); - tool.meta = Some(meta); - Ok(tool) -} - -fn write_connectors_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> { - let config_toml = codex_home.join("config.toml"); - std::fs::write( - config_toml, - format!( - r#" -chatgpt_base_url = "{base_url}" -mcp_oauth_credentials_store = "file" - -[features] -connectors = true -"# - ), - ) -} diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/marketplace_add.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/marketplace_add.rs deleted file mode 100644 index cf3c5736..00000000 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/marketplace_add.rs +++ /dev/null @@ -1,61 +0,0 @@ -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::MarketplaceAddParams; -use codex_app_server_protocol::MarketplaceAddResponse; -use codex_app_server_protocol::RequestId; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use tokio::time::Duration; -use tokio::time::timeout; - -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); - -#[tokio::test] -async fn marketplace_add_local_directory_source() -> Result<()> { - let codex_home = TempDir::new()?; - let source = codex_home.path().join("marketplace"); - std::fs::create_dir_all(source.join(".agents/plugins"))?; - std::fs::create_dir_all(source.join("plugins/sample/.codex-plugin"))?; - std::fs::write( - source.join(".agents/plugins/marketplace.json"), - r#"{"name":"debug","plugins":[]}"#, - )?; - std::fs::write( - source.join("plugins/sample/.codex-plugin/plugin.json"), - r#"{"name":"sample"}"#, - )?; - std::fs::write(source.join("plugins/sample/marker.txt"), "local ref")?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_marketplace_add_request(MarketplaceAddParams { - source: "./marketplace".to_string(), - ref_name: None, - sparse_paths: None, - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let MarketplaceAddResponse { - marketplace_name, - installed_root, - already_added, - } = to_response(response)?; - let expected_root = source.canonicalize()?; - - assert_eq!(marketplace_name, "debug"); - assert_eq!(installed_root.as_path(), expected_root.as_path()); - assert!(!already_added); - assert_eq!( - std::fs::read_to_string(installed_root.as_path().join("plugins/sample/marker.txt"))?, - "local ref" - ); - Ok(()) -} diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/marketplace_remove.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/marketplace_remove.rs deleted file mode 100644 index fb144001..00000000 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/marketplace_remove.rs +++ /dev/null @@ -1,115 +0,0 @@ -use std::time::Duration; - -use anyhow::Context; -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::MarketplaceRemoveParams; -use codex_app_server_protocol::MarketplaceRemoveResponse; -use codex_app_server_protocol::RequestId; -use codex_config::MarketplaceConfigUpdate; -use codex_config::record_user_marketplace; -use codex_core::plugins::marketplace_install_root; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); - -fn configured_marketplace_update() -> MarketplaceConfigUpdate<'static> { - MarketplaceConfigUpdate { - last_updated: "2026-04-13T00:00:00Z", - last_revision: None, - source_type: "git", - source: "https://github.com/owner/repo.git", - ref_name: Some("main"), - sparse_paths: &[], - } -} - -fn write_installed_marketplace(codex_home: &std::path::Path, marketplace_name: &str) -> Result<()> { - let root = marketplace_install_root(codex_home).join(marketplace_name); - std::fs::create_dir_all(root.join(".agents/plugins"))?; - std::fs::write(root.join(".agents/plugins/marketplace.json"), "{}")?; - Ok(()) -} - -fn canonicalize_path_with_existing_parent(path: &std::path::Path) -> Result { - let parent = path - .parent() - .with_context(|| format!("path {} should have a parent", path.display()))?; - let file_name = path - .file_name() - .with_context(|| format!("path {} should have a file name", path.display()))?; - - Ok(parent.canonicalize()?.join(file_name)) -} - -#[tokio::test] -async fn marketplace_remove_deletes_config_and_installed_root() -> Result<()> { - let codex_home = TempDir::new()?; - record_user_marketplace(codex_home.path(), "debug", &configured_marketplace_update())?; - write_installed_marketplace(codex_home.path(), "debug")?; - let installed_root = marketplace_install_root(codex_home.path()).join("debug"); - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_marketplace_remove_request(MarketplaceRemoveParams { - marketplace_name: "debug".to_string(), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: MarketplaceRemoveResponse = to_response(response)?; - assert_eq!(response.marketplace_name, "debug"); - let removed_installed_root = response - .installed_root - .context("marketplace/remove should return removed installed root")?; - assert_eq!( - canonicalize_path_with_existing_parent(removed_installed_root.as_path())?, - canonicalize_path_with_existing_parent(&installed_root)?, - ); - - let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?; - assert!(!config.contains("[marketplaces.debug]")); - assert!( - !marketplace_install_root(codex_home.path()) - .join("debug") - .exists() - ); - Ok(()) -} - -#[tokio::test] -async fn marketplace_remove_rejects_unknown_marketplace() -> Result<()> { - let codex_home = TempDir::new()?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_marketplace_remove_request(MarketplaceRemoveParams { - marketplace_name: "debug".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert_eq!( - err.error.message, - "marketplace `debug` is not configured or installed", - ); - Ok(()) -} diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/mod.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/mod.rs index 4ab21ffc..572df2c4 100644 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/mod.rs +++ b/vendor/codex/codex-rs/app-server/tests/suite/v2/mod.rs @@ -1,6 +1,5 @@ mod account; mod analytics; -mod app_list; mod client_metadata; mod collaboration_mode_list; #[cfg(unix)] @@ -17,8 +16,6 @@ mod experimental_feature_list; mod external_agent_config; mod fs; mod initialize; -mod marketplace_add; -mod marketplace_remove; mod mcp_resource; mod mcp_server_elicitation; mod mcp_server_status; @@ -27,17 +24,12 @@ mod memory_reset; mod model_list; mod output_schema; mod plan_item; -mod plugin_install; -mod plugin_list; -mod plugin_read; -mod plugin_uninstall; mod rate_limits; mod realtime_conversation; mod request_permissions; mod request_user_input; mod review; mod safety_check_downgrade; -mod skills_list; mod thread_archive; mod thread_fork; mod thread_inject_items; diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_install.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_install.rs deleted file mode 100644 index 3555dd74..00000000 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_install.rs +++ /dev/null @@ -1,844 +0,0 @@ -use std::borrow::Cow; -use std::sync::Arc; -use std::sync::Mutex as StdMutex; -use std::time::Duration; - -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::DEFAULT_CLIENT_NAME; -use app_test_support::McpProcess; -use app_test_support::start_analytics_events_server; -use app_test_support::to_response; -use app_test_support::write_chatgpt_auth; -use axum::Json; -use axum::Router; -use axum::extract::State; -use axum::http::HeaderMap; -use axum::http::StatusCode; -use axum::http::Uri; -use axum::http::header::AUTHORIZATION; -use axum::routing::get; -use codex_app_server_protocol::AppInfo; -use codex_app_server_protocol::AppSummary; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::PluginAuthPolicy; -use codex_app_server_protocol::PluginInstallParams; -use codex_app_server_protocol::PluginInstallResponse; -use codex_app_server_protocol::RequestId; -use codex_config::types::AuthCredentialsStoreMode; -use codex_utils_absolute_path::AbsolutePathBuf; -use pretty_assertions::assert_eq; -use rmcp::handler::server::ServerHandler; -use rmcp::model::JsonObject; -use rmcp::model::ListToolsResult; -use rmcp::model::Meta; -use rmcp::model::ServerCapabilities; -use rmcp::model::ServerInfo; -use rmcp::model::Tool; -use rmcp::model::ToolAnnotations; -use rmcp::transport::StreamableHttpServerConfig; -use rmcp::transport::StreamableHttpService; -use rmcp::transport::streamable_http_server::session::local::LocalSessionManager; -use serde_json::json; -use tempfile::TempDir; -use tokio::net::TcpListener; -use tokio::task::JoinHandle; -use tokio::time::timeout; - -// Plugin install tests wait on connector discovery after the install response path -// starts, which is noticeably slower on Windows CI. -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60); - -#[tokio::test] -async fn plugin_install_rejects_relative_marketplace_paths() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_raw_request( - "plugin/install", - Some(serde_json::json!({ - "marketplacePath": "relative-marketplace.json", - "pluginName": "missing-plugin", - })), - ) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!(err.error.message.contains("Invalid request")); - Ok(()) -} - -#[tokio::test] -async fn plugin_install_rejects_missing_install_source() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: None, - remote_marketplace_name: None, - plugin_name: "sample-plugin".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!( - err.error - .message - .contains("requires exactly one of marketplacePath or remoteMarketplaceName") - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_install_rejects_multiple_install_sources() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: Some(AbsolutePathBuf::try_from( - codex_home.path().join("marketplace.json"), - )?), - remote_marketplace_name: Some("openai-curated".to_string()), - plugin_name: "sample-plugin".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!( - err.error - .message - .contains("requires exactly one of marketplacePath or remoteMarketplaceName") - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_install_rejects_remote_marketplace_until_remote_install_is_supported() -> Result<()> -{ - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: None, - remote_marketplace_name: Some("openai-curated".to_string()), - plugin_name: "sample-plugin".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!( - err.error - .message - .contains("remote plugin install is not supported yet") - ); - assert!(err.error.message.contains("openai-curated")); - Ok(()) -} - -#[tokio::test] -async fn plugin_install_returns_invalid_request_for_missing_marketplace_file() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: Some(AbsolutePathBuf::try_from( - codex_home.path().join("missing-marketplace.json"), - )?), - remote_marketplace_name: None, - plugin_name: "missing-plugin".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!(err.error.message.contains("marketplace file")); - assert!(err.error.message.contains("does not exist")); - Ok(()) -} - -#[tokio::test] -async fn plugin_install_returns_invalid_request_for_not_available_plugin() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - write_plugin_marketplace( - repo_root.path(), - "debug", - "sample-plugin", - "./sample-plugin", - Some("NOT_AVAILABLE"), - /*auth_policy*/ None, - )?; - write_plugin_source(repo_root.path(), "sample-plugin", &[])?; - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: Some(marketplace_path), - remote_marketplace_name: None, - plugin_name: "sample-plugin".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!(err.error.message.contains("not available for install")); - Ok(()) -} - -#[tokio::test] -async fn plugin_install_returns_invalid_request_for_disallowed_product_plugin() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - std::fs::create_dir_all(repo_root.path().join(".agents/plugins"))?; - std::fs::write( - repo_root.path().join(".agents/plugins/marketplace.json"), - r#"{ - "name": "debug", - "plugins": [ - { - "name": "sample-plugin", - "source": { - "source": "local", - "path": "./sample-plugin" - }, - "policy": { - "products": ["CHATGPT"] - } - } - ] -}"#, - )?; - write_plugin_source(repo_root.path(), "sample-plugin", &[])?; - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?; - - let mut mcp = - McpProcess::new_with_args(codex_home.path(), &["--session-source", "atlas"]).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: Some(marketplace_path), - remote_marketplace_name: None, - plugin_name: "sample-plugin".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!(err.error.message.contains("not available for install")); - Ok(()) -} - -#[tokio::test] -async fn plugin_install_tracks_analytics_event() -> Result<()> { - let analytics_server = start_analytics_events_server().await?; - let codex_home = TempDir::new()?; - write_analytics_config(codex_home.path(), &analytics_server.uri())?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let repo_root = TempDir::new()?; - write_plugin_marketplace( - repo_root.path(), - "debug", - "sample-plugin", - "./sample-plugin", - /*install_policy*/ None, - /*auth_policy*/ None, - )?; - write_plugin_source(repo_root.path(), "sample-plugin", &[])?; - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: Some(marketplace_path), - remote_marketplace_name: None, - plugin_name: "sample-plugin".to_string(), - }) - .await?; - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginInstallResponse = to_response(response)?; - assert_eq!(response.apps_needing_auth, Vec::::new()); - - let payload = timeout(DEFAULT_TIMEOUT, async { - loop { - let Some(requests) = analytics_server.received_requests().await else { - tokio::time::sleep(Duration::from_millis(25)).await; - continue; - }; - if let Some(request) = requests.iter().find(|request| { - request.method == "POST" && request.url.path() == "/codex/analytics-events/events" - }) { - break request.body.clone(); - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - }) - .await?; - let payload: serde_json::Value = serde_json::from_slice(&payload).expect("analytics payload"); - assert_eq!( - payload, - json!({ - "events": [{ - "event_type": "codex_plugin_installed", - "event_params": { - "plugin_id": "sample-plugin@debug", - "plugin_name": "sample-plugin", - "marketplace_name": "debug", - "has_skills": false, - "mcp_server_count": 0, - "connector_ids": [], - "product_client_id": DEFAULT_CLIENT_NAME, - } - }] - }) - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_install_returns_apps_needing_auth() -> Result<()> { - let connectors = vec![ - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - distribution_channel: Some("featured".to_string()), - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "beta".to_string(), - name: "Beta".to_string(), - description: Some("Beta connector".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = start_apps_server(connectors, tools).await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let repo_root = TempDir::new()?; - write_plugin_marketplace( - repo_root.path(), - "debug", - "sample-plugin", - "./sample-plugin", - /*install_policy*/ None, - /*auth_policy*/ None, - )?; - write_plugin_source(repo_root.path(), "sample-plugin", &["alpha", "beta"])?; - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: Some(marketplace_path), - remote_marketplace_name: None, - plugin_name: "sample-plugin".to_string(), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginInstallResponse = to_response(response)?; - - assert_eq!( - response, - PluginInstallResponse { - auth_policy: PluginAuthPolicy::OnInstall, - apps_needing_auth: vec![AppSummary { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - needs_auth: true, - }], - } - ); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn plugin_install_filters_disallowed_apps_needing_auth() -> Result<()> { - let connectors = vec![AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - distribution_channel: Some("featured".to_string()), - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }]; - let (server_url, server_handle) = start_apps_server(connectors, Vec::new()).await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let repo_root = TempDir::new()?; - write_plugin_marketplace( - repo_root.path(), - "debug", - "sample-plugin", - "./sample-plugin", - /*install_policy*/ None, - Some("ON_USE"), - )?; - write_plugin_source( - repo_root.path(), - "sample-plugin", - &["alpha", "asdk_app_6938a94a61d881918ef32cb999ff937c"], - )?; - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: Some(marketplace_path), - remote_marketplace_name: None, - plugin_name: "sample-plugin".to_string(), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginInstallResponse = to_response(response)?; - - assert_eq!( - response, - PluginInstallResponse { - auth_policy: PluginAuthPolicy::OnUse, - apps_needing_auth: vec![AppSummary { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), - needs_auth: true, - }], - } - ); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn plugin_install_makes_bundled_mcp_servers_available_to_followup_requests() -> Result<()> { - let codex_home = TempDir::new()?; - std::fs::write( - codex_home.path().join("config.toml"), - "[features]\nplugins = true\n", - )?; - let repo_root = TempDir::new()?; - write_plugin_marketplace( - repo_root.path(), - "debug", - "sample-plugin", - "./sample-plugin", - /*install_policy*/ None, - /*auth_policy*/ None, - )?; - write_plugin_source(repo_root.path(), "sample-plugin", &[])?; - std::fs::write( - repo_root.path().join("sample-plugin/.mcp.json"), - r#"{ - "mcpServers": { - "sample-mcp": { - "command": "echo" - } - } -}"#, - )?; - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_install_request(PluginInstallParams { - marketplace_path: Some(marketplace_path), - remote_marketplace_name: None, - plugin_name: "sample-plugin".to_string(), - }) - .await?; - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginInstallResponse = to_response(response)?; - assert_eq!(response.apps_needing_auth, Vec::::new()); - let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?; - assert!(!config.contains("[mcp_servers.sample-mcp]")); - assert!(!config.contains("command = \"echo\"")); - - let request_id = mcp - .send_raw_request( - "mcpServer/oauth/login", - Some(json!({ - "name": "sample-mcp", - })), - ) - .await?; - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert_eq!( - err.error.message, - "OAuth login is only supported for streamable HTTP servers." - ); - Ok(()) -} - -#[derive(Clone)] -struct AppsServerState { - response: Arc>, -} - -#[derive(Clone)] -struct PluginInstallMcpServer { - tools: Arc>>, -} - -impl ServerHandler for PluginInstallMcpServer { - fn get_info(&self) -> ServerInfo { - ServerInfo { - capabilities: ServerCapabilities::builder().enable_tools().build(), - ..ServerInfo::default() - } - } - - fn list_tools( - &self, - _request: Option, - _context: rmcp::service::RequestContext, - ) -> impl std::future::Future> + Send + '_ - { - let tools = self.tools.clone(); - async move { - let tools = tools - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - Ok(ListToolsResult { - tools, - next_cursor: None, - meta: None, - }) - } - } -} - -async fn start_apps_server( - connectors: Vec, - tools: Vec, -) -> Result<(String, JoinHandle<()>)> { - let state = Arc::new(AppsServerState { - response: Arc::new(StdMutex::new( - json!({ "apps": connectors, "next_token": null }), - )), - }); - let tools = Arc::new(StdMutex::new(tools)); - - let listener = TcpListener::bind("127.0.0.1:0").await?; - let addr = listener.local_addr()?; - let mcp_service = StreamableHttpService::new( - { - let tools = tools.clone(); - move || { - Ok(PluginInstallMcpServer { - tools: tools.clone(), - }) - } - }, - Arc::new(LocalSessionManager::default()), - StreamableHttpServerConfig::default(), - ); - let router = Router::new() - .route("/connectors/directory/list", get(list_directory_connectors)) - .route( - "/connectors/directory/list_workspace", - get(list_directory_connectors), - ) - .with_state(state) - .nest_service("/api/codex/apps", mcp_service); - - let handle = tokio::spawn(async move { - let _ = axum::serve(listener, router).await; - }); - - Ok((format!("http://{addr}"), handle)) -} - -async fn list_directory_connectors( - State(state): State>, - headers: HeaderMap, - uri: Uri, -) -> Result { - let bearer_ok = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == "Bearer chatgpt-token"); - let account_ok = headers - .get("chatgpt-account-id") - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == "account-123"); - let external_logos_ok = uri - .query() - .is_some_and(|query| query.split('&').any(|pair| pair == "external_logos=true")); - - if !bearer_ok || !account_ok { - Err(StatusCode::UNAUTHORIZED) - } else if !external_logos_ok { - Err(StatusCode::BAD_REQUEST) - } else { - let response = state - .response - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - Ok(Json(response)) - } -} - -fn connector_tool(connector_id: &str, connector_name: &str) -> Result { - let schema: JsonObject = serde_json::from_value(json!({ - "type": "object", - "additionalProperties": false - }))?; - let mut tool = Tool::new( - Cow::Owned(format!("connector_{connector_id}")), - Cow::Borrowed("Connector test tool"), - Arc::new(schema), - ); - tool.annotations = Some(ToolAnnotations::new().read_only(true)); - - let mut meta = Meta::new(); - meta.0 - .insert("connector_id".to_string(), json!(connector_id)); - meta.0 - .insert("connector_name".to_string(), json!(connector_name)); - tool.meta = Some(meta); - Ok(tool) -} - -fn write_connectors_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> { - std::fs::write( - codex_home.join("config.toml"), - format!( - r#" -chatgpt_base_url = "{base_url}" -mcp_oauth_credentials_store = "file" - -[features] -connectors = true -"# - ), - ) -} - -fn write_analytics_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> { - std::fs::write( - codex_home.join("config.toml"), - format!("chatgpt_base_url = \"{base_url}\"\n"), - ) -} - -fn write_plugin_marketplace( - repo_root: &std::path::Path, - marketplace_name: &str, - plugin_name: &str, - source_path: &str, - install_policy: Option<&str>, - auth_policy: Option<&str>, -) -> std::io::Result<()> { - let policy = if install_policy.is_some() || auth_policy.is_some() { - let installation = install_policy - .map(|installation| format!("\n \"installation\": \"{installation}\"")) - .unwrap_or_default(); - let separator = if install_policy.is_some() && auth_policy.is_some() { - "," - } else { - "" - }; - let authentication = auth_policy - .map(|authentication| { - format!("{separator}\n \"authentication\": \"{authentication}\"") - }) - .unwrap_or_default(); - format!(",\n \"policy\": {{{installation}{authentication}\n }}") - } else { - String::new() - }; - std::fs::create_dir_all(repo_root.join(".git"))?; - std::fs::create_dir_all(repo_root.join(".agents/plugins"))?; - std::fs::write( - repo_root.join(".agents/plugins/marketplace.json"), - format!( - r#"{{ - "name": "{marketplace_name}", - "plugins": [ - {{ - "name": "{plugin_name}", - "source": {{ - "source": "local", - "path": "{source_path}" - }}{policy} - }} - ] -}}"# - ), - ) -} - -fn write_plugin_source( - repo_root: &std::path::Path, - plugin_name: &str, - app_ids: &[&str], -) -> Result<()> { - let plugin_root = repo_root.join(plugin_name); - std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?; - std::fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - format!(r#"{{"name":"{plugin_name}"}}"#), - )?; - - let apps = app_ids - .iter() - .map(|app_id| ((*app_id).to_string(), json!({ "id": app_id }))) - .collect::>(); - std::fs::write( - plugin_root.join(".app.json"), - serde_json::to_vec_pretty(&json!({ "apps": apps }))?, - )?; - Ok(()) -} diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_list.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_list.rs deleted file mode 100644 index 0c22e8da..00000000 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_list.rs +++ /dev/null @@ -1,1507 +0,0 @@ -use std::time::Duration; - -use anyhow::Result; -use anyhow::bail; -use app_test_support::ChatGptAuthFixture; -use app_test_support::McpProcess; -use app_test_support::to_response; -use app_test_support::write_chatgpt_auth; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::PluginAuthPolicy; -use codex_app_server_protocol::PluginInstallPolicy; -use codex_app_server_protocol::PluginListParams; -use codex_app_server_protocol::PluginListResponse; -use codex_app_server_protocol::PluginMarketplaceEntry; -use codex_app_server_protocol::PluginSource; -use codex_app_server_protocol::PluginSummary; -use codex_app_server_protocol::RequestId; -use codex_config::types::AuthCredentialsStoreMode; -use codex_core::config::set_project_trust_level; -use codex_protocol::config_types::TrustLevel; -use codex_utils_absolute_path::AbsolutePathBuf; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; - -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); -const TEST_CURATED_PLUGIN_SHA: &str = "0123456789abcdef0123456789abcdef01234567"; -const STARTUP_REMOTE_PLUGIN_SYNC_MARKER_FILE: &str = ".tmp/app-server-remote-plugin-sync-v1"; -const ALTERNATE_MARKETPLACE_RELATIVE_PATH: &str = ".claude-plugin/marketplace.json"; -const ALTERNATE_PLUGIN_MANIFEST_RELATIVE_PATH: &str = ".claude-plugin/plugin.json"; - -fn write_plugins_enabled_config(codex_home: &std::path::Path) -> std::io::Result<()> { - std::fs::write( - codex_home.join("config.toml"), - r#"[features] -plugins = true -"#, - ) -} - -#[tokio::test] -async fn plugin_list_skips_invalid_marketplace_file_and_reports_error() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - std::fs::create_dir_all(repo_root.path().join(".git"))?; - std::fs::create_dir_all(repo_root.path().join(".agents/plugins"))?; - write_plugins_enabled_config(codex_home.path())?; - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?; - std::fs::write(marketplace_path.as_path(), "{not json")?; - - let home = codex_home.path().to_string_lossy().into_owned(); - let mut mcp = McpProcess::new_with_env( - codex_home.path(), - &[ - ("HOME", Some(home.as_str())), - ("USERPROFILE", Some(home.as_str())), - ], - ) - .await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { - cwds: Some(vec![AbsolutePathBuf::try_from(repo_root.path())?]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - - assert!( - response - .marketplaces - .iter() - .all(|marketplace| { marketplace.path.as_ref() != Some(&marketplace_path) }), - "invalid marketplace should be skipped" - ); - assert_eq!(response.marketplace_load_errors.len(), 1); - assert_eq!( - response.marketplace_load_errors[0].marketplace_path, - marketplace_path - ); - assert!( - response.marketplace_load_errors[0] - .message - .contains("invalid marketplace file"), - "unexpected error: {:?}", - response.marketplace_load_errors - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_list_rejects_relative_cwds() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_raw_request( - "plugin/list", - Some(serde_json::json!({ - "cwds": ["relative-root"], - })), - ) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!(err.error.message.contains("Invalid request")); - Ok(()) -} - -#[tokio::test] -async fn plugin_list_keeps_valid_marketplaces_when_another_marketplace_fails_to_load() -> Result<()> -{ - let codex_home = TempDir::new()?; - let valid_repo_root = TempDir::new()?; - let invalid_repo_root = TempDir::new()?; - std::fs::create_dir_all(valid_repo_root.path().join(".git"))?; - std::fs::create_dir_all(valid_repo_root.path().join(".agents/plugins"))?; - std::fs::create_dir_all( - valid_repo_root - .path() - .join("plugins/valid-plugin/.codex-plugin"), - )?; - std::fs::create_dir_all(invalid_repo_root.path().join(".git"))?; - std::fs::create_dir_all(invalid_repo_root.path().join(".agents/plugins"))?; - write_plugins_enabled_config(codex_home.path())?; - - let valid_marketplace_path = AbsolutePathBuf::try_from( - valid_repo_root - .path() - .join(".agents/plugins/marketplace.json"), - )?; - let invalid_marketplace_path = AbsolutePathBuf::try_from( - invalid_repo_root - .path() - .join(".agents/plugins/marketplace.json"), - )?; - let valid_plugin_path = - AbsolutePathBuf::try_from(valid_repo_root.path().join("plugins/valid-plugin"))?; - - std::fs::write( - valid_marketplace_path.as_path(), - r#"{ - "name": "valid-marketplace", - "plugins": [ - { - "name": "valid-plugin", - "source": { - "source": "local", - "path": "./plugins/valid-plugin" - } - } - ] -}"#, - )?; - std::fs::write( - valid_repo_root - .path() - .join("plugins/valid-plugin/.codex-plugin/plugin.json"), - r#"{"name":"valid-plugin"}"#, - )?; - std::fs::write(invalid_marketplace_path.as_path(), "{not json")?; - - let home = codex_home.path().to_string_lossy().into_owned(); - let mut mcp = McpProcess::new_with_env( - codex_home.path(), - &[ - ("HOME", Some(home.as_str())), - ("USERPROFILE", Some(home.as_str())), - ], - ) - .await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { - cwds: Some(vec![ - AbsolutePathBuf::try_from(valid_repo_root.path())?, - AbsolutePathBuf::try_from(invalid_repo_root.path())?, - ]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - - assert_eq!( - response.marketplaces, - vec![PluginMarketplaceEntry { - name: "valid-marketplace".to_string(), - path: Some(valid_marketplace_path), - interface: None, - plugins: vec![PluginSummary { - id: "valid-plugin@valid-marketplace".to_string(), - name: "valid-plugin".to_string(), - source: PluginSource::Local { - path: valid_plugin_path, - }, - installed: false, - enabled: false, - install_policy: PluginInstallPolicy::Available, - auth_policy: PluginAuthPolicy::OnInstall, - interface: None, - }], - }] - ); - assert_eq!(response.marketplace_load_errors.len(), 1); - assert_eq!( - response.marketplace_load_errors[0].marketplace_path, - invalid_marketplace_path - ); - assert!( - response.marketplace_load_errors[0] - .message - .contains("invalid marketplace file"), - "unexpected error: {:?}", - response.marketplace_load_errors - ); - assert!(response.featured_plugin_ids.is_empty()); - Ok(()) -} - -#[tokio::test] -async fn plugin_list_uses_alternate_discoverable_manifest_and_keeps_undiscoverable_plugins() --> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - let valid_plugin_root = repo_root.path().join("plugins/valid-plugin"); - std::fs::create_dir_all(repo_root.path().join(".git"))?; - std::fs::create_dir_all( - repo_root - .path() - .join(ALTERNATE_MARKETPLACE_RELATIVE_PATH) - .parent() - .unwrap(), - )?; - std::fs::create_dir_all( - valid_plugin_root - .join(ALTERNATE_PLUGIN_MANIFEST_RELATIVE_PATH) - .parent() - .unwrap(), - )?; - write_plugins_enabled_config(codex_home.path())?; - - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(ALTERNATE_MARKETPLACE_RELATIVE_PATH))?; - let valid_plugin_path = AbsolutePathBuf::try_from(valid_plugin_root.clone())?; - - std::fs::write( - marketplace_path.as_path(), - r#"{ - "name": "alternate-marketplace", - "plugins": [ - { - "name": "valid-plugin", - "source": "./plugins/valid-plugin" - }, - { - "name": "missing-plugin", - "source": "./plugins/missing-plugin" - } - ] -}"#, - )?; - std::fs::write( - valid_plugin_root.join(ALTERNATE_PLUGIN_MANIFEST_RELATIVE_PATH), - r#"{ - "name": "valid-plugin", - "interface": { - "displayName": "Valid Plugin" - } -}"#, - )?; - - let home = codex_home.path().to_string_lossy().into_owned(); - let mut mcp = McpProcess::new_with_env( - codex_home.path(), - &[ - ("HOME", Some(home.as_str())), - ("USERPROFILE", Some(home.as_str())), - ], - ) - .await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { - cwds: Some(vec![AbsolutePathBuf::try_from(repo_root.path())?]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - - assert_eq!( - response.marketplaces, - vec![PluginMarketplaceEntry { - name: "alternate-marketplace".to_string(), - path: Some(marketplace_path), - interface: None, - plugins: vec![ - PluginSummary { - id: "valid-plugin@alternate-marketplace".to_string(), - name: "valid-plugin".to_string(), - source: PluginSource::Local { - path: valid_plugin_path, - }, - installed: false, - enabled: false, - install_policy: PluginInstallPolicy::Available, - auth_policy: PluginAuthPolicy::OnInstall, - interface: Some(codex_app_server_protocol::PluginInterface { - display_name: Some("Valid Plugin".to_string()), - short_description: None, - long_description: None, - developer_name: None, - category: None, - capabilities: Vec::new(), - website_url: None, - privacy_policy_url: None, - terms_of_service_url: None, - default_prompt: None, - brand_color: None, - composer_icon: None, - composer_icon_url: None, - logo: None, - logo_url: None, - screenshots: Vec::new(), - screenshot_urls: Vec::new(), - }), - }, - PluginSummary { - id: "missing-plugin@alternate-marketplace".to_string(), - name: "missing-plugin".to_string(), - source: PluginSource::Local { - path: AbsolutePathBuf::try_from( - repo_root.path().join("plugins/missing-plugin"), - )?, - }, - installed: false, - enabled: false, - install_policy: PluginInstallPolicy::Available, - auth_policy: PluginAuthPolicy::OnInstall, - interface: None, - }, - ], - }] - ); - assert!(response.marketplace_load_errors.is_empty()); - Ok(()) -} - -#[tokio::test] -async fn plugin_list_accepts_omitted_cwds() -> Result<()> { - let codex_home = TempDir::new()?; - std::fs::create_dir_all(codex_home.path().join(".agents/plugins"))?; - write_plugins_enabled_config(codex_home.path())?; - std::fs::write( - codex_home.path().join(".agents/plugins/marketplace.json"), - r#"{ - "name": "codex-curated", - "plugins": [ - { - "name": "home-plugin", - "source": { - "source": "local", - "path": "./home-plugin" - } - } - ] -}"#, - )?; - let home = codex_home.path().to_string_lossy().into_owned(); - let mut mcp = McpProcess::new_with_env( - codex_home.path(), - &[ - ("HOME", Some(home.as_str())), - ("USERPROFILE", Some(home.as_str())), - ], - ) - .await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { cwds: None }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let _: PluginListResponse = to_response(response)?; - Ok(()) -} - -#[tokio::test] -async fn plugin_list_includes_install_and_enabled_state_from_config() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - std::fs::create_dir_all(repo_root.path().join(".git"))?; - std::fs::create_dir_all(repo_root.path().join(".agents/plugins"))?; - write_installed_plugin(&codex_home, "codex-curated", "enabled-plugin")?; - write_installed_plugin(&codex_home, "codex-curated", "disabled-plugin")?; - std::fs::write( - repo_root.path().join(".agents/plugins/marketplace.json"), - r#"{ - "name": "codex-curated", - "interface": { - "displayName": "ChatGPT Official" - }, - "plugins": [ - { - "name": "enabled-plugin", - "source": { - "source": "local", - "path": "./enabled-plugin" - } - }, - { - "name": "disabled-plugin", - "source": { - "source": "local", - "path": "./disabled-plugin" - } - }, - { - "name": "uninstalled-plugin", - "source": { - "source": "local", - "path": "./uninstalled-plugin" - } - } - ] -}"#, - )?; - std::fs::write( - codex_home.path().join("config.toml"), - r#"[features] -plugins = true - -[plugins."enabled-plugin@codex-curated"] -enabled = true - -[plugins."disabled-plugin@codex-curated"] -enabled = false -"#, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { - cwds: Some(vec![AbsolutePathBuf::try_from(repo_root.path())?]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - - let marketplace = response - .marketplaces - .into_iter() - .find(|marketplace| { - marketplace.path.as_ref() - == Some( - &AbsolutePathBuf::try_from( - repo_root.path().join(".agents/plugins/marketplace.json"), - ) - .expect("absolute marketplace path"), - ) - }) - .expect("expected repo marketplace entry"); - - assert_eq!(marketplace.name, "codex-curated"); - assert_eq!( - marketplace - .interface - .as_ref() - .and_then(|interface| interface.display_name.as_deref()), - Some("ChatGPT Official") - ); - assert_eq!(marketplace.plugins.len(), 3); - assert_eq!(marketplace.plugins[0].id, "enabled-plugin@codex-curated"); - assert_eq!(marketplace.plugins[0].name, "enabled-plugin"); - assert_eq!(marketplace.plugins[0].installed, true); - assert_eq!(marketplace.plugins[0].enabled, true); - assert_eq!( - marketplace.plugins[0].install_policy, - PluginInstallPolicy::Available - ); - assert_eq!( - marketplace.plugins[0].auth_policy, - PluginAuthPolicy::OnInstall - ); - assert_eq!(marketplace.plugins[1].id, "disabled-plugin@codex-curated"); - assert_eq!(marketplace.plugins[1].name, "disabled-plugin"); - assert_eq!(marketplace.plugins[1].installed, true); - assert_eq!(marketplace.plugins[1].enabled, false); - assert_eq!( - marketplace.plugins[1].install_policy, - PluginInstallPolicy::Available - ); - assert_eq!( - marketplace.plugins[1].auth_policy, - PluginAuthPolicy::OnInstall - ); - assert_eq!( - marketplace.plugins[2].id, - "uninstalled-plugin@codex-curated" - ); - assert_eq!(marketplace.plugins[2].name, "uninstalled-plugin"); - assert_eq!(marketplace.plugins[2].installed, false); - assert_eq!(marketplace.plugins[2].enabled, false); - assert_eq!( - marketplace.plugins[2].install_policy, - PluginInstallPolicy::Available - ); - assert_eq!( - marketplace.plugins[2].auth_policy, - PluginAuthPolicy::OnInstall - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_list_uses_home_config_for_enabled_state() -> Result<()> { - let codex_home = TempDir::new()?; - std::fs::create_dir_all(codex_home.path().join(".agents/plugins"))?; - write_installed_plugin(&codex_home, "codex-curated", "shared-plugin")?; - std::fs::write( - codex_home.path().join(".agents/plugins/marketplace.json"), - r#"{ - "name": "codex-curated", - "plugins": [ - { - "name": "shared-plugin", - "source": { - "source": "local", - "path": "./shared-plugin" - } - } - ] -}"#, - )?; - std::fs::write( - codex_home.path().join("config.toml"), - r#"[features] -plugins = true - -[plugins."shared-plugin@codex-curated"] -enabled = true -"#, - )?; - - let workspace_enabled = TempDir::new()?; - std::fs::create_dir_all(workspace_enabled.path().join(".git"))?; - std::fs::create_dir_all(workspace_enabled.path().join(".agents/plugins"))?; - std::fs::write( - workspace_enabled - .path() - .join(".agents/plugins/marketplace.json"), - r#"{ - "name": "codex-curated", - "plugins": [ - { - "name": "shared-plugin", - "source": { - "source": "local", - "path": "./shared-plugin" - } - } - ] -}"#, - )?; - std::fs::create_dir_all(workspace_enabled.path().join(".codex"))?; - std::fs::write( - workspace_enabled.path().join(".codex/config.toml"), - r#"[plugins."shared-plugin@codex-curated"] -enabled = false -"#, - )?; - set_project_trust_level( - codex_home.path(), - workspace_enabled.path(), - TrustLevel::Trusted, - )?; - - let workspace_default = TempDir::new()?; - let home = codex_home.path().to_string_lossy().into_owned(); - let mut mcp = McpProcess::new_with_env( - codex_home.path(), - &[ - ("HOME", Some(home.as_str())), - ("USERPROFILE", Some(home.as_str())), - ], - ) - .await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { - cwds: Some(vec![ - AbsolutePathBuf::try_from(workspace_enabled.path())?, - AbsolutePathBuf::try_from(workspace_default.path())?, - ]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - - let shared_plugin = response - .marketplaces - .iter() - .flat_map(|marketplace| marketplace.plugins.iter()) - .find(|plugin| plugin.name == "shared-plugin") - .expect("expected shared-plugin entry"); - assert_eq!(shared_plugin.id, "shared-plugin@codex-curated"); - assert_eq!(shared_plugin.installed, true); - assert_eq!(shared_plugin.enabled, true); - Ok(()) -} - -#[tokio::test] -async fn plugin_list_returns_plugin_interface_with_absolute_asset_paths() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - let plugin_root = repo_root.path().join("plugins/demo-plugin"); - std::fs::create_dir_all(repo_root.path().join(".git"))?; - std::fs::create_dir_all(repo_root.path().join(".agents/plugins"))?; - std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?; - write_plugins_enabled_config(codex_home.path())?; - std::fs::write( - repo_root.path().join(".agents/plugins/marketplace.json"), - r#"{ - "name": "codex-curated", - "plugins": [ - { - "name": "demo-plugin", - "source": { - "source": "local", - "path": "./plugins/demo-plugin" - }, - "policy": { - "installation": "AVAILABLE", - "authentication": "ON_INSTALL" - }, - "category": "Design" - } - ] -}"#, - )?; - std::fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - r##"{ - "name": "demo-plugin", - "interface": { - "displayName": "Plugin Display Name", - "shortDescription": "Short description for subtitle", - "longDescription": "Long description for details page", - "developerName": "OpenAI", - "category": "Productivity", - "capabilities": ["Interactive", "Write"], - "websiteURL": "https://openai.com/", - "privacyPolicyURL": "https://openai.com/policies/row-privacy-policy/", - "termsOfServiceURL": "https://openai.com/policies/row-terms-of-use/", - "defaultPrompt": [ - "Starter prompt for trying a plugin", - "Find my next action" - ], - "brandColor": "#3B82F6", - "composerIcon": "./assets/icon.png", - "logo": "./assets/logo.png", - "screenshots": ["./assets/screenshot1.png", "./assets/screenshot2.png"] - } -}"##, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { - cwds: Some(vec![AbsolutePathBuf::try_from(repo_root.path())?]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - - let plugin = response - .marketplaces - .iter() - .flat_map(|marketplace| marketplace.plugins.iter()) - .find(|plugin| plugin.name == "demo-plugin") - .expect("expected demo-plugin entry"); - - assert_eq!(plugin.id, "demo-plugin@codex-curated"); - assert_eq!(plugin.installed, false); - assert_eq!(plugin.enabled, false); - assert_eq!(plugin.install_policy, PluginInstallPolicy::Available); - assert_eq!(plugin.auth_policy, PluginAuthPolicy::OnInstall); - let interface = plugin - .interface - .as_ref() - .expect("expected plugin interface"); - assert_eq!( - interface.display_name.as_deref(), - Some("Plugin Display Name") - ); - assert_eq!(interface.category.as_deref(), Some("Design")); - assert_eq!( - interface.website_url.as_deref(), - Some("https://openai.com/") - ); - assert_eq!( - interface.privacy_policy_url.as_deref(), - Some("https://openai.com/policies/row-privacy-policy/") - ); - assert_eq!( - interface.terms_of_service_url.as_deref(), - Some("https://openai.com/policies/row-terms-of-use/") - ); - assert_eq!( - interface.default_prompt, - Some(vec![ - "Starter prompt for trying a plugin".to_string(), - "Find my next action".to_string() - ]) - ); - assert_eq!( - interface.composer_icon, - Some(AbsolutePathBuf::try_from( - plugin_root.join("assets/icon.png") - )?) - ); - assert_eq!( - interface.logo, - Some(AbsolutePathBuf::try_from( - plugin_root.join("assets/logo.png") - )?) - ); - assert_eq!( - interface.screenshots, - vec![ - AbsolutePathBuf::try_from(plugin_root.join("assets/screenshot1.png"))?, - AbsolutePathBuf::try_from(plugin_root.join("assets/screenshot2.png"))?, - ] - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_list_accepts_legacy_string_default_prompt() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - let plugin_root = repo_root.path().join("plugins/demo-plugin"); - std::fs::create_dir_all(repo_root.path().join(".git"))?; - std::fs::create_dir_all(repo_root.path().join(".agents/plugins"))?; - std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?; - write_plugins_enabled_config(codex_home.path())?; - std::fs::write( - repo_root.path().join(".agents/plugins/marketplace.json"), - r#"{ - "name": "codex-curated", - "plugins": [ - { - "name": "demo-plugin", - "source": { - "source": "local", - "path": "./plugins/demo-plugin" - } - } - ] -}"#, - )?; - std::fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - r##"{ - "name": "demo-plugin", - "interface": { - "defaultPrompt": "Starter prompt for trying a plugin" - } -}"##, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { - cwds: Some(vec![AbsolutePathBuf::try_from(repo_root.path())?]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - - let plugin = response - .marketplaces - .iter() - .flat_map(|marketplace| marketplace.plugins.iter()) - .find(|plugin| plugin.name == "demo-plugin") - .expect("expected demo-plugin entry"); - assert_eq!( - plugin - .interface - .as_ref() - .and_then(|interface| interface.default_prompt.clone()), - Some(vec!["Starter prompt for trying a plugin".to_string()]) - ); - Ok(()) -} - -#[tokio::test] -async fn app_server_startup_remote_plugin_sync_runs_once() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - write_plugin_sync_config(codex_home.path(), &format!("{}/backend-api/", server.uri()))?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - write_openai_curated_marketplace(codex_home.path(), &["linear"])?; - - Mock::given(method("GET")) - .and(path("/backend-api/plugins/list")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string( - r#"[ - {"id":"1","name":"linear","marketplace_name":"openai-curated","version":"1.0.0","enabled":true} -]"#, - )) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/plugins/featured")) - .and(query_param("platform", "codex")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"["linear@openai-curated"]"#)) - .mount(&server) - .await; - - let marker_path = codex_home - .path() - .join(STARTUP_REMOTE_PLUGIN_SYNC_MARKER_FILE); - - { - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - wait_for_path_exists(&marker_path).await?; - wait_for_remote_plugin_request_count(&server, "/plugins/list", /*expected_count*/ 1) - .await?; - let request_id = mcp - .send_plugin_list_request(PluginListParams { cwds: None }) - .await?; - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - let curated_marketplace = response - .marketplaces - .into_iter() - .find(|marketplace| marketplace.name == "openai-curated") - .expect("expected openai-curated marketplace entry"); - assert_eq!( - curated_marketplace - .plugins - .into_iter() - .map(|plugin| (plugin.id, plugin.installed, plugin.enabled)) - .collect::>(), - vec![("linear@openai-curated".to_string(), true, true)] - ); - wait_for_remote_plugin_request_count(&server, "/plugins/list", /*expected_count*/ 1) - .await?; - } - - let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?; - assert!(config.contains(r#"[plugins."linear@openai-curated"]"#)); - - { - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - } - - tokio::time::sleep(Duration::from_millis(250)).await; - wait_for_remote_plugin_request_count(&server, "/plugins/list", /*expected_count*/ 1).await?; - Ok(()) -} - -#[tokio::test] -async fn plugin_list_includes_remote_marketplaces_when_remote_plugin_enabled() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - write_remote_plugin_catalog_config( - codex_home.path(), - &format!("{}/backend-api/", server.uri()), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let global_directory_body = r#"{ - "plugins": [ - { - "id": "linear@chatgpt-global", - "name": "linear", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "display_name": "Linear", - "description": "Track work in Linear", - "app_ids": [], - "interface": { - "short_description": "Plan and track work", - "capabilities": ["Read", "Write"], - "logo_url": "https://example.com/linear.png", - "screenshot_urls": ["https://example.com/linear-shot.png"] - }, - "skills": [] - } - } - ], - "pagination": { - "limit": 50, - "next_page_token": null - } -}"#; - let empty_page_body = r#"{ - "plugins": [], - "pagination": { - "limit": 50, - "next_page_token": null - } -}"#; - let global_installed_body = r#"{ - "plugins": [ - { - "id": "linear@chatgpt-global", - "name": "linear", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "display_name": "Linear", - "description": "Track work in Linear", - "app_ids": [], - "interface": { - "short_description": "Plan and track work", - "capabilities": ["Read", "Write"], - "logo_url": "https://example.com/linear.png", - "screenshot_urls": ["https://example.com/linear-shot.png"] - }, - "skills": [] - }, - "enabled": true, - "disabled_skill_names": [] - } - ], - "pagination": { - "limit": 50, - "next_page_token": null - } -}"#; - - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/list")) - .and(query_param("scope", "GLOBAL")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(global_directory_body)) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/list")) - .and(query_param("scope", "WORKSPACE")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(empty_page_body)) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("scope", "GLOBAL")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(global_installed_body)) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("scope", "WORKSPACE")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(empty_page_body)) - .mount(&server) - .await; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { cwds: None }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - - let remote_marketplace = response - .marketplaces - .into_iter() - .find(|marketplace| marketplace.name == "chatgpt-global") - .expect("expected ChatGPT remote marketplace"); - assert_eq!(remote_marketplace.path, None); - assert_eq!( - remote_marketplace - .interface - .as_ref() - .and_then(|interface| interface.display_name.as_deref()), - Some("ChatGPT Plugins") - ); - assert_eq!(remote_marketplace.plugins.len(), 1); - assert_eq!(remote_marketplace.plugins[0].id, "linear@chatgpt-global"); - assert_eq!(remote_marketplace.plugins[0].name, "linear"); - assert_eq!(remote_marketplace.plugins[0].source, PluginSource::Remote); - assert_eq!(remote_marketplace.plugins[0].installed, true); - assert_eq!(remote_marketplace.plugins[0].enabled, true); - assert_eq!( - remote_marketplace.plugins[0] - .interface - .as_ref() - .and_then(|interface| interface.display_name.as_deref()), - Some("Linear") - ); - assert_eq!(response.featured_plugin_ids, Vec::::new()); - Ok(()) -} - -#[tokio::test] -async fn plugin_list_remote_marketplace_replaces_local_marketplace_with_same_name() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - write_remote_plugin_catalog_config( - codex_home.path(), - &format!("{}/backend-api/", server.uri()), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - let local_plugin_root = codex_home - .path() - .join(".agents/plugins/plugins/local-linear/.codex-plugin"); - std::fs::create_dir_all(&local_plugin_root)?; - std::fs::write( - codex_home.path().join(".agents/plugins/marketplace.json"), - r#"{ - "name": "chatgpt-global", - "plugins": [ - { - "name": "local-linear", - "source": { - "source": "local", - "path": "./plugins/local-linear" - } - } - ] -}"#, - )?; - std::fs::write( - local_plugin_root.join("plugin.json"), - r#"{"name":"local-linear"}"#, - )?; - - let global_directory_body = r#"{ - "plugins": [ - { - "id": "linear@chatgpt-global", - "name": "linear", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "display_name": "Linear", - "description": "Track work in Linear", - "app_ids": [], - "interface": {}, - "skills": [] - } - } - ], - "pagination": { - "limit": 50, - "next_page_token": null - } -}"#; - let empty_page_body = r#"{ - "plugins": [], - "pagination": { - "limit": 50, - "next_page_token": null - } -}"#; - for (path_suffix, scope, body) in [ - ( - "/backend-api/ps/plugins/list", - "GLOBAL", - global_directory_body, - ), - ("/backend-api/ps/plugins/list", "WORKSPACE", empty_page_body), - ( - "/backend-api/ps/plugins/installed", - "GLOBAL", - empty_page_body, - ), - ( - "/backend-api/ps/plugins/installed", - "WORKSPACE", - empty_page_body, - ), - ] { - Mock::given(method("GET")) - .and(path(path_suffix)) - .and(query_param("scope", scope)) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(body)) - .mount(&server) - .await; - } - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { cwds: None }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - let matching_marketplaces = response - .marketplaces - .iter() - .filter(|marketplace| marketplace.name == "chatgpt-global") - .collect::>(); - - assert_eq!(matching_marketplaces.len(), 1); - assert_eq!(matching_marketplaces[0].path, None); - assert_eq!(matching_marketplaces[0].plugins.len(), 1); - assert_eq!( - matching_marketplaces[0].plugins[0].source, - PluginSource::Remote - ); - assert_eq!(matching_marketplaces[0].plugins[0].name, "linear"); - Ok(()) -} - -#[tokio::test] -async fn plugin_list_does_not_fetch_remote_marketplaces_when_plugins_disabled() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - r#" -chatgpt_base_url = "{}/backend-api/" - -[features] -plugins = false -remote_plugin = true -"#, - server.uri() - ), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { cwds: None }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - - assert!(response.marketplaces.is_empty()); - wait_for_remote_plugin_request_count(&server, "/ps/plugins/list", /*expected_count*/ 0).await?; - Ok(()) -} - -#[tokio::test] -async fn plugin_list_fetches_featured_plugin_ids_without_chatgpt_auth() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - write_plugin_sync_config(codex_home.path(), &format!("{}/backend-api/", server.uri()))?; - write_openai_curated_marketplace(codex_home.path(), &["linear", "gmail"])?; - - Mock::given(method("GET")) - .and(path("/backend-api/plugins/featured")) - .and(query_param("platform", "codex")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"["linear@openai-curated"]"#)) - .mount(&server) - .await; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { cwds: None }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - - assert_eq!( - response.featured_plugin_ids, - vec!["linear@openai-curated".to_string()] - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_list_uses_warmed_featured_plugin_ids_cache_on_first_request() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - write_plugin_sync_config(codex_home.path(), &format!("{}/backend-api/", server.uri()))?; - write_openai_curated_marketplace(codex_home.path(), &["linear", "gmail"])?; - - Mock::given(method("GET")) - .and(path("/backend-api/plugins/featured")) - .and(query_param("platform", "codex")) - .respond_with(ResponseTemplate::new(200).set_body_string(r#"["linear@openai-curated"]"#)) - .expect(1) - .mount(&server) - .await; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - wait_for_featured_plugin_request_count(&server, /*expected_count*/ 1).await?; - - let request_id = mcp - .send_plugin_list_request(PluginListParams { cwds: None }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginListResponse = to_response(response)?; - - assert_eq!( - response.featured_plugin_ids, - vec!["linear@openai-curated".to_string()] - ); - Ok(()) -} - -async fn wait_for_featured_plugin_request_count( - server: &MockServer, - expected_count: usize, -) -> Result<()> { - wait_for_remote_plugin_request_count(server, "/plugins/featured", expected_count).await -} - -async fn wait_for_remote_plugin_request_count( - server: &MockServer, - path_suffix: &str, - expected_count: usize, -) -> Result<()> { - timeout(DEFAULT_TIMEOUT, async { - loop { - let Some(requests) = server.received_requests().await else { - bail!("wiremock did not record requests"); - }; - let request_count = requests - .iter() - .filter(|request| { - request.method == "GET" && request.url.path().ends_with(path_suffix) - }) - .count(); - if request_count == expected_count { - return Ok::<(), anyhow::Error>(()); - } - if request_count > expected_count { - bail!( - "expected exactly {expected_count} {path_suffix} requests, got {request_count}" - ); - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await??; - Ok(()) -} - -async fn wait_for_path_exists(path: &std::path::Path) -> Result<()> { - timeout(DEFAULT_TIMEOUT, async { - loop { - if path.exists() { - return Ok::<(), anyhow::Error>(()); - } - tokio::time::sleep(Duration::from_millis(10)).await; - } - }) - .await??; - Ok(()) -} - -fn write_installed_plugin( - codex_home: &TempDir, - marketplace_name: &str, - plugin_name: &str, -) -> Result<()> { - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join(marketplace_name) - .join(plugin_name) - .join("local/.codex-plugin"); - std::fs::create_dir_all(&plugin_root)?; - std::fs::write( - plugin_root.join("plugin.json"), - format!(r#"{{"name":"{plugin_name}"}}"#), - )?; - Ok(()) -} - -fn write_plugin_sync_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> { - std::fs::write( - codex_home.join("config.toml"), - format!( - r#" -chatgpt_base_url = "{base_url}" - -[features] -plugins = true - -[plugins."linear@openai-curated"] -enabled = false - -[plugins."gmail@openai-curated"] -enabled = false - -[plugins."calendar@openai-curated"] -enabled = true -"# - ), - ) -} - -fn write_remote_plugin_catalog_config( - codex_home: &std::path::Path, - base_url: &str, -) -> std::io::Result<()> { - std::fs::write( - codex_home.join("config.toml"), - format!( - r#" -chatgpt_base_url = "{base_url}" - -[features] -plugins = true -remote_plugin = true -"# - ), - ) -} - -fn write_openai_curated_marketplace( - codex_home: &std::path::Path, - plugin_names: &[&str], -) -> std::io::Result<()> { - let curated_root = codex_home.join(".tmp/plugins"); - std::fs::create_dir_all(curated_root.join(".git"))?; - std::fs::create_dir_all(curated_root.join(".agents/plugins"))?; - let plugins = plugin_names - .iter() - .map(|plugin_name| { - format!( - r#"{{ - "name": "{plugin_name}", - "source": {{ - "source": "local", - "path": "./plugins/{plugin_name}" - }} - }}"# - ) - }) - .collect::>() - .join(",\n"); - std::fs::write( - curated_root.join(".agents/plugins/marketplace.json"), - format!( - r#"{{ - "name": "openai-curated", - "plugins": [ -{plugins} - ] -}}"# - ), - )?; - - for plugin_name in plugin_names { - let plugin_root = curated_root.join(format!("plugins/{plugin_name}/.codex-plugin")); - std::fs::create_dir_all(&plugin_root)?; - std::fs::write( - plugin_root.join("plugin.json"), - format!(r#"{{"name":"{plugin_name}"}}"#), - )?; - } - std::fs::create_dir_all(codex_home.join(".tmp"))?; - std::fs::write( - codex_home.join(".tmp/plugins.sha"), - format!("{TEST_CURATED_PLUGIN_SHA}\n"), - )?; - Ok(()) -} diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_read.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_read.rs deleted file mode 100644 index d3697be1..00000000 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_read.rs +++ /dev/null @@ -1,1262 +0,0 @@ -use std::borrow::Cow; -use std::sync::Arc; -use std::sync::Mutex as StdMutex; -use std::time::Duration; - -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::McpProcess; -use app_test_support::to_response; -use app_test_support::write_chatgpt_auth; -use axum::Json; -use axum::Router; -use axum::extract::State; -use axum::http::HeaderMap; -use axum::http::StatusCode; -use axum::http::Uri; -use axum::http::header::AUTHORIZATION; -use axum::routing::get; -use codex_app_server_protocol::AppInfo; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::PluginAuthPolicy; -use codex_app_server_protocol::PluginInstallPolicy; -use codex_app_server_protocol::PluginReadParams; -use codex_app_server_protocol::PluginReadResponse; -use codex_app_server_protocol::PluginSource; -use codex_app_server_protocol::RequestId; -use codex_config::types::AuthCredentialsStoreMode; -use codex_utils_absolute_path::AbsolutePathBuf; -use pretty_assertions::assert_eq; -use rmcp::handler::server::ServerHandler; -use rmcp::model::JsonObject; -use rmcp::model::ListToolsResult; -use rmcp::model::Meta; -use rmcp::model::ServerCapabilities; -use rmcp::model::ServerInfo; -use rmcp::model::Tool; -use rmcp::model::ToolAnnotations; -use rmcp::transport::StreamableHttpServerConfig; -use rmcp::transport::StreamableHttpService; -use rmcp::transport::streamable_http_server::session::local::LocalSessionManager; -use serde_json::json; -use tempfile::TempDir; -use tokio::net::TcpListener; -use tokio::task::JoinHandle; -use tokio::time::timeout; -use wiremock::Mock; -use wiremock::MockServer; -use wiremock::ResponseTemplate; -use wiremock::matchers::header; -use wiremock::matchers::method; -use wiremock::matchers::path; -use wiremock::matchers::query_param; - -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); - -#[tokio::test] -async fn plugin_read_rejects_missing_read_source() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: None, - remote_marketplace_name: None, - plugin_name: "sample-plugin".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!( - err.error - .message - .contains("requires exactly one of marketplacePath or remoteMarketplaceName") - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_rejects_multiple_read_sources() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: Some(AbsolutePathBuf::try_from( - codex_home.path().join("marketplace.json"), - )?), - remote_marketplace_name: Some("openai-curated".to_string()), - plugin_name: "sample-plugin".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!( - err.error - .message - .contains("requires exactly one of marketplacePath or remoteMarketplaceName") - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_rejects_remote_marketplace_when_remote_plugin_is_disabled() -> Result<()> { - let codex_home = TempDir::new()?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: None, - remote_marketplace_name: Some("chatgpt-global".to_string()), - plugin_name: "sample-plugin".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!( - err.error - .message - .contains("remote plugin read is not enabled") - ); - assert!(err.error.message.contains("chatgpt-global")); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_reads_remote_plugin_details_when_remote_plugin_enabled() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - write_remote_plugin_catalog_config( - codex_home.path(), - &format!("{}/backend-api/", server.uri()), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let detail_body = r#"{ - "id": "linear@chatgpt-global", - "name": "linear", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "display_name": "Linear", - "description": "Track work in Linear", - "app_ids": [], - "interface": { - "short_description": "Plan and track work", - "capabilities": ["Read", "Write"], - "logo_url": "https://example.com/linear.png", - "screenshot_urls": ["https://example.com/linear-shot.png"] - }, - "skills": [ - { - "name": "plan-work", - "description": "Plan work from Linear issues", - "plugin_release_skill_id": "skill-1", - "interface": { - "display_name": "Plan Work", - "short_description": "Create a plan from issues" - } - } - ] - } -}"#; - let installed_body = r#"{ - "plugins": [ - { - "id": "linear@chatgpt-global", - "name": "linear", - "scope": "GLOBAL", - "installation_policy": "AVAILABLE", - "authentication_policy": "ON_USE", - "release": { - "display_name": "Linear", - "description": "Track work in Linear", - "app_ids": [], - "interface": { - "short_description": "Plan and track work", - "capabilities": ["Read", "Write"], - "logo_url": "https://example.com/linear.png", - "screenshot_urls": ["https://example.com/linear-shot.png"] - }, - "skills": [ - { - "name": "plan-work", - "description": "Plan work from Linear issues", - "plugin_release_skill_id": "skill-1", - "interface": { - "display_name": "Plan Work", - "short_description": "Create a plan from issues" - } - } - ] - }, - "enabled": false, - "disabled_skill_names": ["plan-work"] - } - ], - "pagination": { - "limit": 50, - "next_page_token": null - } -}"#; - - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/linear@chatgpt-global")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(detail_body)) - .mount(&server) - .await; - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/installed")) - .and(query_param("scope", "GLOBAL")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(200).set_body_string(installed_body)) - .mount(&server) - .await; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: None, - remote_marketplace_name: Some("chatgpt-global".to_string()), - plugin_name: "linear".to_string(), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginReadResponse = to_response(response)?; - - assert_eq!(response.plugin.marketplace_name, "chatgpt-global"); - assert_eq!(response.plugin.marketplace_path, None); - assert_eq!(response.plugin.summary.source, PluginSource::Remote); - assert_eq!(response.plugin.summary.id, "linear@chatgpt-global"); - assert_eq!(response.plugin.summary.name, "linear"); - assert_eq!(response.plugin.summary.installed, true); - assert_eq!(response.plugin.summary.enabled, false); - assert_eq!( - response.plugin.description.as_deref(), - Some("Track work in Linear") - ); - assert_eq!(response.plugin.skills.len(), 1); - assert_eq!(response.plugin.skills[0].name, "plan-work"); - assert_eq!(response.plugin.skills[0].path, None); - assert_eq!(response.plugin.skills[0].enabled, false); - assert_eq!(response.plugin.apps.len(), 0); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_maps_missing_remote_plugin_to_invalid_request() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - write_remote_plugin_catalog_config( - codex_home.path(), - &format!("{}/backend-api/", server.uri()), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - Mock::given(method("GET")) - .and(path("/backend-api/ps/plugins/missing@chatgpt-global")) - .and(header("authorization", "Bearer chatgpt-token")) - .and(header("chatgpt-account-id", "account-123")) - .respond_with(ResponseTemplate::new(404).set_body_string(r#"{"detail":"not found"}"#)) - .mount(&server) - .await; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: None, - remote_marketplace_name: Some("chatgpt-global".to_string()), - plugin_name: "missing".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!( - err.error - .message - .contains("read remote plugin details: remote plugin catalog request") - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_rejects_remote_marketplace_when_plugins_are_disabled() -> Result<()> { - let codex_home = TempDir::new()?; - let server = MockServer::start().await; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - r#" -chatgpt_base_url = "{}/backend-api/" - -[features] -plugins = false -remote_plugin = true -"#, - server.uri() - ), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: None, - remote_marketplace_name: Some("chatgpt-global".to_string()), - plugin_name: "linear".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!( - err.error - .message - .contains("remote plugin read is not enabled") - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_rejects_invalid_remote_plugin_name() -> Result<()> { - let codex_home = TempDir::new()?; - write_remote_plugin_catalog_config(codex_home.path(), "https://example.invalid/backend-api/")?; - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: None, - remote_marketplace_name: Some("chatgpt-global".to_string()), - plugin_name: "linear/../../oops".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!(err.error.message.contains("invalid remote plugin id")); - assert!(err.error.message.contains("invalid plugin name")); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_returns_canonical_openai_curated_marketplace_name() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - write_plugin_marketplace( - repo_root.path(), - "openai-curated", - "demo-plugin", - "./demo-plugin", - )?; - std::fs::create_dir_all(repo_root.path().join("demo-plugin/.codex-plugin"))?; - std::fs::write( - repo_root - .path() - .join("demo-plugin/.codex-plugin/plugin.json"), - r#"{ - "name": "demo-plugin", - "description": "OpenAI curated plugin" -}"#, - )?; - std::fs::write( - codex_home.path().join("config.toml"), - r#"[features] -plugins = true - -[plugins."demo-plugin@openai-curated"] -enabled = true -"#, - )?; - write_installed_plugin(&codex_home, "openai-curated", "demo-plugin")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?; - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: Some(marketplace_path.clone()), - remote_marketplace_name: None, - plugin_name: "demo-plugin".to_string(), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginReadResponse = to_response(response)?; - - assert_eq!(response.plugin.marketplace_name, "openai-curated"); - assert_eq!(response.plugin.marketplace_path, Some(marketplace_path)); - assert_eq!(response.plugin.summary.id, "demo-plugin@openai-curated"); - assert_eq!(response.plugin.summary.name, "demo-plugin"); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_returns_plugin_details_with_bundle_contents() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - let plugin_root = repo_root.path().join("plugins/demo-plugin"); - std::fs::create_dir_all(repo_root.path().join(".git"))?; - std::fs::create_dir_all(repo_root.path().join(".agents/plugins"))?; - std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?; - std::fs::create_dir_all(plugin_root.join("skills/thread-summarizer"))?; - std::fs::create_dir_all(plugin_root.join("skills/chatgpt-only"))?; - std::fs::write( - repo_root.path().join(".agents/plugins/marketplace.json"), - r#"{ - "name": "codex-curated", - "plugins": [ - { - "name": "demo-plugin", - "source": { - "source": "local", - "path": "./plugins/demo-plugin" - }, - "policy": { - "installation": "AVAILABLE", - "authentication": "ON_INSTALL" - }, - "category": "Design" - } - ] -}"#, - )?; - std::fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - r##"{ - "name": "demo-plugin", - "description": "Longer manifest description", - "interface": { - "displayName": "Plugin Display Name", - "shortDescription": "Short description for subtitle", - "longDescription": "Long description for details page", - "developerName": "OpenAI", - "category": "Productivity", - "capabilities": ["Interactive", "Write"], - "websiteURL": "https://openai.com/", - "privacyPolicyURL": "https://openai.com/policies/row-privacy-policy/", - "termsOfServiceURL": "https://openai.com/policies/row-terms-of-use/", - "defaultPrompt": [ - "Draft the reply", - "Find my next action" - ], - "brandColor": "#3B82F6", - "composerIcon": "./assets/icon.png", - "logo": "./assets/logo.png", - "screenshots": ["./assets/screenshot1.png"] - } -}"##, - )?; - std::fs::write( - plugin_root.join("skills/thread-summarizer/SKILL.md"), - r#"--- -name: thread-summarizer -description: Summarize email threads ---- - -# Thread Summarizer -"#, - )?; - std::fs::write( - plugin_root.join("skills/chatgpt-only/SKILL.md"), - r#"--- -name: chatgpt-only -description: Visible only for ChatGPT ---- - -# ChatGPT Only -"#, - )?; - std::fs::create_dir_all(plugin_root.join("skills/thread-summarizer/agents"))?; - std::fs::write( - plugin_root.join("skills/thread-summarizer/agents/openai.yaml"), - r#"policy: - products: - - CODEX -"#, - )?; - std::fs::create_dir_all(plugin_root.join("skills/chatgpt-only/agents"))?; - std::fs::write( - plugin_root.join("skills/chatgpt-only/agents/openai.yaml"), - r#"policy: - products: - - CHATGPT -"#, - )?; - std::fs::write( - plugin_root.join(".app.json"), - r#"{ - "apps": { - "gmail": { - "id": "gmail" - } - } -}"#, - )?; - std::fs::write( - plugin_root.join(".mcp.json"), - r#"{ - "mcpServers": { - "demo": { - "command": "demo-server" - } - } -}"#, - )?; - std::fs::write( - codex_home.path().join("config.toml"), - r#"[features] -plugins = true - -[[skills.config]] -name = "demo-plugin:thread-summarizer" -enabled = false - -[plugins."demo-plugin@codex-curated"] -enabled = true -"#, - )?; - write_installed_plugin(&codex_home, "codex-curated", "demo-plugin")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?; - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: Some(marketplace_path.clone()), - remote_marketplace_name: None, - plugin_name: "demo-plugin".to_string(), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginReadResponse = to_response(response)?; - - assert_eq!(response.plugin.marketplace_name, "codex-curated"); - assert_eq!(response.plugin.marketplace_path, Some(marketplace_path)); - assert_eq!(response.plugin.summary.id, "demo-plugin@codex-curated"); - assert_eq!(response.plugin.summary.name, "demo-plugin"); - assert_eq!( - response.plugin.description.as_deref(), - Some("Longer manifest description") - ); - assert_eq!(response.plugin.summary.installed, true); - assert_eq!(response.plugin.summary.enabled, true); - assert_eq!( - response.plugin.summary.install_policy, - PluginInstallPolicy::Available - ); - assert_eq!( - response.plugin.summary.auth_policy, - PluginAuthPolicy::OnInstall - ); - assert_eq!( - response - .plugin - .summary - .interface - .as_ref() - .and_then(|interface| interface.display_name.as_deref()), - Some("Plugin Display Name") - ); - assert_eq!( - response - .plugin - .summary - .interface - .as_ref() - .and_then(|interface| interface.category.as_deref()), - Some("Design") - ); - assert_eq!( - response - .plugin - .summary - .interface - .as_ref() - .and_then(|interface| interface.default_prompt.clone()), - Some(vec![ - "Draft the reply".to_string(), - "Find my next action".to_string() - ]) - ); - assert_eq!(response.plugin.skills.len(), 1); - assert_eq!( - response.plugin.skills[0].name, - "demo-plugin:thread-summarizer" - ); - assert_eq!( - response.plugin.skills[0].description, - "Summarize email threads" - ); - assert!(!response.plugin.skills[0].enabled); - assert_eq!(response.plugin.apps.len(), 1); - assert_eq!(response.plugin.apps[0].id, "gmail"); - assert_eq!(response.plugin.apps[0].name, "gmail"); - assert_eq!( - response.plugin.apps[0].install_url.as_deref(), - Some("https://chatgpt.com/apps/gmail/gmail") - ); - assert_eq!(response.plugin.apps[0].needs_auth, true); - assert_eq!(response.plugin.mcp_servers.len(), 1); - assert_eq!(response.plugin.mcp_servers[0], "demo"); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_returns_app_needs_auth() -> Result<()> { - let connectors = vec![ - AppInfo { - id: "alpha".to_string(), - name: "Alpha".to_string(), - description: Some("Alpha connector".to_string()), - logo_url: Some("https://example.com/alpha.png".to_string()), - logo_url_dark: None, - distribution_channel: Some("featured".to_string()), - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - AppInfo { - id: "beta".to_string(), - name: "Beta".to_string(), - description: Some("Beta connector".to_string()), - logo_url: None, - logo_url_dark: None, - distribution_channel: None, - branding: None, - app_metadata: None, - labels: None, - install_url: None, - is_accessible: false, - is_enabled: true, - plugin_display_names: Vec::new(), - }, - ]; - let tools = vec![connector_tool("beta", "Beta App")?]; - let (server_url, server_handle) = start_apps_server(connectors, tools).await?; - - let codex_home = TempDir::new()?; - write_connectors_config(codex_home.path(), &server_url)?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let repo_root = TempDir::new()?; - write_plugin_marketplace( - repo_root.path(), - "debug", - "sample-plugin", - "./sample-plugin", - )?; - write_plugin_source(repo_root.path(), "sample-plugin", &["alpha", "beta"])?; - let marketplace_path = - AbsolutePathBuf::try_from(repo_root.path().join(".agents/plugins/marketplace.json"))?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: Some(marketplace_path), - remote_marketplace_name: None, - plugin_name: "sample-plugin".to_string(), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginReadResponse = to_response(response)?; - - assert_eq!( - response - .plugin - .apps - .iter() - .map(|app| (app.id.as_str(), app.needs_auth)) - .collect::>(), - vec![("alpha", true), ("beta", false)] - ); - - server_handle.abort(); - let _ = server_handle.await; - Ok(()) -} - -#[tokio::test] -async fn plugin_read_accepts_legacy_string_default_prompt() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - let plugin_root = repo_root.path().join("plugins/demo-plugin"); - std::fs::create_dir_all(repo_root.path().join(".git"))?; - std::fs::create_dir_all(repo_root.path().join(".agents/plugins"))?; - std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?; - std::fs::write( - repo_root.path().join(".agents/plugins/marketplace.json"), - r#"{ - "name": "codex-curated", - "plugins": [ - { - "name": "demo-plugin", - "source": { - "source": "local", - "path": "./plugins/demo-plugin" - } - } - ] -}"#, - )?; - std::fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - r##"{ - "name": "demo-plugin", - "interface": { - "defaultPrompt": "Starter prompt for trying a plugin" - } -}"##, - )?; - write_plugins_enabled_config(&codex_home)?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: Some(AbsolutePathBuf::try_from( - repo_root.path().join(".agents/plugins/marketplace.json"), - )?), - remote_marketplace_name: None, - plugin_name: "demo-plugin".to_string(), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginReadResponse = to_response(response)?; - - assert_eq!( - response - .plugin - .summary - .interface - .as_ref() - .and_then(|interface| interface.default_prompt.clone()), - Some(vec!["Starter prompt for trying a plugin".to_string()]) - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_describes_uninstalled_git_source_without_cloning() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - let missing_remote_repo = repo_root.path().join("missing-remote-plugin-repo"); - let missing_remote_repo_url = url::Url::from_directory_path(&missing_remote_repo) - .unwrap() - .to_string(); - std::fs::create_dir_all(repo_root.path().join(".git"))?; - std::fs::create_dir_all(repo_root.path().join(".agents/plugins"))?; - std::fs::write( - repo_root.path().join(".agents/plugins/marketplace.json"), - format!( - r#"{{ - "name": "debug", - "plugins": [ - {{ - "name": "toolkit", - "source": {{ - "source": "git-subdir", - "url": "{missing_remote_repo_url}", - "path": "plugins/toolkit" - }} - }} - ] -}}"# - ), - )?; - write_plugins_enabled_config(&codex_home)?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: Some(AbsolutePathBuf::try_from( - repo_root.path().join(".agents/plugins/marketplace.json"), - )?), - remote_marketplace_name: None, - plugin_name: "toolkit".to_string(), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginReadResponse = to_response(response)?; - - let expected_description = format!( - "This is a cross-repo plugin. Install it to view more detailed information. The source of the plugin is {missing_remote_repo_url}, path `plugins/toolkit`." - ); - assert_eq!( - response.plugin.description.as_deref(), - Some(expected_description.as_str()) - ); - assert!(!response.plugin.summary.installed); - assert!(response.plugin.skills.is_empty()); - assert!(response.plugin.apps.is_empty()); - assert!(response.plugin.mcp_servers.is_empty()); - assert!( - !codex_home - .path() - .join("plugins/.marketplace-plugin-source-staging") - .exists() - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_returns_invalid_request_when_plugin_is_missing() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - std::fs::create_dir_all(repo_root.path().join(".git"))?; - std::fs::create_dir_all(repo_root.path().join(".agents/plugins"))?; - std::fs::write( - repo_root.path().join(".agents/plugins/marketplace.json"), - r#"{ - "name": "codex-curated", - "plugins": [ - { - "name": "demo-plugin", - "source": { - "source": "local", - "path": "./plugins/demo-plugin" - } - } - ] -}"#, - )?; - write_plugins_enabled_config(&codex_home)?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: Some(AbsolutePathBuf::try_from( - repo_root.path().join(".agents/plugins/marketplace.json"), - )?), - remote_marketplace_name: None, - plugin_name: "missing-plugin".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!( - err.error - .message - .contains("plugin `missing-plugin` was not found") - ); - Ok(()) -} - -#[tokio::test] -async fn plugin_read_returns_invalid_request_when_plugin_manifest_is_missing() -> Result<()> { - let codex_home = TempDir::new()?; - let repo_root = TempDir::new()?; - let plugin_root = repo_root.path().join("plugins/demo-plugin"); - std::fs::create_dir_all(repo_root.path().join(".git"))?; - std::fs::create_dir_all(repo_root.path().join(".agents/plugins"))?; - std::fs::create_dir_all(&plugin_root)?; - std::fs::write( - repo_root.path().join(".agents/plugins/marketplace.json"), - r#"{ - "name": "codex-curated", - "plugins": [ - { - "name": "demo-plugin", - "source": { - "source": "local", - "path": "./plugins/demo-plugin" - } - } - ] -}"#, - )?; - write_plugins_enabled_config(&codex_home)?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_read_request(PluginReadParams { - marketplace_path: Some(AbsolutePathBuf::try_from( - repo_root.path().join(".agents/plugins/marketplace.json"), - )?), - remote_marketplace_name: None, - plugin_name: "demo-plugin".to_string(), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - - assert_eq!(err.error.code, -32600); - assert!(err.error.message.contains("missing or invalid plugin.json")); - Ok(()) -} - -fn write_installed_plugin( - codex_home: &TempDir, - marketplace_name: &str, - plugin_name: &str, -) -> Result<()> { - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join(marketplace_name) - .join(plugin_name) - .join("local/.codex-plugin"); - std::fs::create_dir_all(&plugin_root)?; - std::fs::write( - plugin_root.join("plugin.json"), - format!(r#"{{"name":"{plugin_name}"}}"#), - )?; - Ok(()) -} - -fn write_plugins_enabled_config(codex_home: &TempDir) -> Result<()> { - std::fs::write( - codex_home.path().join("config.toml"), - r#"[features] -plugins = true -"#, - )?; - Ok(()) -} - -#[derive(Clone)] -struct AppsServerState { - response: Arc>, -} - -#[derive(Clone)] -struct PluginReadMcpServer { - tools: Arc>>, -} - -impl ServerHandler for PluginReadMcpServer { - fn get_info(&self) -> ServerInfo { - ServerInfo { - capabilities: ServerCapabilities::builder().enable_tools().build(), - ..ServerInfo::default() - } - } - - fn list_tools( - &self, - _request: Option, - _context: rmcp::service::RequestContext, - ) -> impl std::future::Future> + Send + '_ - { - let tools = self.tools.clone(); - async move { - let tools = tools - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - Ok(ListToolsResult { - tools, - next_cursor: None, - meta: None, - }) - } - } -} - -async fn start_apps_server( - connectors: Vec, - tools: Vec, -) -> Result<(String, JoinHandle<()>)> { - let state = Arc::new(AppsServerState { - response: Arc::new(StdMutex::new( - json!({ "apps": connectors, "next_token": null }), - )), - }); - let tools = Arc::new(StdMutex::new(tools)); - - let listener = TcpListener::bind("127.0.0.1:0").await?; - let addr = listener.local_addr()?; - let mcp_service = StreamableHttpService::new( - { - let tools = tools.clone(); - move || { - Ok(PluginReadMcpServer { - tools: tools.clone(), - }) - } - }, - Arc::new(LocalSessionManager::default()), - StreamableHttpServerConfig::default(), - ); - let router = Router::new() - .route("/connectors/directory/list", get(list_directory_connectors)) - .route( - "/connectors/directory/list_workspace", - get(list_directory_connectors), - ) - .with_state(state) - .nest_service("/api/codex/apps", mcp_service); - - let handle = tokio::spawn(async move { - let _ = axum::serve(listener, router).await; - }); - - Ok((format!("http://{addr}"), handle)) -} - -async fn list_directory_connectors( - State(state): State>, - headers: HeaderMap, - uri: Uri, -) -> Result { - let bearer_ok = headers - .get(AUTHORIZATION) - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == "Bearer chatgpt-token"); - let account_ok = headers - .get("chatgpt-account-id") - .and_then(|value| value.to_str().ok()) - .is_some_and(|value| value == "account-123"); - let external_logos_ok = uri - .query() - .is_some_and(|query| query.split('&').any(|pair| pair == "external_logos=true")); - - if !bearer_ok || !account_ok { - Err(StatusCode::UNAUTHORIZED) - } else if !external_logos_ok { - Err(StatusCode::BAD_REQUEST) - } else { - let response = state - .response - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - Ok(Json(response)) - } -} - -fn connector_tool(connector_id: &str, connector_name: &str) -> Result { - let schema: JsonObject = serde_json::from_value(json!({ - "type": "object", - "additionalProperties": false - }))?; - let mut tool = Tool::new( - Cow::Owned(format!("connector_{connector_id}")), - Cow::Borrowed("Connector test tool"), - Arc::new(schema), - ); - tool.annotations = Some(ToolAnnotations::new().read_only(true)); - - let mut meta = Meta::new(); - meta.0 - .insert("connector_id".to_string(), json!(connector_id)); - meta.0 - .insert("connector_name".to_string(), json!(connector_name)); - tool.meta = Some(meta); - Ok(tool) -} - -fn write_connectors_config(codex_home: &std::path::Path, base_url: &str) -> std::io::Result<()> { - std::fs::write( - codex_home.join("config.toml"), - format!( - r#" -chatgpt_base_url = "{base_url}" -mcp_oauth_credentials_store = "file" - -[features] -plugins = true -connectors = true -"# - ), - ) -} - -fn write_remote_plugin_catalog_config( - codex_home: &std::path::Path, - base_url: &str, -) -> std::io::Result<()> { - std::fs::write( - codex_home.join("config.toml"), - format!( - r#" -chatgpt_base_url = "{base_url}" - -[features] -plugins = true -remote_plugin = true -"# - ), - ) -} - -fn write_plugin_marketplace( - repo_root: &std::path::Path, - marketplace_name: &str, - plugin_name: &str, - source_path: &str, -) -> std::io::Result<()> { - std::fs::create_dir_all(repo_root.join(".git"))?; - std::fs::create_dir_all(repo_root.join(".agents/plugins"))?; - std::fs::write( - repo_root.join(".agents/plugins/marketplace.json"), - format!( - r#"{{ - "name": "{marketplace_name}", - "plugins": [ - {{ - "name": "{plugin_name}", - "source": {{ - "source": "local", - "path": "{source_path}" - }} - }} - ] -}}"# - ), - ) -} - -fn write_plugin_source( - repo_root: &std::path::Path, - plugin_name: &str, - app_ids: &[&str], -) -> Result<()> { - let plugin_root = repo_root.join(plugin_name); - std::fs::create_dir_all(plugin_root.join(".codex-plugin"))?; - std::fs::write( - plugin_root.join(".codex-plugin/plugin.json"), - format!(r#"{{"name":"{plugin_name}"}}"#), - )?; - - let apps = app_ids - .iter() - .map(|app_id| ((*app_id).to_string(), json!({ "id": app_id }))) - .collect::>(); - std::fs::write( - plugin_root.join(".app.json"), - serde_json::to_vec_pretty(&json!({ "apps": apps }))?, - )?; - Ok(()) -} diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs deleted file mode 100644 index 512cce39..00000000 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/plugin_uninstall.rs +++ /dev/null @@ -1,163 +0,0 @@ -use std::time::Duration; - -use anyhow::Result; -use app_test_support::ChatGptAuthFixture; -use app_test_support::DEFAULT_CLIENT_NAME; -use app_test_support::McpProcess; -use app_test_support::start_analytics_events_server; -use app_test_support::to_response; -use app_test_support::write_chatgpt_auth; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::PluginUninstallParams; -use codex_app_server_protocol::PluginUninstallResponse; -use codex_app_server_protocol::RequestId; -use codex_config::types::AuthCredentialsStoreMode; -use pretty_assertions::assert_eq; -use serde_json::json; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); - -#[tokio::test] -async fn plugin_uninstall_removes_plugin_cache_and_config_entry() -> Result<()> { - let codex_home = TempDir::new()?; - write_installed_plugin(&codex_home, "debug", "sample-plugin")?; - std::fs::write( - codex_home.path().join("config.toml"), - r#"[features] -plugins = true - -[plugins."sample-plugin@debug"] -enabled = true -"#, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let params = PluginUninstallParams { - plugin_id: "sample-plugin@debug".to_string(), - }; - - let request_id = mcp.send_plugin_uninstall_request(params.clone()).await?; - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginUninstallResponse = to_response(response)?; - assert_eq!(response, PluginUninstallResponse {}); - - assert!( - !codex_home - .path() - .join("plugins/cache/debug/sample-plugin") - .exists() - ); - let config = std::fs::read_to_string(codex_home.path().join("config.toml"))?; - assert!(!config.contains(r#"[plugins."sample-plugin@debug"]"#)); - - let request_id = mcp.send_plugin_uninstall_request(params).await?; - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginUninstallResponse = to_response(response)?; - assert_eq!(response, PluginUninstallResponse {}); - - Ok(()) -} - -#[tokio::test] -async fn plugin_uninstall_tracks_analytics_event() -> Result<()> { - let analytics_server = start_analytics_events_server().await?; - let codex_home = TempDir::new()?; - write_installed_plugin(&codex_home, "debug", "sample-plugin")?; - std::fs::write( - codex_home.path().join("config.toml"), - format!( - "chatgpt_base_url = \"{}\"\n\n[features]\nplugins = true\n\n[plugins.\"sample-plugin@debug\"]\nenabled = true\n", - analytics_server.uri() - ), - )?; - write_chatgpt_auth( - codex_home.path(), - ChatGptAuthFixture::new("chatgpt-token") - .account_id("account-123") - .chatgpt_user_id("user-123") - .chatgpt_account_id("account-123"), - AuthCredentialsStoreMode::File, - )?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_plugin_uninstall_request(PluginUninstallParams { - plugin_id: "sample-plugin@debug".to_string(), - }) - .await?; - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let response: PluginUninstallResponse = to_response(response)?; - assert_eq!(response, PluginUninstallResponse {}); - - let payload = timeout(DEFAULT_TIMEOUT, async { - loop { - let Some(requests) = analytics_server.received_requests().await else { - tokio::time::sleep(Duration::from_millis(25)).await; - continue; - }; - if let Some(request) = requests.iter().find(|request| { - request.method == "POST" && request.url.path() == "/codex/analytics-events/events" - }) { - break request.body.clone(); - } - tokio::time::sleep(Duration::from_millis(25)).await; - } - }) - .await?; - let payload: serde_json::Value = serde_json::from_slice(&payload).expect("analytics payload"); - assert_eq!( - payload, - json!({ - "events": [{ - "event_type": "codex_plugin_uninstalled", - "event_params": { - "plugin_id": "sample-plugin@debug", - "plugin_name": "sample-plugin", - "marketplace_name": "debug", - "has_skills": false, - "mcp_server_count": 0, - "connector_ids": [], - "product_client_id": DEFAULT_CLIENT_NAME, - } - }] - }) - ); - Ok(()) -} - -fn write_installed_plugin( - codex_home: &TempDir, - marketplace_name: &str, - plugin_name: &str, -) -> Result<()> { - let plugin_root = codex_home - .path() - .join("plugins/cache") - .join(marketplace_name) - .join(plugin_name) - .join("local/.codex-plugin"); - std::fs::create_dir_all(&plugin_root)?; - std::fs::write( - plugin_root.join("plugin.json"), - format!(r#"{{"name":"{plugin_name}"}}"#), - )?; - Ok(()) -} diff --git a/vendor/codex/codex-rs/app-server/tests/suite/v2/skills_list.rs b/vendor/codex/codex-rs/app-server/tests/suite/v2/skills_list.rs deleted file mode 100644 index 195c4a86..00000000 --- a/vendor/codex/codex-rs/app-server/tests/suite/v2/skills_list.rs +++ /dev/null @@ -1,360 +0,0 @@ -use std::time::Duration; - -use anyhow::Context; -use anyhow::Result; -use app_test_support::McpProcess; -use app_test_support::to_response; -use codex_app_server_protocol::JSONRPCResponse; -use codex_app_server_protocol::RequestId; -use codex_app_server_protocol::SkillsChangedNotification; -use codex_app_server_protocol::SkillsListExtraRootsForCwd; -use codex_app_server_protocol::SkillsListParams; -use codex_app_server_protocol::SkillsListResponse; -use codex_app_server_protocol::ThreadStartParams; -use codex_exec_server::CODEX_EXEC_SERVER_URL_ENV_VAR; -use pretty_assertions::assert_eq; -use tempfile::TempDir; -use tokio::time::timeout; - -const DEFAULT_TIMEOUT: Duration = Duration::from_secs(10); -const WATCHER_TIMEOUT: Duration = Duration::from_secs(20); - -fn write_skill(root: &TempDir, name: &str) -> Result<()> { - let skill_dir = root.path().join("skills").join(name); - std::fs::create_dir_all(&skill_dir)?; - let content = format!("---\nname: {name}\ndescription: {name} description\n---\n\n# Body\n"); - std::fs::write(skill_dir.join("SKILL.md"), content)?; - Ok(()) -} - -#[tokio::test] -async fn skills_list_includes_skills_from_per_cwd_extra_user_roots() -> Result<()> { - let codex_home = TempDir::new()?; - let cwd = TempDir::new()?; - let extra_root = TempDir::new()?; - write_skill(&extra_root, "extra-skill")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![cwd.path().to_path_buf()], - force_reload: true, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: cwd.path().to_path_buf(), - extra_user_roots: vec![extra_root.path().to_path_buf()], - }]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let SkillsListResponse { data } = to_response(response)?; - assert_eq!(data.len(), 1); - assert_eq!(data[0].cwd.as_path(), cwd.path()); - assert!( - data[0] - .skills - .iter() - .any(|skill| skill.name == "extra-skill") - ); - Ok(()) -} - -#[tokio::test] -async fn skills_list_skips_cwd_roots_when_environment_disabled() -> Result<()> { - let codex_home = TempDir::new()?; - let cwd = TempDir::new()?; - let extra_root = TempDir::new()?; - write_skill(&codex_home, "home-skill")?; - write_skill(&extra_root, "extra-skill")?; - - let mut mcp = McpProcess::new_with_env( - codex_home.path(), - &[(CODEX_EXEC_SERVER_URL_ENV_VAR, Some("none"))], - ) - .await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![cwd.path().to_path_buf()], - force_reload: true, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: cwd.path().to_path_buf(), - extra_user_roots: vec![extra_root.path().to_path_buf()], - }]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let SkillsListResponse { data } = to_response(response)?; - assert_eq!(data.len(), 1); - assert_eq!(data[0].cwd, cwd.path().to_path_buf()); - assert_eq!(data[0].errors, Vec::new()); - assert!( - data[0] - .skills - .iter() - .any(|skill| skill.name == "home-skill") - ); - assert!( - data[0] - .skills - .iter() - .all(|skill| skill.name != "extra-skill") - ); - Ok(()) -} - -#[tokio::test] -async fn skills_list_rejects_relative_extra_user_roots() -> Result<()> { - let codex_home = TempDir::new()?; - let cwd = TempDir::new()?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![cwd.path().to_path_buf()], - force_reload: true, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: cwd.path().to_path_buf(), - extra_user_roots: vec![std::path::PathBuf::from("relative/skills")], - }]), - }) - .await?; - - let err = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_error_message(RequestId::Integer(request_id)), - ) - .await??; - assert!( - err.error - .message - .contains("perCwdExtraUserRoots extraUserRoots paths must be absolute"), - "unexpected error: {}", - err.error.message - ); - Ok(()) -} - -#[tokio::test] -async fn skills_list_accepts_relative_cwds() -> Result<()> { - let codex_home = TempDir::new()?; - let relative_cwd = std::path::PathBuf::from("relative-cwd"); - std::fs::create_dir_all(codex_home.path().join(&relative_cwd))?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![relative_cwd.clone()], - force_reload: true, - per_cwd_extra_user_roots: None, - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let SkillsListResponse { data } = to_response(response)?; - assert_eq!(data.len(), 1); - assert_eq!(data[0].cwd, relative_cwd); - assert_eq!(data[0].errors, Vec::new()); - Ok(()) -} - -#[tokio::test] -async fn skills_list_ignores_per_cwd_extra_roots_for_unknown_cwd() -> Result<()> { - let codex_home = TempDir::new()?; - let requested_cwd = TempDir::new()?; - let unknown_cwd = TempDir::new()?; - let extra_root = TempDir::new()?; - write_skill(&extra_root, "ignored-extra-skill")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - let request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![requested_cwd.path().to_path_buf()], - force_reload: true, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: unknown_cwd.path().to_path_buf(), - extra_user_roots: vec![extra_root.path().to_path_buf()], - }]), - }) - .await?; - - let response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(request_id)), - ) - .await??; - let SkillsListResponse { data } = to_response(response)?; - assert_eq!(data.len(), 1); - assert_eq!(data[0].cwd.as_path(), requested_cwd.path()); - assert!( - data[0] - .skills - .iter() - .all(|skill| skill.name != "ignored-extra-skill") - ); - Ok(()) -} - -#[tokio::test] -async fn skills_list_uses_cached_result_until_force_reload() -> Result<()> { - let codex_home = TempDir::new()?; - let cwd = TempDir::new()?; - let extra_root = TempDir::new()?; - write_skill(&extra_root, "late-extra-skill")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - - // Seed the cwd cache first without extra roots. - let first_request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![cwd.path().to_path_buf()], - force_reload: false, - per_cwd_extra_user_roots: None, - }) - .await?; - let first_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(first_request_id)), - ) - .await??; - let SkillsListResponse { data: first_data } = to_response(first_response)?; - assert_eq!(first_data.len(), 1); - assert!( - first_data[0] - .skills - .iter() - .all(|skill| skill.name != "late-extra-skill") - ); - - let second_request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![cwd.path().to_path_buf()], - force_reload: false, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: cwd.path().to_path_buf(), - extra_user_roots: vec![extra_root.path().to_path_buf()], - }]), - }) - .await?; - let second_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(second_request_id)), - ) - .await??; - let SkillsListResponse { data: second_data } = to_response(second_response)?; - assert_eq!(second_data.len(), 1); - assert!( - second_data[0] - .skills - .iter() - .all(|skill| skill.name != "late-extra-skill") - ); - - let third_request_id = mcp - .send_skills_list_request(SkillsListParams { - cwds: vec![cwd.path().to_path_buf()], - force_reload: true, - per_cwd_extra_user_roots: Some(vec![SkillsListExtraRootsForCwd { - cwd: cwd.path().to_path_buf(), - extra_user_roots: vec![extra_root.path().to_path_buf()], - }]), - }) - .await?; - let third_response: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(third_request_id)), - ) - .await??; - let SkillsListResponse { data: third_data } = to_response(third_response)?; - assert_eq!(third_data.len(), 1); - assert!( - third_data[0] - .skills - .iter() - .any(|skill| skill.name == "late-extra-skill") - ); - Ok(()) -} - -#[tokio::test] -async fn skills_changed_notification_is_emitted_after_skill_change() -> Result<()> { - let codex_home = TempDir::new()?; - write_skill(&codex_home, "demo")?; - - let mut mcp = McpProcess::new(codex_home.path()).await?; - timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; - let thread_start_request_id = mcp - .send_thread_start_request(ThreadStartParams { - model: None, - model_provider: None, - service_tier: None, - cwd: None, - approval_policy: None, - approvals_reviewer: None, - sandbox: None, - permission_profile: None, - config: None, - service_name: None, - base_instructions: None, - developer_instructions: None, - personality: None, - ephemeral: None, - session_start_source: None, - dynamic_tools: None, - mock_experimental_field: None, - experimental_raw_events: false, - persist_extended_history: false, - }) - .await?; - let _: JSONRPCResponse = timeout( - DEFAULT_TIMEOUT, - mcp.read_stream_until_response_message(RequestId::Integer(thread_start_request_id)), - ) - .await??; - - let skill_path = codex_home - .path() - .join("skills") - .join("demo") - .join("SKILL.md"); - std::fs::write( - &skill_path, - "---\nname: demo\ndescription: updated\n---\n\n# Updated\n", - )?; - - let notification = timeout( - WATCHER_TIMEOUT, - mcp.read_stream_until_notification_message("skills/changed"), - ) - .await??; - let params = notification - .params - .context("skills/changed params must be present")?; - let notification: SkillsChangedNotification = serde_json::from_value(params)?; - - assert_eq!(notification, SkillsChangedNotification {}); - Ok(()) -}