From dfd1e199a0d8a54c15261ee7159f9a86b337ac4f Mon Sep 17 00:00:00 2001 From: Celia Chen Date: Thu, 12 Feb 2026 15:30:22 -0800 Subject: [PATCH 1/7] [feat] add seatbelt permission files (#11639) Add seatbelt permission extension abstraction as permission files for seatbelt profiles. This should complement our current sandbox policy --- codex-rs/core/README.md | 24 ++ codex-rs/core/src/lib.rs | 1 + codex-rs/core/src/seatbelt.rs | 125 +++++++++- codex-rs/core/src/seatbelt_base_policy.sbpl | 3 - codex-rs/core/src/seatbelt_permissions.rs | 246 ++++++++++++++++++++ 5 files changed, 393 insertions(+), 6 deletions(-) create mode 100644 codex-rs/core/src/seatbelt_permissions.rs diff --git a/codex-rs/core/README.md b/codex-rs/core/README.md index 9974a591cf..8a66b47b48 100644 --- a/codex-rs/core/README.md +++ b/codex-rs/core/README.md @@ -14,6 +14,30 @@ When using the workspace-write sandbox policy, the Seatbelt profile allows writes under the configured writable roots while keeping `.git` (directory or pointer file), the resolved `gitdir:` target, and `.codex` read-only. +Network access and filesystem read/write roots are controlled by +`SandboxPolicy`. Seatbelt consumes the resolved policy and enforces it. + +Seatbelt also supports macOS permission-profile extensions layered on top of +`SandboxPolicy`: + +- no extension profile provided: + keeps legacy default preferences read access (`user-preference-read`). +- extension profile provided with no `macos_preferences` grant: + does not add preferences access clauses. +- `macos_preferences = "readonly"`: + enables cfprefs read clauses and `user-preference-read`. +- `macos_preferences = "readwrite"`: + includes readonly clauses plus `user-preference-write` and cfprefs shm write + clauses. +- `macos_automation = true`: + enables broad Apple Events send permissions. +- `macos_automation = ["com.apple.Notes", ...]`: + enables Apple Events send only to listed bundle IDs. +- `macos_accessibility = true`: + enables `com.apple.axserver` mach lookup. +- `macos_calendar = true`: + enables `com.apple.CalendarAgent` mach lookup. + ### Linux Expects the binary containing `codex-core` to run the equivalent of `codex sandbox linux` (legacy alias: `codex debug landlock`) when `arg0` is `codex-linux-sandbox`. See the `codex-arg0` crate for details. diff --git a/codex-rs/core/src/lib.rs b/codex-rs/core/src/lib.rs index 764fc4fbba..e3888ecf86 100644 --- a/codex-rs/core/src/lib.rs +++ b/codex-rs/core/src/lib.rs @@ -77,6 +77,7 @@ pub use model_provider_info::create_oss_provider_with_base_url; mod event_mapping; pub mod review_format; pub mod review_prompts; +mod seatbelt_permissions; mod thread_manager; pub mod web_search; pub mod windows_sandbox_read_grants; diff --git a/codex-rs/core/src/seatbelt.rs b/codex-rs/core/src/seatbelt.rs index fc425f2184..29c05e0183 100644 --- a/codex-rs/core/src/seatbelt.rs +++ b/codex-rs/core/src/seatbelt.rs @@ -14,6 +14,9 @@ use tokio::process::Child; use url::Url; use crate::protocol::SandboxPolicy; +use crate::seatbelt_permissions::MacOsPreferencesPermission; +use crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions; +use crate::seatbelt_permissions::build_seatbelt_extensions; use crate::spawn::CODEX_SANDBOX_ENV_VAR; use crate::spawn::SpawnChildRequest; use crate::spawn::StdioPolicy; @@ -179,6 +182,24 @@ pub(crate) fn create_seatbelt_command_args( sandbox_policy_cwd: &Path, enforce_managed_network: bool, network: Option<&NetworkProxy>, +) -> Vec { + create_seatbelt_command_args_with_extensions( + command, + sandbox_policy, + sandbox_policy_cwd, + enforce_managed_network, + network, + None, + ) +} + +pub(crate) fn create_seatbelt_command_args_with_extensions( + command: Vec, + sandbox_policy: &SandboxPolicy, + sandbox_policy_cwd: &Path, + enforce_managed_network: bool, + network: Option<&NetworkProxy>, + extensions: Option<&MacOsSeatbeltProfileExtensions>, ) -> Vec { let (file_write_policy, file_write_dir_params) = { if sandbox_policy.has_full_disk_write_access() { @@ -275,15 +296,33 @@ pub(crate) fn create_seatbelt_command_args( let proxy = proxy_policy_inputs(network); let network_policy = dynamic_network_policy(sandbox_policy, enforce_managed_network, &proxy); - - let full_policy = format!( - "{MACOS_SEATBELT_BASE_POLICY}\n{file_read_policy}\n{file_write_policy}\n{network_policy}" + let seatbelt_extensions = extensions.map_or_else( + || { + // Backward-compatibility default when no extension profile is provided. + build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadOnly, + ..Default::default() + }) + }, + build_seatbelt_extensions, ); + let full_policy = if seatbelt_extensions.policy.is_empty() { + format!( + "{MACOS_SEATBELT_BASE_POLICY}\n{file_read_policy}\n{file_write_policy}\n{network_policy}" + ) + } else { + format!( + "{MACOS_SEATBELT_BASE_POLICY}\n{file_read_policy}\n{file_write_policy}\n{network_policy}\n{}", + seatbelt_extensions.policy + ) + }; + let dir_params = [ file_read_dir_params, file_write_dir_params, macos_dir_params(), + seatbelt_extensions.dir_params, ] .concat(); @@ -328,10 +367,14 @@ mod tests { use super::MACOS_SEATBELT_BASE_POLICY; use super::ProxyPolicyInputs; use super::create_seatbelt_command_args; + use super::create_seatbelt_command_args_with_extensions; use super::dynamic_network_policy; use super::macos_dir_params; use crate::protocol::SandboxPolicy; use crate::seatbelt::MACOS_PATH_TO_SEATBELT_EXECUTABLE; + use crate::seatbelt_permissions::MacOsAutomationPermission; + use crate::seatbelt_permissions::MacOsPreferencesPermission; + use crate::seatbelt_permissions::MacOsSeatbeltProfileExtensions; use pretty_assertions::assert_eq; use std::fs; use std::path::Path; @@ -395,6 +438,66 @@ mod tests { ); } + #[test] + fn seatbelt_args_include_macos_permission_extensions() { + let cwd = std::env::temp_dir(); + let args = create_seatbelt_command_args_with_extensions( + vec!["echo".to_string(), "ok".to_string()], + &SandboxPolicy::new_read_only_policy(), + cwd.as_path(), + false, + None, + Some(&MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + "com.apple.Notes".to_string(), + ]), + macos_accessibility: true, + macos_calendar: true, + }), + ); + let policy = &args[1]; + + assert!(policy.contains("(allow user-preference-write)")); + assert!(policy.contains("(appleevent-destination \"com.apple.Notes\")")); + assert!(policy.contains("com.apple.axserver")); + assert!(policy.contains("com.apple.CalendarAgent")); + } + + #[test] + fn seatbelt_args_without_extension_profile_keep_legacy_preferences_read_access() { + let cwd = std::env::temp_dir(); + let args = create_seatbelt_command_args( + vec!["echo".to_string(), "ok".to_string()], + &SandboxPolicy::new_read_only_policy(), + cwd.as_path(), + false, + None, + ); + let policy = &args[1]; + assert!(policy.contains("(allow user-preference-read)")); + assert!(!policy.contains("(allow user-preference-write)")); + } + + #[test] + fn seatbelt_args_omit_macos_extensions_when_profile_is_empty() { + let cwd = std::env::temp_dir(); + let args = create_seatbelt_command_args_with_extensions( + vec!["echo".to_string(), "ok".to_string()], + &SandboxPolicy::new_read_only_policy(), + cwd.as_path(), + false, + None, + Some(&MacOsSeatbeltProfileExtensions::default()), + ); + let policy = &args[1]; + assert!(!policy.contains("appleevent-send")); + assert!(!policy.contains("com.apple.axserver")); + assert!(!policy.contains("com.apple.CalendarAgent")); + assert!(!policy.contains("user-preference-read")); + assert!(!policy.contains("user-preference-write")); + } + #[test] fn create_seatbelt_args_allows_local_binding_when_explicitly_enabled() { let policy = dynamic_network_policy( @@ -564,6 +667,14 @@ mod tests { (allow file-write* (require-all (subpath (param "WRITABLE_ROOT_0")) (require-not (subpath (param "WRITABLE_ROOT_0_RO_0"))) (require-not (subpath (param "WRITABLE_ROOT_0_RO_1"))) ) (subpath (param "WRITABLE_ROOT_1")) (subpath (param "WRITABLE_ROOT_2")) ) + +; macOS permission profile extensions +(allow ipc-posix-shm-read* (ipc-posix-name-prefix "apple.cfprefs.")) +(allow mach-lookup + (global-name "com.apple.cfprefsd.daemon") + (global-name "com.apple.cfprefsd.agent") + (local-name "com.apple.cfprefsd.agent")) +(allow user-preference-read) "#, ); @@ -851,6 +962,14 @@ mod tests { (allow file-write* (require-all (subpath (param "WRITABLE_ROOT_0")) (require-not (subpath (param "WRITABLE_ROOT_0_RO_0"))) (require-not (subpath (param "WRITABLE_ROOT_0_RO_1"))) ) (subpath (param "WRITABLE_ROOT_1")){tempdir_policy_entry} ) + +; macOS permission profile extensions +(allow ipc-posix-shm-read* (ipc-posix-name-prefix "apple.cfprefs.")) +(allow mach-lookup + (global-name "com.apple.cfprefsd.daemon") + (global-name "com.apple.cfprefsd.agent") + (local-name "com.apple.cfprefsd.agent")) +(allow user-preference-read) "#, ); diff --git a/codex-rs/core/src/seatbelt_base_policy.sbpl b/codex-rs/core/src/seatbelt_base_policy.sbpl index 00676a86f4..72b13c96cd 100644 --- a/codex-rs/core/src/seatbelt_base_policy.sbpl +++ b/codex-rs/core/src/seatbelt_base_policy.sbpl @@ -12,9 +12,6 @@ (allow process-fork) (allow signal (target same-sandbox)) -; Allow cf prefs to work. -(allow user-preference-read) - ; process-info (allow process-info* (target same-sandbox)) diff --git a/codex-rs/core/src/seatbelt_permissions.rs b/codex-rs/core/src/seatbelt_permissions.rs new file mode 100644 index 0000000000..29313d7a3c --- /dev/null +++ b/codex-rs/core/src/seatbelt_permissions.rs @@ -0,0 +1,246 @@ +#![cfg(target_os = "macos")] + +use std::collections::BTreeSet; +use std::path::PathBuf; + +#[allow(dead_code)] +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum MacOsPreferencesPermission { + #[default] + None, + ReadOnly, + ReadWrite, +} + +#[allow(dead_code)] +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub enum MacOsAutomationPermission { + #[default] + None, + All, + BundleIds(Vec), +} + +#[allow(dead_code)] +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct MacOsSeatbeltProfileExtensions { + pub macos_preferences: MacOsPreferencesPermission, + pub macos_automation: MacOsAutomationPermission, + pub macos_accessibility: bool, + pub macos_calendar: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub(crate) struct SeatbeltExtensionPolicy { + pub(crate) policy: String, + pub(crate) dir_params: Vec<(String, PathBuf)>, +} + +impl MacOsSeatbeltProfileExtensions { + pub fn normalized(&self) -> Self { + let mut normalized = self.clone(); + if let MacOsAutomationPermission::BundleIds(bundle_ids) = &self.macos_automation { + let bundle_ids = normalize_bundle_ids(bundle_ids); + normalized.macos_automation = if bundle_ids.is_empty() { + MacOsAutomationPermission::None + } else { + MacOsAutomationPermission::BundleIds(bundle_ids) + }; + } + normalized + } +} + +pub(crate) fn build_seatbelt_extensions( + extensions: &MacOsSeatbeltProfileExtensions, +) -> SeatbeltExtensionPolicy { + let extensions = extensions.normalized(); + let mut clauses = Vec::new(); + + match extensions.macos_preferences { + MacOsPreferencesPermission::None => {} + MacOsPreferencesPermission::ReadOnly => { + clauses.push( + "(allow ipc-posix-shm-read* (ipc-posix-name-prefix \"apple.cfprefs.\"))" + .to_string(), + ); + clauses.push( + "(allow mach-lookup\n (global-name \"com.apple.cfprefsd.daemon\")\n (global-name \"com.apple.cfprefsd.agent\")\n (local-name \"com.apple.cfprefsd.agent\"))" + .to_string(), + ); + clauses.push("(allow user-preference-read)".to_string()); + } + MacOsPreferencesPermission::ReadWrite => { + clauses.push( + "(allow ipc-posix-shm-read* (ipc-posix-name-prefix \"apple.cfprefs.\"))" + .to_string(), + ); + clauses.push( + "(allow mach-lookup\n (global-name \"com.apple.cfprefsd.daemon\")\n (global-name \"com.apple.cfprefsd.agent\")\n (local-name \"com.apple.cfprefsd.agent\"))" + .to_string(), + ); + clauses.push("(allow user-preference-read)".to_string()); + clauses.push("(allow user-preference-write)".to_string()); + clauses.push( + "(allow ipc-posix-shm-write-data (ipc-posix-name-prefix \"apple.cfprefs.\"))" + .to_string(), + ); + clauses.push( + "(allow ipc-posix-shm-write-create (ipc-posix-name-prefix \"apple.cfprefs.\"))" + .to_string(), + ); + } + } + + match extensions.macos_automation { + MacOsAutomationPermission::None => {} + MacOsAutomationPermission::All => { + clauses.push( + "(allow mach-lookup\n (global-name \"com.apple.coreservices.launchservicesd\")\n (global-name \"com.apple.coreservices.appleevents\"))" + .to_string(), + ); + clauses.push("(allow appleevent-send)".to_string()); + } + MacOsAutomationPermission::BundleIds(bundle_ids) => { + if !bundle_ids.is_empty() { + clauses.push( + "(allow mach-lookup (global-name \"com.apple.coreservices.appleevents\"))" + .to_string(), + ); + let destinations = bundle_ids + .iter() + .map(|bundle_id| format!(" (appleevent-destination \"{bundle_id}\")")) + .collect::>() + .join("\n"); + clauses.push(format!("(allow appleevent-send\n{destinations}\n)")); + } + } + } + + if extensions.macos_accessibility { + clauses.push("(allow mach-lookup (local-name \"com.apple.axserver\"))".to_string()); + } + + if extensions.macos_calendar { + clauses.push("(allow mach-lookup (global-name \"com.apple.CalendarAgent\"))".to_string()); + } + + if clauses.is_empty() { + SeatbeltExtensionPolicy::default() + } else { + SeatbeltExtensionPolicy { + policy: format!( + "; macOS permission profile extensions\n{}\n", + clauses.join("\n") + ), + dir_params: Vec::new(), + } + } +} + +fn normalize_bundle_ids(bundle_ids: &[String]) -> Vec { + let mut unique = BTreeSet::new(); + for bundle_id in bundle_ids { + let candidate = bundle_id.trim(); + if is_valid_bundle_id(candidate) { + unique.insert(candidate.to_string()); + } + } + unique.into_iter().collect() +} + +fn is_valid_bundle_id(bundle_id: &str) -> bool { + if bundle_id.len() < 3 || !bundle_id.contains('.') { + return false; + } + bundle_id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_') +} + +#[cfg(test)] +mod tests { + use super::MacOsAutomationPermission; + use super::MacOsPreferencesPermission; + use super::MacOsSeatbeltProfileExtensions; + use super::build_seatbelt_extensions; + use pretty_assertions::assert_eq; + + #[test] + fn preferences_read_only_emits_read_clauses_only() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadOnly, + ..Default::default() + }); + assert!(policy.policy.contains("(allow user-preference-read)")); + assert!(!policy.policy.contains("(allow user-preference-write)")); + } + + #[test] + fn preferences_read_write_emits_write_clauses() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_preferences: MacOsPreferencesPermission::ReadWrite, + ..Default::default() + }); + assert!(policy.policy.contains("(allow user-preference-read)")); + assert!(policy.policy.contains("(allow user-preference-write)")); + assert!(policy.policy.contains( + "(allow ipc-posix-shm-write-create (ipc-posix-name-prefix \"apple.cfprefs.\"))" + )); + } + + #[test] + fn automation_all_emits_unscoped_appleevents() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_automation: MacOsAutomationPermission::All, + ..Default::default() + }); + assert!(policy.policy.contains("(allow appleevent-send)")); + assert!( + policy + .policy + .contains("com.apple.coreservices.launchservicesd") + ); + } + + #[test] + fn automation_bundle_ids_are_normalized_and_scoped() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_automation: MacOsAutomationPermission::BundleIds(vec![ + " com.apple.Notes ".to_string(), + "com.apple.Calendar".to_string(), + "bad bundle".to_string(), + "com.apple.Notes".to_string(), + ]), + ..Default::default() + }); + assert!( + policy + .policy + .contains("(appleevent-destination \"com.apple.Calendar\")") + ); + assert!( + policy + .policy + .contains("(appleevent-destination \"com.apple.Notes\")") + ); + assert!(!policy.policy.contains("bad bundle")); + } + + #[test] + fn accessibility_and_calendar_emit_mach_lookups() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions { + macos_accessibility: true, + macos_calendar: true, + ..Default::default() + }); + assert!(policy.policy.contains("com.apple.axserver")); + assert!(policy.policy.contains("com.apple.CalendarAgent")); + } + + #[test] + fn empty_extensions_emit_empty_policy() { + let policy = build_seatbelt_extensions(&MacOsSeatbeltProfileExtensions::default()); + assert_eq!(policy.policy, ""); + } +} From a7ce2a1c3128e8e3a59671480840b3eae277603d Mon Sep 17 00:00:00 2001 From: Wendy Jiao Date: Thu, 12 Feb 2026 15:32:41 -0800 Subject: [PATCH 2/7] Remove absolute path in rollout_summary (#11622) --- codex-rs/core/templates/memories/stage_one_system.md | 1 - 1 file changed, 1 deletion(-) diff --git a/codex-rs/core/templates/memories/stage_one_system.md b/codex-rs/core/templates/memories/stage_one_system.md index b4f16a07d7..38031e8d2f 100644 --- a/codex-rs/core/templates/memories/stage_one_system.md +++ b/codex-rs/core/templates/memories/stage_one_system.md @@ -153,7 +153,6 @@ distilled into MEMORY.md and memory_summary.md. There is no strict size limit, and you should feel free to list a lot of points here as long as they are helpful. Instructional notes in angle brackets are guidance only; do not include them verbatim in the rollout summary. -Use absolute paths for any file paths and commands. You should refer to the cwd of the rollout. Template (items are flexible; include only what is useful): From 0dcfc59171410f8c1baff570eb1430e25271a904 Mon Sep 17 00:00:00 2001 From: Curtis 'Fjord' Hawthorne Date: Thu, 12 Feb 2026 15:41:05 -0800 Subject: [PATCH 3/7] Add js_repl_tools_only model and routing restrictions (#10671) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit # External (non-OpenAI) Pull Request Requirements Before opening this Pull Request, please read the dedicated "Contributing" markdown file or your PR may be closed: https://github.com/openai/codex/blob/main/docs/contributing.md If your PR conforms to our contribution guidelines, replace this text with a detailed and high quality description of your changes. Include a link to a bug report or enhancement request. #### [git stack](https://github.com/magus/git-stack-cli) - ✅ `1` https://github.com/openai/codex/pull/10674 - ✅ `2` https://github.com/openai/codex/pull/10672 - 👉 `3` https://github.com/openai/codex/pull/10671 - ⏳ `4` https://github.com/openai/codex/pull/10673 - ⏳ `5` https://github.com/openai/codex/pull/10670 --- codex-rs/core/config.schema.json | 6 ++ codex-rs/core/src/codex.rs | 2 + codex-rs/core/src/features.rs | 12 +++ codex-rs/core/src/project_doc.rs | 21 ++++ codex-rs/core/src/tools/js_repl/mod.rs | 8 +- codex-rs/core/src/tools/parallel.rs | 8 +- codex-rs/core/src/tools/router.rs | 137 +++++++++++++++++++++++++ codex-rs/core/src/tools/spec.rs | 105 ++++++++++++++++++- docs/js_repl.md | 10 ++ 9 files changed, 306 insertions(+), 3 deletions(-) diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 4c571a6c2e..1bd7c1a938 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -224,6 +224,9 @@ "js_repl": { "type": "boolean" }, + "js_repl_tools_only": { + "type": "boolean" + }, "memory_tool": { "type": "boolean" }, @@ -1308,6 +1311,9 @@ "js_repl": { "type": "boolean" }, + "js_repl_tools_only": { + "type": "boolean" + }, "memory_tool": { "type": "boolean" }, diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 75a2551f79..4405635ce3 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -5515,6 +5515,7 @@ mod tests { use crate::tools::handlers::ShellHandler; use crate::tools::handlers::UnifiedExecHandler; use crate::tools::registry::ToolHandler; + use crate::tools::router::ToolCallSource; use crate::turn_diff_tracker::TurnDiffTracker; use codex_app_server_protocol::AppInfo; use codex_otel::TelemetryAuthMode; @@ -7452,6 +7453,7 @@ mod tests { Arc::clone(&turn_context), tracker, call, + ToolCallSource::Direct, ) .await .expect_err("expected fatal error"); diff --git a/codex-rs/core/src/features.rs b/codex-rs/core/src/features.rs index 4a64d81f89..9df518b816 100644 --- a/codex-rs/core/src/features.rs +++ b/codex-rs/core/src/features.rs @@ -80,6 +80,8 @@ pub enum Feature { // Experimental /// Enable JavaScript REPL tools backed by a persistent Node kernel. JsRepl, + /// Only expose js_repl tools directly to the model. + JsReplToolsOnly, /// Use the single unified PTY-backed exec tool. UnifiedExec, /// Include the freeform apply_patch tool. @@ -322,6 +324,10 @@ impl Features { } overrides.apply(&mut features); + if features.enabled(Feature::JsReplToolsOnly) && !features.enabled(Feature::JsRepl) { + tracing::warn!("js_repl_tools_only requires js_repl; disabling js_repl_tools_only"); + features.disable(Feature::JsReplToolsOnly); + } features } @@ -430,6 +436,12 @@ pub const FEATURES: &[FeatureSpec] = &[ stage: Stage::UnderDevelopment, default_enabled: false, }, + FeatureSpec { + id: Feature::JsReplToolsOnly, + key: "js_repl_tools_only", + stage: Stage::UnderDevelopment, + default_enabled: false, + }, FeatureSpec { id: Feature::WebSearchRequest, key: "web_search_request", diff --git a/codex-rs/core/src/project_doc.rs b/codex-rs/core/src/project_doc.rs index a530a83379..3d2b55ab5b 100644 --- a/codex-rs/core/src/project_doc.rs +++ b/codex-rs/core/src/project_doc.rs @@ -48,6 +48,12 @@ fn render_js_repl_instructions(config: &Config) -> Option { section.push_str("- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n"); section.push_str("- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n"); + if config.features.enabled(Feature::JsReplToolsOnly) { + section.push_str("- Do not call tools directly; use `js_repl` + `codex.tool(...)` for all tool calls, including shell commands.\n"); + section + .push_str("- MCP tools (if any) can also be called by name via `codex.tool(...)`.\n"); + } + section.push_str("- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log` and `codex.tool(...)`."); Some(section) @@ -413,6 +419,21 @@ mod tests { assert_eq!(res, expected); } + #[tokio::test] + async fn js_repl_tools_only_instructions_are_feature_gated() { + let tmp = tempfile::tempdir().expect("tempdir"); + let mut cfg = make_config(&tmp, 4096, None).await; + cfg.features + .enable(Feature::JsRepl) + .enable(Feature::JsReplToolsOnly); + + let res = get_user_instructions(&cfg, None) + .await + .expect("js_repl instructions expected"); + let expected = "## JavaScript REPL (Node)\n- Use `js_repl` for Node-backed JavaScript with top-level await in a persistent kernel. `codex.state` persists for the session (best effort) and is cleared by `js_repl_reset`.\n- `js_repl` is a freeform/custom tool. Direct `js_repl` calls must send raw JavaScript tool input (optionally with first-line `// codex-js-repl: timeout_ms=15000`). Do not wrap code in JSON (for example `{\"code\":\"...\"}`), quotes, or markdown code fences.\n- Helpers: `codex.state`, `codex.tmpDir`, and `codex.tool(name, args?)`.\n- `codex.tool` executes a normal tool call and resolves to the raw tool output object. Use it for shell and non-shell tools alike.\n- To share generated images with the model, write a file under `codex.tmpDir`, call `await codex.tool(\"view_image\", { path: \"/absolute/path\" })`, then delete the file.\n- Top-level bindings persist across cells. If you hit `SyntaxError: Identifier 'x' has already been declared`, reuse the binding, pick a new name, wrap in `{ ... }` for block scope, or reset the kernel with `js_repl_reset`.\n- Top-level static import declarations (for example `import x from \"pkg\"`) are currently unsupported in `js_repl`; use dynamic imports with `await import(\"pkg\")` instead.\n- Do not call tools directly; use `js_repl` + `codex.tool(...)` for all tool calls, including shell commands.\n- MCP tools (if any) can also be called by name via `codex.tool(...)`.\n- Avoid direct access to `process.stdout` / `process.stderr` / `process.stdin`; it can corrupt the JSON line protocol. Use `console.log` and `codex.tool(...)`."; + assert_eq!(res, expected); + } + /// When both system instructions *and* a project doc are present the two /// should be concatenated with the separator. #[tokio::test] diff --git a/codex-rs/core/src/tools/js_repl/mod.rs b/codex-rs/core/src/tools/js_repl/mod.rs index 4285c29889..8b362ab8f3 100644 --- a/codex-rs/core/src/tools/js_repl/mod.rs +++ b/codex-rs/core/src/tools/js_repl/mod.rs @@ -680,7 +680,13 @@ impl JsReplManager { }; match router - .dispatch_tool_call(exec.session, exec.turn, exec.tracker, call) + .dispatch_tool_call( + exec.session, + exec.turn, + exec.tracker, + call, + crate::tools::router::ToolCallSource::JsRepl, + ) .await { Ok(response) => match serde_json::to_value(response) { diff --git a/codex-rs/core/src/tools/parallel.rs b/codex-rs/core/src/tools/parallel.rs index ca08048bd8..04d505c584 100644 --- a/codex-rs/core/src/tools/parallel.rs +++ b/codex-rs/core/src/tools/parallel.rs @@ -85,7 +85,13 @@ impl ToolCallRuntime { }; router - .dispatch_tool_call(session, turn, tracker, call.clone()) + .dispatch_tool_call( + session, + turn, + tracker, + call.clone(), + crate::tools::router::ToolCallSource::Direct, + ) .instrument(dispatch_span.clone()) .await } => res, diff --git a/codex-rs/core/src/tools/router.rs b/codex-rs/core/src/tools/router.rs index 1eb6190bcb..1cc8b91778 100644 --- a/codex-rs/core/src/tools/router.rs +++ b/codex-rs/core/src/tools/router.rs @@ -28,6 +28,12 @@ pub struct ToolCall { pub payload: ToolPayload, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ToolCallSource { + Direct, + JsRepl, +} + pub struct ToolRouter { registry: ToolRegistry, specs: Vec, @@ -138,6 +144,7 @@ impl ToolRouter { turn: Arc, tracker: SharedTurnDiffTracker, call: ToolCall, + source: ToolCallSource, ) -> Result { let ToolCall { tool_name, @@ -147,6 +154,21 @@ impl ToolRouter { let payload_outputs_custom = matches!(payload, ToolPayload::Custom { .. }); let failure_call_id = call_id.clone(); + if source == ToolCallSource::Direct + && turn.tools_config.js_repl_tools_only + && !matches!(tool_name.as_str(), "js_repl" | "js_repl_reset") + { + let err = FunctionCallError::RespondToModel( + "direct tool calls are disabled; use js_repl and codex.tool(...) instead" + .to_string(), + ); + return Ok(Self::failure_response( + failure_call_id, + payload_outputs_custom, + err, + )); + } + let invocation = ToolInvocation { session, turn, @@ -189,3 +211,118 @@ impl ToolRouter { } } } +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use crate::codex::make_session_and_context; + use crate::tools::context::ToolPayload; + use crate::turn_diff_tracker::TurnDiffTracker; + use codex_protocol::models::ResponseInputItem; + + use super::ToolCall; + use super::ToolCallSource; + use super::ToolRouter; + + #[tokio::test] + async fn js_repl_tools_only_blocks_direct_tool_calls() -> anyhow::Result<()> { + let (session, mut turn) = make_session_and_context().await; + turn.tools_config.js_repl_tools_only = true; + + let session = Arc::new(session); + let turn = Arc::new(turn); + let mcp_tools = session + .services + .mcp_connection_manager + .read() + .await + .list_all_tools() + .await; + let router = ToolRouter::from_config( + &turn.tools_config, + Some( + mcp_tools + .into_iter() + .map(|(name, tool)| (name, tool.tool)) + .collect(), + ), + turn.dynamic_tools.as_slice(), + ); + + let call = ToolCall { + tool_name: "shell".to_string(), + call_id: "call-1".to_string(), + payload: ToolPayload::Function { + arguments: "{}".to_string(), + }, + }; + let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())); + let response = router + .dispatch_tool_call(session, turn, tracker, call, ToolCallSource::Direct) + .await?; + + match response { + ResponseInputItem::FunctionCallOutput { output, .. } => { + let content = output.text_content().unwrap_or_default(); + assert!( + content.contains("direct tool calls are disabled"), + "unexpected tool call message: {content}", + ); + } + other => panic!("expected function call output, got {other:?}"), + } + + Ok(()) + } + + #[tokio::test] + async fn js_repl_tools_only_allows_js_repl_source_calls() -> anyhow::Result<()> { + let (session, mut turn) = make_session_and_context().await; + turn.tools_config.js_repl_tools_only = true; + + let session = Arc::new(session); + let turn = Arc::new(turn); + let mcp_tools = session + .services + .mcp_connection_manager + .read() + .await + .list_all_tools() + .await; + let router = ToolRouter::from_config( + &turn.tools_config, + Some( + mcp_tools + .into_iter() + .map(|(name, tool)| (name, tool.tool)) + .collect(), + ), + turn.dynamic_tools.as_slice(), + ); + + let call = ToolCall { + tool_name: "shell".to_string(), + call_id: "call-2".to_string(), + payload: ToolPayload::Function { + arguments: "{}".to_string(), + }, + }; + let tracker = Arc::new(tokio::sync::Mutex::new(TurnDiffTracker::new())); + let response = router + .dispatch_tool_call(session, turn, tracker, call, ToolCallSource::JsRepl) + .await?; + + match response { + ResponseInputItem::FunctionCallOutput { output, .. } => { + let content = output.text_content().unwrap_or_default(); + assert!( + !content.contains("direct tool calls are disabled"), + "js_repl source should bypass direct-call policy gate" + ); + } + other => panic!("expected function call output, got {other:?}"), + } + + Ok(()) + } +} diff --git a/codex-rs/core/src/tools/spec.rs b/codex-rs/core/src/tools/spec.rs index b8618e0c07..82e34298c1 100644 --- a/codex-rs/core/src/tools/spec.rs +++ b/codex-rs/core/src/tools/spec.rs @@ -34,6 +34,7 @@ pub(crate) struct ToolsConfig { pub web_search_mode: Option, pub search_tool: bool, pub js_repl_enabled: bool, + pub js_repl_tools_only: bool, pub collab_tools: bool, pub collaboration_modes_tools: bool, pub request_rule_enabled: bool, @@ -55,6 +56,8 @@ impl ToolsConfig { } = params; let include_apply_patch_tool = features.enabled(Feature::ApplyPatchFreeform); let include_js_repl = features.enabled(Feature::JsRepl); + let include_js_repl_tools_only = + include_js_repl && features.enabled(Feature::JsReplToolsOnly); let include_collab_tools = features.enabled(Feature::Collab); let include_collaboration_modes_tools = features.enabled(Feature::CollaborationModes); let request_rule_enabled = features.enabled(Feature::RequestRule); @@ -91,6 +94,7 @@ impl ToolsConfig { web_search_mode: *web_search_mode, search_tool: include_search_tool, js_repl_enabled: include_js_repl, + js_repl_tools_only: include_js_repl_tools_only, collab_tools: include_collab_tools, collaboration_modes_tools: include_collaboration_modes_tools, request_rule_enabled, @@ -99,8 +103,15 @@ impl ToolsConfig { } } -pub(crate) fn filter_tools_for_model(tools: Vec, _config: &ToolsConfig) -> Vec { +pub(crate) fn filter_tools_for_model(tools: Vec, config: &ToolsConfig) -> Vec { + if !config.js_repl_tools_only { + return tools; + } + tools + .into_iter() + .filter(|spec| matches!(spec.name(), "js_repl" | "js_repl_reset")) + .collect() } /// Generic JSON‑Schema subset needed for our tool definitions @@ -1685,6 +1696,27 @@ mod tests { } } + fn assert_contains_tool_specs(tools: &[ToolSpec], expected_subset: &[&str]) { + use std::collections::HashSet; + let mut names = HashSet::new(); + let mut duplicates = Vec::new(); + for name in tools.iter().map(tool_name) { + if !names.insert(name) { + duplicates.push(name); + } + } + assert!( + duplicates.is_empty(), + "duplicate tool entries detected: {duplicates:?}" + ); + for expected in expected_subset { + assert!( + names.contains(expected), + "expected tool {expected} to be present; had: {names:?}" + ); + } + } + fn shell_tool_name(config: &ToolsConfig) -> Option<&'static str> { match config.shell_type { ConfigShellToolType::Default => Some("shell"), @@ -1910,6 +1942,77 @@ mod tests { assert_contains_tool_names(&tools, &["js_repl", "js_repl_reset"]); } + #[test] + fn js_repl_tools_only_filters_model_tools() { + let config = test_config(); + let model_info = + ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); + let mut features = Features::with_defaults(); + features.enable(Feature::JsRepl); + features.enable(Feature::JsReplToolsOnly); + + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + }); + let (tools, _) = build_specs(&tools_config, None, &[]).build(); + let filtered = filter_tools_for_model( + tools.iter().map(|tool| tool.spec.clone()).collect(), + &tools_config, + ); + assert_contains_tool_specs(&filtered, &["js_repl", "js_repl_reset"]); + assert!( + !filtered.iter().any(|tool| tool_name(tool) == "shell"), + "expected non-js_repl tools to be hidden when js_repl_tools_only is enabled" + ); + } + + #[test] + fn js_repl_tools_only_hides_dynamic_tools_from_model_tools() { + let config = test_config(); + let model_info = + ModelsManager::construct_model_info_offline_for_tests("gpt-5-codex", &config); + let mut features = Features::with_defaults(); + features.enable(Feature::JsRepl); + features.enable(Feature::JsReplToolsOnly); + + let tools_config = ToolsConfig::new(&ToolsConfigParams { + model_info: &model_info, + features: &features, + web_search_mode: Some(WebSearchMode::Cached), + }); + let dynamic_tools = vec![DynamicToolSpec { + name: "dynamic_echo".to_string(), + description: "echo dynamic payload".to_string(), + input_schema: serde_json::json!({ + "type": "object", + "properties": { + "text": {"type": "string"} + }, + "required": ["text"], + "additionalProperties": false + }), + }]; + let (tools, _) = build_specs(&tools_config, None, &dynamic_tools).build(); + assert!( + tools.iter().any(|tool| tool.spec.name() == "dynamic_echo"), + "expected dynamic tool in full router specs" + ); + + let filtered = filter_tools_for_model( + tools.iter().map(|tool| tool.spec.clone()).collect(), + &tools_config, + ); + assert!( + !filtered + .iter() + .any(|tool| tool_name(tool) == "dynamic_echo"), + "expected dynamic tools to be hidden from direct model tools in js_repl_tools_only mode" + ); + assert_contains_tool_specs(&filtered, &["js_repl", "js_repl_reset"]); + } + fn assert_model_tools( model_slug: &str, features: &Features, diff --git a/docs/js_repl.md b/docs/js_repl.md index 2c550b4581..1b19740748 100644 --- a/docs/js_repl.md +++ b/docs/js_repl.md @@ -11,6 +11,16 @@ js_repl = true ``` +`js_repl_tools_only` can be enabled to force direct model tool calls through `js_repl`: + +```toml +[features] +js_repl = true +js_repl_tools_only = true +``` + +When enabled, direct model tool calls are restricted to `js_repl` and `js_repl_reset`; other tools remain available via `await codex.tool(...)` inside js_repl. + ## Node runtime `js_repl` requires a Node version that meets or exceeds `codex-rs/node-version.txt`. From aef4af107904aadf13dd3b68d6163ca07f3f7087 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 12 Feb 2026 15:56:43 -0800 Subject: [PATCH 4/7] app-server tests: disable shell_snapshot for review suite (#11657) ## Why `suite::v2::review::review_start_with_detached_delivery_returns_new_thread_id` was failing on Windows CI due to an unrelated process crash during shell snapshot initialization (`tokio-runtime-worker` stack overflow). This review test suite validates review API behavior and should not depend on shell snapshot behavior. Keeping shell snapshot enabled in this fixture made the test flaky for reasons outside the scenario under test. ## What Changed - Updated the review suite test config in `codex-rs/app-server/tests/suite/v2/review.rs` to set: - `shell_snapshot = false` This keeps the review tests focused on review behavior by disabling shell snapshot initialization in this fixture. ## Verification - `cargo test -p codex-app-server` - Confirmed the previously failing Windows CI job for this test now passes on this PR. --- codex-rs/app-server/tests/suite/v2/review.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/codex-rs/app-server/tests/suite/v2/review.rs b/codex-rs/app-server/tests/suite/v2/review.rs index 641a885807..05397d485d 100644 --- a/codex-rs/app-server/tests/suite/v2/review.rs +++ b/codex-rs/app-server/tests/suite/v2/review.rs @@ -438,6 +438,7 @@ model_provider = "mock_provider" [features] remote_models = false +shell_snapshot = false [model_providers.mock_provider] name = "Mock provider" From 2825ac85a809c9cae31c69d9e29640e04c640136 Mon Sep 17 00:00:00 2001 From: Michael Bolin Date: Thu, 12 Feb 2026 16:12:44 -0800 Subject: [PATCH 5/7] app-server: stabilize detached review start on Windows (#11646) ## Why `review_start_with_detached_delivery_returns_new_thread_id` has been failing on Windows CI. The failure mode is a process crash (`tokio-runtime-worker` stack overflow) during detached review setup, which causes EOF in the test harness. This test is intended to validate detached review thread identity, not shell snapshot behavior. We also still want detached review to avoid unnecessary rollout-path rediscovery when the parent thread is already loaded. ## What Changed - Updated detached review startup in `codex-rs/app-server/src/codex_message_processor.rs`: - `start_detached_review` now receives the loaded parent thread. - It prefers `parent_thread.rollout_path()`. - It falls back to `find_thread_path_by_id_str(...)` only if the in-memory path is unavailable. - Hardened the review test fixture in `codex-rs/app-server/tests/suite/v2/review.rs` by setting `shell_snapshot = false` in test config, so this test no longer depends on unrelated Windows PowerShell snapshot initialization. ## Verification - `cargo test -p codex-app-server` - Verified `suite::v2::review::review_start_with_detached_delivery_returns_new_thread_id` passes locally. ## Notes - Related context: rollout-path lookup behavior changed in #10532. --- codex-rs/app-server/src/codex_message_processor.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index aaffa266f0..f1e4b83d2c 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -5152,10 +5152,13 @@ impl CodexMessageProcessor { &mut self, request_id: &ConnectionRequestId, parent_thread_id: ThreadId, + parent_thread: Arc, review_request: ReviewRequest, display_text: &str, ) -> std::result::Result<(), JSONRPCErrorError> { - let rollout_path = + let rollout_path = if let Some(path) = parent_thread.rollout_path() { + path + } else { find_thread_path_by_id_str(&self.config.codex_home, &parent_thread_id.to_string()) .await .map_err(|err| JSONRPCErrorError { @@ -5167,7 +5170,8 @@ impl CodexMessageProcessor { code: INVALID_REQUEST_ERROR_CODE, message: format!("no rollout found for thread id {parent_thread_id}"), data: None, - })?; + })? + }; let mut config = self.config.as_ref().clone(); if let Some(review_model) = &config.review_model { @@ -5290,6 +5294,7 @@ impl CodexMessageProcessor { .start_detached_review( &request_id, parent_thread_id, + parent_thread, review_request, display_text.as_str(), ) From 8d97b5c2466e9635373e8236a3725cbf7cd7aacf Mon Sep 17 00:00:00 2001 From: Owen Lin Date: Thu, 12 Feb 2026 16:14:55 -0800 Subject: [PATCH 6/7] fix(app-server): surface more helpful errors for json-rpc (#11638) Propagate client JSON-RPC errors for app-server request callbacks. Previously a number of possible errors were collapsed to `channel closed`. Now we should be able to see the underlying client error. ### Summary This change stops masking client JSON-RPC error responses as generic callback cancellation in app-server server->client request flows. Previously, when the client responded with a JSON-RPC error, we removed the callback entry but did not send anything to the waiting oneshot receiver. Waiters then observed channel closure (for example, auth refresh request canceled: channel closed), which hid the actual client error. Now, client JSON-RPC errors are forwarded through the callback channel and handled explicitly by request consumers. ### User-visible behavior - External auth refresh now surfaces real client JSON-RPC errors when provided. - True transport/callback-drop cases still report canceled/channel-closed semantics. ### Example: client JSON-RPC error is now propagated (not masked as "canceled") When app-server asks the client to refresh ChatGPT auth tokens, it sends a server->client JSON-RPC request like: ```json { "id": 42, "method": "account/chatgptAuthTokens/refresh", "params": { "reason": "unauthorized", "previousAccountId": "org-abc" } } ``` If the client cannot refresh and responds with a JSON-RPC error: ``` { "id": 42, "error": { "code": -32000, "message": "refresh failed", "data": null } } ``` app-server now forwards that error through the callback path and surfaces: `auth refresh request failed: code=-32000 message=refresh failed` Previously, this same case could be reported as: `auth refresh request canceled: channel closed` --- .../app-server/src/bespoke_event_handling.rs | 62 ++++++++++++++++--- codex-rs/app-server/src/dynamic_tools.rs | 25 +++++++- codex-rs/app-server/src/message_processor.rs | 17 ++++- codex-rs/app-server/src/outgoing_message.rs | 55 +++++++++++++--- 4 files changed, 137 insertions(+), 22 deletions(-) diff --git a/codex-rs/app-server/src/bespoke_event_handling.rs b/codex-rs/app-server/src/bespoke_event_handling.rs index 79170e64bc..c1f36e1ef3 100644 --- a/codex-rs/app-server/src/bespoke_event_handling.rs +++ b/codex-rs/app-server/src/bespoke_event_handling.rs @@ -4,6 +4,7 @@ use crate::codex_message_processor::read_summary_from_rollout; use crate::codex_message_processor::summary_to_thread; use crate::error_code::INTERNAL_ERROR_CODE; use crate::error_code::INVALID_REQUEST_ERROR_CODE; +use crate::outgoing_message::ClientRequestResult; use crate::outgoing_message::ThreadScopedOutgoingMessageSender; use crate::thread_state::ThreadState; use crate::thread_state::TurnSummary; @@ -1408,12 +1409,25 @@ async fn handle_error( async fn on_patch_approval_response( call_id: String, - receiver: oneshot::Receiver, + receiver: oneshot::Receiver, codex: Arc, ) { let response = receiver.await; let value = match response { - Ok(value) => value, + Ok(Ok(value)) => value, + Ok(Err(err)) => { + error!("request failed with client error: {err:?}"); + if let Err(submit_err) = codex + .submit(Op::PatchApproval { + id: call_id.clone(), + decision: ReviewDecision::Denied, + }) + .await + { + error!("failed to submit denied PatchApproval after request failure: {submit_err}"); + } + return; + } Err(err) => { error!("request failed: {err:?}"); if let Err(submit_err) = codex @@ -1451,12 +1465,16 @@ async fn on_patch_approval_response( async fn on_exec_approval_response( call_id: String, turn_id: String, - receiver: oneshot::Receiver, + receiver: oneshot::Receiver, conversation: Arc, ) { let response = receiver.await; let value = match response { - Ok(value) => value, + Ok(Ok(value)) => value, + Ok(Err(err)) => { + error!("request failed with client error: {err:?}"); + return; + } Err(err) => { error!("request failed: {err:?}"); return; @@ -1488,12 +1506,28 @@ async fn on_exec_approval_response( async fn on_request_user_input_response( event_turn_id: String, - receiver: oneshot::Receiver, + receiver: oneshot::Receiver, conversation: Arc, ) { let response = receiver.await; let value = match response { - Ok(value) => value, + Ok(Ok(value)) => value, + Ok(Err(err)) => { + error!("request failed with client error: {err:?}"); + let empty = CoreRequestUserInputResponse { + answers: HashMap::new(), + }; + if let Err(err) = conversation + .submit(Op::UserInputAnswer { + id: event_turn_id, + response: empty, + }) + .await + { + error!("failed to submit UserInputAnswer: {err}"); + } + return; + } Err(err) => { error!("request failed: {err:?}"); let empty = CoreRequestUserInputResponse { @@ -1628,14 +1662,14 @@ async fn on_file_change_request_approval_response( conversation_id: ThreadId, item_id: String, changes: Vec, - receiver: oneshot::Receiver, + receiver: oneshot::Receiver, codex: Arc, outgoing: ThreadScopedOutgoingMessageSender, thread_state: Arc>, ) { let response = receiver.await; let (decision, completion_status) = match response { - Ok(value) => { + Ok(Ok(value)) => { let response = serde_json::from_value::(value) .unwrap_or_else(|err| { error!("failed to deserialize FileChangeRequestApprovalResponse: {err}"); @@ -1650,6 +1684,10 @@ async fn on_file_change_request_approval_response( // Only short-circuit on declines/cancels/failures. (decision, completion_status) } + Ok(Err(err)) => { + error!("request failed with client error: {err:?}"); + (ReviewDecision::Denied, Some(PatchApplyStatus::Failed)) + } Err(err) => { error!("request failed: {err:?}"); (ReviewDecision::Denied, Some(PatchApplyStatus::Failed)) @@ -1688,13 +1726,13 @@ async fn on_command_execution_request_approval_response( command: String, cwd: PathBuf, command_actions: Vec, - receiver: oneshot::Receiver, + receiver: oneshot::Receiver, conversation: Arc, outgoing: ThreadScopedOutgoingMessageSender, ) { let response = receiver.await; let (decision, completion_status) = match response { - Ok(value) => { + Ok(Ok(value)) => { let response = serde_json::from_value::(value) .unwrap_or_else(|err| { error!("failed to deserialize CommandExecutionRequestApprovalResponse: {err}"); @@ -1729,6 +1767,10 @@ async fn on_command_execution_request_approval_response( }; (decision, completion_status) } + Ok(Err(err)) => { + error!("request failed with client error: {err:?}"); + (ReviewDecision::Denied, Some(CommandExecutionStatus::Failed)) + } Err(err) => { error!("request failed: {err:?}"); (ReviewDecision::Denied, Some(CommandExecutionStatus::Failed)) diff --git a/codex-rs/app-server/src/dynamic_tools.rs b/codex-rs/app-server/src/dynamic_tools.rs index ed284452b4..31374d80b6 100644 --- a/codex-rs/app-server/src/dynamic_tools.rs +++ b/codex-rs/app-server/src/dynamic_tools.rs @@ -7,14 +7,35 @@ use std::sync::Arc; use tokio::sync::oneshot; use tracing::error; +use crate::outgoing_message::ClientRequestResult; + pub(crate) async fn on_call_response( call_id: String, - receiver: oneshot::Receiver, + receiver: oneshot::Receiver, conversation: Arc, ) { let response = receiver.await; let value = match response { - Ok(value) => value, + Ok(Ok(value)) => value, + Ok(Err(err)) => { + error!("request failed with client error: {err:?}"); + let fallback = CoreDynamicToolResponse { + content_items: vec![CoreDynamicToolCallOutputContentItem::InputText { + text: "dynamic tool request failed".to_string(), + }], + success: false, + }; + if let Err(err) = conversation + .submit(Op::DynamicToolResponse { + id: call_id.clone(), + response: fallback, + }) + .await + { + error!("failed to submit DynamicToolResponse: {err}"); + } + return; + } Err(err) => { error!("request failed: {err:?}"); let fallback = CoreDynamicToolResponse { diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index f4b949ed28..cb645ff3f8 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -86,9 +86,20 @@ impl ExternalAuthRefresher for ExternalAuthRefreshBridge { .await; let result = match timeout(EXTERNAL_AUTH_REFRESH_TIMEOUT, rx).await { - Ok(result) => result.map_err(|err| { - std::io::Error::other(format!("auth refresh request canceled: {err}")) - })?, + Ok(result) => { + // Two failure scenarios: + // 1) `oneshot::Receiver` failed (sender dropped) => request canceled/channel closed. + // 2) client answered with JSON-RPC error payload => propagate code/message. + let result = result.map_err(|err| { + std::io::Error::other(format!("auth refresh request canceled: {err}")) + })?; + result.map_err(|err| { + std::io::Error::other(format!( + "auth refresh request failed: code={} message={}", + err.code, err.message + )) + })? + } Err(_) => { let _canceled = self.outgoing.cancel_request(&request_id).await; return Err(std::io::Error::other(format!( diff --git a/codex-rs/app-server/src/outgoing_message.rs b/codex-rs/app-server/src/outgoing_message.rs index 45f33b49d9..2d8b748c90 100644 --- a/codex-rs/app-server/src/outgoing_message.rs +++ b/codex-rs/app-server/src/outgoing_message.rs @@ -20,6 +20,8 @@ use crate::error_code::INTERNAL_ERROR_CODE; #[cfg(test)] use codex_protocol::account::PlanType; +pub(crate) type ClientRequestResult = std::result::Result; + /// Stable identifier for a transport connection. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub(crate) struct ConnectionId(pub(crate) u64); @@ -46,7 +48,7 @@ pub(crate) enum OutgoingEnvelope { pub(crate) struct OutgoingMessageSender { next_server_request_id: AtomicI64, sender: mpsc::Sender, - request_id_to_callback: Mutex>>, + request_id_to_callback: Mutex>>, } #[derive(Clone)] @@ -69,7 +71,7 @@ impl ThreadScopedOutgoingMessageSender { pub(crate) async fn send_request( &self, payload: ServerRequestPayload, - ) -> oneshot::Receiver { + ) -> oneshot::Receiver { if self.connection_ids.is_empty() { let (_tx, rx) = oneshot::channel(); return rx; @@ -118,7 +120,7 @@ impl OutgoingMessageSender { &self, connection_ids: &[ConnectionId], request: ServerRequestPayload, - ) -> oneshot::Receiver { + ) -> oneshot::Receiver { let (_id, rx) = self .send_request_with_id_to_connections(connection_ids, request) .await; @@ -128,7 +130,7 @@ impl OutgoingMessageSender { pub(crate) async fn send_request_with_id( &self, request: ServerRequestPayload, - ) -> (RequestId, oneshot::Receiver) { + ) -> (RequestId, oneshot::Receiver) { self.send_request_with_id_to_connections(&[], request).await } @@ -136,7 +138,7 @@ impl OutgoingMessageSender { &self, connection_ids: &[ConnectionId], request: ServerRequestPayload, - ) -> (RequestId, oneshot::Receiver) { + ) -> (RequestId, oneshot::Receiver) { let id = RequestId::Integer(self.next_server_request_id.fetch_add(1, Ordering::Relaxed)); let outgoing_message_id = id.clone(); let (tx_approve, rx_approve) = oneshot::channel(); @@ -190,7 +192,7 @@ impl OutgoingMessageSender { match entry { Some((id, sender)) => { - if let Err(err) = sender.send(result) { + if let Err(err) = sender.send(Ok(result)) { warn!("could not notify callback for {id:?} due to: {err:?}"); } } @@ -207,8 +209,11 @@ impl OutgoingMessageSender { }; match entry { - Some((id, _sender)) => { + Some((id, sender)) => { warn!("client responded with error for {id:?}: {error:?}"); + if let Err(err) = sender.send(Err(error)) { + warn!("could not notify callback for {id:?} due to: {err:?}"); + } } None => { warn!("could not find callback for {id:?}"); @@ -390,11 +395,13 @@ mod tests { use codex_app_server_protocol::AccountLoginCompletedNotification; use codex_app_server_protocol::AccountRateLimitsUpdatedNotification; use codex_app_server_protocol::AccountUpdatedNotification; + use codex_app_server_protocol::ApplyPatchApprovalParams; use codex_app_server_protocol::AuthMode; use codex_app_server_protocol::ConfigWarningNotification; use codex_app_server_protocol::LoginChatGptCompleteNotification; use codex_app_server_protocol::RateLimitSnapshot; use codex_app_server_protocol::RateLimitWindow; + use codex_protocol::ThreadId; use pretty_assertions::assert_eq; use serde_json::json; use tokio::time::timeout; @@ -609,4 +616,38 @@ mod tests { other => panic!("expected targeted error envelope, got: {other:?}"), } } + + #[tokio::test] + async fn notify_client_error_forwards_error_to_waiter() { + let (tx, _rx) = mpsc::channel::(4); + let outgoing = OutgoingMessageSender::new(tx); + + let (request_id, wait_for_result) = outgoing + .send_request_with_id(ServerRequestPayload::ApplyPatchApproval( + ApplyPatchApprovalParams { + conversation_id: ThreadId::new(), + call_id: "call-id".to_string(), + file_changes: HashMap::new(), + reason: None, + grant_root: None, + }, + )) + .await; + + let error = JSONRPCErrorError { + code: INTERNAL_ERROR_CODE, + message: "refresh failed".to_string(), + data: None, + }; + + outgoing + .notify_client_error(request_id, error.clone()) + .await; + + let result = timeout(Duration::from_secs(1), wait_for_result) + .await + .expect("wait should not time out") + .expect("waiter should receive a callback"); + assert_eq!(result, Err(error)); + } } From c37560069a8c5137a3d74b0bd1b3913bf0a2c9f6 Mon Sep 17 00:00:00 2001 From: Matthew Zeng Date: Thu, 12 Feb 2026 16:30:52 -0800 Subject: [PATCH 7/7] [apps] Add is_enabled to app info. (#11417) - [x] Add is_enabled to app info and the response of `app/list`. - [x] Update TUI to have Enable/Disable button on the app detail page. --- .../schema/json/ServerNotification.json | 5 + .../codex_app_server_protocol.schemas.json | 5 + .../json/v2/AppListUpdatedNotification.json | 5 + .../schema/json/v2/AppsListResponse.json | 5 + .../schema/typescript/v2/AppInfo.ts | 11 +- .../app-server-protocol/src/protocol/v2.rs | 8 + codex-rs/app-server/README.md | 8 +- .../app-server/src/codex_message_processor.rs | 12 +- .../app-server/tests/suite/v2/app_list.rs | 89 ++++++ codex-rs/chatgpt/src/connectors.rs | 8 +- codex-rs/core/src/codex.rs | 122 +++++++- codex-rs/core/src/connectors.rs | 19 ++ .../src/tools/handlers/search_tool_bm25.rs | 151 +++++++++- codex-rs/protocol/src/protocol.rs | 6 + codex-rs/tui/src/app.rs | 133 ++++++++- codex-rs/tui/src/app_event.rs | 8 + codex-rs/tui/src/bottom_pane/app_link_view.rs | 200 +++++++++---- codex-rs/tui/src/bottom_pane/chat_composer.rs | 33 ++- codex-rs/tui/src/bottom_pane/mod.rs | 1 + codex-rs/tui/src/chatwidget.rs | 115 +++++--- codex-rs/tui/src/chatwidget/skills.rs | 6 +- codex-rs/tui/src/chatwidget/tests.rs | 269 ++++++++++++++++++ 22 files changed, 1106 insertions(+), 113 deletions(-) diff --git a/codex-rs/app-server-protocol/schema/json/ServerNotification.json b/codex-rs/app-server-protocol/schema/json/ServerNotification.json index 05667704d7..b4b271eadd 100644 --- a/codex-rs/app-server-protocol/schema/json/ServerNotification.json +++ b/codex-rs/app-server-protocol/schema/json/ServerNotification.json @@ -193,6 +193,11 @@ "default": false, "type": "boolean" }, + "isEnabled": { + "default": true, + "description": "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```", + "type": "boolean" + }, "logoUrl": { "type": [ "string", 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 5820997fb6..eba43fc5e8 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 @@ -10201,6 +10201,11 @@ "default": false, "type": "boolean" }, + "isEnabled": { + "default": true, + "description": "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```", + "type": "boolean" + }, "logoUrl": { "type": [ "string", diff --git a/codex-rs/app-server-protocol/schema/json/v2/AppListUpdatedNotification.json b/codex-rs/app-server-protocol/schema/json/v2/AppListUpdatedNotification.json index cf75f10ce0..1638472c4e 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/AppListUpdatedNotification.json +++ b/codex-rs/app-server-protocol/schema/json/v2/AppListUpdatedNotification.json @@ -29,6 +29,11 @@ "default": false, "type": "boolean" }, + "isEnabled": { + "default": true, + "description": "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```", + "type": "boolean" + }, "logoUrl": { "type": [ "string", diff --git a/codex-rs/app-server-protocol/schema/json/v2/AppsListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/AppsListResponse.json index d2b5cc5ef9..cec3da5ccc 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/AppsListResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/AppsListResponse.json @@ -29,6 +29,11 @@ "default": false, "type": "boolean" }, + "isEnabled": { + "default": true, + "description": "Whether this app is enabled in config.toml. Example: ```toml [apps.bad_app] enabled = false ```", + "type": "boolean" + }, "logoUrl": { "type": [ "string", diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/AppInfo.ts b/codex-rs/app-server-protocol/schema/typescript/v2/AppInfo.ts index 0957c0dd4f..2f65c18327 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/AppInfo.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/AppInfo.ts @@ -5,4 +5,13 @@ /** * EXPERIMENTAL - app metadata returned by app-list APIs. */ -export type AppInfo = { id: string, name: string, description: string | null, logoUrl: string | null, logoUrlDark: string | null, distributionChannel: string | null, installUrl: string | null, isAccessible: boolean, }; +export type AppInfo = { id: string, name: string, description: string | null, logoUrl: string | null, logoUrlDark: string | null, distributionChannel: string | null, installUrl: string | null, isAccessible: boolean, +/** + * Whether this app is enabled in config.toml. + * Example: + * ```toml + * [apps.bad_app] + * enabled = false + * ``` + */ +isEnabled: boolean, }; diff --git a/codex-rs/app-server-protocol/src/protocol/v2.rs b/codex-rs/app-server-protocol/src/protocol/v2.rs index 7cff3e2def..f885a33be3 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2.rs @@ -1290,6 +1290,14 @@ pub struct AppInfo { pub install_url: Option, #[serde(default)] pub is_accessible: bool, + /// Whether this app is enabled in config.toml. + /// Example: + /// ```toml + /// [apps.bad_app] + /// enabled = false + /// ``` + #[serde(default = "default_enabled")] + pub is_enabled: bool, } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema, TS)] diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 13c3fda1e4..ae450fbedb 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -763,7 +763,7 @@ To enable or disable a skill by path: ## Apps -Use `app/list` to fetch available apps (connectors). Each entry includes metadata like the app `id`, display `name`, `installUrl`, and whether it is currently accessible. +Use `app/list` to fetch available apps (connectors). Each entry includes metadata like the app `id`, display `name`, `installUrl`, whether it is currently accessible, and whether it is enabled in config. ```json { "method": "app/list", "id": 50, "params": { @@ -782,7 +782,8 @@ Use `app/list` to fetch available apps (connectors). Each entry includes metadat "logoUrlDark": null, "distributionChannel": null, "installUrl": "https://chatgpt.com/apps/demo-app/demo-app", - "isAccessible": true + "isAccessible": true, + "isEnabled": true } ], "nextCursor": null @@ -808,7 +809,8 @@ The server also emits `app/list/updated` notifications whenever either source (a "logoUrlDark": null, "distributionChannel": null, "installUrl": "https://chatgpt.com/apps/demo-app/demo-app", - "isAccessible": true + "isAccessible": true, + "isEnabled": true } ] } diff --git a/codex-rs/app-server/src/codex_message_processor.rs b/codex-rs/app-server/src/codex_message_processor.rs index f1e4b83d2c..2b5f52a155 100644 --- a/codex-rs/app-server/src/codex_message_processor.rs +++ b/codex-rs/app-server/src/codex_message_processor.rs @@ -4603,8 +4603,9 @@ impl CodexMessageProcessor { let _ = accessible_tx.send(AppListLoadResult::Accessible(result)); }); + let all_config = config.clone(); tokio::spawn(async move { - let result = connectors::list_all_connectors_with_options(&config, force_refetch) + let result = connectors::list_all_connectors_with_options(&all_config, force_refetch) .await .map_err(|err| format!("failed to list apps: {err}")); let _ = tx.send(AppListLoadResult::Directory(result)); @@ -4667,9 +4668,12 @@ impl CodexMessageProcessor { } } - let merged = Self::merge_loaded_apps( - all_connectors.as_deref(), - accessible_connectors.as_deref(), + let merged = connectors::with_app_enabled_state( + Self::merge_loaded_apps( + all_connectors.as_deref(), + accessible_connectors.as_deref(), + ), + &config, ); Self::send_app_list_updated_notification(&outgoing, merged.clone()).await; diff --git a/codex-rs/app-server/tests/suite/v2/app_list.rs b/codex-rs/app-server/tests/suite/v2/app_list.rs index 6fce729084..68d64e84d3 100644 --- a/codex-rs/app-server/tests/suite/v2/app_list.rs +++ b/codex-rs/app-server/tests/suite/v2/app_list.rs @@ -86,6 +86,7 @@ async fn list_apps_uses_thread_feature_flag_when_thread_id_is_provided() -> Resu distribution_channel: None, install_url: None, is_accessible: false, + is_enabled: true, }]; let tools = vec![connector_tool("beta", "Beta App")?]; let (server_url, server_handle) = @@ -173,6 +174,78 @@ connectors = false Ok(()) } +#[tokio::test] +async fn list_apps_reports_is_enabled_from_config() -> Result<()> { + let connectors = vec![AppInfo { + id: "beta".to_string(), + name: "Beta".to_string(), + description: Some("Beta connector".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: None, + is_accessible: false, + is_enabled: true, + }]; + let tools = vec![connector_tool("beta", "Beta App")?]; + let (server_url, server_handle) = + start_apps_server_with_delays(connectors, tools, Duration::ZERO, Duration::ZERO).await?; + + let codex_home = TempDir::new()?; + std::fs::write( + codex_home.path().join("config.toml"), + format!( + r#" +chatgpt_base_url = "{server_url}" + +[features] +connectors = true + +[apps.beta] +enabled = false +"# + ), + )?; + write_chatgpt_auth( + codex_home.path(), + ChatGptAuthFixture::new("chatgpt-token") + .account_id("account-123") + .chatgpt_user_id("user-123") + .chatgpt_account_id("account-123"), + AuthCredentialsStoreMode::File, + )?; + + let mut mcp = McpProcess::new(codex_home.path()).await?; + timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??; + + let request_id = mcp + .send_apps_list_request(AppsListParams { + limit: None, + cursor: None, + thread_id: None, + force_refetch: false, + }) + .await?; + + let response: JSONRPCResponse = timeout( + DEFAULT_TIMEOUT, + mcp.read_stream_until_response_message(RequestId::Integer(request_id)), + ) + .await??; + let AppsListResponse { + data: response_data, + next_cursor, + } = to_response(response)?; + assert!(next_cursor.is_none()); + assert_eq!(response_data.len(), 1); + assert_eq!(response_data[0].id, "beta"); + assert!(!response_data[0].is_enabled); + + server_handle.abort(); + let _ = server_handle.await; + Ok(()) +} + #[tokio::test] async fn list_apps_emits_updates_and_returns_after_both_lists_load() -> Result<()> { let connectors = vec![ @@ -185,6 +258,7 @@ async fn list_apps_emits_updates_and_returns_after_both_lists_load() -> Result<( distribution_channel: None, install_url: None, is_accessible: false, + is_enabled: true, }, AppInfo { id: "beta".to_string(), @@ -195,6 +269,7 @@ async fn list_apps_emits_updates_and_returns_after_both_lists_load() -> Result<( distribution_channel: None, install_url: None, is_accessible: false, + is_enabled: true, }, ]; @@ -239,6 +314,7 @@ async fn list_apps_emits_updates_and_returns_after_both_lists_load() -> Result<( distribution_channel: None, install_url: Some("https://chatgpt.com/apps/beta-app/beta".to_string()), is_accessible: true, + is_enabled: true, }]; let first_update = read_app_list_updated_notification(&mut mcp).await?; @@ -254,6 +330,7 @@ async fn list_apps_emits_updates_and_returns_after_both_lists_load() -> Result<( distribution_channel: None, install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), is_accessible: true, + is_enabled: true, }, AppInfo { id: "alpha".to_string(), @@ -264,6 +341,7 @@ async fn list_apps_emits_updates_and_returns_after_both_lists_load() -> Result<( distribution_channel: None, install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), is_accessible: false, + is_enabled: true, }, ]; @@ -300,6 +378,7 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { distribution_channel: None, install_url: None, is_accessible: false, + is_enabled: true, }, AppInfo { id: "beta".to_string(), @@ -310,6 +389,7 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { distribution_channel: None, install_url: None, is_accessible: false, + is_enabled: true, }, ]; @@ -358,6 +438,7 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { distribution_channel: None, install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), is_accessible: false, + is_enabled: true, }, AppInfo { id: "beta".to_string(), @@ -368,6 +449,7 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { distribution_channel: None, install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), is_accessible: false, + is_enabled: true, }, ] ); @@ -382,6 +464,7 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { distribution_channel: None, install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), is_accessible: true, + is_enabled: true, }, AppInfo { id: "alpha".to_string(), @@ -392,6 +475,7 @@ async fn list_apps_returns_connectors_with_accessible_flags() -> Result<()> { distribution_channel: None, install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), is_accessible: false, + is_enabled: true, }, ]; @@ -423,6 +507,7 @@ async fn list_apps_paginates_results() -> Result<()> { distribution_channel: None, install_url: None, is_accessible: false, + is_enabled: true, }, AppInfo { id: "beta".to_string(), @@ -433,6 +518,7 @@ async fn list_apps_paginates_results() -> Result<()> { distribution_channel: None, install_url: None, is_accessible: false, + is_enabled: true, }, ]; @@ -486,6 +572,7 @@ async fn list_apps_paginates_results() -> Result<()> { distribution_channel: None, install_url: Some("https://chatgpt.com/apps/beta/beta".to_string()), is_accessible: true, + is_enabled: true, }]; assert_eq!(first_page, expected_first); @@ -525,6 +612,7 @@ async fn list_apps_paginates_results() -> Result<()> { distribution_channel: None, install_url: Some("https://chatgpt.com/apps/alpha/alpha".to_string()), is_accessible: false, + is_enabled: true, }]; assert_eq!(second_page, expected_second); @@ -545,6 +633,7 @@ async fn list_apps_force_refetch_preserves_previous_cache_on_failure() -> Result distribution_channel: None, install_url: None, is_accessible: false, + is_enabled: true, }]; let tools = vec![connector_tool("beta", "Beta App")?]; let (server_url, server_handle) = diff --git a/codex-rs/chatgpt/src/connectors.rs b/codex-rs/chatgpt/src/connectors.rs index 6398d13d17..ac0706c841 100644 --- a/codex-rs/chatgpt/src/connectors.rs +++ b/codex-rs/chatgpt/src/connectors.rs @@ -20,6 +20,7 @@ use codex_core::connectors::connector_install_url; pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools; pub use codex_core::connectors::list_accessible_connectors_from_mcp_tools_with_options; use codex_core::connectors::merge_connectors; +pub use codex_core::connectors::with_app_enabled_state; #[derive(Debug, Deserialize)] struct DirectoryListResponse { @@ -72,7 +73,10 @@ pub async fn list_connectors(config: &Config) -> anyhow::Result> { ); let connectors = connectors_result?; let accessible = accessible_result?; - Ok(merge_connectors_with_accessible(connectors, accessible)) + Ok(with_app_enabled_state( + merge_connectors_with_accessible(connectors, accessible), + config, + )) } pub async fn list_all_connectors(config: &Config) -> anyhow::Result> { @@ -283,6 +287,7 @@ fn directory_app_to_app_info(app: DirectoryApp) -> AppInfo { distribution_channel: app.distribution_channel, install_url: None, is_accessible: false, + is_enabled: true, } } @@ -341,6 +346,7 @@ mod tests { distribution_channel: None, install_url: None, is_accessible: false, + is_enabled: true, } } diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 4405635ce3..3f2642eebe 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -114,6 +114,7 @@ use crate::client_common::Prompt; use crate::client_common::ResponseEvent; use crate::codex_thread::ThreadConfigSnapshot; use crate::compact::collect_user_messages; +use crate::config::CONFIG_TOML_FILE; use crate::config::Config; use crate::config::Constrained; use crate::config::ConstraintResult; @@ -246,6 +247,7 @@ use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; use codex_protocol::protocol::CodexErrorInfo; use codex_protocol::protocol::InitialHistory; use codex_protocol::user_input::UserInput; +use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_readiness::Readiness; use codex_utils_readiness::ReadinessFlag; @@ -1765,6 +1767,48 @@ impl Session { .clone() } + pub(crate) async fn reload_user_config_layer(&self) { + let config_toml_path = { + let state = self.state.lock().await; + state + .session_configuration + .codex_home + .join(CONFIG_TOML_FILE) + }; + + let user_config = match std::fs::read_to_string(&config_toml_path) { + Ok(contents) => match toml::from_str::(&contents) { + Ok(config) => config, + Err(err) => { + warn!("failed to parse user config while reloading layer: {err}"); + return; + } + }, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + toml::Value::Table(Default::default()) + } + Err(err) => { + warn!("failed to read user config while reloading layer: {err}"); + return; + } + }; + + let config_toml_path = match AbsolutePathBuf::try_from(config_toml_path) { + Ok(path) => path, + Err(err) => { + warn!("failed to resolve user config path while reloading layer: {err}"); + return; + } + }; + + let mut state = self.state.lock().await; + let mut config = (*state.session_configuration.original_config_do_not_use).clone(); + config.config_layer_stack = config + .config_layer_stack + .with_user_config(&config_toml_path, user_config); + state.session_configuration.original_config_do_not_use = Arc::new(config); + } + pub(crate) async fn new_default_turn_with_sub_id(&self, sub_id: String) -> Arc { let session_configuration = { let state = self.state.lock().await; @@ -3050,6 +3094,9 @@ async fn submission_loop(sess: Arc, config: Arc, rx_sub: Receiv Op::RefreshMcpServers { config } => { handlers::refresh_mcp_servers(&sess, config).await; } + Op::ReloadUserConfig => { + handlers::reload_user_config(&sess).await; + } Op::ListCustomPrompts => { handlers::list_custom_prompts(&sess, sub.id.clone()).await; } @@ -3474,6 +3521,10 @@ mod handlers { *guard = Some(refresh_config); } + pub async fn reload_user_config(sess: &Arc) { + sess.reload_user_config_layer().await; + } + pub async fn list_mcp_tools(sess: &Session, config: &Arc, sub_id: String) { let mcp_connection_manager = sess.services.mcp_connection_manager.read().await; let auth = sess.services.auth_manager.auth().await; @@ -4114,7 +4165,10 @@ pub(crate) async fn run_turn( Ok(mcp_tools) => mcp_tools, Err(_) => return None, }; - connectors::accessible_connectors_from_mcp_tools(&mcp_tools) + connectors::with_app_enabled_state( + connectors::accessible_connectors_from_mcp_tools(&mcp_tools), + &turn_context.config, + ) } else { Vec::new() }; @@ -4464,6 +4518,14 @@ fn filter_connectors_for_input( explicitly_enabled_connectors: &HashSet, skill_name_counts_lower: &HashMap, ) -> Vec { + let connectors = connectors + .into_iter() + .filter(|connector| connector.is_enabled) + .collect::>(); + if connectors.is_empty() { + return Vec::new(); + } + let user_messages = collect_user_messages(input); if user_messages.is_empty() && explicitly_enabled_connectors.is_empty() { return Vec::new(); @@ -4710,7 +4772,10 @@ async fn built_tools( let skill_name_counts_lower = skills_outcome.map_or_else(HashMap::new, |outcome| { build_skill_name_counts(&outcome.skills, &outcome.disabled_paths).1 }); - let connectors = connectors::accessible_connectors_from_mcp_tools(&mcp_tools); + let connectors = connectors::with_app_enabled_state( + connectors::accessible_connectors_from_mcp_tools(&mcp_tools), + &turn_context.config, + ); Some(filter_connectors_for_input( connectors, input, @@ -5577,6 +5642,7 @@ mod tests { distribution_channel: None, install_url: None, is_accessible: true, + is_enabled: true, } } @@ -5662,6 +5728,42 @@ mod tests { } } + #[tokio::test] + async fn reload_user_config_layer_updates_effective_apps_config() { + let (session, _turn_context) = make_session_and_context().await; + let codex_home = session.codex_home().await; + std::fs::create_dir_all(&codex_home).expect("create codex home"); + let config_toml_path = codex_home.join(CONFIG_TOML_FILE); + std::fs::write( + &config_toml_path, + "[apps.calendar]\nenabled = false\ndisabled_reason = \"user\"\n", + ) + .expect("write user config"); + + session.reload_user_config_layer().await; + + let config = session.get_config().await; + let apps_toml = config + .config_layer_stack + .effective_config() + .as_table() + .and_then(|table| table.get("apps")) + .cloned() + .expect("apps table"); + let apps = crate::config::types::AppsConfigToml::deserialize(apps_toml) + .expect("deserialize apps config"); + let app = apps + .apps + .get("calendar") + .expect("calendar app config exists"); + + assert!(!app.enabled); + assert_eq!( + app.disabled_reason, + Some(crate::config::types::AppDisabledReason::User) + ); + } + #[test] fn filter_connectors_for_input_skips_duplicate_slug_mentions() { let connectors = vec![ @@ -5699,6 +5801,22 @@ mod tests { assert_eq!(selected, Vec::new()); } + #[test] + fn filter_connectors_for_input_skips_disabled_connectors() { + let mut connector = make_connector("calendar", "Calendar"); + connector.is_enabled = false; + let input = vec![user_message("use $calendar")]; + let explicitly_enabled_connectors = HashSet::new(); + let selected = filter_connectors_for_input( + vec![connector], + &input, + &explicitly_enabled_connectors, + &HashMap::new(), + ); + + assert_eq!(selected, Vec::new()); + } + #[test] fn collect_explicit_app_ids_from_skill_items_includes_linked_mentions() { let connectors = vec![make_connector("calendar", "Calendar")]; diff --git a/codex-rs/core/src/connectors.rs b/codex-rs/core/src/connectors.rs index 1769446b66..72c5d113e3 100644 --- a/codex-rs/core/src/connectors.rs +++ b/codex-rs/core/src/connectors.rs @@ -9,6 +9,7 @@ use std::time::Instant; use async_channel::unbounded; pub use codex_app_server_protocol::AppInfo; use codex_protocol::protocol::SandboxPolicy; +use serde::Deserialize; use tokio_util::sync::CancellationToken; use tracing::warn; @@ -16,6 +17,7 @@ use crate::AuthManager; use crate::CodexAuth; use crate::SandboxState; use crate::config::Config; +use crate::config::types::AppsConfigToml; use crate::features::Feature; use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::mcp::auth::compute_auth_statuses; @@ -265,6 +267,22 @@ pub fn merge_connectors( merged } +pub fn with_app_enabled_state(mut connectors: Vec, config: &Config) -> Vec { + let apps = read_apps_config(config).map(|apps_config| apps_config.apps); + for connector in &mut connectors { + if let Some(app) = apps.as_ref().and_then(|apps| apps.get(&connector.id)) { + connector.is_enabled = app.enabled; + } + } + connectors +} + +fn read_apps_config(config: &Config) -> Option { + let effective_config = config.config_layer_stack.effective_config(); + let apps_config = effective_config.as_table()?.get("apps")?.clone(); + AppsConfigToml::deserialize(apps_config).ok() +} + fn collect_accessible_connectors(tools: I) -> Vec where I: IntoIterator)>, @@ -291,6 +309,7 @@ where distribution_channel: None, install_url: Some(connector_install_url(&connector_name, &connector_id)), is_accessible: true, + is_enabled: true, }) .collect(); accessible.sort_by(|left, right| { diff --git a/codex-rs/core/src/tools/handlers/search_tool_bm25.rs b/codex-rs/core/src/tools/handlers/search_tool_bm25.rs index 1da8a3d03f..54dd5c3ddb 100644 --- a/codex-rs/core/src/tools/handlers/search_tool_bm25.rs +++ b/codex-rs/core/src/tools/handlers/search_tool_bm25.rs @@ -2,11 +2,17 @@ use async_trait::async_trait; use bm25::Document; use bm25::Language; use bm25::SearchEngineBuilder; +use codex_app_server_protocol::AppInfo; use codex_protocol::models::FunctionCallOutputBody; use serde::Deserialize; use serde_json::json; +use std::collections::HashMap; +use std::collections::HashSet; +use crate::connectors; +use crate::features::Feature; use crate::function_tool::FunctionCallError; +use crate::mcp::CODEX_APPS_MCP_SERVER_NAME; use crate::mcp_connection_manager::ToolInfo; use crate::tools::context::ToolInvocation; use crate::tools::context::ToolOutput; @@ -76,7 +82,10 @@ impl ToolHandler for SearchToolBm25Handler { async fn handle(&self, invocation: ToolInvocation) -> Result { let ToolInvocation { - payload, session, .. + payload, + session, + turn, + .. } = invocation; let arguments = match payload { @@ -111,6 +120,15 @@ impl ToolHandler for SearchToolBm25Handler { .await .list_all_tools() .await; + let mcp_tools = if turn.config.features.enabled(Feature::Apps) { + let connectors = connectors::with_app_enabled_state( + connectors::accessible_connectors_from_mcp_tools(&mcp_tools), + &turn.config, + ); + filter_codex_apps_mcp_tools(mcp_tools, &connectors) + } else { + mcp_tools + }; let mut entries: Vec = mcp_tools .into_iter() @@ -178,6 +196,28 @@ impl ToolHandler for SearchToolBm25Handler { } } +fn filter_codex_apps_mcp_tools( + mut mcp_tools: HashMap, + connectors: &[AppInfo], +) -> HashMap { + let enabled_connectors: HashSet<&str> = connectors + .iter() + .filter(|connector| connector.is_enabled) + .map(|connector| connector.id.as_str()) + .collect(); + + mcp_tools.retain(|_, tool| { + if tool.server_name != CODEX_APPS_MCP_SERVER_NAME { + return true; + } + + tool.connector_id + .as_deref() + .is_some_and(|connector_id| enabled_connectors.contains(connector_id)) + }); + mcp_tools +} + fn build_search_text(name: &str, info: &ToolInfo, input_keys: &[String]) -> String { let mut parts = vec![ name.to_string(), @@ -215,3 +255,112 @@ fn build_search_text(name: &str, info: &ToolInfo, input_keys: &[String]) -> Stri parts.join(" ") } + +#[cfg(test)] +mod tests { + use super::*; + use codex_app_server_protocol::AppInfo; + use pretty_assertions::assert_eq; + use rmcp::model::JsonObject; + use rmcp::model::Tool; + use std::sync::Arc; + + fn make_connector(id: &str, enabled: bool) -> AppInfo { + AppInfo { + id: id.to_string(), + name: id.to_string(), + description: None, + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: None, + is_accessible: true, + is_enabled: enabled, + } + } + + fn make_tool( + qualified_name: &str, + server_name: &str, + tool_name: &str, + connector_id: Option<&str>, + ) -> (String, ToolInfo) { + ( + qualified_name.to_string(), + ToolInfo { + server_name: server_name.to_string(), + tool_name: tool_name.to_string(), + tool: Tool { + name: tool_name.to_string().into(), + title: None, + description: Some(format!("Test tool: {tool_name}").into()), + input_schema: Arc::new(JsonObject::default()), + output_schema: None, + annotations: None, + execution: None, + icons: None, + meta: None, + }, + connector_id: connector_id.map(str::to_string), + connector_name: connector_id.map(str::to_string), + }, + ) + } + + #[test] + fn filter_codex_apps_mcp_tools_keeps_non_apps_and_enabled_apps() { + let mcp_tools = HashMap::from([ + make_tool( + "mcp__codex_apps__calendar_create_event", + CODEX_APPS_MCP_SERVER_NAME, + "calendar_create_event", + Some("calendar"), + ), + make_tool( + "mcp__codex_apps__drive_search", + CODEX_APPS_MCP_SERVER_NAME, + "drive_search", + Some("drive"), + ), + make_tool("mcp__rmcp__echo", "rmcp", "echo", None), + ]); + let connectors = vec![ + make_connector("calendar", false), + make_connector("drive", true), + ]; + + let mut filtered: Vec = filter_codex_apps_mcp_tools(mcp_tools, &connectors) + .into_keys() + .collect(); + filtered.sort(); + + assert_eq!( + filtered, + vec![ + "mcp__codex_apps__drive_search".to_string(), + "mcp__rmcp__echo".to_string(), + ] + ); + } + + #[test] + fn filter_codex_apps_mcp_tools_drops_apps_without_connector_id() { + let mcp_tools = HashMap::from([ + make_tool( + "mcp__codex_apps__unknown", + CODEX_APPS_MCP_SERVER_NAME, + "unknown", + None, + ), + make_tool("mcp__rmcp__echo", "rmcp", "echo", None), + ]); + + let mut filtered: Vec = + filter_codex_apps_mcp_tools(mcp_tools, &[make_connector("calendar", true)]) + .into_keys() + .collect(); + filtered.sort(); + + assert_eq!(filtered, vec!["mcp__rmcp__echo".to_string()]); + } +} diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 745068b16e..82499c6709 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -260,6 +260,12 @@ pub enum Op { /// Request MCP servers to reinitialize and refresh cached tool lists. RefreshMcpServers { config: McpServerRefreshConfig }, + /// Reload user config layer overrides for the active session. + /// + /// This updates runtime config-derived behavior (for example app + /// enable/disable state) without restarting the thread. + ReloadUserConfig, + /// Request the list of available custom prompts. ListCustomPrompts, diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index e30d490bbb..778eedd8de 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -626,6 +626,13 @@ impl App { .wrap_err_with(|| format!("Failed to rebuild config for cwd {cwd_display}")) } + async fn refresh_in_memory_config_from_disk(&mut self) -> Result<()> { + let mut config = self.rebuild_config_for_cwd(self.config.cwd.clone()).await?; + self.apply_runtime_policy_overrides(&mut config); + self.config = config; + Ok(()) + } + fn apply_runtime_policy_overrides(&mut self, config: &mut Config) { if let Some(policy) = self.runtime_approval_policy_override.as_ref() && let Err(err) = config.permissions.approval_policy.set(*policy) @@ -1598,19 +1605,24 @@ impl App { tui.frame_requester().schedule_frame(); } AppEvent::OpenAppLink { + app_id, title, description, instructions, url, is_installed, + is_enabled, } => { - self.chat_widget.open_app_link_view( - title, - description, - instructions, - url, - is_installed, - ); + self.chat_widget + .open_app_link_view(crate::bottom_pane::AppLinkViewParams { + app_id, + title, + description, + instructions, + url, + is_installed, + is_enabled, + }); } AppEvent::OpenUrlInBrowser { url } => { self.open_url_in_browser(url); @@ -2286,6 +2298,12 @@ impl App { { Ok(()) => { self.chat_widget.update_skill_enabled(path.clone(), enabled); + if let Err(err) = self.refresh_in_memory_config_from_disk().await { + tracing::warn!( + error = %err, + "failed to refresh config after skill toggle" + ); + } } Err(err) => { let path_display = path.display(); @@ -2295,6 +2313,55 @@ impl App { } } } + AppEvent::SetAppEnabled { id, enabled } => { + let edits = if enabled { + vec![ + ConfigEdit::ClearPath { + segments: vec!["apps".to_string(), id.clone(), "enabled".to_string()], + }, + ConfigEdit::ClearPath { + segments: vec![ + "apps".to_string(), + id.clone(), + "disabled_reason".to_string(), + ], + }, + ] + } else { + vec![ + ConfigEdit::SetPath { + segments: vec!["apps".to_string(), id.clone(), "enabled".to_string()], + value: false.into(), + }, + ConfigEdit::SetPath { + segments: vec![ + "apps".to_string(), + id.clone(), + "disabled_reason".to_string(), + ], + value: "user".into(), + }, + ] + }; + match ConfigEditsBuilder::new(&self.config.codex_home) + .with_edits(edits) + .apply() + .await + { + Ok(()) => { + self.chat_widget.update_connector_enabled(&id, enabled); + if let Err(err) = self.refresh_in_memory_config_from_disk().await { + tracing::warn!(error = %err, "failed to refresh config after app toggle"); + } + self.chat_widget.submit_op(Op::ReloadUserConfig); + } + Err(err) => { + self.chat_widget.add_error_message(format!( + "Failed to update app config for {id}: {err}" + )); + } + } + } AppEvent::OpenPermissionsPopup => { self.chat_widget.open_permissions_popup(); } @@ -2929,6 +2996,19 @@ mod tests { ) } + fn app_enabled_in_effective_config(config: &Config, app_id: &str) -> Option { + config + .config_layer_stack + .effective_config() + .as_table() + .and_then(|table| table.get("apps")) + .and_then(TomlValue::as_table) + .and_then(|apps| apps.get(app_id)) + .and_then(TomlValue::as_table) + .and_then(|app| app.get("enabled")) + .and_then(TomlValue::as_bool) + } + fn all_model_presets() -> Vec { codex_core::test_support::all_model_presets().clone() } @@ -3108,6 +3188,45 @@ mod tests { ); } + #[tokio::test] + async fn refresh_in_memory_config_from_disk_loads_latest_apps_state() -> Result<()> { + let mut app = make_test_app().await; + let codex_home = tempdir()?; + app.config.codex_home = codex_home.path().to_path_buf(); + let app_id = "connector_1".to_string(); + + assert_eq!(app_enabled_in_effective_config(&app.config, &app_id), None); + + ConfigEditsBuilder::new(&app.config.codex_home) + .with_edits([ + ConfigEdit::SetPath { + segments: vec!["apps".to_string(), app_id.clone(), "enabled".to_string()], + value: false.into(), + }, + ConfigEdit::SetPath { + segments: vec![ + "apps".to_string(), + app_id.clone(), + "disabled_reason".to_string(), + ], + value: "user".into(), + }, + ]) + .apply() + .await + .expect("persist app toggle"); + + assert_eq!(app_enabled_in_effective_config(&app.config, &app_id), None); + + app.refresh_in_memory_config_from_disk().await?; + + assert_eq!( + app_enabled_in_effective_config(&app.config, &app_id), + Some(false) + ); + Ok(()) + } + #[tokio::test] async fn backtrack_selection_with_duplicate_history_targets_unique_turn() { let (mut app, _app_event_rx, mut op_rx) = make_test_app_with_channels().await; diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 67db6d7c8b..c04665eb24 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -107,11 +107,13 @@ pub(crate) enum AppEvent { /// Open the app link view in the bottom pane. OpenAppLink { + app_id: String, title: String, description: Option, instructions: String, url: String, is_installed: bool, + is_enabled: bool, }, /// Open the provided URL in the user's browser. @@ -297,6 +299,12 @@ pub(crate) enum AppEvent { enabled: bool, }, + /// Enable or disable an app by connector ID. + SetAppEnabled { + id: String, + enabled: bool, + }, + /// Notify that the manage skills popup was closed. ManageSkillsClosed, diff --git a/codex-rs/tui/src/bottom_pane/app_link_view.rs b/codex-rs/tui/src/bottom_pane/app_link_view.rs index 05ef32bfa8..698825d6f7 100644 --- a/codex-rs/tui/src/bottom_pane/app_link_view.rs +++ b/codex-rs/tui/src/bottom_pane/app_link_view.rs @@ -32,12 +32,24 @@ enum AppLinkScreen { InstallConfirmation, } +pub(crate) struct AppLinkViewParams { + pub(crate) app_id: String, + pub(crate) title: String, + pub(crate) description: Option, + pub(crate) instructions: String, + pub(crate) url: String, + pub(crate) is_installed: bool, + pub(crate) is_enabled: bool, +} + pub(crate) struct AppLinkView { + app_id: String, title: String, description: Option, instructions: String, url: String, is_installed: bool, + is_enabled: bool, app_event_tx: AppEventSender, screen: AppLinkScreen, selected_action: usize, @@ -45,20 +57,24 @@ pub(crate) struct AppLinkView { } impl AppLinkView { - pub(crate) fn new( - title: String, - description: Option, - instructions: String, - url: String, - is_installed: bool, - app_event_tx: AppEventSender, - ) -> Self { - Self { + pub(crate) fn new(params: AppLinkViewParams, app_event_tx: AppEventSender) -> Self { + let AppLinkViewParams { + app_id, title, description, instructions, url, is_installed, + is_enabled, + } = params; + Self { + app_id, + title, + description, + instructions, + url, + is_installed, + is_enabled, app_event_tx, screen: AppLinkScreen::Link, selected_action: 0, @@ -66,16 +82,24 @@ impl AppLinkView { } } - fn action_labels(&self) -> [&'static str; 2] { + fn action_labels(&self) -> Vec<&'static str> { match self.screen { AppLinkScreen::Link => { if self.is_installed { - ["Manage on ChatGPT", "Back"] + vec![ + "Manage on ChatGPT", + if self.is_enabled { + "Disable app" + } else { + "Enable app" + }, + "Back", + ] } else { - ["Install on ChatGPT", "Back"] + vec!["Install on ChatGPT", "Back"] } } - AppLinkScreen::InstallConfirmation => ["I already Installed it", "Back"], + AppLinkScreen::InstallConfirmation => vec!["I already Installed it", "Back"], } } @@ -87,42 +111,47 @@ impl AppLinkView { self.selected_action = (self.selected_action + 1).min(self.action_labels().len() - 1); } - fn handle_primary_action(&mut self) { - match self.screen { - AppLinkScreen::Link => { - self.app_event_tx.send(AppEvent::OpenUrlInBrowser { - url: self.url.clone(), - }); - if !self.is_installed { - self.screen = AppLinkScreen::InstallConfirmation; - self.selected_action = 0; - } - } - AppLinkScreen::InstallConfirmation => { - self.app_event_tx.send(AppEvent::RefreshConnectors { - force_refetch: true, - }); - self.complete = true; - } + fn open_chatgpt_link(&mut self) { + self.app_event_tx.send(AppEvent::OpenUrlInBrowser { + url: self.url.clone(), + }); + if !self.is_installed { + self.screen = AppLinkScreen::InstallConfirmation; + self.selected_action = 0; } } - fn handle_secondary_action(&mut self) { - match self.screen { - AppLinkScreen::Link => { - self.complete = true; - } - AppLinkScreen::InstallConfirmation => { - self.screen = AppLinkScreen::Link; - self.selected_action = 0; - } - } + fn refresh_connectors_and_close(&mut self) { + self.app_event_tx.send(AppEvent::RefreshConnectors { + force_refetch: true, + }); + self.complete = true; + } + + fn back_to_link_screen(&mut self) { + self.screen = AppLinkScreen::Link; + self.selected_action = 0; + } + + fn toggle_enabled(&mut self) { + self.is_enabled = !self.is_enabled; + self.app_event_tx.send(AppEvent::SetAppEnabled { + id: self.app_id.clone(), + enabled: self.is_enabled, + }); } fn activate_selected_action(&mut self) { - match self.selected_action { - 0 => self.handle_primary_action(), - _ => self.handle_secondary_action(), + match self.screen { + AppLinkScreen::Link => match self.selected_action { + 0 => self.open_chatgpt_link(), + 1 if self.is_installed => self.toggle_enabled(), + _ => self.complete = true, + }, + AppLinkScreen::InstallConfirmation => match self.selected_action { + 0 => self.refresh_connectors_and_close(), + _ => self.back_to_link_screen(), + }, } } @@ -308,20 +337,19 @@ impl BottomPaneView for AppLinkView { .. } => self.move_selection_next(), KeyEvent { - code: KeyCode::Char('1'), + code: KeyCode::Char(c), modifiers: KeyModifiers::NONE, .. } => { - self.selected_action = 0; - self.activate_selected_action(); - } - KeyEvent { - code: KeyCode::Char('2'), - modifiers: KeyModifiers::NONE, - .. - } => { - self.selected_action = 1; - self.activate_selected_action(); + if let Some(index) = c + .to_digit(10) + .and_then(|digit| digit.checked_sub(1)) + .map(|index| index as usize) + && index < self.action_labels().len() + { + self.selected_action = index; + self.activate_selected_action(); + } } KeyEvent { code: KeyCode::Enter, @@ -402,3 +430,67 @@ impl crate::render::renderable::Renderable for AppLinkView { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::app_event::AppEvent; + use tokio::sync::mpsc::unbounded_channel; + + #[test] + fn installed_app_has_toggle_action() { + let (tx_raw, _rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let view = AppLinkView::new( + AppLinkViewParams { + app_id: "connector_1".to_string(), + title: "Notion".to_string(), + description: None, + instructions: "Manage app".to_string(), + url: "https://example.test/notion".to_string(), + is_installed: true, + is_enabled: true, + }, + tx, + ); + + assert_eq!( + view.action_labels(), + vec!["Manage on ChatGPT", "Disable app", "Back"] + ); + } + + #[test] + fn toggle_action_sends_set_app_enabled_and_updates_label() { + let (tx_raw, mut rx) = unbounded_channel::(); + let tx = AppEventSender::new(tx_raw); + let mut view = AppLinkView::new( + AppLinkViewParams { + app_id: "connector_1".to_string(), + title: "Notion".to_string(), + description: None, + instructions: "Manage app".to_string(), + url: "https://example.test/notion".to_string(), + is_installed: true, + is_enabled: true, + }, + tx, + ); + + view.handle_key_event(KeyEvent::new(KeyCode::Char('2'), KeyModifiers::NONE)); + + match rx.try_recv() { + Ok(AppEvent::SetAppEnabled { id, enabled }) => { + assert_eq!(id, "connector_1"); + assert!(!enabled); + } + Ok(other) => panic!("unexpected app event: {other:?}"), + Err(err) => panic!("missing app event: {err}"), + } + + assert_eq!( + view.action_labels(), + vec!["Manage on ChatGPT", "Enable app", "Back"] + ); + } +} diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 3ceeb728c1..5ef643f777 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -3099,7 +3099,7 @@ impl ChatComposer { && let Some(snapshot) = self.connectors_snapshot.as_ref() { for connector in &snapshot.connectors { - if !connector.is_accessible { + if !connector.is_accessible || !connector.is_enabled { continue; } let display_name = connectors::connector_display_label(connector); @@ -4342,6 +4342,7 @@ mod tests { distribution_channel: None, install_url: Some("https://example.test/notion".to_string()), is_accessible: true, + is_enabled: true, }]; composer.set_connector_mentions(Some(ConnectorsSnapshot { connectors })); @@ -4355,6 +4356,36 @@ mod tests { assert_eq!(mention.path, Some("app://connector_1".to_string())); } + #[test] + fn set_connector_mentions_excludes_disabled_apps_from_mention_popup() { + let (tx, _rx) = unbounded_channel::(); + let sender = AppEventSender::new(tx); + let mut composer = ChatComposer::new( + true, + sender, + false, + "Ask Codex to do anything".to_string(), + false, + ); + composer.set_connectors_enabled(true); + composer.set_text_content("$".to_string(), Vec::new(), Vec::new()); + + let connectors = vec![AppInfo { + id: "connector_1".to_string(), + name: "Notion".to_string(), + description: Some("Workspace docs".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: Some("https://example.test/notion".to_string()), + is_accessible: true, + is_enabled: false, + }]; + composer.set_connector_mentions(Some(ConnectorsSnapshot { connectors })); + + assert!(matches!(composer.active_popup, ActivePopup::None)); + } + #[test] fn shortcut_overlay_persists_while_task_running() { use crossterm::event::KeyCode; diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 32029996ae..5ad79df691 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -44,6 +44,7 @@ mod multi_select_picker; mod request_user_input; mod status_line_setup; pub(crate) use app_link_view::AppLinkView; +pub(crate) use app_link_view::AppLinkViewParams; pub(crate) use approval_overlay::ApprovalOverlay; pub(crate) use approval_overlay::ApprovalRequest; pub(crate) use request_user_input::RequestUserInputOverlay; diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 5dc8605f55..81c9faed60 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -1141,22 +1141,8 @@ impl ChatWidget { self.request_redraw(); } - pub(crate) fn open_app_link_view( - &mut self, - title: String, - description: Option, - instructions: String, - url: String, - is_installed: bool, - ) { - let view = crate::bottom_pane::AppLinkView::new( - title, - description, - instructions, - url, - is_installed, - self.app_event_tx.clone(), - ); + pub(crate) fn open_app_link_view(&mut self, params: crate::bottom_pane::AppLinkViewParams) { + let view = crate::bottom_pane::AppLinkView::new(params, self.app_event_tx.clone()); self.bottom_pane.show_view(Box::new(view)); self.request_redraw(); } @@ -3781,7 +3767,7 @@ impl ChatWidget { if !selected_app_ids.insert(app_id.to_string()) { continue; } - if let Some(app) = apps.iter().find(|app| app.id == app_id) { + if let Some(app) = apps.iter().find(|app| app.id == app_id && app.is_enabled) { items.push(UserInput::Mention { name: app.name.clone(), path: binding.path.clone(), @@ -6414,6 +6400,7 @@ impl ChatWidget { let connector_title = connector_label.clone(); let link_description = Self::connector_description(connector); let description = Self::connector_brief_description(connector); + let status_label = Self::connector_status_label(connector); let search_value = format!("{connector_label} {}", connector.id); let mut item = SelectionItem { name: connector_label, @@ -6422,42 +6409,47 @@ impl ChatWidget { ..Default::default() }; let is_installed = connector.is_accessible; - let (selected_label, missing_label, instructions) = if connector.is_accessible { - ( - "Press Enter to view the app link.", - "App link unavailable.", - "Manage this app in your browser.", + let selected_label = if is_installed { + format!( + "{status_label}. Press Enter to open the app page to install, manage, or enable/disable this app." ) } else { - ( - "Press Enter to view the install link.", - "Install link unavailable.", - "Install this app in your browser, then reload Codex.", - ) + format!("{status_label}. Press Enter to open the app page to install this app.") + }; + let missing_label = format!("{status_label}. App link unavailable."); + let instructions = if connector.is_accessible { + "Manage this app in your browser." + } else { + "Install this app in your browser, then reload Codex." }; if let Some(install_url) = connector.install_url.clone() { + let app_id = connector.id.clone(); + let is_enabled = connector.is_enabled; let title = connector_title.clone(); let instructions = instructions.to_string(); let description = link_description.clone(); item.actions = vec![Box::new(move |tx| { tx.send(AppEvent::OpenAppLink { + app_id: app_id.clone(), title: title.clone(), description: description.clone(), instructions: instructions.clone(), url: install_url.clone(), is_installed, + is_enabled, }); })]; item.dismiss_on_select = true; - item.selected_description = Some(selected_label.to_string()); + item.selected_description = Some(selected_label); } else { + let missing_label_for_action = missing_label.clone(); item.actions = vec![Box::new(move |tx| { tx.send(AppEvent::InsertHistoryCell(Box::new( - history_cell::new_info_event(missing_label.to_string(), None), + history_cell::new_info_event(missing_label_for_action.clone(), None), ))); })]; item.dismiss_on_select = true; - item.selected_description = Some(missing_label.to_string()); + item.selected_description = Some(missing_label); } items.push(item); } @@ -6490,17 +6482,25 @@ impl ChatWidget { } fn connector_brief_description(connector: &connectors::AppInfo) -> String { - let status_label = if connector.is_accessible { - "Connected" - } else { - "Can be installed" - }; + let status_label = Self::connector_status_label(connector); match Self::connector_description(connector) { Some(description) => format!("{status_label} · {description}"), None => status_label.to_string(), } } + fn connector_status_label(connector: &connectors::AppInfo) -> &'static str { + if connector.is_accessible { + if connector.is_enabled { + "Installed" + } else { + "Installed · Disabled" + } + } else { + "Can be installed" + } + } + fn connector_description(connector: &connectors::AppInfo) -> Option { connector .description @@ -6727,7 +6727,27 @@ impl ChatWidget { } match result { - Ok(snapshot) => { + Ok(mut snapshot) => { + if !is_final { + snapshot.connectors = connectors::merge_connectors_with_accessible( + Vec::new(), + snapshot.connectors, + ); + } + snapshot.connectors = + connectors::with_app_enabled_state(snapshot.connectors, &self.config); + if let ConnectorsCacheState::Ready(existing_snapshot) = &self.connectors_cache { + let enabled_by_id: HashMap<&str, bool> = existing_snapshot + .connectors + .iter() + .map(|connector| (connector.id.as_str(), connector.is_enabled)) + .collect(); + for connector in &mut snapshot.connectors { + if let Some(is_enabled) = enabled_by_id.get(connector.id.as_str()) { + connector.is_enabled = *is_enabled; + } + } + } self.refresh_connectors_popup_if_open(&snapshot.connectors); if is_final || !matches!(self.connectors_cache, ConnectorsCacheState::Ready(_)) { self.connectors_cache = ConnectorsCacheState::Ready(snapshot.clone()); @@ -6746,6 +6766,29 @@ impl ChatWidget { } } + pub(crate) fn update_connector_enabled(&mut self, connector_id: &str, enabled: bool) { + let ConnectorsCacheState::Ready(mut snapshot) = self.connectors_cache.clone() else { + return; + }; + + let mut changed = false; + for connector in &mut snapshot.connectors { + if connector.id == connector_id { + changed = connector.is_enabled != enabled; + connector.is_enabled = enabled; + break; + } + } + + if !changed { + return; + } + + self.refresh_connectors_popup_if_open(&snapshot.connectors); + self.connectors_cache = ConnectorsCacheState::Ready(snapshot.clone()); + self.bottom_pane.set_connectors_snapshot(Some(snapshot)); + } + pub(crate) fn open_review_popup(&mut self) { let mut items: Vec = Vec::new(); diff --git a/codex-rs/tui/src/chatwidget/skills.rs b/codex-rs/tui/src/chatwidget/skills.rs index ba8dab416d..6ec4aefa6d 100644 --- a/codex-rs/tui/src/chatwidget/skills.rs +++ b/codex-rs/tui/src/chatwidget/skills.rs @@ -267,12 +267,12 @@ pub(crate) fn find_app_mentions( } let mut slug_counts: HashMap = HashMap::new(); - for app in apps { + for app in apps.iter().filter(|app| app.is_enabled) { let slug = connector_mention_slug(app); *slug_counts.entry(slug).or_insert(0) += 1; } - for app in apps { + for app in apps.iter().filter(|app| app.is_enabled) { let slug = connector_mention_slug(app); let slug_count = slug_counts.get(&slug).copied().unwrap_or(0); if mentions.names.contains(&slug) @@ -285,7 +285,7 @@ pub(crate) fn find_app_mentions( } apps.iter() - .filter(|app| selected_ids.contains(&app.id)) + .filter(|app| app.is_enabled && selected_ids.contains(&app.id)) .cloned() .collect() } diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index 82b22790f0..1ff7fc14c1 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -3878,6 +3878,7 @@ async fn apps_popup_refreshes_when_connectors_snapshot_updates() { distribution_channel: None, install_url: Some("https://example.test/notion".to_string()), is_accessible: true, + is_enabled: true, }], }), false, @@ -3893,6 +3894,10 @@ async fn apps_popup_refreshes_when_connectors_snapshot_updates() { before.contains("Installed 1 of 1 available apps."), "expected initial apps popup snapshot, got:\n{before}" ); + assert!( + before.contains("Installed. Press Enter to open the app page"), + "expected selected app description to explain the app page action, got:\n{before}" + ); chat.on_connectors_loaded( Ok(ConnectorsSnapshot { @@ -3906,6 +3911,7 @@ async fn apps_popup_refreshes_when_connectors_snapshot_updates() { distribution_channel: None, install_url: Some("https://example.test/notion".to_string()), is_accessible: true, + is_enabled: true, }, codex_chatgpt::connectors::AppInfo { id: "connector_2".to_string(), @@ -3916,6 +3922,7 @@ async fn apps_popup_refreshes_when_connectors_snapshot_updates() { distribution_channel: None, install_url: Some("https://example.test/linear".to_string()), is_accessible: true, + is_enabled: true, }, ], }), @@ -3949,6 +3956,7 @@ async fn apps_refresh_failure_keeps_existing_full_snapshot() { distribution_channel: None, install_url: Some("https://example.test/notion".to_string()), is_accessible: true, + is_enabled: true, }, codex_chatgpt::connectors::AppInfo { id: "connector_2".to_string(), @@ -3959,6 +3967,7 @@ async fn apps_refresh_failure_keeps_existing_full_snapshot() { distribution_channel: None, install_url: Some("https://example.test/linear".to_string()), is_accessible: false, + is_enabled: true, }, ]; chat.on_connectors_loaded( @@ -3979,6 +3988,7 @@ async fn apps_refresh_failure_keeps_existing_full_snapshot() { distribution_channel: None, install_url: Some("https://example.test/notion".to_string()), is_accessible: true, + is_enabled: true, }], }), false, @@ -3998,6 +4008,265 @@ async fn apps_refresh_failure_keeps_existing_full_snapshot() { ); } +#[tokio::test] +async fn apps_partial_refresh_uses_same_filtering_as_full_refresh() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + chat.config.features.enable(Feature::Apps); + chat.bottom_pane.set_connectors_enabled(true); + + let full_connectors = vec![ + codex_chatgpt::connectors::AppInfo { + id: "unit_test_connector_1".to_string(), + name: "Notion".to_string(), + description: Some("Workspace docs".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: Some("https://example.test/notion".to_string()), + is_accessible: true, + is_enabled: true, + }, + codex_chatgpt::connectors::AppInfo { + id: "unit_test_connector_2".to_string(), + name: "Linear".to_string(), + description: Some("Project tracking".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: Some("https://example.test/linear".to_string()), + is_accessible: false, + is_enabled: true, + }, + ]; + chat.on_connectors_loaded( + Ok(ConnectorsSnapshot { + connectors: full_connectors.clone(), + }), + true, + ); + chat.add_connectors_output(); + + chat.on_connectors_loaded( + Ok(ConnectorsSnapshot { + connectors: vec![ + codex_chatgpt::connectors::AppInfo { + id: "unit_test_connector_1".to_string(), + name: "Notion".to_string(), + description: Some("Workspace docs".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: Some("https://example.test/notion".to_string()), + is_accessible: true, + is_enabled: true, + }, + codex_chatgpt::connectors::AppInfo { + id: "connector_openai_hidden".to_string(), + name: "Hidden OpenAI".to_string(), + description: Some("Should be filtered".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: Some("https://example.test/hidden-openai".to_string()), + is_accessible: true, + is_enabled: true, + }, + ], + }), + false, + ); + + assert_matches!( + &chat.connectors_cache, + ConnectorsCacheState::Ready(snapshot) if snapshot.connectors == full_connectors + ); + + let popup = render_bottom_popup(&chat, 80); + assert!( + popup.contains("Installed 1 of 1 available apps."), + "expected partial refresh popup to use filtered connectors, got:\n{popup}" + ); + assert!( + !popup.contains("Hidden OpenAI"), + "expected disallowed connector to be filtered from partial refresh popup, got:\n{popup}" + ); +} + +#[tokio::test] +async fn apps_popup_shows_disabled_status_for_installed_but_disabled_apps() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + chat.config.features.enable(Feature::Apps); + chat.bottom_pane.set_connectors_enabled(true); + + chat.on_connectors_loaded( + Ok(ConnectorsSnapshot { + connectors: vec![codex_chatgpt::connectors::AppInfo { + id: "connector_1".to_string(), + name: "Notion".to_string(), + description: Some("Workspace docs".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: Some("https://example.test/notion".to_string()), + is_accessible: true, + is_enabled: false, + }], + }), + true, + ); + + chat.add_connectors_output(); + let popup = render_bottom_popup(&chat, 80); + assert!( + popup.contains("Installed · Disabled. Press Enter to open the app page"), + "expected selected app description to include disabled status, got:\n{popup}" + ); + assert!( + popup.contains("enable/disable this app."), + "expected selected app description to mention enable/disable action, got:\n{popup}" + ); +} + +#[tokio::test] +async fn apps_initial_load_applies_enabled_state_from_config() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + chat.config.features.enable(Feature::Apps); + chat.bottom_pane.set_connectors_enabled(true); + + let temp = tempdir().expect("tempdir"); + let config_toml_path = + AbsolutePathBuf::try_from(temp.path().join("config.toml")).expect("absolute config path"); + let user_config = toml::from_str::( + "[apps.connector_1]\nenabled = false\ndisabled_reason = \"user\"\n", + ) + .expect("apps config"); + chat.config.config_layer_stack = chat + .config + .config_layer_stack + .with_user_config(&config_toml_path, user_config); + + chat.on_connectors_loaded( + Ok(ConnectorsSnapshot { + connectors: vec![codex_chatgpt::connectors::AppInfo { + id: "connector_1".to_string(), + name: "Notion".to_string(), + description: Some("Workspace docs".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: Some("https://example.test/notion".to_string()), + is_accessible: true, + is_enabled: true, + }], + }), + true, + ); + + assert_matches!( + &chat.connectors_cache, + ConnectorsCacheState::Ready(snapshot) + if snapshot + .connectors + .iter() + .find(|connector| connector.id == "connector_1") + .is_some_and(|connector| !connector.is_enabled) + ); +} + +#[tokio::test] +async fn apps_refresh_preserves_toggled_enabled_state() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + chat.config.features.enable(Feature::Apps); + chat.bottom_pane.set_connectors_enabled(true); + + chat.on_connectors_loaded( + Ok(ConnectorsSnapshot { + connectors: vec![codex_chatgpt::connectors::AppInfo { + id: "connector_1".to_string(), + name: "Notion".to_string(), + description: Some("Workspace docs".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: Some("https://example.test/notion".to_string()), + is_accessible: true, + is_enabled: true, + }], + }), + true, + ); + chat.update_connector_enabled("connector_1", false); + + chat.on_connectors_loaded( + Ok(ConnectorsSnapshot { + connectors: vec![codex_chatgpt::connectors::AppInfo { + id: "connector_1".to_string(), + name: "Notion".to_string(), + description: Some("Workspace docs".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: Some("https://example.test/notion".to_string()), + is_accessible: true, + is_enabled: true, + }], + }), + true, + ); + + assert_matches!( + &chat.connectors_cache, + ConnectorsCacheState::Ready(snapshot) + if snapshot + .connectors + .iter() + .find(|connector| connector.id == "connector_1") + .is_some_and(|connector| !connector.is_enabled) + ); + + chat.add_connectors_output(); + let popup = render_bottom_popup(&chat, 80); + assert!( + popup.contains("Installed · Disabled. Press Enter to open the app page"), + "expected disabled status to persist after reload, got:\n{popup}" + ); +} + +#[tokio::test] +async fn apps_popup_for_not_installed_app_uses_install_only_selected_description() { + let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await; + chat.config.features.enable(Feature::Apps); + chat.bottom_pane.set_connectors_enabled(true); + + chat.on_connectors_loaded( + Ok(ConnectorsSnapshot { + connectors: vec![codex_chatgpt::connectors::AppInfo { + id: "connector_2".to_string(), + name: "Linear".to_string(), + description: Some("Project tracking".to_string()), + logo_url: None, + logo_url_dark: None, + distribution_channel: None, + install_url: Some("https://example.test/linear".to_string()), + is_accessible: false, + is_enabled: true, + }], + }), + true, + ); + + chat.add_connectors_output(); + let popup = render_bottom_popup(&chat, 80); + assert!( + popup.contains("Can be installed. Press Enter to open the app page to install"), + "expected selected app description to be install-only for not-installed apps, got:\n{popup}" + ); + assert!( + !popup.contains("enable/disable this app."), + "did not expect enable/disable text for not-installed apps, got:\n{popup}" + ); +} + #[tokio::test] async fn experimental_features_popup_snapshot() { let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;