diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 5d17c0f603..700af4c4b0 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2780,6 +2780,7 @@ dependencies = [ "anyhow", "chrono", "codex-config", + "codex-plugin", "codex-protocol", "codex-utils-absolute-path", "futures", @@ -3151,6 +3152,7 @@ dependencies = [ name = "codex-plugin" version = "0.0.0" dependencies = [ + "codex-config", "codex-utils-absolute-path", "codex-utils-plugins", "thiserror 2.0.18", diff --git a/codex-rs/analytics/src/events.rs b/codex-rs/analytics/src/events.rs index 98d0e6ff6b..24ae8e00b9 100644 --- a/codex-rs/analytics/src/events.rs +++ b/codex-rs/analytics/src/events.rs @@ -684,6 +684,7 @@ fn analytics_hook_source(source: HookSource) -> &'static str { HookSource::Project => "project", HookSource::Mdm => "mdm", HookSource::SessionFlags => "session_flags", + HookSource::Plugin => "plugin", HookSource::LegacyManagedConfigFile => "legacy_managed_config_file", HookSource::LegacyManagedConfigMdm => "legacy_managed_config_mdm", HookSource::Unknown => "unknown", diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index aa5c944d9c..c94559c112 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -1900,6 +1900,7 @@ "project", "mdm", "sessionFlags", + "plugin", "legacyManagedConfigFile", "legacyManagedConfigMdm", "unknown" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index db834cb578..11f0638555 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -5345,6 +5345,26 @@ "title": "AccountUpdatedNotification", "type": "object" }, + "ActivePermissionProfile": { + "properties": { + "extends": { + "default": null, + "description": "Parent profile identifier once permissions profiles support inheritance. This is currently always `null`.", + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "Identifier from `default_permissions`, such as a built-in `:workspace` profile or a user-defined `[permissions.]` profile.", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, "AddCreditsNudgeCreditType": { "enum": [ "credits", @@ -9680,6 +9700,7 @@ "project", "mdm", "sessionFlags", + "plugin", "legacyManagedConfigFile", "legacyManagedConfigMdm", "unknown" diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 826d0da65c..13448e5ec3 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -130,6 +130,26 @@ "title": "AccountUpdatedNotification", "type": "object" }, + "ActivePermissionProfile": { + "properties": { + "extends": { + "default": null, + "description": "Parent profile identifier once permissions profiles support inheritance. This is currently always `null`.", + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "Identifier from `default_permissions`, such as a built-in `:workspace` profile or a user-defined `[permissions.]` profile.", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, "AddCreditsNudgeCreditType": { "enum": [ "credits", @@ -6310,6 +6330,7 @@ "project", "mdm", "sessionFlags", + "plugin", "legacyManagedConfigFile", "legacyManagedConfigMdm", "unknown" diff --git a/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json index a4d378649b..7c03e35543 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/HookCompletedNotification.json @@ -160,6 +160,7 @@ "project", "mdm", "sessionFlags", + "plugin", "legacyManagedConfigFile", "legacyManagedConfigMdm", "unknown" diff --git a/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json index ac77d6163f..d08300d526 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/HookStartedNotification.json @@ -160,6 +160,7 @@ "project", "mdm", "sessionFlags", + "plugin", "legacyManagedConfigFile", "legacyManagedConfigMdm", "unknown" diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json index b5d6b139b2..2699d77d02 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadForkResponse.json @@ -5,6 +5,26 @@ "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", "type": "string" }, + "ActivePermissionProfile": { + "properties": { + "extends": { + "default": null, + "description": "Parent profile identifier once permissions profiles support inheritance. This is currently always `null`.", + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "Identifier from `default_permissions`, such as a built-in `:workspace` profile or a user-defined `[permissions.]` profile.", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, "AgentPath": { "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json index 7135a53174..bec0986e5a 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadResumeResponse.json @@ -5,6 +5,26 @@ "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", "type": "string" }, + "ActivePermissionProfile": { + "properties": { + "extends": { + "default": null, + "description": "Parent profile identifier once permissions profiles support inheritance. This is currently always `null`.", + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "Identifier from `default_permissions`, such as a built-in `:workspace` profile or a user-defined `[permissions.]` profile.", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, "AgentPath": { "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json index 5deca9f699..31de006a59 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ThreadStartResponse.json @@ -5,6 +5,26 @@ "description": "A path that is guaranteed to be absolute and normalized (though it is not guaranteed to be canonicalized or exist on the filesystem).\n\nIMPORTANT: When deserializing an `AbsolutePathBuf`, a base path must be set using [AbsolutePathBufGuard::new]. If no base path is set, the deserialization will fail unless the path being deserialized is already absolute.", "type": "string" }, + "ActivePermissionProfile": { + "properties": { + "extends": { + "default": null, + "description": "Parent profile identifier once permissions profiles support inheritance. This is currently always `null`.", + "type": [ + "string", + "null" + ] + }, + "id": { + "description": "Identifier from `default_permissions`, such as a built-in `:workspace` profile or a user-defined `[permissions.]` profile.", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, "AgentPath": { "type": "string" }, diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ActivePermissionProfile.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ActivePermissionProfile.ts new file mode 100644 index 0000000000..d6e560d0f1 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ActivePermissionProfile.ts @@ -0,0 +1,15 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +export type ActivePermissionProfile = { +/** + * Identifier from `default_permissions`, such as a built-in `:workspace` + * profile or a user-defined `[permissions.]` profile. + */ +id: string, +/** + * Parent profile identifier once permissions profiles support + * inheritance. This is currently always `null`. + */ +extends: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/HookSource.ts b/codex-rs/app-server-protocol/schema/typescript/v2/HookSource.ts index 7edf61f918..24a06bd138 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/HookSource.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/HookSource.ts @@ -2,4 +2,4 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. -export type HookSource = "system" | "user" | "project" | "mdm" | "sessionFlags" | "legacyManagedConfigFile" | "legacyManagedConfigMdm" | "unknown"; +export type HookSource = "system" | "user" | "project" | "mdm" | "sessionFlags" | "plugin" | "legacyManagedConfigFile" | "legacyManagedConfigMdm" | "unknown"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index 3c0178c290..35a87aed62 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -4,6 +4,7 @@ export type { Account } from "./Account"; export type { AccountLoginCompletedNotification } from "./AccountLoginCompletedNotification"; export type { AccountRateLimitsUpdatedNotification } from "./AccountRateLimitsUpdatedNotification"; export type { AccountUpdatedNotification } from "./AccountUpdatedNotification"; +export type { ActivePermissionProfile } from "./ActivePermissionProfile"; export type { AddCreditsNudgeCreditType } from "./AddCreditsNudgeCreditType"; export type { AddCreditsNudgeEmailStatus } from "./AddCreditsNudgeEmailStatus"; export type { AdditionalFileSystemPermissions } from "./AdditionalFileSystemPermissions"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 99f4d7d3e1..ee95d4e081 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -2003,6 +2003,7 @@ mod tests { ) .into(), ), + active_permission_profile: None, reasoning_effort: None, }, }; @@ -2048,6 +2049,7 @@ mod tests { "permissionProfile": { "type": "disabled" }, + "activePermissionProfile": null, "reasoningEffort": null } }), diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 2a9b41392b..bd922f99f4 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -38,6 +38,7 @@ use codex_protocol::mcp::ResourceTemplate as McpResourceTemplate; use codex_protocol::mcp::Tool as McpTool; use codex_protocol::memory_citation::MemoryCitation as CoreMemoryCitation; use codex_protocol::memory_citation::MemoryCitationEntry as CoreMemoryCitationEntry; +use codex_protocol::models::ActivePermissionProfile as CoreActivePermissionProfile; use codex_protocol::models::AdditionalPermissionProfile as CoreAdditionalPermissionProfile; use codex_protocol::models::FileSystemPermissions as CoreFileSystemPermissions; use codex_protocol::models::ManagedFileSystemPermissions as CoreManagedFileSystemPermissions; @@ -469,6 +470,7 @@ v2_enum_from_core!( Project, Mdm, SessionFlags, + Plugin, LegacyManagedConfigFile, LegacyManagedConfigMdm, Unknown, @@ -1657,6 +1659,37 @@ impl From for CorePermissionProfile { } } +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct ActivePermissionProfile { + /// Identifier from `default_permissions`, such as a built-in `:workspace` + /// profile or a user-defined `[permissions.]` profile. + pub id: String, + /// Parent profile identifier once permissions profiles support + /// inheritance. This is currently always `null`. + #[serde(default)] + pub extends: Option, +} + +impl From for ActivePermissionProfile { + fn from(value: CoreActivePermissionProfile) -> Self { + Self { + id: value.id, + extends: value.extends, + } + } +} + +impl From for CoreActivePermissionProfile { + fn from(value: ActivePermissionProfile) -> Self { + Self { + id: value.id, + extends: value.extends, + } + } +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] #[ts(export_to = "v2/")] @@ -3469,6 +3502,11 @@ pub struct ThreadStartResponse { #[experimental("thread/start.permissionProfile")] #[serde(default)] pub permission_profile: Option, + /// Named profile that produced `permissionProfile`, when the active + /// permissions came from `default_permissions`. + #[experimental("thread/start.activePermissionProfile")] + #[serde(default)] + pub active_permission_profile: Option, pub reasoning_effort: Option, } @@ -3575,6 +3613,11 @@ pub struct ThreadResumeResponse { #[experimental("thread/resume.permissionProfile")] #[serde(default)] pub permission_profile: Option, + /// Named profile that produced `permissionProfile`, when the active + /// permissions came from `default_permissions`. + #[experimental("thread/resume.activePermissionProfile")] + #[serde(default)] + pub active_permission_profile: Option, pub reasoning_effort: Option, } @@ -3672,6 +3715,11 @@ pub struct ThreadForkResponse { #[experimental("thread/fork.permissionProfile")] #[serde(default)] pub permission_profile: Option, + /// Named profile that produced `permissionProfile`, when the active + /// permissions came from `default_permissions`. + #[experimental("thread/fork.activePermissionProfile")] + #[serde(default)] + pub active_permission_profile: Option, pub reasoning_effort: Option, } @@ -10658,6 +10706,9 @@ mod tests { assert_eq!(start.permission_profile, None); assert_eq!(resume.permission_profile, None); assert_eq!(fork.permission_profile, None); + assert_eq!(start.active_permission_profile, None); + assert_eq!(resume.active_permission_profile, None); + assert_eq!(fork.active_permission_profile, None); } #[test] diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index 362f8692b6..1c6b981b98 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -2798,6 +2798,9 @@ impl CodexMessageProcessor { ); let permission_profile = thread_response_permission_profile(config_snapshot.permission_profile); + let active_permission_profile = thread_response_active_permission_profile( + config_snapshot.active_permission_profile, + ); let response = ThreadStartResponse { thread: thread.clone(), @@ -2810,6 +2813,7 @@ impl CodexMessageProcessor { approvals_reviewer: config_snapshot.approvals_reviewer.into(), sandbox, permission_profile, + active_permission_profile, reasoning_effort: config_snapshot.reasoning_effort, }; Ok::<_, JSONRPCErrorError>((response, thread_started_notification(thread))) @@ -4348,7 +4352,10 @@ impl CodexMessageProcessor { config_snapshot.cwd.as_path(), ); let permission_profile = - thread_response_permission_profile(config_snapshot.permission_profile.clone()); + thread_response_permission_profile(config_snapshot.permission_profile); + let active_permission_profile = thread_response_active_permission_profile( + config_snapshot.active_permission_profile, + ); let response = ThreadResumeResponse { thread, @@ -4361,6 +4368,7 @@ impl CodexMessageProcessor { approvals_reviewer: session_configured.approvals_reviewer.into(), sandbox, permission_profile, + active_permission_profile, reasoning_effort: session_configured.reasoning_effort, }; self.analytics_events_client.track_response( @@ -4949,6 +4957,9 @@ impl CodexMessageProcessor { ); let permission_profile = thread_response_permission_profile(config_snapshot.permission_profile); + let active_permission_profile = thread_response_active_permission_profile( + config_snapshot.active_permission_profile, + ); let response = ThreadForkResponse { thread: thread.clone(), @@ -4961,6 +4972,7 @@ impl CodexMessageProcessor { approvals_reviewer: session_configured.approvals_reviewer.into(), sandbox, permission_profile, + active_permission_profile, reasoning_effort: session_configured.reasoning_effort, }; @@ -8223,6 +8235,7 @@ async fn handle_pending_thread_resume_request( approval_policy, approvals_reviewer, permission_profile, + active_permission_profile, cwd, reasoning_effort, .. @@ -8230,6 +8243,8 @@ async fn handle_pending_thread_resume_request( let instruction_sources = pending.instruction_sources; let sandbox = thread_response_sandbox_policy(&permission_profile, cwd.as_path()); let permission_profile = thread_response_permission_profile(permission_profile); + let active_permission_profile = + thread_response_active_permission_profile(active_permission_profile); let response = ThreadResumeResponse { thread, @@ -8242,6 +8257,7 @@ async fn handle_pending_thread_resume_request( approvals_reviewer: approvals_reviewer.into(), sandbox, permission_profile, + active_permission_profile, reasoning_effort, }; let token_usage_thread = pending.include_turns.then(|| response.thread.clone()); @@ -9371,6 +9387,12 @@ fn thread_response_permission_profile( Some(permission_profile.into()) } +fn thread_response_active_permission_profile( + active_permission_profile: Option, +) -> Option { + active_permission_profile.map(Into::into) +} + fn thread_response_sandbox_policy( permission_profile: &codex_protocol::models::PermissionProfile, cwd: &Path, @@ -10165,6 +10187,7 @@ mod tests { approval_policy: codex_protocol::protocol::AskForApproval::OnRequest, approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User, permission_profile: codex_protocol::models::PermissionProfile::Disabled, + active_permission_profile: None, cwd, ephemeral: false, reasoning_effort: None, diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rs index 4369bbee31..beacb3251c 100644 --- a/codex-rs/app-server/src/lib.rs +++ b/codex-rs/app-server/src/lib.rs @@ -564,12 +564,13 @@ pub async fn run_main_with_transport_options( let feedback_layer = feedback.logger_layer(); let feedback_metadata_layer = feedback.metadata_layer(); - let state_db = codex_state::StateRuntime::init( + let state_db_result = codex_state::StateRuntime::init( config.sqlite_home.clone(), config.model_provider_id.clone(), ) - .await - .ok(); + .await; + let state_db_init_error = state_db_result.as_ref().err().map(ToString::to_string); + let state_db = state_db_result.ok(); let log_db = state_db.clone().map(log_db::start); let log_db_layer = log_db .clone() @@ -590,6 +591,9 @@ pub async fn run_main_with_transport_options( None => error!("{}", warning.summary), } } + if let Some(err) = &state_db_init_error { + error!("failed to initialize sqlite state db: {err}"); + } let transport_shutdown_token = CancellationToken::new(); let mut transport_accept_handles = Vec::>::new(); @@ -635,11 +639,19 @@ pub async fn run_main_with_transport_options( let auth_manager = AuthManager::shared_from_config(&config, /*enable_codex_api_key_env*/ false).await; - let remote_control_enabled = config.features.enabled(Feature::RemoteControl); + let remote_control_config_enabled = config.features.enabled(Feature::RemoteControl); + let remote_control_enabled = remote_control_config_enabled && state_db.is_some(); + if remote_control_config_enabled && state_db.is_none() { + error!("remote control disabled because sqlite state db is unavailable"); + } if transport_accept_handles.is_empty() && !remote_control_enabled { return Err(std::io::Error::new( ErrorKind::InvalidInput, - "no transport configured; use --listen or enable remote control", + if remote_control_config_enabled && state_db.is_none() { + "no transport configured; remote control disabled because sqlite state db is unavailable" + } else { + "no transport configured; use --listen or enable remote control" + }, )); } diff --git a/codex-rs/app-server/src/transport/remote_control/enroll.rs b/codex-rs/app-server/src/transport/remote_control/enroll.rs index ba69c459e8..fb7f727b83 100644 --- a/codex-rs/app-server/src/transport/remote_control/enroll.rs +++ b/codex-rs/app-server/src/transport/remote_control/enroll.rs @@ -38,13 +38,15 @@ pub(super) async fn load_persisted_remote_control_enrollment( remote_control_target: &RemoteControlTarget, account_id: &str, app_server_client_name: Option<&str>, -) -> Option { +) -> io::Result> { let Some(state_db) = state_db else { - info!( - "remote control enrollment cache unavailable because sqlite state db is disabled: websocket_url={}, account_id={}, app_server_client_name={:?}", - remote_control_target.websocket_url, account_id, app_server_client_name - ); - return None; + return Err(io::Error::new( + ErrorKind::NotFound, + format!( + "remote control enrollment cache unavailable because sqlite state db is disabled: websocket_url={}, account_id={}, app_server_client_name={:?}", + remote_control_target.websocket_url, account_id, app_server_client_name + ), + )); }; let enrollment = match state_db .get_remote_control_enrollment( @@ -60,7 +62,7 @@ pub(super) async fn load_persisted_remote_control_enrollment( "failed to load persisted remote control enrollment: websocket_url={}, account_id={}, app_server_client_name={:?}, err={err}", remote_control_target.websocket_url, account_id, app_server_client_name ); - return None; + return Err(io::Error::other(err)); } }; @@ -74,19 +76,19 @@ pub(super) async fn load_persisted_remote_control_enrollment( enrollment.server_id, enrollment.environment_id ); - Some(RemoteControlEnrollment { + Ok(Some(RemoteControlEnrollment { account_id: enrollment.account_id, environment_id: enrollment.environment_id, server_id: enrollment.server_id, server_name: enrollment.server_name, - }) + })) } None => { info!( "no persisted remote control enrollment found: websocket_url={}, account_id={}, app_server_client_name={:?}", remote_control_target.websocket_url, account_id, app_server_client_name ); - None + Ok(None) } } } @@ -99,14 +101,16 @@ pub(super) async fn update_persisted_remote_control_enrollment( enrollment: Option<&RemoteControlEnrollment>, ) -> io::Result<()> { let Some(state_db) = state_db else { - info!( - "skipping remote control enrollment persistence because sqlite state db is disabled: websocket_url={}, account_id={}, app_server_client_name={:?}, has_enrollment={}", - remote_control_target.websocket_url, - account_id, - app_server_client_name, - enrollment.is_some() - ); - return Ok(()); + return Err(io::Error::new( + ErrorKind::NotFound, + format!( + "remote control enrollment persistence unavailable because sqlite state db is disabled: websocket_url={}, account_id={}, app_server_client_name={:?}, has_enrollment={}", + remote_control_target.websocket_url, + account_id, + app_server_client_name, + enrollment.is_some() + ), + )); }; if let &Some(enrollment) = &enrollment && enrollment.account_id != account_id @@ -322,7 +326,8 @@ mod tests { "account-a", Some("desktop-client"), ) - .await, + .await + .expect("first enrollment should load"), Some(first_enrollment.clone()) ); assert_eq!( @@ -332,7 +337,8 @@ mod tests { "account-b", Some("desktop-client"), ) - .await, + .await + .expect("missing account should load"), None ); assert_eq!( @@ -342,7 +348,8 @@ mod tests { "account-a", Some("desktop-client"), ) - .await, + .await + .expect("second enrollment should load"), Some(second_enrollment) ); } @@ -405,7 +412,8 @@ mod tests { "account-a", /*app_server_client_name*/ None, ) - .await, + .await + .expect("cleared enrollment should load"), None ); assert_eq!( @@ -415,7 +423,8 @@ mod tests { "account-a", /*app_server_client_name*/ None, ) - .await, + .await + .expect("remaining enrollment should load"), Some(second_enrollment) ); } diff --git a/codex-rs/app-server/src/transport/remote_control/mod.rs b/codex-rs/app-server/src/transport/remote_control/mod.rs index c014c7a2c9..eca6047ef2 100644 --- a/codex-rs/app-server/src/transport/remote_control/mod.rs +++ b/codex-rs/app-server/src/transport/remote_control/mod.rs @@ -21,6 +21,7 @@ use tokio::sync::oneshot; use tokio::sync::watch; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; +use tracing::warn; pub(super) struct QueuedServerEnvelope { pub(super) event: ServerEvent, @@ -32,10 +33,16 @@ pub(super) struct QueuedServerEnvelope { #[derive(Clone)] pub(crate) struct RemoteControlHandle { enabled_tx: Arc>, + state_db_available: bool, } impl RemoteControlHandle { pub(crate) fn set_enabled(&self, enabled: bool) { + let requested_enabled = enabled; + let enabled = enabled && self.state_db_available; + if requested_enabled && !self.state_db_available { + warn!("remote control cannot be enabled because sqlite state db is unavailable"); + } self.enabled_tx.send_if_modified(|state| { let changed = *state != enabled; *state = enabled; @@ -53,6 +60,12 @@ pub(crate) async fn start_remote_control( app_server_client_name_rx: Option>, initial_enabled: bool, ) -> io::Result<(JoinHandle<()>, RemoteControlHandle)> { + let state_db_available = state_db.is_some(); + let requested_initial_enabled = initial_enabled; + let initial_enabled = initial_enabled && state_db_available; + if requested_initial_enabled && !state_db_available { + warn!("remote control disabled because sqlite state db is unavailable"); + } let remote_control_target = if initial_enabled { Some(normalize_remote_control_url(&remote_control_url)?) } else { @@ -78,6 +91,7 @@ pub(crate) async fn start_remote_control( join_handle, RemoteControlHandle { enabled_tx: Arc::new(enabled_tx), + state_db_available, }, )) } diff --git a/codex-rs/app-server/src/transport/remote_control/tests.rs b/codex-rs/app-server/src/transport/remote_control/tests.rs index 82e02ae5de..9b0896184c 100644 --- a/codex-rs/app-server/src/transport/remote_control/tests.rs +++ b/codex-rs/app-server/src/transport/remote_control/tests.rs @@ -504,7 +504,7 @@ async fn remote_control_start_allows_missing_auth_when_enabled() { let shutdown_token = CancellationToken::new(); let (remote_task, _remote_handle) = start_remote_control( remote_control_url, - /*state_db*/ None, + Some(remote_control_state_runtime(&codex_home).await), auth_manager, transport_event_tx, shutdown_token.clone(), @@ -525,6 +525,43 @@ async fn remote_control_start_allows_missing_auth_when_enabled() { .expect("remote control task should join"); } +#[tokio::test] +async fn remote_control_start_disables_remote_control_without_state_db() { + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("listener should bind"); + let remote_control_url = remote_control_url_for_listener(&listener); + let (transport_event_tx, _transport_event_rx) = + mpsc::channel::(CHANNEL_CAPACITY); + let shutdown_token = CancellationToken::new(); + let (remote_task, remote_handle) = start_remote_control( + remote_control_url, + /*state_db*/ None, + remote_control_auth_manager(), + transport_event_tx, + shutdown_token.clone(), + /*app_server_client_name_rx*/ None, + /*initial_enabled*/ true, + ) + .await + .expect("remote control should start disabled without sqlite state db"); + + timeout(Duration::from_millis(100), listener.accept()) + .await + .expect_err("remote control should not connect without sqlite state db"); + + remote_handle.set_enabled(/*enabled*/ true); + timeout(Duration::from_millis(100), listener.accept()) + .await + .expect_err("remote control should remain disabled without sqlite state db"); + + shutdown_token.cancel(); + timeout(Duration::from_secs(1), remote_task) + .await + .expect("remote control task should stop") + .expect("remote control task should join"); +} + #[tokio::test] async fn remote_control_handle_set_enabled_stops_and_restarts_connections() { let listener = TcpListener::bind("127.0.0.1:0") @@ -1001,7 +1038,8 @@ async fn remote_control_http_mode_reuses_persisted_enrollment_before_reenrolling "account_id", /*app_server_client_name*/ None, ) - .await, + .await + .expect("persisted enrollment should load"), Some(persisted_enrollment) ); @@ -1231,7 +1269,8 @@ async fn remote_control_http_mode_clears_stale_persisted_enrollment_after_404() "account_id", /*app_server_client_name*/ None, ) - .await, + .await + .expect("refreshed enrollment should load"), Some(refreshed_enrollment) ); diff --git a/codex-rs/app-server/src/transport/remote_control/websocket.rs b/codex-rs/app-server/src/transport/remote_control/websocket.rs index 4cd078455a..5e0af24fbb 100644 --- a/codex-rs/app-server/src/transport/remote_control/websocket.rs +++ b/codex-rs/app-server/src/transport/remote_control/websocket.rs @@ -753,6 +753,14 @@ pub(super) async fn connect_remote_control_websocket( )> { ensure_rustls_crypto_provider(); + let Some(state_db) = state_db else { + *enrollment = None; + return Err(io::Error::new( + ErrorKind::NotFound, + "remote control requires sqlite state db", + )); + }; + let auth = load_remote_control_auth(auth_manager).await?; let enrollment_account_id = enrollment.as_ref().map(|enrollment| &enrollment.account_id); if enrollment_account_id.is_some_and(|account_id| account_id != &auth.account_id) { @@ -769,12 +777,12 @@ pub(super) async fn connect_remote_control_websocket( if enrollment.is_none() { *enrollment = load_persisted_remote_control_enrollment( - state_db, + Some(state_db), remote_control_target, &auth.account_id, app_server_client_name, ) - .await; + .await?; } if enrollment.is_none() { @@ -796,7 +804,7 @@ pub(super) async fn connect_remote_control_websocket( Err(err) => return Err(err), }; if let Err(err) = update_persisted_remote_control_enrollment( - state_db, + Some(state_db), remote_control_target, &auth.account_id, app_server_client_name, @@ -804,7 +812,9 @@ pub(super) async fn connect_remote_control_websocket( ) .await { - warn!("failed to persist remote control enrollment in sqlite state db: {err}"); + return Err(io::Error::other(format!( + "failed to persist remote control enrollment in sqlite state db: {err}" + ))); } info!( "created new remote control enrollment: websocket_url={}, account_id={}, server_id={}, environment_id={}", @@ -839,7 +849,7 @@ pub(super) async fn connect_remote_control_websocket( enrollment_ref.environment_id ); if let Err(clear_err) = update_persisted_remote_control_enrollment( - state_db, + Some(state_db), remote_control_target, &auth.account_id, app_server_client_name, @@ -1214,6 +1224,36 @@ mod tests { ); } + #[tokio::test] + async fn connect_remote_control_websocket_requires_sqlite_state_db() { + let remote_control_target = normalize_remote_control_url("http://127.0.0.1:9/backend-api/") + .expect("target should parse"); + let auth_manager = remote_control_auth_manager(); + let mut auth_recovery = auth_manager.unauthorized_recovery(); + let mut enrollment = Some(RemoteControlEnrollment { + account_id: "account_id".to_string(), + environment_id: "env_test".to_string(), + server_id: "srv_e_test".to_string(), + server_name: "test-server".to_string(), + }); + + let err = connect_remote_control_websocket( + &remote_control_target, + /*state_db*/ None, + &auth_manager, + &mut auth_recovery, + &mut enrollment, + /*subscribe_cursor*/ None, + /*app_server_client_name*/ None, + ) + .await + .expect_err("missing sqlite state db should fail remote control"); + + assert_eq!(err.kind(), ErrorKind::NotFound); + assert_eq!(err.to_string(), "remote control requires sqlite state db"); + assert_eq!(enrollment, None); + } + #[tokio::test] async fn run_remote_control_websocket_loop_shutdown_cancels_reconnect_backoff() { let listener = TcpListener::bind("127.0.0.1:0") diff --git a/codex-rs/codex-api/src/common.rs b/codex-rs/codex-api/src/common.rs index 4b150b55f1..e2d2ed3c3c 100644 --- a/codex-rs/codex-api/src/common.rs +++ b/codex-rs/codex-api/src/common.rs @@ -287,6 +287,8 @@ pub fn create_text_param_for_request( pub struct ResponseStream { pub rx_event: mpsc::Receiver>, + /// Server-assigned `x-request-id` response header, when present. + pub upstream_request_id: Option, } impl Stream for ResponseStream { diff --git a/codex-rs/codex-api/src/endpoint/responses_websocket.rs b/codex-rs/codex-api/src/endpoint/responses_websocket.rs index 364dc1e9b9..4e97ecef9d 100644 --- a/codex-rs/codex-api/src/endpoint/responses_websocket.rs +++ b/codex-rs/codex-api/src/endpoint/responses_websocket.rs @@ -279,7 +279,10 @@ impl ResponsesWebsocketConnection { .instrument(current_span), ); - Ok(ResponseStream { rx_event }) + Ok(ResponseStream { + rx_event, + upstream_request_id: None, + }) } } diff --git a/codex-rs/codex-api/src/sse/responses.rs b/codex-rs/codex-api/src/sse/responses.rs index fb1742463f..4e949e43ae 100644 --- a/codex-rs/codex-api/src/sse/responses.rs +++ b/codex-rs/codex-api/src/sse/responses.rs @@ -28,6 +28,7 @@ use tracing::trace; const X_REASONING_INCLUDED_HEADER: &str = "x-reasoning-included"; const OPENAI_MODEL_HEADER: &str = "openai-model"; +const REQUEST_ID_HEADER: &str = "x-request-id"; const TRUSTED_ACCESS_FOR_CYBER_VERIFICATION: &str = "trusted_access_for_cyber"; /// Streams SSE events from an on-disk fixture for tests. @@ -53,7 +54,10 @@ pub fn stream_from_fixture( idle_timeout, /*telemetry*/ None, )); - Ok(ResponseStream { rx_event }) + Ok(ResponseStream { + rx_event, + upstream_request_id: None, + }) } pub fn spawn_response_stream( @@ -77,6 +81,11 @@ pub fn spawn_response_stream( .headers .get(X_REASONING_INCLUDED_HEADER) .is_some(); + let upstream_request_id = stream_response + .headers + .get(REQUEST_ID_HEADER) + .and_then(|value| value.to_str().ok()) + .map(str::to_string); if let Some(turn_state) = turn_state.as_ref() && let Some(header_value) = stream_response .headers @@ -104,7 +113,10 @@ pub fn spawn_response_stream( process_sse(stream_response.bytes, tx_event, idle_timeout, telemetry).await; }); - ResponseStream { rx_event } + ResponseStream { + rx_event, + upstream_request_id, + } } #[derive(Debug, Deserialize)] @@ -1058,8 +1070,9 @@ mod tests { } #[tokio::test] - async fn spawn_response_stream_emits_server_model_header() { + async fn spawn_response_stream_emits_header_events() { let mut headers = HeaderMap::new(); + headers.insert(REQUEST_ID_HEADER, HeaderValue::from_static("req-1")); headers.insert( OPENAI_MODEL_HEADER, HeaderValue::from_static(CYBER_RESTRICTED_MODEL_FOR_TESTS), @@ -1077,13 +1090,13 @@ mod tests { /*telemetry*/ None, /*turn_state*/ None, ); + assert_eq!(stream.upstream_request_id.as_deref(), Some("req-1")); let event = stream .rx_event .recv() .await .expect("expected server model event") .expect("expected ok event"); - match event { ResponseEvent::ServerModel(model) => { assert_eq!(model, CYBER_RESTRICTED_MODEL_FOR_TESTS); diff --git a/codex-rs/core-plugins/src/loader.rs b/codex-rs/core-plugins/src/loader.rs index 589467199e..55b8c0b57c 100644 --- a/codex-rs/core-plugins/src/loader.rs +++ b/codex-rs/core-plugins/src/loader.rs @@ -1,4 +1,5 @@ use crate::OPENAI_CURATED_MARKETPLACE_NAME; +use crate::manifest::PluginManifestHooks; use crate::manifest::PluginManifestPaths; use crate::manifest::load_plugin_manifest; use crate::marketplace::MarketplacePluginSource; @@ -7,6 +8,7 @@ use crate::marketplace::load_marketplace; use crate::store::PluginStore; use crate::store::plugin_version_for_source; use codex_config::ConfigLayerStack; +use codex_config::HooksFile; use codex_config::types::McpServerConfig; use codex_config::types::PluginConfig; use codex_core_skills::SkillMetadata; @@ -19,6 +21,7 @@ use codex_exec_server::LOCAL_FS; use codex_plugin::AppConnectorId; use codex_plugin::LoadedPlugin; use codex_plugin::PluginCapabilitySummary; +use codex_plugin::PluginHookSource; use codex_plugin::PluginId; use codex_plugin::PluginIdError; use codex_plugin::PluginLoadOutcome; @@ -26,6 +29,7 @@ use codex_plugin::PluginTelemetryMetadata; use codex_protocol::protocol::Product; use codex_protocol::protocol::SkillScope; use codex_utils_absolute_path::AbsolutePathBuf; +use codex_utils_plugins::find_plugin_manifest_path; use serde::Deserialize; use serde_json::Map as JsonMap; use serde_json::Value as JsonValue; @@ -39,6 +43,7 @@ use tempfile::TempDir; use tracing::warn; const DEFAULT_SKILLS_DIR_NAME: &str = "skills"; +const DEFAULT_HOOKS_CONFIG_FILE: &str = "hooks/hooks.json"; const DEFAULT_MCP_CONFIG_FILE: &str = ".mcp.json"; const DEFAULT_APP_CONFIG_FILE: &str = ".app.json"; const CONFIG_TOML_FILE: &str = "config.toml"; @@ -477,6 +482,8 @@ async fn load_plugin( has_enabled_skills: false, mcp_servers: HashMap::new(), apps: Vec::new(), + hook_sources: Vec::new(), + hook_load_warnings: Vec::new(), error: None, }; @@ -484,14 +491,14 @@ async fn load_plugin( return loaded_plugin; } - let plugin_root = match plugin_id { - Ok(_) => match active_plugin_root { - Some(plugin_root) => plugin_root, - None => { + let (loaded_plugin_id, plugin_root) = match plugin_id { + Ok(plugin_id) => { + let Some(plugin_root) = active_plugin_root else { loaded_plugin.error = Some("plugin is not installed".to_string()); return loaded_plugin; - } - }, + }; + (plugin_id, plugin_root) + } Err(err) => { loaded_plugin.error = Some(err.to_string()); return loaded_plugin; @@ -545,6 +552,14 @@ async fn load_plugin( } loaded_plugin.mcp_servers = mcp_servers; loaded_plugin.apps = load_plugin_apps(plugin_root.as_path()).await; + let (hook_sources, hook_load_warnings) = load_plugin_hooks( + &plugin_root, + &loaded_plugin_id, + &store.plugin_data_root(&loaded_plugin_id), + manifest_paths, + ); + loaded_plugin.hook_sources = hook_sources; + loaded_plugin.hook_load_warnings = hook_load_warnings; loaded_plugin } @@ -674,6 +689,116 @@ fn default_app_config_paths(plugin_root: &Path) -> Vec { paths } +// Discover plugin-bundled hooks from manifest `hooks` entries when present +// (path, paths, inline object, or inline objects), otherwise from the default +// `hooks/hooks.json` file. +pub fn load_plugin_hooks( + plugin_root: &AbsolutePathBuf, + plugin_id: &PluginId, + plugin_data_root: &AbsolutePathBuf, + manifest_paths: &PluginManifestPaths, +) -> (Vec, Vec) { + let mut sources = Vec::new(); + let mut warnings = Vec::new(); + match &manifest_paths.hooks { + Some(PluginManifestHooks::Paths(paths)) => { + for path in paths { + append_plugin_hook_file( + plugin_root, + plugin_id, + plugin_data_root, + path, + &mut sources, + &mut warnings, + ); + } + } + Some(PluginManifestHooks::Inline(hooks_files)) => { + let manifest_path = find_plugin_manifest_path(plugin_root.as_path()) + .and_then(|path| AbsolutePathBuf::try_from(path).ok()) + .unwrap_or_else(|| plugin_root.join(".codex-plugin/plugin.json")); + for (index, hooks_file) in hooks_files.iter().enumerate() { + if hooks_file.hooks.is_empty() { + continue; + } + sources.push(PluginHookSource { + plugin_id: plugin_id.clone(), + plugin_root: plugin_root.clone(), + plugin_data_root: plugin_data_root.clone(), + source_path: manifest_path.clone(), + source_relative_path: format!("plugin.json#hooks[{index}]"), + hooks: hooks_file.hooks.clone(), + }); + } + } + None => { + let default_path = plugin_root.join(DEFAULT_HOOKS_CONFIG_FILE); + if default_path.as_path().is_file() { + append_plugin_hook_file( + plugin_root, + plugin_id, + plugin_data_root, + &default_path, + &mut sources, + &mut warnings, + ); + } + } + } + (sources, warnings) +} + +// Append one resolved plugin hook file, keeping source metadata for runtime +// reporting and collecting load warnings for startup surfacing. +fn append_plugin_hook_file( + plugin_root: &AbsolutePathBuf, + plugin_id: &PluginId, + plugin_data_root: &AbsolutePathBuf, + path: &AbsolutePathBuf, + sources: &mut Vec, + warnings: &mut Vec, +) { + let contents = match fs::read_to_string(path.as_path()) { + Ok(contents) => contents, + Err(err) => { + warnings.push(format!( + "failed to read plugin hooks config {}: {err}", + path.display() + )); + return; + } + }; + let parsed = match serde_json::from_str::(&contents) { + Ok(parsed) => parsed, + Err(err) => { + warnings.push(format!( + "failed to parse plugin hooks config {}: {err}", + path.display() + )); + return; + } + }; + if parsed.hooks.is_empty() { + return; + } + + let source_relative_path = path + .as_path() + .strip_prefix(plugin_root.as_path()) + .unwrap_or(path.as_path()) + .to_string_lossy() + .replace('\\', "/"); + + sources.push(PluginHookSource { + plugin_id: plugin_id.clone(), + plugin_root: plugin_root.clone(), + plugin_data_root: plugin_data_root.clone(), + source_path: path.clone(), + source_relative_path, + hooks: parsed.hooks, + }); +} + async fn load_apps_from_paths( plugin_root: &Path, app_config_paths: Vec, @@ -1014,149 +1139,5 @@ fn run_git(args: &[&str], cwd: Option<&Path>) -> Result<(), String> { } #[cfg(test)] -mod tests { - use super::*; - use pretty_assertions::assert_eq; - - #[test] - fn plugin_mcp_file_supports_mcp_servers_object_format() { - let parsed = serde_json::from_str::( - r#"{ - "mcpServers": { - "sample": { - "command": "sample-mcp" - } - } -}"#, - ) - .expect("parse wrapped plugin mcp config") - .into_mcp_servers(); - - assert_eq!( - parsed, - HashMap::from([( - "sample".to_string(), - serde_json::json!({ - "command": "sample-mcp" - }), - )]) - ); - } - - #[test] - fn plugin_mcp_file_supports_mcp_servers_object_format_with_metadata() { - let parsed = serde_json::from_str::( - r#"{ - "$schema": "https://example.com/plugin-mcp.schema.json", - "mcpServers": { - "sample": { - "command": "sample-mcp" - } - } -}"#, - ) - .expect("parse plugin mcp config with metadata") - .into_mcp_servers(); - - assert_eq!( - parsed, - HashMap::from([( - "sample".to_string(), - serde_json::json!({ - "command": "sample-mcp" - }), - )]) - ); - } - - #[test] - fn plugin_mcp_file_supports_top_level_server_map_format() { - let parsed = serde_json::from_str::( - r#"{ - "linear": { - "type": "http", - "url": "https://mcp.linear.app/mcp" - } -}"#, - ) - .expect("parse flat plugin mcp config") - .into_mcp_servers(); - - assert_eq!( - parsed, - HashMap::from([( - "linear".to_string(), - serde_json::json!({ - "type": "http", - "url": "https://mcp.linear.app/mcp" - }), - )]) - ); - } - - #[test] - fn curated_plugin_cache_version_shortens_full_git_sha() { - assert_eq!( - curated_plugin_cache_version("0123456789abcdef0123456789abcdef01234567"), - "01234567" - ); - } - - #[test] - fn curated_plugin_cache_version_preserves_non_git_sha_versions() { - assert_eq!( - curated_plugin_cache_version("export-backup"), - "export-backup" - ); - assert_eq!(curated_plugin_cache_version("0123456"), "0123456"); - } - - #[test] - fn materialize_git_subdir_uses_sparse_checkout() { - let codex_home = tempfile::tempdir().expect("create codex home"); - let repo = tempfile::tempdir().expect("create git repo"); - let plugin_dir = repo.path().join("plugins/toolkit"); - fs::create_dir_all(&plugin_dir).expect("create plugin directory"); - fs::create_dir_all(repo.path().join("plugins/other")).expect("create other plugin"); - fs::write(plugin_dir.join("marker.txt"), "toolkit").expect("write plugin marker"); - fs::write(repo.path().join("plugins/other/marker.txt"), "other") - .expect("write other marker"); - fs::write(repo.path().join("root.txt"), "root").expect("write root marker"); - - run_git(&["init"], Some(repo.path())).expect("init git repo"); - run_git( - &["config", "user.email", "test@example.com"], - Some(repo.path()), - ) - .expect("configure git email"); - run_git(&["config", "user.name", "Test User"], Some(repo.path())) - .expect("configure git name"); - run_git(&["add", "."], Some(repo.path())).expect("stage git repo"); - run_git(&["commit", "-m", "init"], Some(repo.path())).expect("commit git repo"); - - let materialized = materialize_marketplace_plugin_source( - codex_home.path(), - &MarketplacePluginSource::Git { - url: repo.path().display().to_string(), - path: Some("plugins/toolkit".to_string()), - ref_name: None, - sha: None, - }, - ) - .expect("materialize git source"); - - assert_eq!( - plugin_dir.file_name(), - materialized.path.as_path().file_name() - ); - assert!(materialized.path.as_path().join("marker.txt").is_file()); - let checkout_root = materialized - .path - .as_path() - .parent() - .and_then(Path::parent) - .expect("materialized path should be nested under checkout root"); - assert!(!checkout_root.join("root.txt").exists()); - assert!(!checkout_root.join("plugins/other/marker.txt").exists()); - } -} +#[path = "loader_tests.rs"] +mod tests; diff --git a/codex-rs/core-plugins/src/loader_tests.rs b/codex-rs/core-plugins/src/loader_tests.rs new file mode 100644 index 0000000000..d9029c584e --- /dev/null +++ b/codex-rs/core-plugins/src/loader_tests.rs @@ -0,0 +1,369 @@ +use super::*; +use crate::manifest::load_plugin_manifest; +use codex_plugin::PluginId; +use pretty_assertions::assert_eq; + +#[test] +fn plugin_mcp_file_supports_mcp_servers_object_format() { + let parsed = serde_json::from_str::( + r#"{ + "mcpServers": { + "sample": { + "command": "sample-mcp" + } + } +}"#, + ) + .expect("parse wrapped plugin mcp config") + .into_mcp_servers(); + + assert_eq!( + parsed, + HashMap::from([( + "sample".to_string(), + serde_json::json!({ + "command": "sample-mcp" + }), + )]) + ); +} + +#[test] +fn plugin_mcp_file_supports_mcp_servers_object_format_with_metadata() { + let parsed = serde_json::from_str::( + r#"{ + "$schema": "https://example.com/plugin-mcp.schema.json", + "mcpServers": { + "sample": { + "command": "sample-mcp" + } + } +}"#, + ) + .expect("parse plugin mcp config with metadata") + .into_mcp_servers(); + + assert_eq!( + parsed, + HashMap::from([( + "sample".to_string(), + serde_json::json!({ + "command": "sample-mcp" + }), + )]) + ); +} + +#[test] +fn plugin_mcp_file_supports_top_level_server_map_format() { + let parsed = serde_json::from_str::( + r#"{ + "linear": { + "type": "http", + "url": "https://mcp.linear.app/mcp" + } +}"#, + ) + .expect("parse flat plugin mcp config") + .into_mcp_servers(); + + assert_eq!( + parsed, + HashMap::from([( + "linear".to_string(), + serde_json::json!({ + "type": "http", + "url": "https://mcp.linear.app/mcp" + }), + )]) + ); +} + +#[test] +fn curated_plugin_cache_version_shortens_full_git_sha() { + assert_eq!( + curated_plugin_cache_version("0123456789abcdef0123456789abcdef01234567"), + "01234567" + ); +} + +#[test] +fn curated_plugin_cache_version_preserves_non_git_sha_versions() { + assert_eq!( + curated_plugin_cache_version("export-backup"), + "export-backup" + ); + assert_eq!(curated_plugin_cache_version("0123456"), "0123456"); +} + +fn plugin_id() -> PluginId { + PluginId::parse("demo-plugin@test-marketplace").expect("plugin id") +} + +fn plugin_root() -> (tempfile::TempDir, AbsolutePathBuf) { + let tmp = tempfile::tempdir().expect("tempdir"); + let plugin_root = + AbsolutePathBuf::try_from(tmp.path().join("demo-plugin")).expect("plugin root"); + fs::create_dir_all(plugin_root.join(".codex-plugin")).expect("create manifest dir"); + fs::create_dir_all(plugin_root.join("hooks")).expect("create hooks dir"); + (tmp, plugin_root) +} + +fn write_manifest(plugin_root: &AbsolutePathBuf, manifest: &str) { + fs::write(plugin_root.join(".codex-plugin/plugin.json"), manifest).expect("write manifest"); +} + +fn write_hook_file(plugin_root: &AbsolutePathBuf, relative_path: &str, event: &str, command: &str) { + fs::write( + plugin_root.join(relative_path), + format!( + r#"{{ + "hooks": {{ + "{event}": [ + {{ + "hooks": [{{ "type": "command", "command": "{command}" }}] + }} + ] + }} +}}"# + ), + ) + .expect("write hooks"); +} + +fn load_sources(plugin_root: &AbsolutePathBuf) -> (Vec, Vec) { + let manifest = load_plugin_manifest(plugin_root.as_path()).expect("manifest"); + let plugin_data_root = AbsolutePathBuf::try_from( + plugin_root + .as_path() + .parent() + .expect("plugin root parent") + .join("plugin-data"), + ) + .expect("plugin data root"); + load_plugin_hooks( + plugin_root, + &plugin_id(), + &plugin_data_root, + &manifest.paths, + ) +} + +fn assert_sources(sources: &[PluginHookSource], expected_relative_paths: &[&str]) { + assert_eq!( + sources + .iter() + .map(|source| source.plugin_id.clone()) + .collect::>(), + vec![plugin_id(); expected_relative_paths.len()] + ); + assert_eq!( + sources + .iter() + .map(|source| source.source_relative_path.as_str()) + .collect::>(), + expected_relative_paths + ); + assert_eq!( + sources + .iter() + .map(|source| source.hooks.handler_count()) + .collect::>(), + vec![1; expected_relative_paths.len()] + ); +} + +#[test] +fn load_plugin_hooks_discovers_default_hooks_file() { + let (_tmp, plugin_root) = plugin_root(); + write_manifest(&plugin_root, r#"{ "name": "demo-plugin" }"#); + fs::write( + plugin_root.join("hooks/hooks.json"), + r#"{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [{ "type": "command", "command": "echo default" }] + } + ] + } +}"#, + ) + .expect("write hooks"); + + let (sources, warnings) = load_sources(&plugin_root); + + assert_eq!(warnings, Vec::::new()); + assert_sources(&sources, &["hooks/hooks.json"]); +} + +#[test] +fn load_plugin_hooks_supports_manifest_hook_path() { + let (_tmp, plugin_root) = plugin_root(); + write_manifest( + &plugin_root, + r#"{ + "name": "demo-plugin", + "hooks": "./hooks/one.json" +}"#, + ); + write_hook_file(&plugin_root, "hooks/one.json", "PreToolUse", "echo one"); + + let (sources, warnings) = load_sources(&plugin_root); + + assert_eq!(warnings, Vec::::new()); + assert_sources(&sources, &["hooks/one.json"]); +} + +#[test] +fn load_plugin_hooks_manifest_paths_replace_default_hooks_file() { + let (_tmp, plugin_root) = plugin_root(); + write_manifest( + &plugin_root, + r#"{ + "name": "demo-plugin", + "hooks": ["./hooks/one.json", "./hooks/two.json"] +}"#, + ); + write_hook_file( + &plugin_root, + "hooks/hooks.json", + "PreToolUse", + "echo ignored", + ); + write_hook_file(&plugin_root, "hooks/one.json", "PreToolUse", "echo one"); + write_hook_file(&plugin_root, "hooks/two.json", "PostToolUse", "echo two"); + + let (sources, warnings) = load_sources(&plugin_root); + + assert_eq!(warnings, Vec::::new()); + assert_sources(&sources, &["hooks/one.json", "hooks/two.json"]); +} + +#[test] +fn load_plugin_hooks_supports_inline_manifest_hooks() { + let (_tmp, plugin_root) = plugin_root(); + write_manifest( + &plugin_root, + r#"{ + "name": "demo-plugin", + "hooks": { + "hooks": { + "SessionStart": [ + { + "matcher": "startup", + "hooks": [{ "type": "command", "command": "echo inline" }] + } + ] + } + } +}"#, + ); + + let (sources, warnings) = load_sources(&plugin_root); + + assert_eq!(warnings, Vec::::new()); + assert_sources(&sources, &["plugin.json#hooks[0]"]); +} + +#[test] +fn load_plugin_hooks_reports_invalid_hook_file() { + let (_tmp, plugin_root) = plugin_root(); + write_manifest(&plugin_root, r#"{ "name": "demo-plugin" }"#); + fs::write(plugin_root.join("hooks/hooks.json"), "{ not-json").expect("write invalid hooks"); + + let (sources, warnings) = load_sources(&plugin_root); + + assert_eq!(sources, Vec::::new()); + assert_eq!( + warnings, + vec![format!( + "failed to parse plugin hooks config {}: key must be a string at line 1 column 3", + plugin_root.join("hooks/hooks.json").display() + )] + ); +} + +#[test] +fn load_plugin_hooks_supports_inline_manifest_hook_list() { + let (_tmp, plugin_root) = plugin_root(); + write_manifest( + &plugin_root, + r#"{ + "name": "demo-plugin", + "hooks": [ + { + "hooks": { + "SessionStart": [ + { + "hooks": [{ "type": "command", "command": "echo inline one" }] + } + ] + } + }, + { + "hooks": { + "Stop": [ + { + "hooks": [{ "type": "command", "command": "echo inline two" }] + } + ] + } + } + ] +}"#, + ); + + let (sources, warnings) = load_sources(&plugin_root); + + assert_eq!(warnings, Vec::::new()); + assert_sources(&sources, &["plugin.json#hooks[0]", "plugin.json#hooks[1]"]); +} + +#[test] +fn materialize_git_subdir_uses_sparse_checkout() { + let codex_home = tempfile::tempdir().expect("create codex home"); + let repo = tempfile::tempdir().expect("create git repo"); + let plugin_dir = repo.path().join("plugins/toolkit"); + fs::create_dir_all(&plugin_dir).expect("create plugin directory"); + fs::create_dir_all(repo.path().join("plugins/other")).expect("create other plugin"); + fs::write(plugin_dir.join("marker.txt"), "toolkit").expect("write plugin marker"); + fs::write(repo.path().join("plugins/other/marker.txt"), "other").expect("write other marker"); + fs::write(repo.path().join("root.txt"), "root").expect("write root marker"); + + run_git(&["init"], Some(repo.path())).expect("init git repo"); + run_git( + &["config", "user.email", "test@example.com"], + Some(repo.path()), + ) + .expect("configure git email"); + run_git(&["config", "user.name", "Test User"], Some(repo.path())).expect("configure git name"); + run_git(&["add", "."], Some(repo.path())).expect("stage git repo"); + run_git(&["commit", "-m", "init"], Some(repo.path())).expect("commit git repo"); + + let materialized = materialize_marketplace_plugin_source( + codex_home.path(), + &MarketplacePluginSource::Git { + url: repo.path().display().to_string(), + path: Some("plugins/toolkit".to_string()), + ref_name: None, + sha: None, + }, + ) + .expect("materialize git source"); + + assert_eq!( + plugin_dir.file_name(), + materialized.path.as_path().file_name() + ); + assert!(materialized.path.as_path().join("marker.txt").is_file()); + let checkout_root = materialized + .path + .as_path() + .parent() + .and_then(Path::parent) + .expect("materialized path should be nested under checkout root"); + assert!(!checkout_root.join("root.txt").exists()); + assert!(!checkout_root.join("plugins/other/marker.txt").exists()); +} diff --git a/codex-rs/core-plugins/src/manifest.rs b/codex-rs/core-plugins/src/manifest.rs index 5b53662599..12b738f537 100644 --- a/codex-rs/core-plugins/src/manifest.rs +++ b/codex-rs/core-plugins/src/manifest.rs @@ -1,3 +1,4 @@ +use codex_config::HooksFile; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_plugins::find_plugin_manifest_path; use serde::Deserialize; @@ -26,6 +27,8 @@ struct RawPluginManifest { #[serde(default)] apps: Option, #[serde(default)] + hooks: Option, + #[serde(default)] interface: Option, } @@ -43,6 +46,13 @@ pub struct PluginManifestPaths { pub skills: Option, pub mcp_servers: Option, pub apps: Option, + pub hooks: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PluginManifestHooks { + Paths(Vec), + Inline(Vec), } #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -114,6 +124,16 @@ enum RawPluginManifestDefaultPromptEntry { Invalid(JsonValue), } +#[derive(Debug, Deserialize)] +#[serde(untagged)] +enum RawPluginManifestHooks { + Path(String), + Paths(Vec), + Inline(HooksFile), + InlineList(Vec), + Invalid(JsonValue), +} + pub fn load_plugin_manifest(plugin_root: &Path) -> Option { let manifest_path = find_plugin_manifest_path(plugin_root)?; let contents = fs::read_to_string(&manifest_path).ok()?; @@ -126,6 +146,7 @@ pub fn load_plugin_manifest(plugin_root: &Path) -> Option { skills, mcp_servers, apps, + hooks, interface, } = manifest; let name = plugin_root @@ -219,6 +240,7 @@ pub fn load_plugin_manifest(plugin_root: &Path) -> Option { mcp_servers.as_deref(), ), apps: resolve_manifest_path(plugin_root, "apps", apps.as_deref()), + hooks: resolve_manifest_hooks(plugin_root, hooks), }, interface, }) @@ -233,6 +255,36 @@ pub fn load_plugin_manifest(plugin_root: &Path) -> Option { } } +fn resolve_manifest_hooks( + plugin_root: &Path, + hooks: Option, +) -> Option { + match hooks? { + RawPluginManifestHooks::Path(path) => { + resolve_manifest_path(plugin_root, "hooks", Some(&path)) + .map(|path| PluginManifestHooks::Paths(vec![path])) + } + RawPluginManifestHooks::Paths(paths) => { + let hooks = paths + .iter() + .filter_map(|path| resolve_manifest_path(plugin_root, "hooks", Some(path))) + .collect::>(); + (!hooks.is_empty()).then_some(PluginManifestHooks::Paths(hooks)) + } + RawPluginManifestHooks::Inline(hooks) => Some(PluginManifestHooks::Inline(vec![hooks])), + RawPluginManifestHooks::InlineList(hooks) => { + (!hooks.is_empty()).then_some(PluginManifestHooks::Inline(hooks)) + } + RawPluginManifestHooks::Invalid(value) => { + tracing::warn!( + "ignoring hooks: expected a string, string array, object, or object array; found {}", + json_value_type(&value) + ); + None + } + } +} + fn resolve_interface_asset_path( plugin_root: &Path, field: &'static str, diff --git a/codex-rs/core-plugins/src/marketplace_add.rs b/codex-rs/core-plugins/src/marketplace_add.rs index 57e587e480..927d337d24 100644 --- a/codex-rs/core-plugins/src/marketplace_add.rs +++ b/codex-rs/core-plugins/src/marketplace_add.rs @@ -123,14 +123,12 @@ where let marketplace_name = validate_marketplace_source_root(path)?; if marketplace_name == OPENAI_CURATED_MARKETPLACE_NAME { return Err(MarketplaceAddError::InvalidRequest(format!( - "marketplace '{OPENAI_CURATED_MARKETPLACE_NAME}' is reserved and cannot be added from {}", - source.display() + "marketplace '{OPENAI_CURATED_MARKETPLACE_NAME}' is reserved and cannot be added from this source" ))); } if find_marketplace_root_by_name(codex_home, &install_root, &marketplace_name)?.is_some() { return Err(MarketplaceAddError::InvalidRequest(format!( - "marketplace '{marketplace_name}' is already added from a different source; remove it before adding {}", - source.display() + "marketplace '{marketplace_name}' is already added from a different source; remove it before adding this source" ))); } record_added_marketplace_entry(codex_home, &marketplace_name, &install_metadata)?; @@ -169,8 +167,7 @@ where let marketplace_name = validate_marketplace_source_root(&staged_root)?; if marketplace_name == OPENAI_CURATED_MARKETPLACE_NAME { return Err(MarketplaceAddError::InvalidRequest(format!( - "marketplace '{OPENAI_CURATED_MARKETPLACE_NAME}' is reserved and cannot be added from {}", - source.display() + "marketplace '{OPENAI_CURATED_MARKETPLACE_NAME}' is reserved and cannot be added from this source" ))); } @@ -178,8 +175,7 @@ where ensure_marketplace_destination_is_inside_install_root(&install_root, &destination)?; if destination.exists() { return Err(MarketplaceAddError::InvalidRequest(format!( - "marketplace '{marketplace_name}' is already added from a different source; remove it before adding {}", - source.display() + "marketplace '{marketplace_name}' is already added from a different source; remove it before adding this source" ))); } diff --git a/codex-rs/core-plugins/src/marketplace_add/source.rs b/codex-rs/core-plugins/src/marketplace_add/source.rs index fdcbd4094e..3cec309494 100644 --- a/codex-rs/core-plugins/src/marketplace_add/source.rs +++ b/codex-rs/core-plugins/src/marketplace_add/source.rs @@ -58,9 +58,10 @@ pub(crate) fn parse_marketplace_source( }); } - Err(MarketplaceAddError::InvalidRequest(format!( - "invalid marketplace source format: {source}" - ))) + Err(MarketplaceAddError::InvalidRequest( + "invalid marketplace source format; expected owner/repo, a git URL, or a local marketplace path" + .to_string(), + )) } pub(super) fn stage_marketplace_source( @@ -160,8 +161,7 @@ fn resolve_local_source_path(source: &str) -> Result Result { let root = AbsolutePathBuf::from_absolute_path_checked(codex_home.join(PLUGINS_CACHE_DIR)) .map_err(|err| PluginStoreError::io("failed to resolve plugin cache root", err))?; + let data_root = + AbsolutePathBuf::from_absolute_path_checked(codex_home.join(PLUGINS_DATA_DIR)) + .map_err(|err| PluginStoreError::io("failed to resolve plugin data root", err))?; - Ok(Self { root }) + Ok(Self { root, data_root }) } pub fn root(&self) -> &AbsolutePathBuf { @@ -53,6 +58,13 @@ impl PluginStore { self.plugin_base_root(plugin_id).join(plugin_version) } + pub fn plugin_data_root(&self, plugin_id: &PluginId) -> AbsolutePathBuf { + self.data_root.join(format!( + "{}-{}", + plugin_id.plugin_name, plugin_id.marketplace_name + )) + } + pub fn active_plugin_version(&self, plugin_id: &PluginId) -> Option { let mut discovered_versions = fs::read_dir(self.plugin_base_root(plugin_id).as_path()) .ok()? diff --git a/codex-rs/core-plugins/src/store_tests.rs b/codex-rs/core-plugins/src/store_tests.rs index 45feff61bd..0ba6b0d2c6 100644 --- a/codex-rs/core-plugins/src/store_tests.rs +++ b/codex-rs/core-plugins/src/store_tests.rs @@ -109,6 +109,18 @@ fn plugin_root_derives_path_from_key_and_version() { ); } +#[test] +fn plugin_data_root_derives_path_from_key() { + let tmp = tempdir().unwrap(); + let store = PluginStore::new(tmp.path().to_path_buf()); + let plugin_id = PluginId::new("sample".to_string(), "debug".to_string()).unwrap(); + + assert_eq!( + store.plugin_data_root(&plugin_id).as_path(), + tmp.path().join("plugins/data/sample-debug") + ); +} + #[test] fn install_with_version_uses_requested_cache_version() { let tmp = tempdir().unwrap(); diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 1f8a93da4e..c971895e04 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -463,6 +463,9 @@ "personality": { "type": "boolean" }, + "plugin_hooks": { + "type": "boolean" + }, "plugins": { "type": "boolean" }, @@ -3379,6 +3382,9 @@ "personality": { "type": "boolean" }, + "plugin_hooks": { + "type": "boolean" + }, "plugins": { "type": "boolean" }, diff --git a/codex-rs/core/src/client.rs b/codex-rs/core/src/client.rs index fe64099cc9..ba81b451a7 100644 --- a/codex-rs/core/src/client.rs +++ b/codex-rs/core/src/client.rs @@ -1234,8 +1234,13 @@ impl ModelClientSession { Err(ApiError::Transport( unauthorized_transport @ TransportError::Http { status, .. }, )) if status == StatusCode::UNAUTHORIZED => { - inference_trace_attempt - .record_failed(&unauthorized_transport, /*output_items*/ &[]); + let response_debug_context = + extract_response_debug_context(&unauthorized_transport); + inference_trace_attempt.record_failed( + &unauthorized_transport, + response_debug_context.request_id.as_deref(), + /*output_items*/ &[], + ); pending_retry = PendingUnauthorizedRetry::from_recovery( handle_unauthorized( unauthorized_transport, @@ -1247,8 +1252,14 @@ impl ModelClientSession { continue; } Err(err) => { + let response_debug_context = + extract_response_debug_context_from_api_error(&err); let err = map_api_error(err); - inference_trace_attempt.record_failed(&err, /*output_items*/ &[]); + inference_trace_attempt.record_failed( + &err, + response_debug_context.request_id.as_deref(), + /*output_items*/ &[], + ); return Err(err); } } @@ -1374,8 +1385,14 @@ impl ModelClientSession { .stream_request(ws_request, self.websocket_session.connection_reused()) .await .map_err(|err| { + let response_debug_context = + extract_response_debug_context_from_api_error(&err); let err = map_api_error(err); - inference_trace_attempt.record_failed(&err, /*output_items*/ &[]); + inference_trace_attempt.record_failed( + &err, + response_debug_context.request_id.as_deref(), + /*output_items*/ &[], + ); err })?; let (stream, last_request_rx) = map_response_stream( @@ -1636,7 +1653,29 @@ fn parent_thread_id_header_value(session_source: &SessionSource) -> Option( +fn map_response_stream( + api_stream: codex_api::ResponseStream, + session_telemetry: SessionTelemetry, + inference_trace_attempt: InferenceTraceAttempt, +) -> (ResponseStream, oneshot::Receiver) { + let codex_api::ResponseStream { + rx_event, + upstream_request_id, + } = api_stream; + let api_stream = codex_api::ResponseStream { + rx_event, + upstream_request_id: None, + }; + map_response_events( + upstream_request_id, + api_stream, + session_telemetry, + inference_trace_attempt, + ) +} + +fn map_response_events( + upstream_request_id: Option, api_stream: S, session_telemetry: SessionTelemetry, inference_trace_attempt: InferenceTraceAttempt, @@ -1658,10 +1697,15 @@ where let mut tx_last_response = Some(tx_last_response); let mut items_added: Vec = Vec::new(); let mut api_stream = api_stream; + let upstream_request_id = upstream_request_id.as_deref(); loop { let event = tokio::select! { _ = consumer_dropped.cancelled() => { - inference_trace_attempt.record_cancelled(STREAM_DROPPED_REASON, &items_added); + inference_trace_attempt.record_cancelled( + STREAM_DROPPED_REASON, + upstream_request_id, + &items_added, + ); return; } event = api_stream.next() => event, @@ -1677,8 +1721,11 @@ where .await .is_err() { - inference_trace_attempt - .record_cancelled(STREAM_DROPPED_REASON, &items_added); + inference_trace_attempt.record_cancelled( + STREAM_DROPPED_REASON, + upstream_request_id, + &items_added, + ); return; } } @@ -1698,6 +1745,7 @@ where } inference_trace_attempt.record_completed( &response_id, + upstream_request_id, &token_usage, &items_added, ); @@ -1721,14 +1769,25 @@ where } Ok(event) => { if tx_event.send(Ok(event)).await.is_err() { - inference_trace_attempt - .record_cancelled(STREAM_DROPPED_REASON, &items_added); + inference_trace_attempt.record_cancelled( + STREAM_DROPPED_REASON, + upstream_request_id, + &items_added, + ); return; } } Err(err) => { + let response_debug_context = + extract_response_debug_context_from_api_error(&err); + let upstream_request_id = + upstream_request_id.or(response_debug_context.request_id.as_deref()); let mapped = map_api_error(err); - inference_trace_attempt.record_failed(&mapped, &items_added); + inference_trace_attempt.record_failed( + &mapped, + upstream_request_id, + &items_added, + ); if !logged_error { session_telemetry.see_event_completed_failed(&mapped); logged_error = true; @@ -1739,8 +1798,11 @@ where } } } - inference_trace_attempt - .record_failed("stream closed before response.completed", &items_added); + inference_trace_attempt.record_failed( + "stream closed before response.completed", + upstream_request_id, + &items_added, + ); }); ( diff --git a/codex-rs/core/src/client_tests.rs b/codex-rs/core/src/client_tests.rs index f7d263c0e7..e56500ba5f 100644 --- a/codex-rs/core/src/client_tests.rs +++ b/codex-rs/core/src/client_tests.rs @@ -282,7 +282,12 @@ async fn dropped_response_stream_traces_cancelled_partial_output() -> anyhow::Re let item = output_message("msg-1", "partial answer"); let api_stream = futures::stream::iter([Ok(ResponseEvent::OutputItemDone(item))]) .chain(futures::stream::pending()); - let (mut stream, _) = super::map_response_stream(api_stream, test_session_telemetry(), attempt); + let (mut stream, _) = super::map_response_events( + /*upstream_request_id*/ None, + api_stream, + test_session_telemetry(), + attempt, + ); let observed = stream .next() @@ -332,7 +337,12 @@ async fn dropped_backpressured_response_stream_traces_cancelled_partial_output() notify: Arc::clone(&backpressured_item_yielded), }; - let (stream, _) = super::map_response_stream(api_stream, test_session_telemetry(), attempt); + let (stream, _) = super::map_response_events( + /*upstream_request_id*/ None, + api_stream, + test_session_telemetry(), + attempt, + ); // Fill the mapper channel with non-terminal events, then yield one output // item. The mapper has observed that item and is blocked trying to send it diff --git a/codex-rs/core/src/codex_thread.rs b/codex-rs/core/src/codex_thread.rs index a2f64e86f4..644b355edd 100644 --- a/codex-rs/core/src/codex_thread.rs +++ b/codex-rs/core/src/codex_thread.rs @@ -15,6 +15,7 @@ use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::error::CodexErr; use codex_protocol::error::Result as CodexResult; use codex_protocol::mcp::CallToolResult; +use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::ContentItem; use codex_protocol::models::PermissionProfile; use codex_protocol::models::ResponseInputItem; @@ -48,6 +49,7 @@ pub struct ThreadConfigSnapshot { pub approval_policy: AskForApproval, pub approvals_reviewer: ApprovalsReviewer, pub permission_profile: PermissionProfile, + pub active_permission_profile: Option, pub cwd: AbsolutePathBuf, pub ephemeral: bool, pub reasoning_effort: Option, diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index f075a4b7fc..0a58ab6d44 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -906,6 +906,14 @@ async fn default_permissions_profile_populates_runtime_sandbox_policy() -> std:: config.permissions.network_sandbox_policy(), NetworkSandboxPolicy::Restricted ); + assert_eq!( + config + .permissions + .active_permission_profile() + .as_ref() + .map(|active| active.id.as_str()), + Some("workspace") + ); Ok(()) } @@ -927,6 +935,7 @@ async fn permission_profile_override_populates_runtime_permissions() -> std::io: .await?; assert_eq!(config.permissions.permission_profile(), permission_profile); + assert_eq!(config.permissions.active_permission_profile(), None); assert_eq!( &config.legacy_sandbox_policy(), &SandboxPolicy::DangerFullAccess @@ -1266,6 +1275,14 @@ async fn default_permissions_can_select_builtin_profile_without_permissions_tabl .await?; let policy = config.permissions.file_system_sandbox_policy(); + assert_eq!( + config + .permissions + .active_permission_profile() + .as_ref() + .map(|active| active.id.as_str()), + Some(":workspace") + ); assert!( policy.can_write_path_with_cwd(cwd.path(), cwd.path()), "expected :workspace to allow writing the project root, policy: {policy:?}" @@ -1302,6 +1319,18 @@ async fn empty_config_defaults_to_builtin_profile_for_trusted_project() -> std:: .await?; let policy = config.permissions.file_system_sandbox_policy(); + assert_eq!( + config + .permissions + .active_permission_profile() + .as_ref() + .map(|active| active.id.as_str()), + Some(if cfg!(target_os = "windows") { + ":read-only" + } else { + ":workspace" + }) + ); if cfg!(target_os = "windows") { assert!( !policy.can_write_path_with_cwd(cwd.path(), cwd.path()), @@ -1483,6 +1512,14 @@ async fn default_permissions_can_select_builtin_no_sandbox_profile() -> std::io: config.permissions.permission_profile(), PermissionProfile::Disabled ); + assert_eq!( + config + .permissions + .active_permission_profile() + .as_ref() + .map(|active| active.id.as_str()), + Some(":danger-no-sandbox") + ); Ok(()) } @@ -5893,6 +5930,7 @@ async fn test_precedence_fixture_with_o3_profile() -> std::io::Result<()> { permissions: Permissions { approval_policy: Constrained::allow_any(AskForApproval::Never), permission_profile: Constrained::allow_any(PermissionProfile::read_only()), + active_permission_profile: None, network: None, allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), @@ -6087,6 +6125,7 @@ async fn test_precedence_fixture_with_gpt3_profile() -> std::io::Result<()> { permissions: Permissions { approval_policy: Constrained::allow_any(AskForApproval::UnlessTrusted), permission_profile: Constrained::allow_any(PermissionProfile::read_only()), + active_permission_profile: None, network: None, allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), @@ -6235,6 +6274,7 @@ async fn test_precedence_fixture_with_zdr_profile() -> std::io::Result<()> { permissions: Permissions { approval_policy: Constrained::allow_any(AskForApproval::OnFailure), permission_profile: Constrained::allow_any(PermissionProfile::read_only()), + active_permission_profile: None, network: None, allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), @@ -6368,6 +6408,7 @@ async fn test_precedence_fixture_with_gpt5_profile() -> std::io::Result<()> { permissions: Permissions { approval_policy: Constrained::allow_any(AskForApproval::OnFailure), permission_profile: Constrained::allow_any(PermissionProfile::read_only()), + active_permission_profile: None, network: None, allow_login_shell: true, shell_environment_policy: ShellEnvironmentPolicy::default(), diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 6c8258c519..8bfb071ca3 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -82,6 +82,7 @@ use codex_protocol::config_types::Verbosity; use codex_protocol::config_types::WebSearchConfig; use codex_protocol::config_types::WebSearchMode; use codex_protocol::config_types::WindowsSandboxLevel; +use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::PermissionProfile; use codex_protocol::models::SandboxEnforcement; use codex_protocol::openai_models::ModelsResponse; @@ -224,6 +225,9 @@ pub struct Permissions { /// Canonical effective runtime permissions after config requirements and /// runtime readable-root additions have been applied. pub permission_profile: Constrained, + /// Named profile selected by config, when the active permissions came from + /// `default_permissions` rather than an ad-hoc override. + pub active_permission_profile: Option, /// Effective network configuration applied to all spawned processes. pub network: Option, /// Whether the model may request a login shell for shell-based tools. @@ -251,6 +255,11 @@ impl Permissions { self.permission_profile.get().clone() } + /// Named profile selected by config, if the current profile has one. + pub fn active_permission_profile(&self) -> Option { + self.active_permission_profile.clone() + } + /// Effective filesystem sandbox policy derived from the canonical profile. pub fn file_system_sandbox_policy(&self) -> FileSystemSandboxPolicy { self.permission_profile.get().file_system_sandbox_policy() @@ -309,6 +318,7 @@ impl Permissions { ); self.permission_profile.set(permission_profile)?; + self.active_permission_profile = None; Ok(()) } @@ -316,10 +326,21 @@ impl Permissions { pub fn set_permission_profile( &mut self, permission_profile: PermissionProfile, + ) -> ConstraintResult<()> { + self.set_permission_profile_with_active_profile(permission_profile, None) + } + + /// Replace permissions from the canonical profile and record the named + /// source profile, if one is known. + pub fn set_permission_profile_with_active_profile( + &mut self, + permission_profile: PermissionProfile, + active_permission_profile: Option, ) -> ConstraintResult<()> { self.permission_profile.can_set(&permission_profile)?; self.permission_profile.set(permission_profile)?; + self.active_permission_profile = active_permission_profile; Ok(()) } } @@ -1947,6 +1968,7 @@ impl Config { configured_network_proxy_config, permission_profile, file_system_sandbox_policy, + active_permission_profile, ) = if let Some(mut permission_profile) = permission_profile { let (mut file_system_sandbox_policy, network_sandbox_policy) = permission_profile.to_runtime_permissions(); @@ -1992,6 +2014,7 @@ impl Config { configured_network_proxy_config, permission_profile, file_system_sandbox_policy, + None, ) } else if profiles_are_active { let default_permissions = cfg.default_permissions.as_deref().unwrap_or_else(|| { @@ -2046,6 +2069,7 @@ impl Config { configured_network_proxy_config, permission_profile, file_system_sandbox_policy, + Some(ActivePermissionProfile::new(default_permissions)), ) } else { let configured_network_proxy_config = NetworkProxyConfig::default(); @@ -2107,6 +2131,7 @@ impl Config { configured_network_proxy_config, permission_profile, file_system_sandbox_policy, + None, ) }; let approval_policy_was_explicit = approval_policy_override.is_some() @@ -2564,6 +2589,7 @@ impl Config { permissions: Permissions { approval_policy: constrained_approval_policy.value, permission_profile: constrained_permission_profile.value, + active_permission_profile, network, allow_login_shell, shell_environment_policy, diff --git a/codex-rs/core/src/hook_runtime.rs b/codex-rs/core/src/hook_runtime.rs index db47688685..b534c63cf4 100644 --- a/codex-rs/core/src/hook_runtime.rs +++ b/codex-rs/core/src/hook_runtime.rs @@ -473,6 +473,7 @@ fn hook_run_metric_tags(run: &HookRunSummary) -> [(&'static str, &'static str); HookSource::Project => "project", HookSource::Mdm => "mdm", HookSource::SessionFlags => "session_flags", + HookSource::Plugin => "plugin", HookSource::LegacyManagedConfigFile => "legacy_managed_config_file", HookSource::LegacyManagedConfigMdm => "legacy_managed_config_mdm", HookSource::Unknown => "unknown", diff --git a/codex-rs/core/src/plugins/manager_tests.rs b/codex-rs/core/src/plugins/manager_tests.rs index 2c5c6805b1..fb4b5a6212 100644 --- a/codex-rs/core/src/plugins/manager_tests.rs +++ b/codex-rs/core/src/plugins/manager_tests.rs @@ -219,6 +219,8 @@ async fn load_plugins_loads_default_skills_and_mcp_servers() { }, )]), apps: vec![AppConnectorId("connector_example".to_string())], + hook_sources: Vec::new(), + hook_load_warnings: Vec::new(), error: None, }] ); @@ -719,6 +721,8 @@ async fn load_plugins_preserves_disabled_plugins_without_effective_contributions has_enabled_skills: false, mcp_servers: HashMap::new(), apps: Vec::new(), + hook_sources: Vec::new(), + hook_load_warnings: Vec::new(), error: None, }] ); @@ -836,6 +840,8 @@ fn capability_index_filters_inactive_and_zero_capability_plugins() { has_enabled_skills: false, mcp_servers: HashMap::new(), apps: Vec::new(), + hook_sources: Vec::new(), + hook_load_warnings: Vec::new(), error: None, }; let summary = |config_name: &str, display_name: &str| PluginCapabilitySummary { diff --git a/codex-rs/core/src/session/mod.rs b/codex-rs/core/src/session/mod.rs index d58e065f28..2c6ed17aa5 100644 --- a/codex-rs/core/src/session/mod.rs +++ b/codex-rs/core/src/session/mod.rs @@ -90,6 +90,7 @@ use codex_protocol::dynamic_tools::DynamicToolSpec; use codex_protocol::items::TurnItem; use codex_protocol::items::UserMessageItem; use codex_protocol::mcp::CallToolResult; +use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::AdditionalPermissionProfile; use codex_protocol::models::BaseInstructions; use codex_protocol::models::PermissionProfile; @@ -601,6 +602,7 @@ impl Codex { approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, permission_profile: config.permissions.permission_profile.clone(), + active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), diff --git a/codex-rs/core/src/session/session.rs b/codex-rs/core/src/session/session.rs index 9a13ce3351..65d29ae7e5 100644 --- a/codex-rs/core/src/session/session.rs +++ b/codex-rs/core/src/session/session.rs @@ -60,6 +60,8 @@ pub(crate) struct SessionConfiguration { pub(super) approvals_reviewer: ApprovalsReviewer, /// Canonical permission profile for the session. pub(super) permission_profile: Constrained, + /// Named permissions profile selected from config, if any. + pub(super) active_permission_profile: Option, pub(super) windows_sandbox_level: WindowsSandboxLevel, /// Absolute working directory that should be treated as the *root* of the @@ -97,6 +99,10 @@ impl SessionConfiguration { self.permission_profile.get().clone() } + pub(super) fn active_permission_profile(&self) -> Option { + self.active_permission_profile.clone() + } + pub(super) fn sandbox_policy(&self) -> SandboxPolicy { self.permission_profile() .to_legacy_sandbox_policy(&self.cwd) @@ -127,6 +133,7 @@ impl SessionConfiguration { approval_policy: self.approval_policy.value(), approvals_reviewer: self.approvals_reviewer, permission_profile: self.permission_profile(), + active_permission_profile: self.active_permission_profile(), cwd: self.cwd.clone(), ephemeral: self.original_config_do_not_use.ephemeral, reasoning_effort: self.collaboration_mode.reasoning_effort(), @@ -210,6 +217,7 @@ impl SessionConfiguration { permission_profile, Some(¤t_file_system_sandbox_policy), )?; + next_configuration.active_permission_profile = None; } else if let Some(sandbox_policy) = updates.sandbox_policy.clone() { let file_system_sandbox_policy = FileSystemSandboxPolicy::from_legacy_sandbox_policy_preserving_deny_entries( @@ -225,6 +233,7 @@ impl SessionConfiguration { network_sandbox_policy, ), )?; + next_configuration.active_permission_profile = None; } else if cwd_changed && file_system_policy_matches_legacy && file_system_policy_has_rebindable_project_root_write @@ -750,10 +759,22 @@ impl Session { default_shell.derive_exec_args("", /*use_login_shell*/ false); let hook_shell_program = hook_shell_argv.remove(0); let _ = hook_shell_argv.pop(); + let plugin_hooks_enabled = config.features.enabled(Feature::PluginHooks); + let (plugin_hook_sources, plugin_hook_load_warnings) = if plugin_hooks_enabled { + let plugin_outcome = plugins_manager.plugins_for_config(&config).await; + ( + plugin_outcome.effective_plugin_hook_sources(), + plugin_outcome.effective_plugin_hook_warnings(), + ) + } else { + (Vec::new(), Vec::new()) + }; let hooks = Hooks::new(HooksConfig { legacy_notify_argv: config.notify.clone(), feature_enabled: config.features.enabled(Feature::CodexHooks), config_layer_stack: Some(config.config_layer_stack.clone()), + plugin_hook_sources, + plugin_hook_load_warnings, shell_program: Some(hook_shell_program), shell_args: hook_shell_argv, }); @@ -875,6 +896,7 @@ impl Session { approval_policy: session_configuration.approval_policy.value(), approvals_reviewer: session_configuration.approvals_reviewer, permission_profile: session_configuration.permission_profile(), + active_permission_profile: session_configuration.active_permission_profile(), cwd: session_configuration.cwd.clone(), reasoning_effort: session_configuration.collaboration_mode.reasoning_effort(), history_log_id, diff --git a/codex-rs/core/src/session/tests.rs b/codex-rs/core/src/session/tests.rs index 8854744b76..a344021b75 100644 --- a/codex-rs/core/src/session/tests.rs +++ b/codex-rs/core/src/session/tests.rs @@ -2293,6 +2293,7 @@ async fn set_rate_limits_retains_previous_credits() { approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, permission_profile: config.permissions.permission_profile.clone(), + active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), @@ -2395,6 +2396,7 @@ async fn set_rate_limits_updates_plan_type_when_present() { approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, permission_profile: config.permissions.permission_profile.clone(), + active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), @@ -2842,6 +2844,7 @@ pub(crate) async fn make_session_configuration_for_tests() -> SessionConfigurati approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, permission_profile: config.permissions.permission_profile.clone(), + active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), @@ -3278,6 +3281,7 @@ async fn session_new_fails_when_zsh_fork_enabled_without_zsh_path() { approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, permission_profile: config.permissions.permission_profile.clone(), + active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), @@ -3382,6 +3386,7 @@ pub(crate) async fn make_session_and_context() -> (Session, TurnContext) { approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, permission_profile: config.permissions.permission_profile.clone(), + active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), @@ -3594,6 +3599,7 @@ async fn make_session_with_config_and_rx( approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, permission_profile: config.permissions.permission_profile.clone(), + active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), @@ -4776,6 +4782,7 @@ where approval_policy: config.permissions.approval_policy.clone(), approvals_reviewer: config.approvals_reviewer, permission_profile: config.permissions.permission_profile.clone(), + active_permission_profile: config.permissions.active_permission_profile(), windows_sandbox_level: WindowsSandboxLevel::from_config(&config), cwd: config.cwd.clone(), codex_home: config.codex_home.clone(), diff --git a/codex-rs/core/tests/suite/hooks.rs b/codex-rs/core/tests/suite/hooks.rs index 28185a0a5c..6d232afd21 100644 --- a/codex-rs/core/tests/suite/hooks.rs +++ b/codex-rs/core/tests/suite/hooks.rs @@ -727,7 +727,7 @@ fn request_message_input_texts(body: &[u8], role: &str) -> Vec { .collect() } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn stop_hook_can_block_multiple_times_in_same_turn() -> Result<()> { skip_if_no_network!(Ok(())); @@ -841,7 +841,7 @@ async fn stop_hook_can_block_multiple_times_in_same_turn() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn session_start_hook_sees_materialized_transcript_path() -> Result<()> { skip_if_no_network!(Ok(())); @@ -886,7 +886,7 @@ async fn session_start_hook_sees_materialized_transcript_path() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn resumed_thread_keeps_stop_continuation_prompt_in_history() -> Result<()> { skip_if_no_network!(Ok(())); @@ -962,7 +962,7 @@ async fn resumed_thread_keeps_stop_continuation_prompt_in_history() -> Result<() Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn multiple_blocking_stop_hooks_persist_multiple_hook_prompt_fragments() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1028,7 +1028,7 @@ async fn multiple_blocking_stop_hooks_persist_multiple_hook_prompt_fragments() - Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn blocked_user_prompt_submit_persists_additional_context_for_next_turn() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1111,7 +1111,7 @@ async fn blocked_user_prompt_submit_persists_additional_context_for_next_turn() Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn blocked_queued_prompt_does_not_strand_earlier_accepted_prompt() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1276,7 +1276,7 @@ async fn blocked_queued_prompt_does_not_strand_earlier_accepted_prompt() -> Resu Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn permission_request_hook_allows_shell_command_without_user_approval() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1355,7 +1355,7 @@ async fn permission_request_hook_allows_shell_command_without_user_approval() -> Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn permission_request_hook_allows_apply_patch_with_write_alias() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1437,7 +1437,7 @@ async fn permission_request_hook_allows_apply_patch_with_write_alias() -> Result Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn permission_request_hook_sees_raw_exec_command_input() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1518,7 +1518,7 @@ async fn permission_request_hook_sees_raw_exec_command_input() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn permission_request_hook_allows_network_approval_without_prompt() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1649,7 +1649,7 @@ allow_local_binding = true } #[cfg(not(target_os = "linux"))] -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn permission_request_hook_sees_retry_context_after_sandbox_denial() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1719,7 +1719,7 @@ async fn permission_request_hook_sees_retry_context_after_sandbox_denial() -> Re Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn pre_tool_use_blocks_shell_command_before_execution() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1821,7 +1821,151 @@ async fn pre_tool_use_blocks_shell_command_before_execution() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] +async fn plugin_pre_tool_use_blocks_shell_command_before_execution() -> Result<()> { + skip_if_no_network!(Ok(())); + + let server = start_mock_server().await; + let call_id = "plugin-pretooluse-shell-command"; + let marker = std::env::temp_dir().join("plugin-pretooluse-shell-command-marker"); + let command = format!("printf blocked > {}", marker.display()); + let args = serde_json::json!({ "command": command }); + let responses = mount_sse_sequence( + &server, + vec![ + sse(vec![ + ev_response_created("resp-1"), + core_test_support::responses::ev_function_call( + call_id, + "shell_command", + &serde_json::to_string(&args)?, + ), + ev_completed("resp-1"), + ]), + sse(vec![ + ev_response_created("resp-2"), + ev_assistant_message("msg-1", "plugin hook blocked it"), + ev_completed("resp-2"), + ]), + ], + ) + .await; + + let home = Arc::new(TempDir::new()?); + let plugin_root = home.path().join("plugins/cache/test/sample/local"); + let hooks_dir = plugin_root.join("hooks"); + fs::create_dir_all(plugin_root.join(".codex-plugin")) + .context("create plugin manifest directory")?; + fs::create_dir_all(&hooks_dir).context("create plugin hooks directory")?; + fs::write( + plugin_root.join(".codex-plugin/plugin.json"), + r#"{"name":"sample"}"#, + ) + .context("write plugin manifest")?; + fs::write( + home.path().join("config.toml"), + r#"[plugins."sample@test"] +enabled = true +"#, + ) + .context("write plugin config")?; + + let script_path = hooks_dir.join("pre_tool_use_hook.py"); + let log_path = hooks_dir.join("pre_tool_use_hook_log.jsonl"); + fs::write( + &script_path, + format!( + r#"import json +from pathlib import Path +import sys + +payload = json.load(sys.stdin) +with Path(r"{log_path}").open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload) + "\n") + +print(json.dumps({{ + "hookSpecificOutput": {{ + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": "blocked by plugin hook" + }} +}})) +"#, + log_path = log_path.display(), + ), + ) + .context("write plugin pre tool use hook script")?; + fs::write( + hooks_dir.join("hooks.json"), + r#"{ + "hooks": { + "PreToolUse": [{ + "matcher": "^Bash$", + "hooks": [{ + "type": "command", + "command": "python3 ${PLUGIN_ROOT}/hooks/pre_tool_use_hook.py" + }] + }] + } +}"#, + ) + .context("write plugin hooks config")?; + + let mut builder = test_codex() + .with_home(Arc::clone(&home)) + .with_config(|config| { + config + .features + .enable(Feature::Plugins) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::CodexHooks) + .expect("test config should allow feature update"); + config + .features + .enable(Feature::PluginHooks) + .expect("test config should allow feature update"); + }); + let test = builder.build(&server).await?; + + if marker.exists() { + fs::remove_file(&marker).context("remove leftover plugin pre tool use marker")?; + } + + test.submit_turn_with_policy( + "run the shell command blocked by a plugin hook", + codex_protocol::protocol::SandboxPolicy::DangerFullAccess, + ) + .await?; + + let requests = responses.requests(); + assert_eq!(requests.len(), 2); + let output_item = requests[1].function_call_output(call_id); + let output = output_item + .get("output") + .and_then(Value::as_str) + .expect("shell command output string"); + assert!( + output.contains("Command blocked by PreToolUse hook: blocked by plugin hook"), + "blocked tool output should surface the plugin hook reason", + ); + assert!( + !marker.exists(), + "plugin hook should block shell command execution" + ); + + let hook_inputs = read_hook_inputs_from_log(&log_path)?; + assert_eq!(hook_inputs.len(), 1); + assert_eq!(hook_inputs[0]["hook_event_name"], "PreToolUse"); + assert_eq!(hook_inputs[0]["tool_name"], "Bash"); + assert_eq!(hook_inputs[0]["tool_use_id"], call_id); + assert_eq!(hook_inputs[0]["tool_input"]["command"], command); + + Ok(()) +} + +#[tokio::test] async fn pre_tool_use_blocks_shell_when_defined_in_config_toml() -> Result<()> { skip_if_no_network!(Ok(())); @@ -1904,7 +2048,7 @@ async fn pre_tool_use_blocks_shell_when_defined_in_config_toml() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn pre_tool_use_merges_hooks_json_and_config_toml() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2005,7 +2149,7 @@ async fn pre_tool_use_merges_hooks_json_and_config_toml() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn pre_tool_use_blocks_local_shell_before_execution() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2099,7 +2243,7 @@ async fn pre_tool_use_blocks_local_shell_before_execution() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn pre_tool_use_blocks_exec_command_before_execution() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2186,7 +2330,7 @@ async fn pre_tool_use_blocks_exec_command_before_execution() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn pre_tool_use_blocks_apply_patch_before_execution() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2263,7 +2407,7 @@ async fn pre_tool_use_blocks_apply_patch_before_execution() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn pre_tool_use_blocks_apply_patch_with_write_alias() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2338,7 +2482,7 @@ async fn pre_tool_use_blocks_apply_patch_with_write_alias() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn pre_tool_use_does_not_fire_for_plan_tool() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2410,7 +2554,7 @@ async fn pre_tool_use_does_not_fire_for_plan_tool() -> Result<()> { Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn post_tool_use_records_additional_context_for_shell_command() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2507,7 +2651,7 @@ async fn post_tool_use_records_additional_context_for_shell_command() -> Result< Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn post_tool_use_block_decision_replaces_shell_command_output_with_reason() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2575,7 +2719,7 @@ async fn post_tool_use_block_decision_replaces_shell_command_output_with_reason( Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn post_tool_use_continue_false_replaces_shell_command_output_with_stop_reason() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2644,7 +2788,7 @@ async fn post_tool_use_continue_false_replaces_shell_command_output_with_stop_re Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn post_tool_use_records_additional_context_for_local_shell() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2718,7 +2862,7 @@ async fn post_tool_use_records_additional_context_for_local_shell() -> Result<() Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn post_tool_use_exit_two_replaces_one_shot_exec_command_output_with_feedback() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2793,7 +2937,7 @@ async fn post_tool_use_exit_two_replaces_one_shot_exec_command_output_with_feedb Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn post_tool_use_blocks_when_exec_session_completes_via_write_stdin() -> Result<()> { skip_if_no_network!(Ok(())); skip_if_windows!(Ok(())); @@ -2899,7 +3043,7 @@ async fn post_tool_use_blocks_when_exec_session_completes_via_write_stdin() -> R Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn post_tool_use_records_additional_context_for_apply_patch() -> Result<()> { skip_if_no_network!(Ok(())); @@ -2990,7 +3134,7 @@ async fn post_tool_use_records_additional_context_for_apply_patch() -> Result<() Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn post_tool_use_records_apply_patch_context_with_edit_alias() -> Result<()> { skip_if_no_network!(Ok(())); @@ -3063,7 +3207,7 @@ async fn post_tool_use_records_apply_patch_context_with_edit_alias() -> Result<( Ok(()) } -#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +#[tokio::test] async fn post_tool_use_does_not_fire_for_plan_tool() -> Result<()> { skip_if_no_network!(Ok(())); diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index d4044a728d..93e546da34 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -1050,6 +1050,7 @@ fn session_configured_from_thread_response( permission_profile: permission_profile.unwrap_or_else(|| { PermissionProfile::from_legacy_sandbox_policy_for_cwd(&sandbox_policy, cwd.as_path()) }), + active_permission_profile: None, cwd, reasoning_effort, history_log_id: 0, diff --git a/codex-rs/exec/src/lib_tests.rs b/codex-rs/exec/src/lib_tests.rs index bcb17fb87d..d10331f571 100644 --- a/codex-rs/exec/src/lib_tests.rs +++ b/codex-rs/exec/src/lib_tests.rs @@ -432,6 +432,7 @@ fn session_configured_from_thread_response_uses_review_policy_from_response() { ) .into(), ), + active_permission_profile: None, reasoning_effort: None, }; diff --git a/codex-rs/exec/tests/event_processor_with_json_output.rs b/codex-rs/exec/tests/event_processor_with_json_output.rs index 23dcd6733a..f6f6d35f21 100644 --- a/codex-rs/exec/tests/event_processor_with_json_output.rs +++ b/codex-rs/exec/tests/event_processor_with_json_output.rs @@ -115,6 +115,7 @@ fn session_configured_produces_thread_started_event() { approval_policy: AskForApproval::Never, approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/tmp/project").abs(), reasoning_effort: None, history_log_id: 0, diff --git a/codex-rs/features/src/lib.rs b/codex-rs/features/src/lib.rs index f20ca6577c..d997cc771f 100644 --- a/codex-rs/features/src/lib.rs +++ b/codex-rs/features/src/lib.rs @@ -159,6 +159,8 @@ pub enum Feature { ToolSuggest, /// Enable plugins. Plugins, + /// Enable plugin-bundled lifecycle hooks. + PluginHooks, /// Allow the in-app browser pane in desktop apps. /// /// Requirements-only gate: this should be set from requirements, not user config. @@ -876,6 +878,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::Stable, default_enabled: true, }, + FeatureSpec { + id: Feature::PluginHooks, + key: "plugin_hooks", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::InAppBrowser, key: "in_app_browser", diff --git a/codex-rs/hooks/Cargo.toml b/codex-rs/hooks/Cargo.toml index d4d2f9cbc7..028a055424 100644 --- a/codex-rs/hooks/Cargo.toml +++ b/codex-rs/hooks/Cargo.toml @@ -16,6 +16,7 @@ workspace = true anyhow = { workspace = true } chrono = { workspace = true, features = ["serde"] } codex-config = { workspace = true } +codex-plugin = { workspace = true } codex-protocol = { workspace = true } codex-utils-absolute-path = { workspace = true } futures = { workspace = true, features = ["alloc"] } diff --git a/codex-rs/hooks/src/engine/command_runner.rs b/codex-rs/hooks/src/engine/command_runner.rs index e0e08c3fa5..7366d4ec51 100644 --- a/codex-rs/hooks/src/engine/command_runner.rs +++ b/codex-rs/hooks/src/engine/command_runner.rs @@ -108,12 +108,12 @@ fn build_command(shell: &CommandShell, handler: &ConfiguredHandler) -> Command { }; if shell.program.is_empty() { command.arg(&handler.command); - command } else { command.args(&shell.args); command.arg(&handler.command); - command } + command.envs(&handler.env); + command } fn default_shell_command() -> Command { diff --git a/codex-rs/hooks/src/engine/discovery.rs b/codex-rs/hooks/src/engine/discovery.rs index 4e704e0a03..f2e195bb94 100644 --- a/codex-rs/hooks/src/engine/discovery.rs +++ b/codex-rs/hooks/src/engine/discovery.rs @@ -12,8 +12,10 @@ use codex_config::HooksFile; use codex_config::ManagedHooksRequirementsToml; use codex_config::MatcherGroup; use codex_config::RequirementSource; +use codex_plugin::PluginHookSource; use codex_utils_absolute_path::AbsolutePathBuf; use serde::Deserialize; +use std::collections::HashMap; use super::ConfiguredHandler; use crate::events::common::matcher_pattern_for_event; @@ -25,23 +27,34 @@ pub(crate) struct DiscoveryResult { pub warnings: Vec, } -#[derive(Clone, Copy)] +#[derive(Clone)] struct HookHandlerSource<'a> { path: &'a AbsolutePathBuf, is_managed: bool, source: HookSource, + env: HashMap, } -pub(crate) fn discover_handlers(config_layer_stack: Option<&ConfigLayerStack>) -> DiscoveryResult { +pub(crate) fn discover_handlers( + config_layer_stack: Option<&ConfigLayerStack>, + plugin_hook_sources: Vec, + plugin_hook_load_warnings: Vec, +) -> DiscoveryResult { let Some(config_layer_stack) = config_layer_stack else { - return DiscoveryResult { - handlers: Vec::new(), - warnings: Vec::new(), - }; + let mut handlers = Vec::new(); + let mut warnings = plugin_hook_load_warnings; + let mut display_order = 0_i64; + append_plugin_hook_sources( + &mut handlers, + &mut warnings, + &mut display_order, + plugin_hook_sources, + ); + return DiscoveryResult { handlers, warnings }; }; let mut handlers = Vec::new(); - let mut warnings = Vec::new(); + let mut warnings = plugin_hook_load_warnings; let mut display_order = 0_i64; append_managed_requirement_handlers( @@ -80,6 +93,7 @@ pub(crate) fn discover_handlers(config_layer_stack: Option<&ConfigLayerStack>) - path: &source_path, is_managed: false, source: hook_source, + env: HashMap::new(), }, hook_events, ); @@ -94,12 +108,20 @@ pub(crate) fn discover_handlers(config_layer_stack: Option<&ConfigLayerStack>) - path: &source_path, is_managed: false, source: hook_source, + env: HashMap::new(), }, hook_events, ); } } + append_plugin_hook_sources( + &mut handlers, + &mut warnings, + &mut display_order, + plugin_hook_sources, + ); + DiscoveryResult { handlers, warnings } } @@ -125,11 +147,51 @@ fn append_managed_requirement_handlers( path: &source_path, is_managed: true, source: hook_source_for_requirement_source(managed_hooks.source.as_ref()), + env: HashMap::new(), }, managed_hooks.get().hooks.clone(), ); } +fn append_plugin_hook_sources( + handlers: &mut Vec, + warnings: &mut Vec, + display_order: &mut i64, + plugin_hook_sources: Vec, +) { + // TODO(abhinav): check enabled/trusted state here before plugin hooks become runnable. + for source in plugin_hook_sources { + let PluginHookSource { + plugin_root, + plugin_data_root, + source_path, + hooks, + .. + } = source; + let mut env = HashMap::new(); + let plugin_root_value = plugin_root.display().to_string(); + let plugin_data_root_value = plugin_data_root.display().to_string(); + env.insert("PLUGIN_ROOT".to_string(), plugin_root_value.clone()); + // For OOTB compat with existing plugins that use this env var. + env.insert("CLAUDE_PLUGIN_ROOT".to_string(), plugin_root_value); + env.insert("PLUGIN_DATA".to_string(), plugin_data_root_value.clone()); + // For OOTB compat with existing plugins that use this env var. + env.insert("CLAUDE_PLUGIN_DATA".to_string(), plugin_data_root_value); + append_hook_events( + handlers, + warnings, + display_order, + HookHandlerSource { + path: &source_path, + is_managed: false, + source: HookSource::Plugin, + env, + }, + hooks, + ); + } +} + fn managed_hooks_source_path( managed_hooks: &ManagedHooksRequirementsToml, requirement_source: Option<&RequirementSource>, @@ -278,7 +340,7 @@ fn append_hook_events( handlers, warnings, display_order, - source, + source.clone(), event_name, groups, ); @@ -298,7 +360,7 @@ fn append_matcher_groups( handlers, warnings, display_order, - source, + source.clone(), event_name, matcher_pattern_for_event(event_name, group.matcher.as_deref()), group.hooks, @@ -347,6 +409,9 @@ fn append_group_handlers( )); continue; } + let command = source.env.iter().fold(command, |command, (key, value)| { + command.replace(&format!("${{{key}}}"), value) + }); let timeout_sec = timeout_sec.unwrap_or(600).max(1); handlers.push(ConfiguredHandler { event_name, @@ -358,6 +423,7 @@ fn append_group_handlers( source_path: source.path.clone(), source: source.source, display_order: *display_order, + env: source.env.clone(), }); *display_order += 1; } @@ -431,6 +497,7 @@ mod tests { path, is_managed: false, source: hook_source(), + env: std::collections::HashMap::new(), } } @@ -475,6 +542,7 @@ mod tests { source_path: source_path.clone(), source: hook_source(), display_order: 0, + env: std::collections::HashMap::new(), }] ); } @@ -508,6 +576,7 @@ mod tests { source_path: source_path.clone(), source: hook_source(), display_order: 0, + env: std::collections::HashMap::new(), }] ); } diff --git a/codex-rs/hooks/src/engine/dispatcher.rs b/codex-rs/hooks/src/engine/dispatcher.rs index d1cda96541..c19b311843 100644 --- a/codex-rs/hooks/src/engine/dispatcher.rs +++ b/codex-rs/hooks/src/engine/dispatcher.rs @@ -164,6 +164,7 @@ mod tests { source_path: test_path_buf("/tmp/hooks.json").abs(), source: HookSource::User, display_order, + env: std::collections::HashMap::new(), } } diff --git a/codex-rs/hooks/src/engine/mod.rs b/codex-rs/hooks/src/engine/mod.rs index 3bfb17f6d6..89daf501ca 100644 --- a/codex-rs/hooks/src/engine/mod.rs +++ b/codex-rs/hooks/src/engine/mod.rs @@ -4,7 +4,10 @@ pub(crate) mod dispatcher; pub(crate) mod output_parser; pub(crate) mod schema_loader; +use std::collections::HashMap; + use codex_config::ConfigLayerStack; +use codex_plugin::PluginHookSource; use codex_protocol::protocol::HookRunSummary; use codex_protocol::protocol::HookSource; use codex_utils_absolute_path::AbsolutePathBuf; @@ -39,6 +42,7 @@ pub(crate) struct ConfiguredHandler { pub source_path: AbsolutePathBuf, pub source: HookSource, pub display_order: i64, + pub env: HashMap, } impl ConfiguredHandler { @@ -74,6 +78,8 @@ impl ClaudeHooksEngine { pub(crate) fn new( enabled: bool, config_layer_stack: Option<&ConfigLayerStack>, + plugin_hook_sources: Vec, + plugin_hook_load_warnings: Vec, shell: CommandShell, ) -> Self { if !enabled { @@ -85,7 +91,11 @@ impl ClaudeHooksEngine { } let _ = schema_loader::generated_hook_schemas(); - let discovered = discovery::discover_handlers(config_layer_stack); + let discovered = discovery::discover_handlers( + config_layer_stack, + plugin_hook_sources, + plugin_hook_load_warnings, + ); Self { handlers: discovered.handlers, warnings: discovered.warnings, diff --git a/codex-rs/hooks/src/engine/mod_tests.rs b/codex-rs/hooks/src/engine/mod_tests.rs index 81004aefb4..06ec3b2513 100644 --- a/codex-rs/hooks/src/engine/mod_tests.rs +++ b/codex-rs/hooks/src/engine/mod_tests.rs @@ -1,3 +1,4 @@ +use std::collections::HashMap; use std::fs; use std::path::Path; @@ -15,7 +16,12 @@ use codex_config::ManagedHooksRequirementsToml; use codex_config::MatcherGroup; use codex_config::RequirementSource; use codex_config::TomlValue; +use codex_plugin::PluginHookSource; +use codex_plugin::PluginId; use codex_protocol::ThreadId; +use codex_protocol::protocol::HookOutputEntryKind; +use codex_protocol::protocol::HookRunStatus; +use codex_protocol::protocol::HookSource; use pretty_assertions::assert_eq; use tempfile::tempdir; @@ -105,6 +111,8 @@ with Path(r"{log_path}").open("a", encoding="utf-8") as handle: let engine = ClaudeHooksEngine::new( /*enabled*/ true, Some(&config_layer_stack), + Vec::new(), + Vec::new(), CommandShell { program: String::new(), args: Vec::new(), @@ -188,6 +196,8 @@ fn requirements_managed_hooks_warn_when_managed_dir_is_missing() { let engine = ClaudeHooksEngine::new( /*enabled*/ true, Some(&config_layer_stack), + Vec::new(), + Vec::new(), CommandShell { program: String::new(), args: Vec::new(), @@ -295,6 +305,8 @@ fn discovers_hooks_from_json_and_toml_in_the_same_layer() { let engine = ClaudeHooksEngine::new( /*enabled*/ true, Some(&config_layer_stack), + Vec::new(), + Vec::new(), CommandShell { program: String::new(), args: Vec::new(), @@ -325,3 +337,194 @@ fn discovers_hooks_from_json_and_toml_in_the_same_layer() { assert_eq!(preview[0].source_path, hooks_json_path); assert_eq!(preview[1].source_path, config_path); } + +#[tokio::test] +async fn plugin_hook_sources_run_with_plugin_env_and_plugin_source() { + let temp = tempdir().expect("create temp dir"); + let plugin_root = + AbsolutePathBuf::try_from(temp.path().join("demo-plugin")).expect("plugin root"); + let plugin_data_root = + AbsolutePathBuf::try_from(temp.path().join("plugin-data")).expect("plugin data root"); + fs::create_dir_all(plugin_root.join("hooks")).expect("create hooks dir"); + let source_path = plugin_root.join("hooks/hooks.json"); + let script_path = plugin_root.join("hooks/write_env.py"); + fs::write( + script_path.as_path(), + r#"import json +import os +print(json.dumps({ + "systemMessage": json.dumps({ + "plugin": os.environ.get("PLUGIN_ROOT"), + "claude": os.environ.get("CLAUDE_PLUGIN_ROOT"), + }) +})) +"#, + ) + .expect("write hook script"); + let plugin_id = PluginId::parse("demo-plugin@test-marketplace").expect("plugin id"); + let plugin_hook_sources = vec![PluginHookSource { + plugin_id, + plugin_root: plugin_root.clone(), + plugin_data_root: plugin_data_root.clone(), + source_path: source_path.clone(), + source_relative_path: "hooks/hooks.json".to_string(), + hooks: HookEventsToml { + pre_tool_use: vec![MatcherGroup { + matcher: Some("Bash".to_string()), + hooks: vec![HookHandlerConfig::Command { + command: format!("python3 {}", script_path.display()), + timeout_sec: Some(5), + r#async: false, + status_message: None, + }], + }], + ..Default::default() + }, + }]; + let engine = ClaudeHooksEngine::new( + /*enabled*/ true, + /*config_layer_stack*/ None, + plugin_hook_sources, + Vec::new(), + CommandShell { + program: String::new(), + args: Vec::new(), + }, + ); + + let preview = engine.preview_pre_tool_use(&PreToolUseRequest { + session_id: ThreadId::new(), + turn_id: "turn-1".to_string(), + cwd: cwd(), + transcript_path: None, + model: "gpt-test".to_string(), + permission_mode: "default".to_string(), + tool_name: "Bash".to_string(), + matcher_aliases: Vec::new(), + tool_use_id: "tool-1".to_string(), + tool_input: serde_json::json!({ "command": "echo hello" }), + }); + assert_eq!(preview.len(), 1); + assert_eq!(preview[0].source, HookSource::Plugin); + assert_eq!(preview[0].source_path, source_path); + + let outcome = engine + .run_pre_tool_use(PreToolUseRequest { + session_id: ThreadId::new(), + turn_id: "turn-1".to_string(), + cwd: cwd(), + transcript_path: None, + model: "gpt-test".to_string(), + permission_mode: "default".to_string(), + tool_name: "Bash".to_string(), + matcher_aliases: Vec::new(), + tool_use_id: "tool-1".to_string(), + tool_input: serde_json::json!({ "command": "echo hello" }), + }) + .await; + + assert_eq!(outcome.hook_events.len(), 1); + assert_eq!(outcome.hook_events[0].run.source, HookSource::Plugin); + assert_eq!(outcome.hook_events[0].run.status, HookRunStatus::Completed); + assert_eq!(outcome.hook_events[0].run.entries.len(), 1); + assert_eq!( + outcome.hook_events[0].run.entries[0].kind, + HookOutputEntryKind::Warning + ); + let logged: serde_json::Value = + serde_json::from_str(&outcome.hook_events[0].run.entries[0].text) + .expect("parse env payload"); + assert_eq!( + logged, + serde_json::json!({ + "plugin": plugin_root.display().to_string(), + "claude": plugin_root.display().to_string(), + }) + ); +} + +#[test] +fn plugin_hook_sources_expand_plugin_placeholders() { + let temp = tempdir().expect("create temp dir"); + let plugin_root = + AbsolutePathBuf::try_from(temp.path().join("demo-plugin")).expect("plugin root"); + let plugin_data_root = + AbsolutePathBuf::try_from(temp.path().join("plugin-data")).expect("plugin data root"); + let source_path = plugin_root.join("hooks/hooks.json"); + let plugin_id = PluginId::parse("demo-plugin@test-marketplace").expect("plugin id"); + let plugin_hook_sources = vec![PluginHookSource { + plugin_id, + plugin_root: plugin_root.clone(), + plugin_data_root: plugin_data_root.clone(), + source_path, + source_relative_path: "hooks/hooks.json".to_string(), + hooks: HookEventsToml { + pre_tool_use: vec![MatcherGroup { + matcher: Some("Bash".to_string()), + hooks: vec![HookHandlerConfig::Command { + command: "run ${PLUGIN_ROOT} ${CLAUDE_PLUGIN_ROOT} ${PLUGIN_DATA} ${CLAUDE_PLUGIN_DATA}" + .to_string(), + timeout_sec: Some(5), + r#async: false, + status_message: None, + }], + }], + ..Default::default() + }, + }]; + let engine = ClaudeHooksEngine::new( + /*enabled*/ true, + /*config_layer_stack*/ None, + plugin_hook_sources, + Vec::new(), + CommandShell { + program: String::new(), + args: Vec::new(), + }, + ); + + assert_eq!( + engine.handlers[0].command, + format!( + "run {} {} {} {}", + plugin_root.display(), + plugin_root.display(), + plugin_data_root.display(), + plugin_data_root.display() + ) + ); + assert_eq!( + engine.handlers[0].env, + HashMap::from([ + ("PLUGIN_ROOT".to_string(), plugin_root.display().to_string()), + ( + "CLAUDE_PLUGIN_ROOT".to_string(), + plugin_root.display().to_string() + ), + ( + "PLUGIN_DATA".to_string(), + plugin_data_root.display().to_string() + ), + ( + "CLAUDE_PLUGIN_DATA".to_string(), + plugin_data_root.display().to_string() + ), + ]) + ); +} + +#[test] +fn plugin_hook_load_warnings_are_startup_warnings() { + let engine = ClaudeHooksEngine::new( + /*enabled*/ true, + /*config_layer_stack*/ None, + Vec::new(), + vec!["failed plugin hook".to_string()], + CommandShell { + program: String::new(), + args: Vec::new(), + }, + ); + + assert_eq!(engine.warnings(), &["failed plugin hook".to_string()]); +} diff --git a/codex-rs/hooks/src/events/post_tool_use.rs b/codex-rs/hooks/src/events/post_tool_use.rs index 20cdfd2010..c01cebf78a 100644 --- a/codex-rs/hooks/src/events/post_tool_use.rs +++ b/codex-rs/hooks/src/events/post_tool_use.rs @@ -551,6 +551,7 @@ mod tests { source_path: test_path_buf("/tmp/hooks.json").abs(), source: codex_protocol::protocol::HookSource::User, display_order: 0, + env: std::collections::HashMap::new(), } } diff --git a/codex-rs/hooks/src/events/pre_tool_use.rs b/codex-rs/hooks/src/events/pre_tool_use.rs index 46012150bb..3b20c2c2c0 100644 --- a/codex-rs/hooks/src/events/pre_tool_use.rs +++ b/codex-rs/hooks/src/events/pre_tool_use.rs @@ -542,6 +542,7 @@ mod tests { source_path: test_path_buf("/tmp/hooks.json").abs(), source: codex_protocol::protocol::HookSource::User, display_order: 0, + env: std::collections::HashMap::new(), } } diff --git a/codex-rs/hooks/src/events/session_start.rs b/codex-rs/hooks/src/events/session_start.rs index b1ccdd440a..54c7f51732 100644 --- a/codex-rs/hooks/src/events/session_start.rs +++ b/codex-rs/hooks/src/events/session_start.rs @@ -364,6 +364,7 @@ mod tests { source_path: test_path_buf("/tmp/hooks.json").abs(), source: codex_protocol::protocol::HookSource::User, display_order: 0, + env: std::collections::HashMap::new(), } } diff --git a/codex-rs/hooks/src/events/stop.rs b/codex-rs/hooks/src/events/stop.rs index f376dccd2c..392f15eee2 100644 --- a/codex-rs/hooks/src/events/stop.rs +++ b/codex-rs/hooks/src/events/stop.rs @@ -531,6 +531,7 @@ mod tests { source_path: test_path_buf("/tmp/hooks.json").abs(), source: codex_protocol::protocol::HookSource::User, display_order: 0, + env: std::collections::HashMap::new(), } } diff --git a/codex-rs/hooks/src/events/user_prompt_submit.rs b/codex-rs/hooks/src/events/user_prompt_submit.rs index 2acd4808b8..8aaf3ad608 100644 --- a/codex-rs/hooks/src/events/user_prompt_submit.rs +++ b/codex-rs/hooks/src/events/user_prompt_submit.rs @@ -422,6 +422,7 @@ mod tests { source_path: test_path_buf("/tmp/hooks.json").abs(), source: codex_protocol::protocol::HookSource::User, display_order: 0, + env: std::collections::HashMap::new(), } } diff --git a/codex-rs/hooks/src/registry.rs b/codex-rs/hooks/src/registry.rs index 6f4e56b1bf..7dd93213a1 100644 --- a/codex-rs/hooks/src/registry.rs +++ b/codex-rs/hooks/src/registry.rs @@ -1,4 +1,5 @@ use codex_config::ConfigLayerStack; +use codex_plugin::PluginHookSource; use tokio::process::Command; use crate::engine::ClaudeHooksEngine; @@ -25,6 +26,8 @@ pub struct HooksConfig { pub legacy_notify_argv: Option>, pub feature_enabled: bool, pub config_layer_stack: Option, + pub plugin_hook_sources: Vec, + pub plugin_hook_load_warnings: Vec, pub shell_program: Option, pub shell_args: Vec, } @@ -53,6 +56,8 @@ impl Hooks { let engine = ClaudeHooksEngine::new( config.feature_enabled, config.config_layer_stack.as_ref(), + config.plugin_hook_sources, + config.plugin_hook_load_warnings, CommandShell { program: config.shell_program.unwrap_or_default(), args: config.shell_args, diff --git a/codex-rs/network-proxy/src/http_proxy.rs b/codex-rs/network-proxy/src/http_proxy.rs index fa3616844e..658ee9f610 100644 --- a/codex-rs/network-proxy/src/http_proxy.rs +++ b/codex-rs/network-proxy/src/http_proxy.rs @@ -1034,7 +1034,10 @@ mod tests { #[tokio::test] async fn http_connect_accept_allows_allowlisted_host_in_full_mode() { let policy = { - let mut policy = NetworkProxySettings::default(); + let mut policy = NetworkProxySettings { + allow_local_binding: true, + ..NetworkProxySettings::default() + }; policy.set_allowed_domains(vec!["example.com".to_string()]); policy }; diff --git a/codex-rs/network-proxy/src/policy.rs b/codex-rs/network-proxy/src/policy.rs index 40e71caf36..f83863ded6 100644 --- a/codex-rs/network-proxy/src/policy.rs +++ b/codex-rs/network-proxy/src/policy.rs @@ -32,7 +32,7 @@ impl Host { /// Returns true if the host is a loopback hostname or IP literal. pub fn is_loopback_host(host: &Host) -> bool { let host = host.as_str(); - let host = host.split_once('%').map(|(ip, _)| ip).unwrap_or(host); + let host = unscoped_ip_literal(host).unwrap_or(host); if host == "localhost" { return true; } @@ -103,24 +103,48 @@ pub fn normalize_host(host: &str) -> String { if host.starts_with('[') && let Some(end) = host.find(']') { - return normalize_dns_host(&host[1..end]); + return normalize_dns_host_or_ip_literal(&host[1..end]); } // The proxy stack should typically hand us a host without a port, but be // defensive and strip `:port` when there is exactly one `:`. if host.bytes().filter(|b| *b == b':').count() == 1 { let host = host.split(':').next().unwrap_or_default(); - return normalize_dns_host(host); + return normalize_dns_host_or_ip_literal(host); } // Avoid mangling unbracketed IPv6 literals, but strip trailing dots so fully qualified domain // names are treated the same as their dotless variants. - normalize_dns_host(host) + normalize_dns_host_or_ip_literal(host) } -fn normalize_dns_host(host: &str) -> String { +fn normalize_dns_host_or_ip_literal(host: &str) -> String { let host = host.to_ascii_lowercase(); - host.trim_end_matches('.').to_string() + let host = host.trim_end_matches('.'); + if let Some(ip) = normalize_ip_literal(host) { + return ip; + } + host.to_string() +} + +pub(crate) fn unscoped_ip_literal(host: &str) -> Option<&str> { + let (ip, _) = host.split_once('%')?; + ip.parse::().ok()?; + Some(ip) +} + +fn normalize_ip_literal(host: &str) -> Option { + if host.parse::().is_ok() { + return Some(host.to_string()); + } + for delimiter in ["%25", "%"] { + if let Some((ip, scope)) = host.split_once(delimiter) + && ip.parse::().is_ok() + { + return Some(format!("{ip}%{scope}")); + } + } + None } fn normalize_pattern(pattern: &str) -> String { @@ -392,6 +416,15 @@ mod tests { assert_eq!(true, set.is_match("::1")); } + #[test] + fn compile_globset_preserves_scoped_ipv6_literals() { + let set = compile_denylist_globset(&["[fe80::1%25lo0]".to_string()]).unwrap(); + + assert_eq!(true, set.is_match("fe80::1%lo0")); + assert_eq!(false, set.is_match("fe80::1%lo1")); + assert_eq!(false, set.is_match("fe80::1")); + } + #[test] fn is_loopback_host_handles_localhost_variants() { assert!(is_loopback_host(&Host::parse("localhost").unwrap())); @@ -462,4 +495,11 @@ mod tests { assert_eq!(normalize_host("[::1]"), "::1"); assert_eq!(normalize_host("[::1]:443"), "::1"); } + + #[test] + fn normalize_host_preserves_ipv6_scope_ids() { + assert_eq!(normalize_host("fe80::1%lo0"), "fe80::1%lo0"); + assert_eq!(normalize_host("[fe80::1%lo0]"), "fe80::1%lo0"); + assert_eq!(normalize_host("[fe80::1%25lo0]"), "fe80::1%lo0"); + } } diff --git a/codex-rs/network-proxy/src/proxy.rs b/codex-rs/network-proxy/src/proxy.rs index 2d70ae3e1c..2b76b27b8f 100644 --- a/codex-rs/network-proxy/src/proxy.rs +++ b/codex-rs/network-proxy/src/proxy.rs @@ -790,9 +790,16 @@ mod tests { #[tokio::test] async fn managed_proxy_builder_uses_loopback_ports() { + let http_listener = StdTcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0))).unwrap(); + let http_addr = http_listener.local_addr().unwrap(); + let socks_listener = StdTcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0))).unwrap(); + let socks_addr = socks_listener.local_addr().unwrap(); + drop(http_listener); + drop(socks_listener); + let state = Arc::new(network_proxy_state_for_policy(NetworkProxySettings { - proxy_url: "http://127.0.0.1:43128".to_string(), - socks_url: "http://127.0.0.1:48081".to_string(), + proxy_url: format!("http://{http_addr}"), + socks_url: format!("http://{socks_addr}"), ..NetworkProxySettings::default() })); let proxy = match NetworkProxy::builder().state(state).build().await { @@ -812,14 +819,8 @@ mod tests { assert!(proxy.socks_addr.ip().is_loopback()); #[cfg(target_os = "windows")] { - assert_eq!( - proxy.http_addr, - "127.0.0.1:43128".parse::().unwrap() - ); - assert_eq!( - proxy.socks_addr, - "127.0.0.1:48081".parse::().unwrap() - ); + assert_eq!(proxy.http_addr, http_addr); + assert_eq!(proxy.socks_addr, socks_addr); } #[cfg(not(target_os = "windows"))] { diff --git a/codex-rs/network-proxy/src/runtime.rs b/codex-rs/network-proxy/src/runtime.rs index bddf814415..984236d892 100644 --- a/codex-rs/network-proxy/src/runtime.rs +++ b/codex-rs/network-proxy/src/runtime.rs @@ -7,6 +7,7 @@ use crate::policy::Host; use crate::policy::is_loopback_host; use crate::policy::is_non_public_ip; use crate::policy::normalize_host; +use crate::policy::unscoped_ip_literal; use crate::reasons::REASON_DENIED; use crate::reasons::REASON_NOT_ALLOWED; use crate::reasons::REASON_NOT_ALLOWED_LOCAL; @@ -371,11 +372,11 @@ impl NetworkProxyState { // 1) explicit deny always wins // 2) local/private networking is opt-in (defense-in-depth) // 3) allowlist is enforced when configured - if deny_set.is_match(host_str) { + if globset_matches_host_or_unscoped(&deny_set, host_str) { return Ok(HostBlockDecision::Blocked(HostBlockReason::Denied)); } - let is_allowlisted = allow_set.is_match(host_str); + let is_allowlisted = globset_matches_host_or_unscoped(&allow_set, host_str); if !allow_local_binding { // If the intent is "prevent access to local/internal networks", we must not rely solely // on string checks like `localhost` / `127.0.0.1`. Attackers can use DNS rebinding or @@ -386,10 +387,7 @@ impl NetworkProxyState { // allowlisted; hostnames that resolve to local/private IPs are blocked even if // allowlisted. let local_literal = { - let host_no_scope = host_str - .split_once('%') - .map(|(ip, _)| ip) - .unwrap_or(host_str); + let host_no_scope = unscoped_ip_literal(host_str).unwrap_or(host_str); if is_loopback_host(&host) { true } else if let Ok(ip) = host_no_scope.parse::() { @@ -797,8 +795,13 @@ fn log_domain_list_changes(list_name: &str, previous: &[String], next: &[String] } } +fn globset_matches_host_or_unscoped(set: &GlobSet, host: &str) -> bool { + set.is_match(host) || unscoped_ip_literal(host).is_some_and(|ip| set.is_match(ip)) +} + fn is_explicit_local_allowlisted(allowed_domains: &[String], host: &Host) -> bool { let normalized_host = host.as_str(); + let unscoped_host = unscoped_ip_literal(normalized_host); allowed_domains.iter().any(|pattern| { let pattern = pattern.trim(); if pattern == "*" || pattern.starts_with("*.") || pattern.starts_with("**.") { @@ -807,7 +810,9 @@ fn is_explicit_local_allowlisted(allowed_domains: &[String], host: &Host) -> boo if pattern.contains('*') || pattern.contains('?') { return false; } - normalize_host(pattern) == normalized_host + let normalized_pattern = normalize_host(pattern); + normalized_pattern == normalized_host + || unscoped_host.is_some_and(|ip| normalized_pattern == ip) }) } @@ -1247,7 +1252,7 @@ mod tests { #[tokio::test] async fn host_blocked_allows_scoped_ipv6_literal_when_explicitly_allowlisted() { - let state = network_proxy_state_for_policy(network_settings(&["fe80::1%lo0"], &[])); + let state = network_proxy_state_for_policy(network_settings(&["fe80::1"], &[])); assert_eq!( state @@ -1258,6 +1263,68 @@ mod tests { ); } + #[tokio::test] + async fn host_blocked_requires_exact_scoped_ipv6_allowlist_match() { + let state = network_proxy_state_for_policy(NetworkProxySettings { + allow_local_binding: true, + ..network_settings(&["fe80::1%eth0"], &[]) + }); + + assert_eq!( + state + .host_blocked("fe80::1%eth0", /*port*/ 80) + .await + .unwrap(), + HostBlockDecision::Allowed + ); + assert_eq!( + state + .host_blocked("fe80::1%eth1", /*port*/ 80) + .await + .unwrap(), + HostBlockDecision::Blocked(HostBlockReason::NotAllowed) + ); + } + + #[tokio::test] + async fn host_blocked_denies_scoped_ipv6_literal_before_local_binding() { + let state = network_proxy_state_for_policy(NetworkProxySettings { + allow_local_binding: true, + ..network_settings(&["*"], &["fd00::1"]) + }); + + for host in ["fd00::1%eth0", "[fd00::1%eth0]", "[fd00::1%25eth0]"] { + assert_eq!( + state.host_blocked(host, /*port*/ 80).await.unwrap(), + HostBlockDecision::Blocked(HostBlockReason::Denied), + "host should be denied after normalization: {host}" + ); + } + } + + #[tokio::test] + async fn host_blocked_requires_exact_scoped_ipv6_denylist_match() { + let state = network_proxy_state_for_policy(NetworkProxySettings { + allow_local_binding: true, + ..network_settings(&["*"], &["fd00::1%eth0"]) + }); + + assert_eq!( + state + .host_blocked("fd00::1%eth0", /*port*/ 80) + .await + .unwrap(), + HostBlockDecision::Blocked(HostBlockReason::Denied) + ); + assert_eq!( + state + .host_blocked("fd00::1%eth1", /*port*/ 80) + .await + .unwrap(), + HostBlockDecision::Allowed + ); + } + #[tokio::test] async fn host_blocked_rejects_private_ip_literals_when_local_binding_disabled() { let state = network_proxy_state_for_policy(network_settings(&["example.com"], &[])); diff --git a/codex-rs/plugin/Cargo.toml b/codex-rs/plugin/Cargo.toml index b72d74682c..a431a543d4 100644 --- a/codex-rs/plugin/Cargo.toml +++ b/codex-rs/plugin/Cargo.toml @@ -13,6 +13,7 @@ path = "src/lib.rs" workspace = true [dependencies] +codex-config = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-plugins = { workspace = true } thiserror = { workspace = true } diff --git a/codex-rs/plugin/src/lib.rs b/codex-rs/plugin/src/lib.rs index b984b9d2fc..2140645de3 100644 --- a/codex-rs/plugin/src/lib.rs +++ b/codex-rs/plugin/src/lib.rs @@ -6,6 +6,8 @@ pub use codex_utils_plugins::plugin_namespace_for_skill_path; mod load_outcome; mod plugin_id; +use codex_config::HookEventsToml; +use codex_utils_absolute_path::AbsolutePathBuf; pub use load_outcome::EffectiveSkillRoots; pub use load_outcome::LoadedPlugin; pub use load_outcome::PluginLoadOutcome; @@ -27,6 +29,16 @@ pub struct PluginCapabilitySummary { pub app_connector_ids: Vec, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PluginHookSource { + pub plugin_id: PluginId, + pub plugin_root: AbsolutePathBuf, + pub plugin_data_root: AbsolutePathBuf, + pub source_path: AbsolutePathBuf, + pub source_relative_path: String, + pub hooks: HookEventsToml, +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct PluginTelemetryMetadata { pub plugin_id: PluginId, diff --git a/codex-rs/plugin/src/load_outcome.rs b/codex-rs/plugin/src/load_outcome.rs index 062886be5c..0865b9020f 100644 --- a/codex-rs/plugin/src/load_outcome.rs +++ b/codex-rs/plugin/src/load_outcome.rs @@ -5,6 +5,7 @@ use codex_utils_absolute_path::AbsolutePathBuf; use crate::AppConnectorId; use crate::PluginCapabilitySummary; +use crate::PluginHookSource; const MAX_CAPABILITY_SUMMARY_DESCRIPTION_LEN: usize = 1024; @@ -21,6 +22,8 @@ pub struct LoadedPlugin { pub has_enabled_skills: bool, pub mcp_servers: HashMap, pub apps: Vec, + pub hook_sources: Vec, + pub hook_load_warnings: Vec, pub error: Option, } @@ -140,6 +143,22 @@ impl PluginLoadOutcome { apps } + pub fn effective_plugin_hook_sources(&self) -> Vec { + self.plugins + .iter() + .filter(|plugin| plugin.is_active()) + .flat_map(|plugin| plugin.hook_sources.iter().cloned()) + .collect() + } + + pub fn effective_plugin_hook_warnings(&self) -> Vec { + self.plugins + .iter() + .filter(|plugin| plugin.is_active()) + .flat_map(|plugin| plugin.hook_load_warnings.iter().cloned()) + .collect() + } + pub fn capability_summaries(&self) -> &[PluginCapabilitySummary] { &self.capability_summaries } diff --git a/codex-rs/protocol/src/models.rs b/codex-rs/protocol/src/models.rs index 2d7dba7d54..e38f0db834 100644 --- a/codex-rs/protocol/src/models.rs +++ b/codex-rs/protocol/src/models.rs @@ -317,6 +317,34 @@ pub enum PermissionProfile { External { network: NetworkSandboxPolicy }, } +/// Metadata for the named permissions profile that produced the active +/// `PermissionProfile`. +/// +/// The runtime must honor `PermissionProfile`; this sidecar exists so clients +/// can display stable profile identity without trying to reverse-engineer a +/// name from the compiled permissions. +#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, JsonSchema, TS)] +pub struct ActivePermissionProfile { + /// Profile identifier from `default_permissions`, such as `:workspace` or a + /// user-defined `[permissions.]` profile. + pub id: String, + + /// Optional parent profile identifier once permissions profiles support + /// inheritance. This is always `None` until that config feature exists. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub extends: Option, +} + +impl ActivePermissionProfile { + pub fn new(id: impl Into) -> Self { + Self { + id: id.into(), + extends: None, + } + } +} + impl Default for PermissionProfile { fn default() -> Self { Self::Managed { diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 34e5a47945..c239cec3eb 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -33,6 +33,7 @@ use crate::mcp::ResourceTemplate as McpResourceTemplate; use crate::mcp::Tool as McpTool; use crate::memory_citation::MemoryCitation; use crate::message_history::HistoryEntry; +use crate::models::ActivePermissionProfile; use crate::models::BaseInstructions; use crate::models::ContentItem; use crate::models::MessagePhase; @@ -1563,6 +1564,7 @@ pub enum HookSource { Project, Mdm, SessionFlags, + Plugin, LegacyManagedConfigFile, LegacyManagedConfigMdm, #[default] @@ -3507,6 +3509,12 @@ pub struct SessionConfiguredEvent { /// Canonical effective permissions for commands executed in the session. pub permission_profile: PermissionProfile, + /// Named profile that produced `permission_profile`, when the active + /// permissions came from `default_permissions`. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[ts(optional)] + pub active_permission_profile: Option, + /// Working directory that should be treated as the *root* of the /// session. pub cwd: AbsolutePathBuf, @@ -3558,6 +3566,8 @@ impl<'de> Deserialize<'de> for SessionConfiguredEvent { // and immediately project it into the canonical `permission_profile`. sandbox_policy: Option, permission_profile: Option, + #[serde(default)] + active_permission_profile: Option, cwd: AbsolutePathBuf, reasoning_effort: Option, history_log_id: u64, @@ -3589,6 +3599,7 @@ impl<'de> Deserialize<'de> for SessionConfiguredEvent { approval_policy: wire.approval_policy, approvals_reviewer: wire.approvals_reviewer, permission_profile, + active_permission_profile: wire.active_permission_profile, cwd: wire.cwd, reasoning_effort: wire.reasoning_effort, history_log_id: wire.history_log_id, @@ -5101,6 +5112,7 @@ mod tests { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: permission_profile.clone(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, diff --git a/codex-rs/rollout-trace/src/inference.rs b/codex-rs/rollout-trace/src/inference.rs index 3162308fb3..b05f891e7b 100644 --- a/codex-rs/rollout-trace/src/inference.rs +++ b/codex-rs/rollout-trace/src/inference.rs @@ -84,6 +84,7 @@ struct EnabledInferenceTraceAttempt { #[derive(Serialize)] struct TracedResponseStreamOutput<'a> { response_id: Option<&'a str>, + upstream_request_id: Option<&'a str>, token_usage: Option<&'a TokenUsage>, output_items: Vec, } @@ -174,6 +175,7 @@ impl InferenceTraceAttempt { pub fn record_completed( &self, response_id: &str, + upstream_request_id: Option<&str>, token_usage: &Option, output_items: &[ResponseItem], ) { @@ -183,6 +185,7 @@ impl InferenceTraceAttempt { let Some(response_payload) = write_response_payload_best_effort( attempt, Some(response_id), + upstream_request_id, token_usage.as_ref(), output_items, ) else { @@ -194,13 +197,19 @@ impl InferenceTraceAttempt { RawTraceEventPayload::InferenceCompleted { inference_call_id: attempt.inference_call_id.clone(), response_id: Some(response_id.to_string()), + upstream_request_id: upstream_request_id.map(str::to_string), response_payload, }, ); } /// Records pre-response and mid-stream failures. - pub fn record_failed(&self, error: impl Display, output_items: &[ResponseItem]) { + pub fn record_failed( + &self, + error: impl Display, + upstream_request_id: Option<&str>, + output_items: &[ResponseItem], + ) { let Some(attempt) = self.take_terminal_attempt() else { return; }; @@ -210,6 +219,7 @@ impl InferenceTraceAttempt { write_response_payload_best_effort( attempt, /*response_id*/ None, + upstream_request_id, /*token_usage*/ None, output_items, ) @@ -218,6 +228,7 @@ impl InferenceTraceAttempt { &attempt.context, RawTraceEventPayload::InferenceFailed { inference_call_id: attempt.inference_call_id.clone(), + upstream_request_id: upstream_request_id.map(str::to_string), error: error.to_string(), partial_response_payload, }, @@ -229,7 +240,12 @@ impl InferenceTraceAttempt { /// This happens when the turn is interrupted or when mailbox delivery /// preempts the current sampling request. Complete output items observed /// before that point are retained as partial response evidence. - pub fn record_cancelled(&self, reason: impl Display, output_items: &[ResponseItem]) { + pub fn record_cancelled( + &self, + reason: impl Display, + upstream_request_id: Option<&str>, + output_items: &[ResponseItem], + ) { let Some(attempt) = self.take_terminal_attempt() else { return; }; @@ -239,6 +255,7 @@ impl InferenceTraceAttempt { write_response_payload_best_effort( attempt, /*response_id*/ None, + upstream_request_id, /*token_usage*/ None, output_items, ) @@ -247,6 +264,7 @@ impl InferenceTraceAttempt { &attempt.context, RawTraceEventPayload::InferenceCancelled { inference_call_id: attempt.inference_call_id.clone(), + upstream_request_id: upstream_request_id.map(str::to_string), reason: reason.to_string(), partial_response_payload, }, @@ -312,11 +330,13 @@ fn write_json_payload_best_effort( fn write_response_payload_best_effort( attempt: &EnabledInferenceTraceAttempt, response_id: Option<&str>, + upstream_request_id: Option<&str>, token_usage: Option<&TokenUsage>, output_items: &[ResponseItem], ) -> Option { let response_payload = TracedResponseStreamOutput { response_id, + upstream_request_id, token_usage, output_items: output_items.iter().map(trace_response_item_json).collect(), }; @@ -387,7 +407,7 @@ mod tests { "content": [{"type": "input_text", "text": "hello"}] }], })); - attempt.record_completed("resp-1", &None, &[]); + attempt.record_completed("resp-1", Some("req-1"), &None, &[]); let rollout = replay_bundle(temp.path())?; let inference = rollout @@ -400,7 +420,7 @@ mod tests { assert_eq!(inference.thread_id, "thread-root"); assert_eq!(inference.codex_turn_id, "turn-1"); assert_eq!(inference.execution.status, ExecutionStatus::Completed); - assert_eq!(inference.upstream_request_id, Some("resp-1".to_string())); + assert_eq!(inference.upstream_request_id, Some("req-1".to_string())); assert_eq!(rollout.raw_payloads.len(), 2); Ok(()) diff --git a/codex-rs/rollout-trace/src/model/conversation.rs b/codex-rs/rollout-trace/src/model/conversation.rs index e248b72d42..1a8af02709 100644 --- a/codex-rs/rollout-trace/src/model/conversation.rs +++ b/codex-rs/rollout-trace/src/model/conversation.rs @@ -152,7 +152,9 @@ pub struct InferenceCall { pub execution: ExecutionWindow, pub model: String, pub provider_name: String, - /// Upstream request ID returned by HTTP/proxy/engine infrastructure. + /// Responses API response id, used by follow-up `previous_response_id` requests. + pub response_id: Option, + /// Request id returned by HTTP/proxy/engine infrastructure. pub upstream_request_id: Option, /// Complete ordered input snapshot sent with this request. pub request_item_ids: Vec, diff --git a/codex-rs/rollout-trace/src/raw_event.rs b/codex-rs/rollout-trace/src/raw_event.rs index ad8f436da7..d60a2b6c48 100644 --- a/codex-rs/rollout-trace/src/raw_event.rs +++ b/codex-rs/rollout-trace/src/raw_event.rs @@ -101,17 +101,26 @@ pub enum RawTraceEventPayload { }, InferenceCompleted { inference_call_id: InferenceCallId, + /// Responses API `response.id`; used by `previous_response_id`. response_id: Option, + /// Provider transport request id, such as `x-request-id`. + upstream_request_id: Option, response_payload: RawPayloadRef, }, InferenceFailed { inference_call_id: InferenceCallId, + /// Provider transport request id, such as `x-request-id`, when the + /// provider returned one before the stream failed. + upstream_request_id: Option, error: String, /// Partial response payload, when stream events arrived before failure. partial_response_payload: Option, }, InferenceCancelled { inference_call_id: InferenceCallId, + /// Provider transport request id, such as `x-request-id`, when observed + /// before Codex stopped consuming the stream. + upstream_request_id: Option, /// Why Codex stopped consuming the provider stream before a terminal response event. reason: String, /// Completed output items observed before cancellation, if any. diff --git a/codex-rs/rollout-trace/src/reducer/code_cell_tests.rs b/codex-rs/rollout-trace/src/reducer/code_cell_tests.rs index f77921352e..1aabdb8438 100644 --- a/codex-rs/rollout-trace/src/reducer/code_cell_tests.rs +++ b/codex-rs/rollout-trace/src/reducer/code_cell_tests.rs @@ -64,6 +64,7 @@ fn code_cell_lifecycle_links_nested_tools_waits_and_outputs() -> anyhow::Result< writer.append(RawTraceEventPayload::InferenceCompleted { inference_call_id: "inference-1".to_string(), response_id: Some("resp-1".to_string()), + upstream_request_id: None, response_payload: response, })?; writer.append_with_context( @@ -247,6 +248,7 @@ fn fast_code_cell_lifecycle_waits_for_source_item() -> anyhow::Result<()> { writer.append(RawTraceEventPayload::InferenceCompleted { inference_call_id: "inference-1".to_string(), response_id: Some("resp-1".to_string()), + upstream_request_id: None, response_payload: response, })?; @@ -301,6 +303,7 @@ fn cancelled_turn_terminates_unfinished_code_cell() -> anyhow::Result<()> { writer.append(RawTraceEventPayload::InferenceCompleted { inference_call_id: "inference-1".to_string(), response_id: Some("resp-1".to_string()), + upstream_request_id: None, response_payload: response, })?; writer.append_with_context( @@ -388,6 +391,7 @@ fn runtime_code_cell_ids_can_repeat_across_threads() -> anyhow::Result<()> { writer.append(RawTraceEventPayload::InferenceCompleted { inference_call_id: inference_call_id.to_string(), response_id: Some(format!("resp-{thread_id}")), + upstream_request_id: None, response_payload: response, })?; writer.append_with_context( diff --git a/codex-rs/rollout-trace/src/reducer/conversation.rs b/codex-rs/rollout-trace/src/reducer/conversation.rs index 53ae60824d..2502e770b6 100644 --- a/codex-rs/rollout-trace/src/reducer/conversation.rs +++ b/codex-rs/rollout-trace/src/reducer/conversation.rs @@ -76,7 +76,7 @@ impl TraceReducer { .values() .find(|inference| { inference.thread_id == thread_id - && inference.upstream_request_id.as_deref() == Some(previous_response_id) + && inference.response_id.as_deref() == Some(previous_response_id) }) .map(|inference| { let mut ids = inference.request_item_ids.clone(); diff --git a/codex-rs/rollout-trace/src/reducer/inference.rs b/codex-rs/rollout-trace/src/reducer/inference.rs index c65b4236a2..5becb59ca0 100644 --- a/codex-rs/rollout-trace/src/reducer/inference.rs +++ b/codex-rs/rollout-trace/src/reducer/inference.rs @@ -13,6 +13,7 @@ use crate::model::InferenceCall; use crate::model::InferenceCallId; use crate::payload::RawPayloadRef; use crate::raw_event::RawEventSeq; +use crate::raw_event::RawTraceEventPayload; /// Raw inference-start fields after dispatch has stripped the common event envelope. /// @@ -91,6 +92,7 @@ impl TraceReducer { }, model: started.model, provider_name: started.provider_name, + response_id: None, upstream_request_id: None, request_item_ids, response_item_ids: Vec::new(), @@ -137,11 +139,49 @@ impl TraceReducer { &mut self, seq: RawEventSeq, wall_time_unix_ms: i64, - inference_call_id: InferenceCallId, - status: ExecutionStatus, - response_id: Option, - response_payload: Option, + payload: RawTraceEventPayload, ) -> Result<()> { + let (inference_call_id, status, response_id, upstream_request_id, response_payload) = + match payload { + RawTraceEventPayload::InferenceCompleted { + inference_call_id, + response_id, + upstream_request_id, + response_payload, + } => ( + inference_call_id, + ExecutionStatus::Completed, + response_id, + upstream_request_id, + Some(response_payload), + ), + RawTraceEventPayload::InferenceFailed { + inference_call_id, + upstream_request_id, + partial_response_payload, + .. + } => ( + inference_call_id, + ExecutionStatus::Failed, + None, + upstream_request_id, + partial_response_payload, + ), + RawTraceEventPayload::InferenceCancelled { + inference_call_id, + upstream_request_id, + partial_response_payload, + .. + } => ( + inference_call_id, + ExecutionStatus::Cancelled, + None, + upstream_request_id, + partial_response_payload, + ), + _ => bail!("complete_inference_call received a non-terminal inference event"), + }; + if !self .rollout .inference_calls @@ -156,23 +196,31 @@ impl TraceReducer { self.reduce_inference_response(wall_time_unix_ms, &inference_call_id, payload) }) .transpose()?; - let Some(inference) = self.rollout.inference_calls.get_mut(&inference_call_id) else { - bail!("inference call {inference_call_id} disappeared during response reduction"); - }; - // Turn-end cleanup can close a stream before the async mapper observes - // cancellation. Preserve that terminal status while still retaining any - // late partial response evidence from the mapper. - if inference.execution.status == ExecutionStatus::Running { - inference.execution.ended_at_unix_ms = Some(wall_time_unix_ms); - inference.execution.ended_seq = Some(seq); - inference.execution.status = status; - inference.upstream_request_id = response_id; - } - if let Some(response_payload) = response_payload { - inference.raw_response_payload_id = Some(response_payload.raw_payload_id); - } - if let Some(response_item_ids) = response_item_ids { - inference.response_item_ids = response_item_ids; + { + let Some(inference) = self.rollout.inference_calls.get_mut(&inference_call_id) else { + bail!("inference call {inference_call_id} disappeared during response reduction"); + }; + inference.response_id = response_id; + // Turn-end cleanup can close a stream before the async mapper observes + // cancellation. Preserve that terminal status while still retaining any + // late partial response evidence from the mapper. + if inference.execution.status == ExecutionStatus::Running { + inference.execution.ended_at_unix_ms = Some(wall_time_unix_ms); + inference.execution.ended_seq = Some(seq); + inference.execution.status = status; + } + // Turn-end cleanup can mark an inference terminal before the stream + // mapper records its late partial payload. Keep the server request + // id from that late payload even when the status is already closed. + if let Some(upstream_request_id) = upstream_request_id { + inference.upstream_request_id = Some(upstream_request_id); + } + if let Some(response_payload) = response_payload { + inference.raw_response_payload_id = Some(response_payload.raw_payload_id); + } + if let Some(response_item_ids) = response_item_ids { + inference.response_item_ids = response_item_ids; + } } Ok(()) } diff --git a/codex-rs/rollout-trace/src/reducer/inference_tests.rs b/codex-rs/rollout-trace/src/reducer/inference_tests.rs index d5ba0ba9d0..77e0f39a9a 100644 --- a/codex-rs/rollout-trace/src/reducer/inference_tests.rs +++ b/codex-rs/rollout-trace/src/reducer/inference_tests.rs @@ -40,6 +40,7 @@ fn cancelled_inference_reduces_partial_response_items() -> anyhow::Result<()> { )?; writer.append(RawTraceEventPayload::InferenceCancelled { inference_call_id: "inference-1".to_string(), + upstream_request_id: Some("req-cancelled".to_string()), reason: "test interruption".to_string(), partial_response_payload: Some(partial_response), })?; @@ -49,6 +50,10 @@ fn cancelled_inference_reduces_partial_response_items() -> anyhow::Result<()> { let response_item_id = &inference.response_item_ids[0]; assert_eq!(inference.execution.status, ExecutionStatus::Cancelled); + assert_eq!( + inference.upstream_request_id, + Some("req-cancelled".to_string()), + ); assert_eq!(inference.response_item_ids.len(), 1); assert_eq!( rollout.conversation_items[response_item_id].kind, @@ -123,6 +128,7 @@ fn late_cancelled_inference_preserves_turn_end_status() -> anyhow::Result<()> { )?; writer.append(RawTraceEventPayload::InferenceCancelled { inference_call_id: "inference-1".to_string(), + upstream_request_id: Some("req-late-cancelled".to_string()), reason: "stream mapper noticed cancellation after turn end".to_string(), partial_response_payload: Some(partial_response.clone()), })?; @@ -135,6 +141,10 @@ fn late_cancelled_inference_preserves_turn_end_status() -> anyhow::Result<()> { inference.raw_response_payload_id, Some(partial_response.raw_payload_id), ); + assert_eq!( + inference.upstream_request_id, + Some("req-late-cancelled".to_string()), + ); assert_eq!(inference.response_item_ids.len(), 1); let response_item_id = &inference.response_item_ids[0]; assert_eq!( diff --git a/codex-rs/rollout-trace/src/reducer/mod.rs b/codex-rs/rollout-trace/src/reducer/mod.rs index 34a4e5dcfd..3e8f6f1353 100644 --- a/codex-rs/rollout-trace/src/reducer/mod.rs +++ b/codex-rs/rollout-trace/src/reducer/mod.rs @@ -226,47 +226,10 @@ impl TraceReducer { }, )?; } - RawTraceEventPayload::InferenceCompleted { - inference_call_id, - response_id, - response_payload, - } => { - self.complete_inference_call( - event.seq, - event.wall_time_unix_ms, - inference_call_id, - ExecutionStatus::Completed, - response_id, - Some(response_payload), - )?; - } - RawTraceEventPayload::InferenceFailed { - inference_call_id, - partial_response_payload, - .. - } => { - self.complete_inference_call( - event.seq, - event.wall_time_unix_ms, - inference_call_id, - ExecutionStatus::Failed, - /*response_id*/ None, - partial_response_payload, - )?; - } - RawTraceEventPayload::InferenceCancelled { - inference_call_id, - partial_response_payload, - .. - } => { - self.complete_inference_call( - event.seq, - event.wall_time_unix_ms, - inference_call_id, - ExecutionStatus::Cancelled, - /*response_id*/ None, - partial_response_payload, - )?; + payload @ (RawTraceEventPayload::InferenceCompleted { .. } + | RawTraceEventPayload::InferenceFailed { .. } + | RawTraceEventPayload::InferenceCancelled { .. }) => { + self.complete_inference_call(event.seq, event.wall_time_unix_ms, payload)?; } RawTraceEventPayload::ProtocolEventObserved { .. } => { // Protocol wrappers are raw debug breadcrumbs. Typed hooks own diff --git a/codex-rs/rollout-trace/src/reducer/test_support.rs b/codex-rs/rollout-trace/src/reducer/test_support.rs index eae93eff64..bd12e9d652 100644 --- a/codex-rs/rollout-trace/src/reducer/test_support.rs +++ b/codex-rs/rollout-trace/src/reducer/test_support.rs @@ -146,6 +146,7 @@ pub(crate) fn append_inference_completion( writer.append(RawTraceEventPayload::InferenceCompleted { inference_call_id: inference_call_id.to_string(), response_id: Some(response_id.to_string()), + upstream_request_id: None, response_payload, })?; Ok(()) @@ -184,6 +185,7 @@ pub(crate) fn append_completed_inference( RawTraceEventPayload::InferenceCompleted { inference_call_id: inference_id.to_string(), response_id: Some(format!("resp-{inference_id}")), + upstream_request_id: None, response_payload: response, }, )?; diff --git a/codex-rs/rollout-trace/src/reducer/tool/terminal_tests.rs b/codex-rs/rollout-trace/src/reducer/tool/terminal_tests.rs index ddf76fe5a9..e51e54a740 100644 --- a/codex-rs/rollout-trace/src/reducer/tool/terminal_tests.rs +++ b/codex-rs/rollout-trace/src/reducer/tool/terminal_tests.rs @@ -551,6 +551,7 @@ fn append_inference_with_tool_call(writer: &TraceWriter) -> anyhow::Result<()> { writer.append(RawTraceEventPayload::InferenceCompleted { inference_call_id: "inference-1".to_string(), response_id: Some("resp-1".to_string()), + upstream_request_id: None, response_payload: response, })?; Ok(()) diff --git a/codex-rs/rollout-trace/src/thread_tests.rs b/codex-rs/rollout-trace/src/thread_tests.rs index a27026f28d..6421b29af3 100644 --- a/codex-rs/rollout-trace/src/thread_tests.rs +++ b/codex-rs/rollout-trace/src/thread_tests.rs @@ -133,8 +133,8 @@ fn disabled_thread_context_accepts_trace_calls_without_writing() -> anyhow::Resu let inference_attempt = inference_trace.start_attempt(); inference_attempt.record_started(&serde_json::json!({ "kind": "inference" })); let token_usage: Option = None; - inference_attempt.record_completed("response-1", &token_usage, &[]); - inference_attempt.record_failed("inference failed", &[]); + inference_attempt.record_completed("response-1", Some("req-1"), &token_usage, &[]); + inference_attempt.record_failed("inference failed", /*upstream_request_id*/ None, &[]); let compaction_trace = thread_trace.compaction_trace_context( "turn-1", diff --git a/codex-rs/rollout-trace/src/writer.rs b/codex-rs/rollout-trace/src/writer.rs index 1676ff2e64..925f7bab7a 100644 --- a/codex-rs/rollout-trace/src/writer.rs +++ b/codex-rs/rollout-trace/src/writer.rs @@ -226,6 +226,7 @@ mod tests { writer.append(RawTraceEventPayload::InferenceCompleted { inference_call_id: "inference-1".to_string(), response_id: Some("resp-1".to_string()), + upstream_request_id: Some("req-1".to_string()), response_payload: inference_response.clone(), })?; writer.append(RawTraceEventPayload::CodexTurnEnded { diff --git a/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs b/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs index 3aa31c80f9..611bafd2b8 100644 --- a/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs +++ b/codex-rs/shell-command/src/command_safety/is_dangerous_command.rs @@ -58,7 +58,10 @@ fn is_git_global_option_with_inline_value(arg: &str) -> bool { pub(crate) fn git_global_option_requires_prompt(arg: &str) -> bool { matches!( arg, - "-c" | "--config-env" + // `-C` can redirect Git into a repo whose config runs helpers such as + // `core.fsmonitor` during read-only commands like `status`. + "-C" | "-c" + | "--config-env" | "--exec-path" | "--git-dir" | "--namespace" @@ -66,7 +69,7 @@ pub(crate) fn git_global_option_requires_prompt(arg: &str) -> bool { | "--work-tree" ) || matches!( arg, - s if (s.starts_with("-c") && s.len() > 2) + s if ((s.starts_with("-C") || s.starts_with("-c")) && s.len() > 2) || s.starts_with("--config-env=") || s.starts_with("--exec-path=") || s.starts_with("--git-dir=") @@ -181,4 +184,10 @@ mod tests { fn rm_f_is_dangerous() { assert!(command_might_be_dangerous(&vec_str(&["rm", "-f", "/"]))); } + + #[test] + fn git_dash_c_requires_prompt() { + assert!(git_global_option_requires_prompt("-C")); + assert!(git_global_option_requires_prompt("-C/path/to/repo")); + } } diff --git a/codex-rs/shell-command/src/command_safety/is_safe_command.rs b/codex-rs/shell-command/src/command_safety/is_safe_command.rs index 2906fef276..26fe235fbe 100644 --- a/codex-rs/shell-command/src/command_safety/is_safe_command.rs +++ b/codex-rs/shell-command/src/command_safety/is_safe_command.rs @@ -331,20 +331,19 @@ mod tests { #[test] fn git_branch_global_options_respect_safety_rules() { - use pretty_assertions::assert_eq; - - assert_eq!( - is_known_safe_command(&vec_str(&["git", "-C", ".", "branch", "--show-current"])), - true - ); - assert_eq!( - is_known_safe_command(&vec_str(&["git", "-C", ".", "branch", "-d", "feature"])), - false - ); - assert_eq!( - is_known_safe_command(&vec_str(&["bash", "-lc", "git -C . branch -d feature",])), - false - ); + assert!(is_known_safe_command(&vec_str(&[ + "git", + "branch", + "--show-current", + ]))); + assert!(!is_known_safe_command(&vec_str(&[ + "git", "branch", "-d", "feature", + ]))); + assert!(!is_known_safe_command(&vec_str(&[ + "bash", + "-lc", + "git branch -d feature", + ]))); } #[test] @@ -381,6 +380,10 @@ mod tests { #[test] fn git_global_override_flags_are_not_safe() { + assert!(!is_known_safe_command(&vec_str(&[ + "git", "-C", ".", "status", + ]))); + assert!(!is_known_safe_command(&vec_str(&["git", "-C.", "status",]))); assert!(!is_known_safe_command(&vec_str(&[ "git", "-c", @@ -415,6 +418,11 @@ mod tests { ); } + assert!(!is_known_safe_command(&vec_str(&[ + "bash", + "-lc", + "git -C .project-deps/test-fixtures status", + ]))); assert!(!is_known_safe_command(&vec_str(&[ "bash", "-lc", diff --git a/codex-rs/tui/src/app/background_requests.rs b/codex-rs/tui/src/app/background_requests.rs index 80879dbd79..559bdfd99c 100644 --- a/codex-rs/tui/src/app/background_requests.rs +++ b/codex-rs/tui/src/app/background_requests.rs @@ -5,6 +5,9 @@ //! the main event loop remains single-threaded. use super::*; +use codex_app_server_protocol::MarketplaceAddParams; +use codex_app_server_protocol::MarketplaceAddResponse; +use codex_utils_absolute_path::AbsolutePathBuf; impl App { pub(super) fn fetch_mcp_inventory( @@ -105,6 +108,28 @@ impl App { }); } + pub(super) fn fetch_marketplace_add( + &mut self, + app_server: &AppServerSession, + cwd: PathBuf, + source: String, + ) { + let request_handle = app_server.request_handle(); + let app_event_tx = self.app_event_tx.clone(); + tokio::spawn(async move { + let cwd_for_event = cwd.clone(); + let source_for_event = source.clone(); + let result = fetch_marketplace_add(request_handle, cwd, source) + .await + .map_err(|err| format!("Failed to add marketplace: {err}")); + app_event_tx.send(AppEvent::MarketplaceAddLoaded { + cwd: cwd_for_event, + source: source_for_event, + result, + }); + }); + } + pub(super) fn fetch_plugin_install( &mut self, app_server: &AppServerSession, @@ -509,6 +534,54 @@ pub(super) async fn fetch_plugin_detail( .wrap_err("plugin/read failed in TUI") } +pub(super) async fn fetch_marketplace_add( + request_handle: AppServerRequestHandle, + cwd: PathBuf, + source: String, +) -> Result { + let cwd = AbsolutePathBuf::try_from(cwd).wrap_err("marketplace/add cwd must be absolute")?; + let source = marketplace_add_source_for_request(cwd.as_path(), source); + let request_id = RequestId::String(format!("marketplace-add-{}", Uuid::new_v4())); + request_handle + .request_typed(ClientRequest::MarketplaceAdd { + request_id, + params: MarketplaceAddParams { + source, + ref_name: None, + sparse_paths: None, + }, + }) + .await + .wrap_err("marketplace/add failed in TUI") +} + +fn marketplace_add_source_for_request(cwd: &std::path::Path, source: String) -> String { + let (base_source, suffix) = if let Some((base, ref_name)) = source.rsplit_once('#') { + (base, Some(format!("#{ref_name}"))) + } else if let Some((base, ref_name)) = source.rsplit_once('@') { + (base, Some(format!("@{ref_name}"))) + } else { + (source.as_str(), None) + }; + + if matches!(base_source, "." | "..") + || base_source.starts_with("./") + || base_source.starts_with("../") + || base_source.starts_with(".\\") + || base_source.starts_with("..\\") + { + let mut resolved = AbsolutePathBuf::resolve_path_against_base(base_source, cwd) + .to_string_lossy() + .into_owned(); + if let Some(suffix) = suffix { + resolved.push_str(&suffix); + } + return resolved; + } + + source +} + pub(super) async fn fetch_plugin_install( request_handle: AppServerRequestHandle, marketplace_path: AbsolutePathBuf, @@ -650,6 +723,31 @@ mod tests { AbsolutePathBuf::try_from(PathBuf::from(path)).expect("absolute test path") } + #[test] + fn marketplace_add_source_for_request_resolves_relative_local_paths() { + let cwd = if cfg!(windows) { + PathBuf::from(r"C:\workspace\project") + } else { + PathBuf::from("/workspace/project") + }; + + let resolved = marketplace_add_source_for_request(&cwd, "./marketplace".to_string()); + assert!(std::path::Path::new(&resolved).is_absolute()); + assert_eq!(resolved, cwd.join("marketplace").display().to_string()); + assert_eq!( + marketplace_add_source_for_request(&cwd, "./marketplace#main".to_string()), + format!("{}#main", cwd.join("marketplace").display()) + ); + assert_eq!( + marketplace_add_source_for_request(&cwd, "owner/repo".to_string()), + "owner/repo" + ); + assert_eq!( + marketplace_add_source_for_request(&cwd, "~/marketplace".to_string()), + "~/marketplace" + ); + } + #[test] fn hide_cli_only_plugin_marketplaces_removes_openai_bundled() { let mut response = PluginListResponse { diff --git a/codex-rs/tui/src/app/config_persistence.rs b/codex-rs/tui/src/app/config_persistence.rs index 3b5479f1d5..937e0a9fcc 100644 --- a/codex-rs/tui/src/app/config_persistence.rs +++ b/codex-rs/tui/src/app/config_persistence.rs @@ -648,6 +648,7 @@ mod tests { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: next_cwd.clone().abs(), reasoning_effort: None, history_log_id: 0, diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index 39f837e968..d4002f2453 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -385,6 +385,12 @@ impl App { AppEvent::FetchPluginsList { cwd } => { self.fetch_plugins_list(app_server, cwd); } + AppEvent::OpenMarketplaceAddPrompt => { + self.chat_widget.open_marketplace_add_prompt(); + } + AppEvent::OpenMarketplaceAddLoading { source } => { + self.chat_widget.open_marketplace_add_loading_popup(&source); + } AppEvent::OpenPluginDetailLoading { plugin_display_name, } => { @@ -406,6 +412,21 @@ impl App { AppEvent::PluginsLoaded { cwd, result } => { self.chat_widget.on_plugins_loaded(cwd, result); } + AppEvent::FetchMarketplaceAdd { cwd, source } => { + self.fetch_marketplace_add(app_server, cwd, source); + } + AppEvent::MarketplaceAddLoaded { + cwd, + source, + result, + } => { + let add_succeeded = result.is_ok(); + self.chat_widget + .on_marketplace_add_loaded(cwd.clone(), source, result); + if add_succeeded && self.chat_widget.config_ref().cwd.as_path() == cwd.as_path() { + self.fetch_plugins_list(app_server, cwd); + } + } AppEvent::FetchPluginDetail { cwd, params } => { self.fetch_plugin_detail(app_server, cwd, params); } diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 29f82ab85d..59b247fa52 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -3570,6 +3570,7 @@ async fn render_clear_ui_header_after_long_transcript_for_snapshot() -> String { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/tmp/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::High), history_log_id: 0, @@ -3809,6 +3810,7 @@ fn test_thread_session(thread_id: ThreadId, cwd: PathBuf) -> ThreadSessionState approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: cwd.abs(), instruction_source_paths: Vec::new(), reasoning_effort: None, @@ -4321,6 +4323,7 @@ async fn backtrack_selection_with_duplicate_history_targets_unique_turn() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: None, history_log_id: 0, @@ -4384,6 +4387,7 @@ async fn backtrack_selection_with_duplicate_history_targets_unique_turn() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: None, history_log_id: 0, @@ -4477,6 +4481,7 @@ async fn backtrack_resubmit_preserves_data_image_urls_in_user_turn() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: None, history_log_id: 0, @@ -4863,6 +4868,7 @@ async fn new_session_requests_shutdown_for_previous_conversation() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: None, history_log_id: 0, @@ -4975,6 +4981,7 @@ async fn clear_only_ui_reset_preserves_chat_session_state() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/tmp/project").abs(), reasoning_effort: None, history_log_id: 0, diff --git a/codex-rs/tui/src/app/thread_events.rs b/codex-rs/tui/src/app/thread_events.rs index 10fc370f58..2c4e560afa 100644 --- a/codex-rs/tui/src/app/thread_events.rs +++ b/codex-rs/tui/src/app/thread_events.rs @@ -350,6 +350,7 @@ mod tests { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: cwd.abs(), instruction_source_paths: Vec::new(), reasoning_effort: None, diff --git a/codex-rs/tui/src/app/thread_session_state.rs b/codex-rs/tui/src/app/thread_session_state.rs index 9b6d7e9726..efe0adf846 100644 --- a/codex-rs/tui/src/app/thread_session_state.rs +++ b/codex-rs/tui/src/app/thread_session_state.rs @@ -3,6 +3,7 @@ use crate::app_server_session::ThreadSessionState; use crate::read_session_model; use codex_app_server_protocol::Thread; use codex_protocol::ThreadId; +use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::PermissionProfile; impl App { @@ -18,10 +19,16 @@ impl App { .config_ref() .permissions .permission_profile(); + let active_permission_profile = self + .chat_widget + .config_ref() + .permissions + .active_permission_profile(); let update_session = |session: &mut ThreadSessionState| { session.approval_policy = approval_policy; session.approvals_reviewer = approvals_reviewer; session.permission_profile = permission_profile.clone(); + session.active_permission_profile = active_permission_profile.clone(); }; if self.primary_thread_id == Some(active_thread_id) @@ -43,7 +50,8 @@ impl App { thread_id: ThreadId, thread: &Thread, ) -> ThreadSessionState { - let permission_profile = self.active_permission_profile(); + let permission_profile = self.current_permission_profile(); + let active_permission_profile = self.current_active_permission_profile(); let mut session = self .primary_session_configured .clone() @@ -58,6 +66,7 @@ impl App { approval_policy: self.config.permissions.approval_policy.value(), approvals_reviewer: self.config.approvals_reviewer, permission_profile: permission_profile.clone(), + active_permission_profile: active_permission_profile.clone(), cwd: thread.cwd.clone(), instruction_source_paths: Vec::new(), reasoning_effort: self.chat_widget.current_reasoning_effort(), @@ -71,6 +80,7 @@ impl App { session.model_provider_id = thread.model_provider.clone(); session.cwd = thread.cwd.clone(); session.permission_profile = permission_profile; + session.active_permission_profile = active_permission_profile; session.instruction_source_paths = Vec::new(); session.rollout_path = thread.path.clone(); if let Some(model) = @@ -85,12 +95,19 @@ impl App { session } - fn active_permission_profile(&self) -> PermissionProfile { + fn current_permission_profile(&self) -> PermissionProfile { self.chat_widget .config_ref() .permissions .permission_profile() } + + fn current_active_permission_profile(&self) -> Option { + self.chat_widget + .config_ref() + .permissions + .active_permission_profile() + } } #[cfg(test)] @@ -125,6 +142,7 @@ mod tests { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: cwd.abs(), instruction_source_paths: Vec::new(), reasoning_effort: None, diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 5c5e2bc941..ee0de5082f 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -13,6 +13,7 @@ use std::path::PathBuf; use codex_app_server_protocol::AddCreditsNudgeCreditType; use codex_app_server_protocol::AddCreditsNudgeEmailStatus; use codex_app_server_protocol::AppInfo; +use codex_app_server_protocol::MarketplaceAddResponse; use codex_app_server_protocol::McpServerStatus; use codex_app_server_protocol::McpServerStatusDetail; use codex_app_server_protocol::PluginInstallResponse; @@ -287,6 +288,27 @@ pub(crate) enum AppEvent { result: Result, }, + /// Open the prompt for adding a marketplace source. + OpenMarketplaceAddPrompt, + + /// Replace the plugins popup with a marketplace-add loading state. + OpenMarketplaceAddLoading { + source: String, + }, + + /// Add a marketplace from the provided source. + FetchMarketplaceAdd { + cwd: PathBuf, + source: String, + }, + + /// Result of adding a marketplace. + MarketplaceAddLoaded { + cwd: PathBuf, + source: String, + result: Result, + }, + /// Replace the plugins popup with a plugin-detail loading state. OpenPluginDetailLoading { plugin_display_name: String, diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index 96757998ff..1e613078a5 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -93,6 +93,7 @@ use codex_app_server_protocol::TurnSteerParams; use codex_app_server_protocol::TurnSteerResponse; use codex_otel::TelemetryAuthMode; use codex_protocol::ThreadId; +use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::PermissionProfile; use codex_protocol::models::ResponseItem; use codex_protocol::openai_models::ModelAvailabilityNux; @@ -160,6 +161,9 @@ pub(crate) struct ThreadSessionState { /// responses are converted to a profile at ingestion time using the /// response cwd so cached sessions do not reinterpret cwd-bound grants. pub(crate) permission_profile: PermissionProfile, + /// Named profile that produced `permission_profile`, when the server knows + /// the permissions came from `default_permissions`. + pub(crate) active_permission_profile: Option, pub(crate) cwd: AbsolutePathBuf, pub(crate) instruction_source_paths: Vec, pub(crate) reasoning_effort: Option, @@ -1311,6 +1315,7 @@ async fn thread_session_state_from_thread_start_response( response.cwd.as_path(), ) }), + response.active_permission_profile.clone().map(Into::into), response.cwd.clone(), response.instruction_sources.clone(), response.reasoning_effort, @@ -1343,6 +1348,7 @@ async fn thread_session_state_from_thread_resume_response( response.cwd.as_path(), ) }), + response.active_permission_profile.clone().map(Into::into), response.cwd.clone(), response.instruction_sources.clone(), response.reasoning_effort, @@ -1375,6 +1381,7 @@ async fn thread_session_state_from_thread_fork_response( response.cwd.as_path(), ) }), + response.active_permission_profile.clone().map(Into::into), response.cwd.clone(), response.instruction_sources.clone(), response.reasoning_effort, @@ -1417,6 +1424,7 @@ async fn thread_session_state_from_thread_response( approval_policy: AskForApproval, approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer, permission_profile: PermissionProfile, + active_permission_profile: Option, cwd: AbsolutePathBuf, instruction_source_paths: Vec, reasoning_effort: Option, @@ -1442,6 +1450,7 @@ async fn thread_session_state_from_thread_response( approval_policy, approvals_reviewer, permission_profile, + active_permission_profile, cwd, instruction_source_paths, reasoning_effort, @@ -1792,6 +1801,7 @@ mod tests { .expect("read-only profile must be legacy-compatible") .into(), permission_profile: Some(read_only_profile.into()), + active_permission_profile: None, reasoning_effort: None, }; @@ -1839,6 +1849,7 @@ mod tests { AskForApproval::Never, codex_protocol::config_types::ApprovalsReviewer::User, PermissionProfile::read_only(), + None, test_path_buf("/tmp/project").abs(), Vec::new(), /*reasoning_effort*/ None, @@ -1869,6 +1880,7 @@ mod tests { AskForApproval::Never, codex_protocol::config_types::ApprovalsReviewer::User, PermissionProfile::read_only(), + None, test_path_buf("/tmp/project").abs(), Vec::new(), /*reasoning_effort*/ None, diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index e8486a08e9..1e3106bf50 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -910,6 +910,7 @@ pub(crate) struct ChatWidget { plugin_install_apps_needing_auth: Vec, plugin_install_auth_flow: Option, plugins_active_tab_id: Option, + newly_installed_marketplace_tab_id: Option, // Queue of interruptive UI events deferred during an active write cycle interrupts: InterruptManager, // Accumulates the current reasoning block text to extract a header @@ -1650,6 +1651,7 @@ fn thread_session_state_to_legacy_event( approval_policy: session.approval_policy, approvals_reviewer: session.approvals_reviewer, permission_profile: session.permission_profile, + active_permission_profile: session.active_permission_profile, cwd: session.cwd, reasoning_effort: session.reasoning_effort, history_log_id: session.history_log_id, @@ -2382,11 +2384,16 @@ impl ChatWidget { let permission_sync = self .config .permissions - .set_permission_profile(event.permission_profile.clone()); + .set_permission_profile_with_active_profile( + event.permission_profile.clone(), + event.active_permission_profile.clone(), + ); if let Err(err) = permission_sync { tracing::warn!(%err, "failed to sync permissions from SessionConfigured"); self.config.permissions.permission_profile = Constrained::allow_only(event.permission_profile.clone()); + self.config.permissions.active_permission_profile = + event.active_permission_profile.clone(); } self.config.approvals_reviewer = event.approvals_reviewer; self.status_line_project_root_name_cache = None; @@ -5599,6 +5606,7 @@ impl ChatWidget { plugin_install_apps_needing_auth: Vec::new(), plugin_install_auth_flow: None, plugins_active_tab_id: None, + newly_installed_marketplace_tab_id: None, interrupts: InterruptManager::new(), reasoning_buffer: String::new(), full_reasoning_buffer: String::new(), diff --git a/codex-rs/tui/src/chatwidget/plugins.rs b/codex-rs/tui/src/chatwidget/plugins.rs index ae6b08c07d..b6b5242f0b 100644 --- a/codex-rs/tui/src/chatwidget/plugins.rs +++ b/codex-rs/tui/src/chatwidget/plugins.rs @@ -1,3 +1,4 @@ +use std::path::Path; use std::path::PathBuf; use std::time::Duration; use std::time::Instant; @@ -11,12 +12,14 @@ use crate::bottom_pane::SelectionRowDisplay; use crate::bottom_pane::SelectionTab; use crate::bottom_pane::SelectionToggle; use crate::bottom_pane::SelectionViewParams; +use crate::bottom_pane::custom_prompt_view::CustomPromptView; use crate::history_cell; use crate::onboarding::mark_url_hyperlink; use crate::render::renderable::ColumnRenderable; use crate::render::renderable::Renderable; use crate::shimmer::shimmer_spans; use crate::tui::FrameRequester; +use codex_app_server_protocol::MarketplaceAddResponse; use codex_app_server_protocol::PluginDetail; use codex_app_server_protocol::PluginInstallPolicy; use codex_app_server_protocol::PluginInstallResponse; @@ -41,7 +44,9 @@ use unicode_width::UnicodeWidthStr; const PLUGINS_SELECTION_VIEW_ID: &str = "plugins-selection"; const ALL_PLUGINS_TAB_ID: &str = "all-plugins"; const INSTALLED_PLUGINS_TAB_ID: &str = "installed-plugins"; +const MARKETPLACE_TAB_ID_PREFIX: &str = "marketplace:"; const OPENAI_CURATED_TAB_ID: &str = "marketplace:openai-curated"; +const ADD_MARKETPLACE_TAB_ID: &str = "add-marketplace"; const PLUGIN_ROW_PREFIX_WIDTH: usize = 6; const LOADING_ANIMATION_DELAY: Duration = Duration::from_secs(1); const LOADING_ANIMATION_INTERVAL: Duration = Duration::from_millis(100); @@ -183,10 +188,25 @@ impl ChatWidget { match result { Ok(response) => { self.plugins_fetch_state.cache_cwd = Some(cwd); + let active_tab_id = self + .plugins_active_tab_id + .as_deref() + .and_then(|tab_id| { + marketplace_tab_id_matching_saved_id(tab_id, &response.marketplaces) + }) + .or_else(|| self.plugins_active_tab_id.clone()); + self.newly_installed_marketplace_tab_id = self + .newly_installed_marketplace_tab_id + .as_deref() + .and_then(|tab_id| { + marketplace_tab_id_matching_saved_id(tab_id, &response.marketplaces) + }); + self.plugins_active_tab_id = active_tab_id; self.plugins_cache = PluginsCacheState::Ready(response.clone()); if !auth_flow_active { self.refresh_plugins_popup_if_open(&response); } + self.newly_installed_marketplace_tab_id = None; } Err(err) => { if !auth_flow_active { @@ -243,6 +263,44 @@ impl ChatWidget { )); } + pub(crate) fn open_marketplace_add_prompt(&mut self) { + self.plugins_active_tab_id = Some(ADD_MARKETPLACE_TAB_ID.to_string()); + let tx = self.app_event_tx.clone(); + let cwd = self.config.cwd.to_path_buf(); + let view = CustomPromptView::new( + "Add marketplace".to_string(), + "owner/repo, git URL, or local marketplace path".to_string(), + String::new(), + Some("Examples: owner/repo, git URL, ./marketplace".to_string()), + Box::new(move |source: String| { + let source = source.trim().to_string(); + if source.is_empty() { + return; + } + tx.send(AppEvent::OpenMarketplaceAddLoading { + source: source.clone(), + }); + tx.send(AppEvent::FetchMarketplaceAdd { + cwd: cwd.clone(), + source, + }); + }), + ); + self.bottom_pane.show_view(Box::new(view)); + } + + pub(crate) fn open_marketplace_add_loading_popup(&mut self, _source: &str) { + self.plugins_active_tab_id = Some(ADD_MARKETPLACE_TAB_ID.to_string()); + let params = self.marketplace_add_loading_popup_params(); + if !self + .bottom_pane + .replace_selection_view_if_active(PLUGINS_SELECTION_VIEW_ID, params) + { + self.bottom_pane + .show_selection_view(self.marketplace_add_loading_popup_params()); + } + } + pub(crate) fn open_plugin_detail_loading_popup(&mut self, plugin_display_name: &str) { self.plugins_active_tab_id = self .bottom_pane @@ -361,6 +419,52 @@ impl ChatWidget { } } + pub(crate) fn on_marketplace_add_loaded( + &mut self, + cwd: PathBuf, + _source: String, + result: Result, + ) { + if self.config.cwd.as_path() != cwd.as_path() { + return; + } + + match result { + Ok(response) => { + let marketplace_tab_id = marketplace_tab_id_from_path(&response.installed_root); + self.plugins_active_tab_id = Some(marketplace_tab_id.clone()); + self.newly_installed_marketplace_tab_id = + (!response.already_added).then_some(marketplace_tab_id); + let message = if response.already_added { + format!( + "Marketplace {} is already added.", + response.marketplace_name + ) + } else { + format!("Added marketplace {}.", response.marketplace_name) + }; + self.add_info_message( + message, + Some(format!( + "Marketplace root: {}", + response.installed_root.as_path().display() + )), + ); + } + Err(_) => { + self.plugins_active_tab_id = Some(ADD_MARKETPLACE_TAB_ID.to_string()); + let params = self.marketplace_add_error_popup_params(); + if !self + .bottom_pane + .replace_selection_view_if_active(PLUGINS_SELECTION_VIEW_ID, params) + { + self.bottom_pane + .show_selection_view(self.marketplace_add_error_popup_params()); + } + } + } + } + pub(crate) fn on_plugin_enabled_set( &mut self, cwd: PathBuf, @@ -655,6 +759,27 @@ impl ChatWidget { } } + fn marketplace_add_loading_popup_params(&self) -> SelectionViewParams { + SelectionViewParams { + view_id: Some(PLUGINS_SELECTION_VIEW_ID), + header: Box::new(DelayedLoadingHeader::new( + self.frame_requester.clone(), + self.config.animations, + "Adding marketplace...".to_string(), + /*note*/ None, + )), + items: vec![SelectionItem { + name: "Adding marketplace...".to_string(), + description: Some( + "This updates when marketplace installation completes.".to_string(), + ), + is_disabled: true, + ..Default::default() + }], + ..Default::default() + } + } + fn plugin_detail_loading_popup_params(&self, plugin_display_name: &str) -> SelectionViewParams { SelectionViewParams { view_id: Some(PLUGINS_SELECTION_VIEW_ID), @@ -738,6 +863,56 @@ impl ChatWidget { } } + fn marketplace_add_error_popup_params(&self) -> SelectionViewParams { + let mut header = ColumnRenderable::new(); + header.push(Line::from("Plugins".bold())); + header.push(Line::from("Failed to add marketplace.".dim())); + + let mut items = vec![ + SelectionItem { + name: "Marketplace add failed".to_string(), + description: Some( + "Failed to add marketplace from the provided source.".to_string(), + ), + is_disabled: true, + ..Default::default() + }, + SelectionItem { + name: "Try again".to_string(), + description: Some("Enter a marketplace source.".to_string()), + selected_description: Some("Enter a marketplace source.".to_string()), + actions: vec![Box::new(|tx| { + tx.send(AppEvent::OpenMarketplaceAddPrompt); + })], + ..Default::default() + }, + ]; + + if let PluginsCacheState::Ready(plugins_response) = self.plugins_cache_for_current_cwd() { + let cwd = self.config.cwd.to_path_buf(); + items.push(SelectionItem { + name: "Back to plugins".to_string(), + description: Some("Return to the plugin list.".to_string()), + selected_description: Some("Return to the plugin list.".to_string()), + actions: vec![Box::new(move |tx| { + tx.send(AppEvent::PluginsLoaded { + cwd: cwd.clone(), + result: Ok(plugins_response.clone()), + }); + })], + ..Default::default() + }); + } + + SelectionViewParams { + view_id: Some(PLUGINS_SELECTION_VIEW_ID), + header: Box::new(header), + footer_hint: Some(plugin_detail_hint_line()), + items, + ..Default::default() + } + } + fn plugin_detail_error_popup_params( &self, err: &str, @@ -802,6 +977,7 @@ impl ChatWidget { .map(|(_, _, display_name)| { PLUGIN_ROW_PREFIX_WIDTH + UnicodeWidthStr::width(display_name.as_str()) }) + .chain([UnicodeWidthStr::width("Add marketplace")]) .max(); let installed_entries = all_entries .iter() @@ -893,15 +1069,25 @@ impl ChatWidget { .iter() .filter(|(_, plugin, _)| plugin.installed) .count(); - tabs.push(SelectionTab { - id: marketplace_tab_id(marketplace), - label: label.clone(), - header: plugins_header( + let tab_id = marketplace_tab_id(marketplace); + let header = if self.newly_installed_marketplace_tab_id.as_deref() == Some(&tab_id) { + plugins_header( + format!("{label} installed successfully."), + "Select the plugins you want to use and press Enter to install or view details." + .to_string(), + ) + } else { + plugins_header( format!("{label}."), format!( "Installed {marketplace_installed} of {marketplace_total} {label} plugins." ), - ), + ) + }; + tabs.push(SelectionTab { + id: tab_id, + label: label.clone(), + header, items: self.plugin_selection_items( entries, /*include_marketplace_names*/ false, @@ -911,6 +1097,8 @@ impl ChatWidget { }); } + tabs.push(self.marketplace_add_tab()); + SelectionViewParams { view_id: Some(PLUGINS_SELECTION_VIEW_ID), header: Box::new(()), @@ -927,6 +1115,30 @@ impl ChatWidget { } } + fn marketplace_add_tab(&self) -> SelectionTab { + SelectionTab { + id: ADD_MARKETPLACE_TAB_ID.to_string(), + label: "Add Marketplace".to_string(), + header: plugins_header( + "Add a marketplace from a Git repo or local root.".to_string(), + "Enter a source to make its plugins available in this menu.".to_string(), + ), + items: vec![SelectionItem { + name: "Add marketplace".to_string(), + description: Some( + "Enter owner/repo, a Git URL, or a local marketplace path.".to_string(), + ), + selected_description: Some( + "Press Enter to enter a marketplace source.".to_string(), + ), + actions: vec![Box::new(|tx| { + tx.send(AppEvent::OpenMarketplaceAddPrompt); + })], + ..Default::default() + }], + } + } + fn plugin_detail_popup_params( &self, plugins_response: &PluginListResponse, @@ -1107,7 +1319,7 @@ impl ChatWidget { format!("{selected_status_label} Space to {toggle_action}.") } } else if can_view_details { - format!("{selected_status_label} Press Enter to view plugin details.") + format!("{selected_status_label} Press Enter to install or view plugin details.") } else { format!("{selected_status_label} Remote plugin details are not available yet.") }; @@ -1227,11 +1439,40 @@ fn sort_plugin_entries(entries: &mut [(&PluginMarketplaceEntry, &PluginSummary, fn marketplace_tab_id(marketplace: &PluginMarketplaceEntry) -> String { match marketplace.path.as_ref() { - Some(path) => format!("marketplace:{}", path.display()), + Some(path) => marketplace_tab_id_from_path(path.as_path()), None => format!("marketplace:{}", marketplace.name), } } +fn marketplace_tab_id_from_path(path: &Path) -> String { + format!("{MARKETPLACE_TAB_ID_PREFIX}{}", path.display()) +} + +fn marketplace_tab_id_matching_saved_id( + saved_tab_id: &str, + marketplaces: &[PluginMarketplaceEntry], +) -> Option { + if let Some(tab_id) = marketplaces.iter().find_map(|marketplace| { + let tab_id = marketplace_tab_id(marketplace); + (tab_id == saved_tab_id).then_some(tab_id) + }) { + return Some(tab_id); + } + + let root = saved_tab_id.strip_prefix(MARKETPLACE_TAB_ID_PREFIX)?; + if root.is_empty() { + return None; + } + let root = Path::new(root); + marketplaces.iter().find_map(|marketplace| { + marketplace + .path + .as_ref() + .is_some_and(|path| path.as_path().starts_with(root)) + .then(|| marketplace_tab_id(marketplace)) + }) +} + fn disambiguate_duplicate_tab_labels(labels: Vec) -> Vec { let mut counts: Vec<(String, usize)> = Vec::new(); for label in &labels { diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__plugins_popup_curated_marketplace.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__plugins_popup_curated_marketplace.snap index e0f99b443e..40d26d3c9d 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__plugins_popup_curated_marketplace.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__plugins_popup_curated_marketplace.snap @@ -6,7 +6,7 @@ expression: popup Browse plugins from available marketplaces. Installed 1 of 4 available plugins. - [All Plugins] Installed (1) OpenAI Curated Repo Marketplace + [All Plugins] Installed (1) OpenAI Curated Repo Marketplace Add Marketplace Type to search plugins › [ ] Alpha Sync Disabled Space to enable; Enter view details. diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__plugins_popup_newly_installed_marketplace.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__plugins_popup_newly_installed_marketplace.snap new file mode 100644 index 0000000000..8fa4721157 --- /dev/null +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__plugins_popup_newly_installed_marketplace.snap @@ -0,0 +1,15 @@ +--- +source: tui/src/chatwidget/tests/popups_and_settings.rs +assertion_line: 329 +expression: popup +--- + Plugins + Debug Marketplace installed successfully. + Select the plugins you want to use and press Enter to install or view details. + + All Plugins Installed (0) OpenAI Curated [Debug Marketplace] Add Marketplace + + Type to search plugins +› [-] Debug Plugin Available Press Enter to install or view plugin details. + + space enable/disable · ←/→ select marketplace · enter view details · esc close diff --git a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__plugins_popup_search_filtered.snap b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__plugins_popup_search_filtered.snap index da1b0913fe..849b90b2ce 100644 --- a/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__plugins_popup_search_filtered.snap +++ b/codex-rs/tui/src/chatwidget/snapshots/codex_tui__chatwidget__tests__plugins_popup_search_filtered.snap @@ -1,14 +1,15 @@ --- -source: tui/src/chatwidget/tests.rs +source: tui/src/chatwidget/tests/popups_and_settings.rs +assertion_line: 767 expression: popup --- Plugins Browse plugins from available marketplaces. Installed 0 of 3 available plugins. - [All Plugins] Installed (0) OpenAI Curated + [All Plugins] Installed (0) OpenAI Curated Add Marketplace sla -› [-] Slack Available Press Enter to view plugin details. +› [-] Slack Available Press Enter to install or view plugin details. space enable/disable · ←/→ select marketplace · enter view details · esc close diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 547c425093..1641dc7e32 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -65,6 +65,7 @@ pub(super) use codex_app_server_protocol::ItemCompletedNotification; pub(super) use codex_app_server_protocol::ItemGuardianApprovalReviewCompletedNotification; pub(super) use codex_app_server_protocol::ItemGuardianApprovalReviewStartedNotification; pub(super) use codex_app_server_protocol::ItemStartedNotification; +pub(super) use codex_app_server_protocol::MarketplaceAddResponse; pub(super) use codex_app_server_protocol::MarketplaceInterface; pub(super) use codex_app_server_protocol::McpServerStartupState; pub(super) use codex_app_server_protocol::McpServerStatusDetail; diff --git a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs index a99bc15183..e2ac788da2 100644 --- a/codex-rs/tui/src/chatwidget/tests/composer_submission.rs +++ b/codex-rs/tui/src/chatwidget/tests/composer_submission.rs @@ -17,6 +17,7 @@ async fn submission_preserves_text_elements_and_local_images() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -121,6 +122,7 @@ async fn submission_includes_configured_permission_profile() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: expected_permission_profile.clone(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -171,6 +173,7 @@ async fn submission_keeps_profile_when_legacy_projection_is_external() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: expected_permission_profile.clone(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -214,6 +217,7 @@ async fn submission_with_remote_and_local_images_keeps_local_placeholder_numberi approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -309,6 +313,7 @@ async fn enter_with_only_remote_images_submits_user_turn() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -374,6 +379,7 @@ async fn shift_enter_with_only_remote_images_does_not_submit_user_turn() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -414,6 +420,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_modal_is_active() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -454,6 +461,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_input_disabled() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -497,6 +505,7 @@ async fn submission_prefers_selected_duplicate_skill_path() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, diff --git a/codex-rs/tui/src/chatwidget/tests/exec_flow.rs b/codex-rs/tui/src/chatwidget/tests/exec_flow.rs index d3d5de1f12..89f9debe54 100644 --- a/codex-rs/tui/src/chatwidget/tests/exec_flow.rs +++ b/codex-rs/tui/src/chatwidget/tests/exec_flow.rs @@ -1059,6 +1059,7 @@ async fn bang_shell_enter_while_task_running_submits_run_user_shell_command() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, diff --git a/codex-rs/tui/src/chatwidget/tests/helpers.rs b/codex-rs/tui/src/chatwidget/tests/helpers.rs index 464508c7a1..d26a503a89 100644 --- a/codex-rs/tui/src/chatwidget/tests/helpers.rs +++ b/codex-rs/tui/src/chatwidget/tests/helpers.rs @@ -244,6 +244,7 @@ pub(super) async fn make_chatwidget_manual( plugin_install_apps_needing_auth: Vec::new(), plugin_install_auth_flow: None, plugins_active_tab_id: None, + newly_installed_marketplace_tab_id: None, connectors_prefetch_in_flight: false, connectors_force_refetch_pending: false, plugins_cache: PluginsCacheState::default(), diff --git a/codex-rs/tui/src/chatwidget/tests/history_replay.rs b/codex-rs/tui/src/chatwidget/tests/history_replay.rs index 86346885b6..5fdb615b97 100644 --- a/codex-rs/tui/src/chatwidget/tests/history_replay.rs +++ b/codex-rs/tui/src/chatwidget/tests/history_replay.rs @@ -24,6 +24,7 @@ async fn resumed_initial_messages_render_history() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: codex_protocol::models::PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -137,6 +138,7 @@ async fn replayed_user_message_preserves_text_elements_and_local_images() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: codex_protocol::models::PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -198,6 +200,7 @@ async fn replayed_user_message_preserves_remote_image_urls() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: codex_protocol::models::PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -286,6 +289,7 @@ async fn session_configured_syncs_widget_config_permissions_and_cwd() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: expected_permission_profile.clone(), + active_permission_profile: None, cwd: expected_cwd.clone(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -344,6 +348,7 @@ async fn session_configured_external_sandbox_keeps_external_runtime_policy() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: expected_permission_profile, + active_permission_profile: None, cwd: test_path_buf("/home/user/external").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -393,6 +398,7 @@ async fn replayed_user_message_with_only_remote_images_renders_history_cell() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: codex_protocol::models::PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -446,6 +452,7 @@ async fn replayed_user_message_with_only_local_images_does_not_render_history_ce approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: codex_protocol::models::PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -767,6 +774,7 @@ async fn replayed_reasoning_item_hides_raw_reasoning_when_disabled() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: codex_protocol::models::PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_project_path().abs(), reasoning_effort: None, history_log_id: 0, @@ -814,6 +822,7 @@ async fn replayed_reasoning_item_shows_raw_reasoning_when_enabled() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: codex_protocol::models::PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_project_path().abs(), reasoning_effort: None, history_log_id: 0, diff --git a/codex-rs/tui/src/chatwidget/tests/permissions.rs b/codex-rs/tui/src/chatwidget/tests/permissions.rs index 829fa77f5d..1a0440c55c 100644 --- a/codex-rs/tui/src/chatwidget/tests/permissions.rs +++ b/codex-rs/tui/src/chatwidget/tests/permissions.rs @@ -542,6 +542,7 @@ async fn permissions_selection_marks_auto_review_current_after_session_configure approval_policy: AskForApproval::OnRequest, approvals_reviewer: ApprovalsReviewer::AutoReview, permission_profile: PermissionProfile::workspace_write(), + active_permission_profile: None, cwd: test_project_path().abs(), reasoning_effort: None, history_log_id: 0, @@ -596,6 +597,7 @@ async fn permissions_selection_marks_auto_review_current_with_custom_workspace_w approval_policy: AskForApproval::OnRequest, approvals_reviewer: ApprovalsReviewer::AutoReview, permission_profile, + active_permission_profile: None, cwd, reasoning_effort: None, history_log_id: 0, diff --git a/codex-rs/tui/src/chatwidget/tests/plan_mode.rs b/codex-rs/tui/src/chatwidget/tests/plan_mode.rs index d369eb710d..143afab52c 100644 --- a/codex-rs/tui/src/chatwidget/tests/plan_mode.rs +++ b/codex-rs/tui/src/chatwidget/tests/plan_mode.rs @@ -1196,6 +1196,7 @@ async fn submit_user_message_emits_structured_plugin_mentions_from_bindings() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, @@ -1441,6 +1442,7 @@ async fn plan_slash_command_with_args_submits_prompt_in_plan_mode() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, diff --git a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs index 728cbf0170..11505b3e71 100644 --- a/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs +++ b/codex-rs/tui/src/chatwidget/tests/popups_and_settings.rs @@ -163,6 +163,190 @@ async fn plugins_popup_snapshot_shows_all_marketplaces_and_sorts_installed_then_ ); } +#[tokio::test] +async fn plugins_popup_truncates_long_descriptions_in_list_rows() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + chat.set_feature_enabled(Feature::Plugins, /*enabled*/ true); + + let response = plugins_test_response(vec![plugins_test_curated_marketplace(vec![ + plugins_test_summary( + "plugin-alpha", + "alpha", + Some("Alpha"), + Some("Short description."), + /*installed*/ false, + /*enabled*/ true, + PluginInstallPolicy::Available, + ), + plugins_test_summary( + "plugin-verbose", + "verbose", + Some("Verbose Plugin"), + Some("This description keeps going and going until the row would normally wrap."), + /*installed*/ false, + /*enabled*/ true, + PluginInstallPolicy::Available, + ), + ])]); + + let cwd = chat.config.cwd.to_path_buf(); + chat.on_plugins_loaded(cwd, Ok(response)); + chat.add_plugins_output(); + + let popup = render_bottom_popup(&chat, /*width*/ 70); + let verbose_row = popup + .lines() + .find(|line| line.contains("Verbose Plugin")) + .expect("expected verbose plugin row in popup"); + insta::assert_snapshot!( + verbose_row, + @" [-] Verbose Plugin Available · ChatGPT Marketplace · This descri…" + ); + assert!( + !popup + .contains("This description keeps going and going until the row would normally wrap."), + "expected the long plugin description to truncate instead of wrapping, got:\n{popup}" + ); +} + +#[tokio::test] +async fn plugins_popup_add_marketplace_tab_opens_prompt_and_submits_source() { + let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + chat.set_feature_enabled(Feature::Plugins, /*enabled*/ true); + + let cwd = chat.config.cwd.to_path_buf(); + render_loaded_plugins_popup( + &mut chat, + plugins_test_response(vec![plugins_test_curated_marketplace(Vec::new())]), + ); + + while rx.try_recv().is_ok() {} + for _ in 0..3 { + chat.handle_key_event(KeyEvent::from(KeyCode::Right)); + } + + let popup = render_bottom_popup(&chat, /*width*/ 100); + assert!( + popup.contains("Add a marketplace from a Git repo or local root."), + "expected Add Marketplace tab, got:\n{popup}" + ); + + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + match rx.try_recv() { + Ok(AppEvent::OpenMarketplaceAddPrompt) => {} + other => panic!("expected OpenMarketplaceAddPrompt event, got {other:?}"), + } + + chat.open_marketplace_add_prompt(); + let prompt = render_bottom_popup(&chat, /*width*/ 100); + assert!( + prompt.contains("owner/repo, git URL, or local marketplace path"), + "expected marketplace source prompt, got:\n{prompt}" + ); + + chat.handle_key_event(KeyEvent::new(KeyCode::Char('o'), KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Char('w'), KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Char('n'), KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Char('/'), KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Char('r'), KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Char('e'), KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Char('p'), KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::new(KeyCode::Char('o'), KeyModifiers::NONE)); + chat.handle_key_event(KeyEvent::from(KeyCode::Enter)); + + match rx.try_recv() { + Ok(AppEvent::OpenMarketplaceAddLoading { source }) => { + assert_eq!(source, "owner/repo"); + } + other => panic!("expected OpenMarketplaceAddLoading event, got {other:?}"), + } + match rx.try_recv() { + Ok(AppEvent::FetchMarketplaceAdd { + cwd: event_cwd, + source, + }) => { + assert_eq!(event_cwd, cwd); + assert_eq!(source, "owner/repo"); + } + other => panic!("expected FetchMarketplaceAdd event, got {other:?}"), + } +} + +#[tokio::test] +async fn marketplace_add_success_refreshes_to_new_marketplace_tab() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; + chat.set_feature_enabled(Feature::Plugins, /*enabled*/ true); + + let cwd = chat.config.cwd.to_path_buf(); + let marketplace_root = plugins_test_absolute_path("marketplaces/debug"); + let marketplace_path = + plugins_test_absolute_path("marketplaces/debug/.agents/plugins/marketplace.json"); + render_loaded_plugins_popup( + &mut chat, + plugins_test_response(vec![plugins_test_curated_marketplace(Vec::new())]), + ); + chat.open_marketplace_add_loading_popup("owner/repo"); + let loading_popup = render_bottom_popup(&chat, /*width*/ 100); + assert!( + !loading_popup.contains("owner/repo"), + "expected marketplace loading popup to avoid echoing the source, got:\n{loading_popup}" + ); + chat.on_marketplace_add_loaded( + cwd.clone(), + "owner/repo".to_string(), + Ok(MarketplaceAddResponse { + marketplace_name: "debug".to_string(), + installed_root: marketplace_root, + already_added: false, + }), + ); + chat.on_plugins_loaded( + cwd, + Ok(plugins_test_response(vec![ + plugins_test_curated_marketplace(Vec::new()), + PluginMarketplaceEntry { + name: "debug".to_string(), + path: Some(marketplace_path), + interface: Some(MarketplaceInterface { + display_name: Some("Debug Marketplace".to_string()), + }), + plugins: vec![plugins_test_summary( + "plugin-debug", + "debug", + Some("Debug Plugin"), + Some("Debug marketplace plugin."), + /*installed*/ false, + /*enabled*/ true, + PluginInstallPolicy::Available, + )], + }, + ])), + ); + + let popup = render_bottom_popup(&chat, /*width*/ 100); + assert_chatwidget_snapshot!("plugins_popup_newly_installed_marketplace", popup); + assert!( + popup.contains("Debug Marketplace installed successfully.") + && popup.contains("Debug Plugin"), + "expected marketplace add refresh to switch to the new marketplace tab, got:\n{popup}" + ); + + chat.handle_key_event(KeyEvent::from(KeyCode::Esc)); + chat.add_plugins_output(); + for _ in 0..3 { + chat.handle_key_event(KeyEvent::from(KeyCode::Right)); + } + + let reopened_popup = render_bottom_popup(&chat, /*width*/ 100); + assert!( + reopened_popup.contains("Installed 0 of 1 Debug Marketplace plugins.") + && !reopened_popup.contains("installed successfully"), + "expected reopening the marketplace tab later to use the normal header, got:\n{reopened_popup}" + ); +} + #[tokio::test] async fn plugin_detail_popup_snapshot_shows_install_actions_and_capability_summaries() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; diff --git a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs index e812e69293..3b445c1b9f 100644 --- a/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs +++ b/codex-rs/tui/src/chatwidget/tests/status_and_layout.rs @@ -1732,6 +1732,7 @@ async fn session_configured_clears_goal_status_footer() { approval_policy: AskForApproval::Never, approvals_reviewer: ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/home/user/project").abs(), reasoning_effort: Some(ReasoningEffortConfig::default()), history_log_id: 0, diff --git a/codex-rs/tui/src/history_cell.rs b/codex-rs/tui/src/history_cell.rs index 9d009a93fb..803cfcde5f 100644 --- a/codex-rs/tui/src/history_cell.rs +++ b/codex-rs/tui/src/history_cell.rs @@ -3194,6 +3194,7 @@ mod tests { approval_policy: AskForApproval::Never, approvals_reviewer: codex_protocol::config_types::ApprovalsReviewer::User, permission_profile: PermissionProfile::read_only(), + active_permission_profile: None, cwd: test_path_buf("/tmp/project").abs(), reasoning_effort: None, history_log_id: 0, diff --git a/codex-rs/tui/src/status/card.rs b/codex-rs/tui/src/status/card.rs index b9366df208..1671a5512c 100644 --- a/codex-rs/tui/src/status/card.rs +++ b/codex-rs/tui/src/status/card.rs @@ -9,6 +9,7 @@ use chrono::Local; use codex_model_provider_info::WireApi; use codex_protocol::ThreadId; use codex_protocol::account::PlanType; +use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::PermissionProfile; use codex_protocol::openai_models::ReasoningEffort; use codex_protocol::protocol::AskForApproval; @@ -281,18 +282,15 @@ impl StatusHistoryCell { .map(|(_, v)| v.clone()) .unwrap_or_else(|| "".to_string()); let permission_profile = config.permissions.permission_profile(); + let active_permission_profile = config.permissions.active_permission_profile(); let sandbox = status_permission_summary(&permission_profile, config.cwd.as_path()); - let permissions = if config.permissions.approval_policy.value() == AskForApproval::OnRequest - && permission_profile == PermissionProfile::workspace_write() - { - "Default".to_string() - } else if config.permissions.approval_policy.value() == AskForApproval::Never - && permission_profile == PermissionProfile::Disabled - { - "Full Access".to_string() - } else { - format!("Custom ({sandbox}, {approval})") - }; + let permissions = status_permissions_label( + active_permission_profile.as_ref(), + &permission_profile, + config.permissions.approval_policy.value(), + &sandbox, + &approval, + ); let model_provider = format_model_provider(config); let account = compose_account_display(account_display); let session_id = session_id.as_ref().map(std::string::ToString::to_string); @@ -549,6 +547,39 @@ fn status_permission_summary(permission_profile: &PermissionProfile, cwd: &Path) summary } +fn status_permissions_label( + active_permission_profile: Option<&ActivePermissionProfile>, + permission_profile: &PermissionProfile, + approval_policy: AskForApproval, + sandbox: &str, + approval: &str, +) -> String { + if active_permission_profile.is_some_and(|active| active.id == ":workspace") + && approval_policy == AskForApproval::OnRequest + { + return "Default".to_string(); + } + if active_permission_profile.is_some_and(|active| active.id == ":danger-no-sandbox") + && approval_policy == AskForApproval::Never + { + return "Full Access".to_string(); + } + if let Some(active) = active_permission_profile { + return format!("Profile {} ({sandbox}, {approval})", active.id); + } + if approval_policy == AskForApproval::OnRequest + && permission_profile == &PermissionProfile::workspace_write() + { + return "Default".to_string(); + } + if approval_policy == AskForApproval::Never + && permission_profile == &PermissionProfile::Disabled + { + return "Full Access".to_string(); + } + format!("Custom ({sandbox}, {approval})") +} + impl HistoryCell for StatusHistoryCell { fn display_lines(&self, width: u16) -> Vec> { let mut lines: Vec> = Vec::new(); diff --git a/codex-rs/tui/src/status/tests.rs b/codex-rs/tui/src/status/tests.rs index b6b38cad10..324196d81a 100644 --- a/codex-rs/tui/src/status/tests.rs +++ b/codex-rs/tui/src/status/tests.rs @@ -13,6 +13,7 @@ use chrono::TimeZone; use chrono::Utc; use codex_protocol::ThreadId; use codex_protocol::config_types::ReasoningSummary; +use codex_protocol::models::ActivePermissionProfile; use codex_protocol::models::ManagedFileSystemPermissions; use codex_protocol::models::PermissionProfile; use codex_protocol::openai_models::ReasoningEffort; @@ -239,6 +240,49 @@ async fn status_permissions_non_default_workspace_write_is_custom() { ); } +#[tokio::test] +async fn status_permissions_named_workspace_profile_is_default() { + let temp_home = TempDir::new().expect("temp home"); + let mut config = test_config(&temp_home).await; + config + .permissions + .approval_policy + .set(AskForApproval::OnRequest) + .expect("set approval policy"); + config + .permissions + .set_permission_profile_with_active_profile( + PermissionProfile::workspace_write_with( + &[], + NetworkSandboxPolicy::Enabled, + /*exclude_tmpdir_env_var*/ false, + /*exclude_slash_tmp*/ false, + ), + Some(ActivePermissionProfile::new(":workspace")), + ) + .expect("set permission profile"); + + assert_eq!(permissions_text_for(&config).as_deref(), Some("Default")); +} + +#[tokio::test] +async fn status_permissions_user_defined_profile_shows_name() { + let temp_home = TempDir::new().expect("temp home"); + let mut config = test_config(&temp_home).await; + config + .permissions + .set_permission_profile_with_active_profile( + PermissionProfile::read_only(), + Some(ActivePermissionProfile::new("locked")), + ) + .expect("set permission profile"); + + assert_eq!( + permissions_text_for(&config).as_deref(), + Some("Profile locked (read-only, on-request)") + ); +} + #[tokio::test] async fn status_permissions_full_disk_managed_with_network_is_danger_full_access() { let temp_home = TempDir::new().expect("temp home");