refactor ambiguous bool and option helper APIs

Replace several comment-heavy helper APIs with clearer shapes.
Use named methods for TUI navigation and feature toggles, add
explicit cache and shell startup types, and split default config
loading and input or thread activation helpers into clearer entry
points.

This trims many /*arg=*/ comments from the follow-up branch while
keeping the argument comment lint for one-off literal call sites.

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Josh McKinney
2026-03-13 21:54:16 -07:00
co-authored by Codex
parent 7e41132334
commit 5152b2ff65
26 changed files with 423 additions and 256 deletions
@@ -446,7 +446,7 @@ impl CodexMessageProcessor {
}
pub(crate) async fn maybe_start_curated_repo_sync_for_latest_config(&self) {
match self.load_latest_config(/*fallback_cwd=*/ None).await {
match self.load_latest_config().await {
Ok(config) => self
.thread_manager
.plugins_manager()
@@ -519,7 +519,11 @@ impl CodexMessageProcessor {
}
}
async fn load_latest_config(
async fn load_latest_config(&self) -> Result<Config, JSONRPCErrorError> {
self.load_latest_config_with_fallback_cwd(None).await
}
async fn load_latest_config_with_fallback_cwd(
&self,
fallback_cwd: Option<PathBuf>,
) -> Result<Config, JSONRPCErrorError> {
@@ -4394,7 +4398,7 @@ impl CodexMessageProcessor {
params: ExperimentalFeatureListParams,
) {
let ExperimentalFeatureListParams { cursor, limit } = params;
let config = match self.load_latest_config(/*fallback_cwd=*/ None).await {
let config = match self.load_latest_config().await {
Ok(config) => config,
Err(error) => {
self.outgoing.send_error(request_id, error).await;
@@ -4509,7 +4513,7 @@ impl CodexMessageProcessor {
}
async fn mcp_server_refresh(&self, request_id: ConnectionRequestId, _params: Option<()>) {
let config = match self.load_latest_config(/*fallback_cwd=*/ None).await {
let config = match self.load_latest_config().await {
Ok(config) => config,
Err(error) => {
self.outgoing.send_error(request_id, error).await;
@@ -4568,7 +4572,7 @@ impl CodexMessageProcessor {
request_id: ConnectionRequestId,
params: McpServerOauthLoginParams,
) {
let config = match self.load_latest_config(/*fallback_cwd=*/ None).await {
let config = match self.load_latest_config().await {
Ok(config) => config,
Err(error) => {
self.outgoing.send_error(request_id, error).await;
@@ -4680,7 +4684,7 @@ impl CodexMessageProcessor {
let request = request_id.clone();
let outgoing = Arc::clone(&self.outgoing);
let config = match self.load_latest_config(/*fallback_cwd=*/ None).await {
let config = match self.load_latest_config().await {
Ok(config) => config,
Err(error) => {
self.outgoing.send_error(request, error).await;
@@ -5088,7 +5092,7 @@ impl CodexMessageProcessor {
}
async fn apps_list(&self, request_id: ConnectionRequestId, params: AppsListParams) {
let mut config = match self.load_latest_config(/*fallback_cwd=*/ None).await {
let mut config = match self.load_latest_config().await {
Ok(config) => config,
Err(error) => {
self.outgoing.send_error(request_id, error).await;
@@ -5180,9 +5184,15 @@ impl CodexMessageProcessor {
let all_config = config.clone();
tokio::spawn(async move {
let result = connectors::list_all_connectors_with_options(&all_config, force_refetch)
.await
.map_err(|err| format!("failed to list apps: {err}"));
let cache_policy = if force_refetch {
connectors::CachePolicy::ForceRefresh
} else {
connectors::CachePolicy::UseCache
};
let result =
connectors::list_all_connectors_with_cache_policy(&all_config, cache_policy)
.await
.map_err(|err| format!("failed to list apps: {err}"));
let _ = tx.send(AppListLoadResult::Directory(result));
});
@@ -5385,7 +5395,7 @@ impl CodexMessageProcessor {
} = params;
let roots = cwds.unwrap_or_default();
let mut config = match self.load_latest_config(/*fallback_cwd=*/ None).await {
let mut config = match self.load_latest_config().await {
Ok(config) => config,
Err(err) => {
self.outgoing.send_error(request_id, err).await;
@@ -5418,7 +5428,7 @@ impl CodexMessageProcessor {
}
}
config = match self.load_latest_config(/*fallback_cwd=*/ None).await {
config = match self.load_latest_config().await {
Ok(config) => config,
Err(err) => {
self.outgoing.send_error(request_id, err).await;
@@ -5490,7 +5500,7 @@ impl CodexMessageProcessor {
} = params;
let config_cwd = marketplace_path.as_path().parent().map(Path::to_path_buf);
let config = match self.load_latest_config(config_cwd).await {
let config = match self.load_latest_config_with_fallback_cwd(config_cwd).await {
Ok(config) => config,
Err(err) => {
self.outgoing.send_error(request_id, err).await;
@@ -5672,7 +5682,7 @@ impl CodexMessageProcessor {
match plugins_manager.install_plugin(request).await {
Ok(result) => {
let config = match self.load_latest_config(config_cwd).await {
let config = match self.load_latest_config_with_fallback_cwd(config_cwd).await {
Ok(config) => config,
Err(err) => {
warn!(
@@ -5688,7 +5698,10 @@ impl CodexMessageProcessor {
Vec::new()
} else {
let (all_connectors_result, accessible_connectors_result) = tokio::join!(
connectors::list_all_connectors_with_options(&config, /*force_refetch=*/ true),
connectors::list_all_connectors_with_cache_policy(
&config,
connectors::CachePolicy::ForceRefresh
),
connectors::list_accessible_connectors_from_mcp_tools_with_options_and_status(
&config, /*force_refetch=*/ true
),
@@ -15,8 +15,9 @@ pub(super) async fn load_plugin_app_summaries(
return Vec::new();
}
let connectors = match connectors::list_all_connectors_with_options(
config, /*force_refetch=*/ false,
let connectors = match connectors::list_all_connectors_with_cache_policy(
config,
connectors::CachePolicy::UseCache,
)
.await
{
+16 -6
View File
@@ -8,7 +8,10 @@ use crate::chatgpt_client::chatgpt_get_request_with_timeout;
use crate::chatgpt_token::get_chatgpt_token_data;
use crate::chatgpt_token::init_chatgpt_token_from_auth;
use codex_connectors::AccountScope;
use codex_connectors::AllConnectorsCacheKey;
pub use codex_connectors::CachePolicy;
use codex_connectors::ConnectorListOptions;
use codex_connectors::DirectoryListResponse;
pub use codex_core::connectors::AppInfo;
@@ -53,7 +56,7 @@ pub async fn list_connectors(config: &Config) -> anyhow::Result<Vec<AppInfo>> {
}
pub async fn list_all_connectors(config: &Config) -> anyhow::Result<Vec<AppInfo>> {
list_all_connectors_with_options(config, /*force_refetch=*/ false).await
list_all_connectors_with_cache_policy(config, CachePolicy::UseCache).await
}
pub async fn list_cached_all_connectors(config: &Config) -> Option<Vec<AppInfo>> {
@@ -75,9 +78,9 @@ pub async fn list_cached_all_connectors(config: &Config) -> Option<Vec<AppInfo>>
})
}
pub async fn list_all_connectors_with_options(
pub async fn list_all_connectors_with_cache_policy(
config: &Config,
force_refetch: bool,
cache_policy: CachePolicy,
) -> anyhow::Result<Vec<AppInfo>> {
if !apps_enabled(config).await {
return Ok(Vec::new());
@@ -88,10 +91,17 @@ pub async fn list_all_connectors_with_options(
let token_data =
get_chatgpt_token_data().ok_or_else(|| anyhow::anyhow!("ChatGPT token not available"))?;
let cache_key = all_connectors_cache_key(config, &token_data);
let connectors = codex_connectors::list_all_connectors_with_options(
let account_scope = if token_data.id_token.is_workspace_account() {
AccountScope::IncludeWorkspace
} else {
AccountScope::PersonalOnly
};
let connectors = codex_connectors::list_all_connectors(
cache_key,
token_data.id_token.is_workspace_account(),
force_refetch,
ConnectorListOptions {
account_scope,
cache_policy,
},
|path| async move {
chatgpt_get_request_with_timeout::<DirectoryListResponse>(
config,
+2 -2
View File
@@ -841,7 +841,7 @@ async fn enable_feature_in_config(interactive: &TuiCli, feature: &str) -> anyhow
let codex_home = find_codex_home()?;
ConfigEditsBuilder::new(&codex_home)
.with_profile(interactive.config_profile.as_deref())
.set_feature_enabled(feature, /*enabled=*/ true)
.enable_feature(feature)
.apply()
.await?;
println!("Enabled feature `{feature}` in config.toml.");
@@ -854,7 +854,7 @@ async fn disable_feature_in_config(interactive: &TuiCli, feature: &str) -> anyho
let codex_home = find_codex_home()?;
ConfigEditsBuilder::new(&codex_home)
.with_profile(interactive.config_profile.as_deref())
.set_feature_enabled(feature, /*enabled=*/ false)
.disable_feature(feature)
.apply()
.await?;
println!("Disabled feature `{feature}` in config.toml.");
+91 -51
View File
@@ -12,6 +12,24 @@ use serde::Deserialize;
pub const CONNECTORS_CACHE_TTL: Duration = Duration::from_secs(3600);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AccountScope {
PersonalOnly,
IncludeWorkspace,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CachePolicy {
UseCache,
ForceRefresh,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ConnectorListOptions {
pub account_scope: AccountScope,
pub cache_policy: CachePolicy,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AllConnectorsCacheKey {
chatgpt_base_url: String,
@@ -89,22 +107,23 @@ pub fn cached_all_connectors(cache_key: &AllConnectorsCacheKey) -> Option<Vec<Ap
None
}
pub async fn list_all_connectors_with_options<F, Fut>(
pub async fn list_all_connectors<F, Fut>(
cache_key: AllConnectorsCacheKey,
is_workspace_account: bool,
force_refetch: bool,
options: ConnectorListOptions,
mut fetch_page: F,
) -> anyhow::Result<Vec<AppInfo>>
where
F: FnMut(String) -> Fut,
Fut: Future<Output = anyhow::Result<DirectoryListResponse>>,
{
if !force_refetch && let Some(cached_connectors) = cached_all_connectors(&cache_key) {
if matches!(options.cache_policy, CachePolicy::UseCache)
&& let Some(cached_connectors) = cached_all_connectors(&cache_key)
{
return Ok(cached_connectors);
}
let mut apps = list_directory_connectors(&mut fetch_page).await?;
if is_workspace_account {
if matches!(options.account_scope, AccountScope::IncludeWorkspace) {
apps.extend(list_workspace_connectors(&mut fetch_page).await?);
}
@@ -444,21 +463,35 @@ mod tests {
let call_counter = Arc::clone(&calls);
let key = cache_key("shared");
let first = list_all_connectors_with_options(key.clone(), false, false, move |_path| {
let call_counter = Arc::clone(&call_counter);
async move {
call_counter.fetch_add(1, Ordering::SeqCst);
Ok(DirectoryListResponse {
apps: vec![app("alpha", "Alpha")],
next_token: None,
})
}
})
let first = list_all_connectors(
key.clone(),
ConnectorListOptions {
account_scope: AccountScope::PersonalOnly,
cache_policy: CachePolicy::UseCache,
},
move |_path| {
let call_counter = Arc::clone(&call_counter);
async move {
call_counter.fetch_add(1, Ordering::SeqCst);
Ok(DirectoryListResponse {
apps: vec![app("alpha", "Alpha")],
next_token: None,
})
}
},
)
.await?;
let second = list_all_connectors_with_options(key, false, false, move |_path| async move {
anyhow::bail!("cache should have been used");
})
let second = list_all_connectors(
key,
ConnectorListOptions {
account_scope: AccountScope::PersonalOnly,
cache_policy: CachePolicy::UseCache,
},
move |_path| async move {
anyhow::bail!("cache should have been used");
},
)
.await?;
assert_eq!(calls.load(Ordering::SeqCst), 1);
@@ -472,40 +505,47 @@ mod tests {
let calls = Arc::new(AtomicUsize::new(0));
let call_counter = Arc::clone(&calls);
let connectors = list_all_connectors_with_options(key, true, true, move |path| {
let call_counter = Arc::clone(&call_counter);
async move {
call_counter.fetch_add(1, Ordering::SeqCst);
if path.starts_with("/connectors/directory/list_workspace") {
Ok(DirectoryListResponse {
apps: vec![
DirectoryApp {
description: Some("Merged description".to_string()),
branding: Some(AppBranding {
category: Some("calendar".to_string()),
developer: None,
website: None,
privacy_policy: None,
terms_of_service: None,
is_discoverable_app: true,
}),
..app("alpha", "")
},
DirectoryApp {
visibility: Some("HIDDEN".to_string()),
..app("hidden", "Hidden")
},
],
next_token: None,
})
} else {
Ok(DirectoryListResponse {
apps: vec![app("alpha", " Alpha "), app("beta", "Beta")],
next_token: None,
})
let connectors = list_all_connectors(
key,
ConnectorListOptions {
account_scope: AccountScope::IncludeWorkspace,
cache_policy: CachePolicy::ForceRefresh,
},
move |path| {
let call_counter = Arc::clone(&call_counter);
async move {
call_counter.fetch_add(1, Ordering::SeqCst);
if path.starts_with("/connectors/directory/list_workspace") {
Ok(DirectoryListResponse {
apps: vec![
DirectoryApp {
description: Some("Merged description".to_string()),
branding: Some(AppBranding {
category: Some("calendar".to_string()),
developer: None,
website: None,
privacy_policy: None,
terms_of_service: None,
is_discoverable_app: true,
}),
..app("alpha", "")
},
DirectoryApp {
visibility: Some("HIDDEN".to_string()),
..app("hidden", "Hidden")
},
],
next_token: None,
})
} else {
Ok(DirectoryListResponse {
apps: vec![app("alpha", " Alpha "), app("beta", "Beta")],
next_token: None,
})
}
}
}
})
},
)
.await?;
assert_eq!(calls.load(Ordering::SeqCst), 2);
+2 -2
View File
@@ -264,6 +264,7 @@ use crate::rollout::map_session_init_error;
use crate::rollout::metadata;
use crate::rollout::policy::EventPersistenceMode;
use crate::shell;
use crate::shell::ShellStartupMode;
use crate::shell_snapshot::ShellSnapshot;
use crate::skills::SkillError;
use crate::skills::SkillInjections;
@@ -1696,8 +1697,7 @@ impl Session {
(None, None)
};
let mut hook_shell_argv =
default_shell.derive_exec_args("", /*use_login_shell=*/ false);
let mut hook_shell_argv = default_shell.derive_exec_args("", ShellStartupMode::NonLogin);
let hook_shell_program = hook_shell_argv.remove(0);
let _ = hook_shell_argv.pop();
let hooks = Hooks::new(HooksConfig {
+12 -3
View File
@@ -857,11 +857,20 @@ impl ConfigEditsBuilder {
self
}
/// Enable or disable a feature flag by key under the `[features]` table.
pub fn set_feature_enabled(mut self, key: &str, enabled: bool) -> Self {
/// Enable a feature flag by key under the `[features]` table.
pub fn enable_feature(mut self, key: &str) -> Self {
self.edits.push(ConfigEdit::SetPath {
segments: vec!["features".to_string(), key.to_string()],
value: value(enabled),
value: value(true),
});
self
}
/// Disable a feature flag by key under the `[features]` table.
pub fn disable_feature(mut self, key: &str) -> Self {
self.edits.push(ConfigEdit::SetPath {
segments: vec!["features".to_string(), key.to_string()],
value: value(false),
});
self
}
+9 -3
View File
@@ -412,10 +412,16 @@ async fn list_directory_connectors_for_tool_suggest_with_auth(
is_workspace_account,
);
codex_connectors::list_all_connectors_with_options(
codex_connectors::list_all_connectors(
cache_key,
is_workspace_account,
/*force_refetch=*/ false,
codex_connectors::ConnectorListOptions {
account_scope: if is_workspace_account {
codex_connectors::AccountScope::IncludeWorkspace
} else {
codex_connectors::AccountScope::PersonalOnly
},
cache_policy: codex_connectors::CachePolicy::UseCache,
},
|path| {
let access_token = access_token.clone();
let account_id = account_id.clone();
+5 -4
View File
@@ -1,5 +1,6 @@
use crate::is_safe_command::is_known_safe_command;
use crate::parse_command::parse_command;
use crate::shell::ShellStartupMode;
use crate::tools::context::ToolInvocation;
use crate::tools::context::ToolPayload;
use crate::tools::handlers::unified_exec::ExecCommandArgs;
@@ -90,10 +91,10 @@ fn shell_command_for_invocation(invocation: &ToolInvocation) -> Option<(Vec<Stri
let use_login_shell = params
.login
.unwrap_or(invocation.turn.tools_config.allow_login_shell);
let command = invocation
.session
.user_shell()
.derive_exec_args(&params.command, use_login_shell);
let command = invocation.session.user_shell().derive_exec_args(
&params.command,
ShellStartupMode::from_login_shell(use_login_shell),
);
(command, invocation.turn.resolve_path(params.workdir))
}),
"exec_command" => serde_json::from_str::<ExecCommandArgs>(arguments)
+23 -3
View File
@@ -15,6 +15,22 @@ pub enum ShellType {
Cmd,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ShellStartupMode {
Login,
NonLogin,
}
impl ShellStartupMode {
pub fn from_login_shell(use_login_shell: bool) -> Self {
if use_login_shell {
Self::Login
} else {
Self::NonLogin
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Shell {
pub(crate) shell_type: ShellType,
@@ -40,10 +56,14 @@ impl Shell {
/// Takes a string of shell and returns the full list of command args to
/// use with `exec()` to run the shell command.
pub fn derive_exec_args(&self, command: &str, use_login_shell: bool) -> Vec<String> {
pub fn derive_exec_args(&self, command: &str, startup_mode: ShellStartupMode) -> Vec<String> {
match self.shell_type {
ShellType::Zsh | ShellType::Bash | ShellType::Sh => {
let arg = if use_login_shell { "-lc" } else { "-c" };
let arg = if matches!(startup_mode, ShellStartupMode::Login) {
"-lc"
} else {
"-c"
};
vec![
self.shell_path.to_string_lossy().to_string(),
arg.to_string(),
@@ -52,7 +72,7 @@ impl Shell {
}
ShellType::PowerShell => {
let mut args = vec![self.shell_path.to_string_lossy().to_string()];
if !use_login_shell {
if matches!(startup_mode, ShellStartupMode::NonLogin) {
args.push("-NoProfile".to_string());
}
+2 -1
View File
@@ -8,6 +8,7 @@ use std::time::SystemTime;
use crate::rollout::list::find_thread_path_by_id_str;
use crate::shell::Shell;
use crate::shell::ShellStartupMode;
use crate::shell::ShellType;
use crate::shell::get_shell;
use anyhow::Context;
@@ -272,7 +273,7 @@ async fn run_script_with_timeout(
use_login_shell: bool,
cwd: &Path,
) -> Result<String> {
let args = shell.derive_exec_args(script, use_login_shell);
let args = shell.derive_exec_args(script, ShellStartupMode::from_login_shell(use_login_shell));
let shell_name = shell.name();
// Handler is kept as guard to control the drop. The `mut` pattern is required because .args()
+7 -7
View File
@@ -64,7 +64,7 @@ fn can_run_on_shell_test() {
fn shell_works(shell: Option<Shell>, command: &str, required: bool) -> bool {
if let Some(shell) = shell {
let args = shell.derive_exec_args(command, false);
let args = shell.derive_exec_args(command, ShellStartupMode::NonLogin);
let output = Command::new(args[0].clone())
.args(&args[1..])
.output()
@@ -85,11 +85,11 @@ fn derive_exec_args() {
shell_snapshot: empty_shell_snapshot_receiver(),
};
assert_eq!(
test_bash_shell.derive_exec_args("echo hello", false),
test_bash_shell.derive_exec_args("echo hello", ShellStartupMode::NonLogin),
vec!["/bin/bash", "-c", "echo hello"]
);
assert_eq!(
test_bash_shell.derive_exec_args("echo hello", true),
test_bash_shell.derive_exec_args("echo hello", ShellStartupMode::Login),
vec!["/bin/bash", "-lc", "echo hello"]
);
@@ -99,11 +99,11 @@ fn derive_exec_args() {
shell_snapshot: empty_shell_snapshot_receiver(),
};
assert_eq!(
test_zsh_shell.derive_exec_args("echo hello", false),
test_zsh_shell.derive_exec_args("echo hello", ShellStartupMode::NonLogin),
vec!["/bin/zsh", "-c", "echo hello"]
);
assert_eq!(
test_zsh_shell.derive_exec_args("echo hello", true),
test_zsh_shell.derive_exec_args("echo hello", ShellStartupMode::Login),
vec!["/bin/zsh", "-lc", "echo hello"]
);
@@ -113,11 +113,11 @@ fn derive_exec_args() {
shell_snapshot: empty_shell_snapshot_receiver(),
};
assert_eq!(
test_powershell_shell.derive_exec_args("echo hello", false),
test_powershell_shell.derive_exec_args("echo hello", ShellStartupMode::NonLogin),
vec!["pwsh.exe", "-NoProfile", "-Command", "echo hello"]
);
assert_eq!(
test_powershell_shell.derive_exec_args("echo hello", true),
test_powershell_shell.derive_exec_args("echo hello", ShellStartupMode::Login),
vec!["pwsh.exe", "-Command", "echo hello"]
);
}
+5 -1
View File
@@ -26,6 +26,7 @@ use crate::protocol::SandboxPolicy;
use crate::protocol::TurnStartedEvent;
use crate::sandboxing::ExecRequest;
use crate::sandboxing::SandboxPermissions;
use crate::shell::ShellStartupMode;
use crate::state::TaskKind;
use crate::tools::format_exec_output_str;
use crate::tools::runtimes::maybe_wrap_shell_lc_with_snapshot;
@@ -124,7 +125,10 @@ pub(crate) async fn execute_user_shell_command(
// We do not source rc files or otherwise reformat the script.
let use_login_shell = true;
let session_shell = session.user_shell();
let display_command = session_shell.derive_exec_args(&command, use_login_shell);
let display_command = session_shell.derive_exec_args(
&command,
ShellStartupMode::from_login_shell(use_login_shell),
);
let exec_command = maybe_wrap_shell_lc_with_snapshot(
&display_command,
session_shell.as_ref(),
+2 -1
View File
@@ -13,6 +13,7 @@ use crate::function_tool::FunctionCallError;
use crate::is_safe_command::is_known_safe_command;
use crate::protocol::ExecCommandSource;
use crate::shell::Shell;
use crate::shell::ShellStartupMode;
use crate::skills::maybe_emit_implicit_skill_invocation;
use crate::tools::context::FunctionToolOutput;
use crate::tools::context::ToolInvocation;
@@ -106,7 +107,7 @@ impl ShellCommandHandler {
}
fn base_command(shell: &Shell, command: &str, use_login_shell: bool) -> Vec<String> {
shell.derive_exec_args(command, use_login_shell)
shell.derive_exec_args(command, ShellStartupMode::from_login_shell(use_login_shell))
}
fn to_exec_params(
@@ -11,6 +11,7 @@ use crate::powershell::try_find_powershell_executable_blocking;
use crate::powershell::try_find_pwsh_executable_blocking;
use crate::sandboxing::SandboxPermissions;
use crate::shell::Shell;
use crate::shell::ShellStartupMode;
use crate::shell::ShellType;
use crate::shell_snapshot::ShellSnapshot;
use crate::tools::handlers::ShellCommandHandler;
@@ -56,10 +57,10 @@ fn commands_generated_by_shell_command_handler_can_be_matched_by_is_known_safe_c
fn assert_safe(shell: &Shell, command: &str) {
assert!(is_known_safe_command(
&shell.derive_exec_args(command, /* use_login_shell */ true)
&shell.derive_exec_args(command, ShellStartupMode::Login)
));
assert!(is_known_safe_command(
&shell.derive_exec_args(command, /* use_login_shell */ false)
&shell.derive_exec_args(command, ShellStartupMode::NonLogin)
));
}
@@ -74,7 +75,9 @@ async fn shell_command_handler_to_exec_params_uses_session_shell_and_turn_contex
let sandbox_permissions = SandboxPermissions::RequireEscalated;
let justification = Some("because tests".to_string());
let expected_command = session.user_shell().derive_exec_args(&command, true);
let expected_command = session
.user_shell()
.derive_exec_args(&command, ShellStartupMode::Login);
let expected_cwd = turn_context.resolve_path(workdir.clone());
let expected_env = create_env(
&turn_context.shell_environment_policy,
@@ -127,14 +130,14 @@ fn shell_command_handler_respects_explicit_login_flag() {
let login_command = ShellCommandHandler::base_command(&shell, "echo login shell", true);
assert_eq!(
login_command,
shell.derive_exec_args("echo login shell", true)
shell.derive_exec_args("echo login shell", ShellStartupMode::Login)
);
let non_login_command =
ShellCommandHandler::base_command(&shell, "echo non login shell", false);
assert_eq!(
non_login_command,
shell.derive_exec_args("echo non login shell", false)
shell.derive_exec_args("echo non login shell", ShellStartupMode::NonLogin)
);
}
@@ -163,7 +166,9 @@ async fn shell_command_handler_defaults_to_non_login_when_disallowed() {
assert_eq!(
exec_params.command,
session.user_shell().derive_exec_args("echo hello", false)
session
.user_shell()
.derive_exec_args("echo hello", ShellStartupMode::NonLogin)
);
}
@@ -5,6 +5,7 @@ use crate::protocol::EventMsg;
use crate::protocol::TerminalInteractionEvent;
use crate::sandboxing::SandboxPermissions;
use crate::shell::Shell;
use crate::shell::ShellStartupMode;
use crate::shell::get_shell_by_model_provided_path;
use crate::skills::maybe_emit_implicit_skill_invocation;
use crate::tools::context::ExecCommandToolOutput;
@@ -339,7 +340,10 @@ pub(crate) fn get_command(
None => allow_login_shell,
};
Ok(shell.derive_exec_args(&args.cmd, use_login_shell))
Ok(shell.derive_exec_args(
&args.cmd,
ShellStartupMode::from_login_shell(use_login_shell),
))
}
#[cfg(test)]
+3 -8
View File
@@ -341,16 +341,11 @@ impl ToolRegistryBuilder {
}
pub fn push_spec(&mut self, spec: ToolSpec) {
self.push_spec_with_parallel_support(spec, /*supports_parallel_tool_calls=*/ false);
self.specs.push(ConfiguredToolSpec::new(spec, false));
}
pub fn push_spec_with_parallel_support(
&mut self,
spec: ToolSpec,
supports_parallel_tool_calls: bool,
) {
self.specs
.push(ConfiguredToolSpec::new(spec, supports_parallel_tool_calls));
pub fn push_parallel_spec(&mut self, spec: ToolSpec) {
self.specs.push(ConfiguredToolSpec::new(spec, true));
}
pub fn register_handler<H>(&mut self, name: impl Into<String>, handler: Arc<H>)
+2 -5
View File
@@ -2165,7 +2165,7 @@ fn push_tool_spec(
) {
let spec = augment_tool_spec_for_code_mode(spec, code_mode_enabled);
if supports_parallel_tool_calls {
builder.push_spec_with_parallel_support(spec, /*supports_parallel_tool_calls=*/ true);
builder.push_parallel_spec(spec);
} else {
builder.push_spec(spec);
}
@@ -2664,10 +2664,7 @@ pub(crate) fn build_specs_with_discoverable_tools(
.as_ref()
.filter(|tools| !tools.is_empty())
{
builder.push_spec_with_parallel_support(
create_tool_suggest_tool(discoverable_tools),
/*supports_parallel_tool_calls=*/ true,
);
builder.push_parallel_spec(create_tool_suggest_tool(discoverable_tools));
builder.register_handler(TOOL_SUGGEST_TOOL_NAME, tool_suggest_handler);
}
+3 -4
View File
@@ -10,6 +10,7 @@ use codex_core::CodexThread;
use codex_core::config::Config;
use codex_core::config::ConfigBuilder;
use codex_core::config::ConfigOverrides;
use codex_core::shell::ShellStartupMode;
use codex_utils_absolute_path::AbsolutePathBuf;
use regex_lite::Regex;
use std::path::PathBuf;
@@ -264,8 +265,7 @@ pub fn sandbox_network_env_var() -> &'static str {
}
pub fn format_with_current_shell(command: &str) -> Vec<String> {
codex_core::shell::default_user_shell()
.derive_exec_args(command, /*use_login_shell=*/ true)
codex_core::shell::default_user_shell().derive_exec_args(command, ShellStartupMode::Login)
}
pub fn format_with_current_shell_display(command: &str) -> String {
@@ -274,8 +274,7 @@ pub fn format_with_current_shell_display(command: &str) -> String {
}
pub fn format_with_current_shell_non_login(command: &str) -> Vec<String> {
codex_core::shell::default_user_shell()
.derive_exec_args(command, /*use_login_shell=*/ false)
codex_core::shell::default_user_shell().derive_exec_args(command, ShellStartupMode::NonLogin)
}
pub fn format_with_current_shell_display_non_login(command: &str) -> String {
+20 -11
View File
@@ -860,12 +860,15 @@ impl App {
continue;
}
let effective_enabled = self.config.features.enabled(feature);
self.chat_widget
.set_feature_enabled(feature, effective_enabled);
if effective_enabled {
builder = builder.set_feature_enabled(feature_key, /*enabled=*/ true);
self.chat_widget.enable_feature(feature);
} else {
self.chat_widget.disable_feature(feature);
}
if effective_enabled {
builder = builder.enable_feature(feature_key);
} else if feature.default_enabled() {
builder = builder.set_feature_enabled(feature_key, /*enabled=*/ false);
builder = builder.disable_feature(feature_key);
} else {
// If the feature already default to `false`, we drop the key
// in the config file so that the user does not miss the feature
@@ -1018,10 +1021,17 @@ impl App {
.or_insert_with(|| ThreadEventChannel::new(THREAD_EVENT_CHANNEL_CAPACITY))
}
async fn set_thread_active(&mut self, thread_id: ThreadId, active: bool) {
async fn activate_thread(&mut self, thread_id: ThreadId) {
if let Some(channel) = self.thread_event_channels.get_mut(&thread_id) {
let mut store = channel.store.lock().await;
store.active = active;
store.active = true;
}
}
async fn deactivate_thread(&mut self, thread_id: ThreadId) {
if let Some(channel) = self.thread_event_channels.get_mut(&thread_id) {
let mut store = channel.store.lock().await;
store.active = false;
}
}
@@ -1029,7 +1039,7 @@ impl App {
if self.active_thread_id.is_some() {
return;
}
self.set_thread_active(thread_id, /*active=*/ true).await;
self.activate_thread(thread_id).await;
let receiver = if let Some(channel) = self.thread_event_channels.get_mut(&thread_id) {
channel.receiver.take()
} else {
@@ -1070,7 +1080,7 @@ impl App {
async fn clear_active_thread(&mut self) {
if let Some(active_id) = self.active_thread_id.take() {
self.set_thread_active(active_id, /*active=*/ false).await;
self.deactivate_thread(active_id).await;
}
self.active_thread_rx = None;
self.refresh_pending_thread_approvals().await;
@@ -4229,7 +4239,7 @@ mod tests {
let thread_id = ThreadId::new();
app.thread_event_channels
.insert(thread_id, ThreadEventChannel::new(1));
app.set_thread_active(thread_id, true).await;
app.activate_thread(thread_id).await;
let event = Event {
id: String::new(),
@@ -5179,8 +5189,7 @@ mod tests {
app.config
.features
.set_enabled(Feature::GuardianApproval, true)?;
app.chat_widget
.set_feature_enabled(Feature::GuardianApproval, true);
app.chat_widget.enable_feature(Feature::GuardianApproval);
let current_session_policy = app.config.permissions.approval_policy.value();
app.update_feature_flags(vec![(Feature::GuardianApproval, false)])
+10 -5
View File
@@ -3699,13 +3699,18 @@ impl ChatComposer {
self.voice_state.voice.is_some()
}
pub(crate) fn enable_input(&mut self) {
self.input_enabled = true;
self.input_disabled_placeholder = None;
}
#[allow(dead_code)]
pub(crate) fn set_input_enabled(&mut self, enabled: bool, placeholder: Option<String>) {
self.input_enabled = enabled;
self.input_disabled_placeholder = if enabled { None } else { placeholder };
pub(crate) fn disable_input(&mut self, placeholder: Option<String>) {
self.input_enabled = false;
self.input_disabled_placeholder = placeholder;
// Avoid leaving interactive popups open while input is blocked.
if !enabled && !matches!(self.active_popup, ActivePopup::None) {
if !matches!(self.active_popup, ActivePopup::None) {
self.active_popup = ActivePopup::None;
}
}
@@ -9764,7 +9769,7 @@ mod tests {
);
composer.set_text_content("hello".to_string(), Vec::new(), Vec::new());
composer.set_input_enabled(false, Some("Input disabled for test.".to_string()));
composer.disable_input(Some("Input disabled for test.".to_string()));
let (result, needs_redraw) =
composer.handle_key_event(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE));
@@ -982,14 +982,24 @@ impl McpServerElicitationOverlay {
.clamp(MIN_COMPOSER_HEIGHT, MIN_COMPOSER_HEIGHT.saturating_add(5))
}
fn move_field(&mut self, next: bool) {
fn move_to_next_field(&mut self) {
let len = self.field_count();
if len == 0 {
return;
}
self.save_current_draft();
let offset = if next { 1 } else { len.saturating_sub(1) };
self.current_idx = (self.current_idx + offset) % len;
self.current_idx = (self.current_idx + 1) % len;
self.validation_error = None;
self.restore_current_draft();
}
fn move_to_previous_field(&mut self) {
let len = self.field_count();
if len == 0 {
return;
}
self.save_current_draft();
self.current_idx = (self.current_idx + len.saturating_sub(1)) % len;
self.validation_error = None;
self.restore_current_draft();
}
@@ -1056,11 +1066,11 @@ impl McpServerElicitationOverlay {
(idx < self.options_len()).then_some(idx)
}
fn select_current_option(&mut self, committed: bool) {
fn commit_current_option(&mut self) {
let options_len = self.options_len();
if let Some(answer) = self.current_answer_mut() {
answer.selection.clamp_selection(options_len);
answer.answer_committed = committed;
answer.answer_committed = true;
}
}
@@ -1164,7 +1174,7 @@ impl McpServerElicitationOverlay {
if self.current_index() + 1 >= self.field_count() {
self.submit_answers();
} else {
self.move_field(/*next=*/ true);
self.move_to_next_field();
}
}
@@ -1459,7 +1469,7 @@ impl BottomPaneView for McpServerElicitationOverlay {
modifiers: KeyModifiers::NONE,
..
} => {
self.move_field(/*next=*/ false);
self.move_to_previous_field();
return;
}
KeyEvent {
@@ -1472,7 +1482,7 @@ impl BottomPaneView for McpServerElicitationOverlay {
modifiers: KeyModifiers::NONE,
..
} => {
self.move_field(/*next=*/ true);
self.move_to_next_field();
return;
}
KeyEvent {
@@ -1480,7 +1490,7 @@ impl BottomPaneView for McpServerElicitationOverlay {
modifiers: KeyModifiers::NONE,
..
} if self.current_field_is_select() => {
self.move_field(/*next=*/ false);
self.move_to_previous_field();
return;
}
KeyEvent {
@@ -1488,7 +1498,7 @@ impl BottomPaneView for McpServerElicitationOverlay {
modifiers: KeyModifiers::NONE,
..
} if self.current_field_is_select() => {
self.move_field(/*next=*/ true);
self.move_to_next_field();
return;
}
_ => {}
@@ -1511,10 +1521,10 @@ impl BottomPaneView for McpServerElicitationOverlay {
}
}
KeyCode::Backspace | KeyCode::Delete => self.clear_selection(),
KeyCode::Char(' ') => self.select_current_option(/*committed=*/ true),
KeyCode::Char(' ') => self.commit_current_option(),
KeyCode::Enter => {
if self.selected_option_index().is_some() {
self.select_current_option(/*committed=*/ true);
self.commit_current_option();
}
self.go_next_or_submit();
}
@@ -1523,7 +1533,7 @@ impl BottomPaneView for McpServerElicitationOverlay {
if let Some(answer) = self.current_answer_mut() {
answer.selection.selected_idx = Some(option_idx);
}
self.select_current_option(/*committed=*/ true);
self.commit_current_option();
self.go_next_or_submit();
}
}
@@ -2013,7 +2023,7 @@ mod tests {
.expect("expected supported form");
let mut overlay = McpServerElicitationOverlay::new(request, tx, true, false, false);
overlay.select_current_option(true);
overlay.commit_current_option();
overlay.submit_answers();
let event = rx.try_recv().expect("expected resolution");
@@ -2064,7 +2074,7 @@ mod tests {
if let Some(answer) = overlay.current_answer_mut() {
answer.selection.selected_idx = Some(1);
}
overlay.select_current_option(true);
overlay.commit_current_option();
overlay.submit_answers();
let event = rx.try_recv().expect("expected resolution");
@@ -2115,7 +2125,7 @@ mod tests {
if let Some(answer) = overlay.current_answer_mut() {
answer.selection.selected_idx = Some(2);
}
overlay.select_current_option(true);
overlay.commit_current_option();
overlay.submit_answers();
let event = rx.try_recv().expect("expected resolution");
@@ -2247,12 +2257,12 @@ mod tests {
overlay.try_consume_mcp_server_elicitation_request(second);
overlay.try_consume_mcp_server_elicitation_request(third);
overlay.select_current_option(true);
overlay.commit_current_option();
overlay.submit_answers();
assert_eq!(overlay.request.message, "Second");
overlay.select_current_option(true);
overlay.commit_current_option();
overlay.submit_answers();
assert_eq!(overlay.request.message, "Third");
+16 -19
View File
@@ -556,12 +556,14 @@ impl BottomPane {
}
#[allow(dead_code)]
pub(crate) fn set_composer_input_enabled(
&mut self,
enabled: bool,
placeholder: Option<String>,
) {
self.composer.set_input_enabled(enabled, placeholder);
pub(crate) fn enable_composer_input(&mut self) {
self.composer.enable_input();
self.request_redraw();
}
#[allow(dead_code)]
pub(crate) fn disable_composer_input(&mut self, placeholder: Option<String>) {
self.composer.disable_input(placeholder);
self.request_redraw();
}
@@ -942,10 +944,7 @@ impl BottomPane {
self.disable_paste_burst,
);
self.pause_status_timer_for_modal();
self.set_composer_input_enabled(
/*enabled=*/ false,
Some("Answer the questions to continue.".to_string()),
);
self.disable_composer_input(Some("Answer the questions to continue.".to_string()));
self.push_view(Box::new(modal));
}
@@ -1003,10 +1002,9 @@ impl BottomPane {
self.app_event_tx.clone(),
);
self.pause_status_timer_for_modal();
self.set_composer_input_enabled(
/*enabled=*/ false,
Some("Respond to the tool suggestion to continue.".to_string()),
);
self.disable_composer_input(Some(
"Respond to the tool suggestion to continue.".to_string(),
));
self.push_view(Box::new(view));
return;
}
@@ -1019,16 +1017,15 @@ impl BottomPane {
self.disable_paste_burst,
);
self.pause_status_timer_for_modal();
self.set_composer_input_enabled(
/*enabled=*/ false,
Some("Respond to the MCP server request to continue.".to_string()),
);
self.disable_composer_input(Some(
"Respond to the MCP server request to continue.".to_string(),
));
self.push_view(Box::new(modal));
}
fn on_active_view_complete(&mut self) {
self.resume_status_timer_after_modal();
self.set_composer_input_enabled(/*enabled=*/ true, /*placeholder=*/ None);
self.enable_composer_input();
}
fn pause_status_timer_for_modal(&mut self) {
@@ -612,15 +612,24 @@ impl RequestUserInputOverlay {
None
}
/// Move to the next/previous question, wrapping in either direction.
fn move_question(&mut self, next: bool) {
fn move_to_next_question(&mut self) {
let len = self.question_count();
if len == 0 {
return;
}
self.save_current_draft();
let offset = if next { 1 } else { len.saturating_sub(1) };
self.current_idx = (self.current_idx + offset) % len;
self.current_idx = (self.current_idx + 1) % len;
self.restore_current_draft();
self.ensure_focus_available();
}
fn move_to_previous_question(&mut self) {
let len = self.question_count();
if len == 0 {
return;
}
self.save_current_draft();
self.current_idx = (self.current_idx + len.saturating_sub(1)) % len;
self.restore_current_draft();
self.ensure_focus_available();
}
@@ -635,15 +644,33 @@ impl RequestUserInputOverlay {
self.ensure_focus_available();
}
/// Synchronize selection state to the currently focused option.
fn select_current_option(&mut self, committed: bool) {
fn commit_current_option(&mut self) {
if !self.has_options() {
return;
}
let options_len = self.options_len();
let updated = if let Some(answer) = self.current_answer_mut() {
answer.options_state.clamp_selection(options_len);
answer.answer_committed = committed;
answer.answer_committed = true;
true
} else {
false
};
if updated {
self.sync_composer_placeholder();
}
}
#[cfg_attr(not(test), allow(dead_code))]
/// Synchronize selection state to the currently focused option.
fn preview_current_option(&mut self) {
if !self.has_options() {
return;
}
let options_len = self.options_len();
let updated = if let Some(answer) = self.current_answer_mut() {
answer.options_state.clamp_selection(options_len);
answer.answer_committed = false;
true
} else {
false
@@ -706,7 +733,7 @@ impl RequestUserInputOverlay {
self.submit_answers();
}
} else {
self.move_question(/*next=*/ true);
self.move_to_next_question();
}
}
@@ -1024,7 +1051,7 @@ impl BottomPaneView for RequestUserInputOverlay {
modifiers: KeyModifiers::NONE,
..
} => {
self.move_question(/*next=*/ false);
self.move_to_previous_question();
return;
}
KeyEvent {
@@ -1037,7 +1064,7 @@ impl BottomPaneView for RequestUserInputOverlay {
modifiers: KeyModifiers::CONTROL,
..
} => {
self.move_question(/*next=*/ true);
self.move_to_next_question();
return;
}
KeyEvent {
@@ -1045,7 +1072,7 @@ impl BottomPaneView for RequestUserInputOverlay {
modifiers: KeyModifiers::NONE,
..
} if self.has_options() && matches!(self.focus, Focus::Options) => {
self.move_question(/*next=*/ false);
self.move_to_previous_question();
return;
}
KeyEvent {
@@ -1053,7 +1080,7 @@ impl BottomPaneView for RequestUserInputOverlay {
modifiers: KeyModifiers::NONE,
..
} if self.has_options() && matches!(self.focus, Focus::Options) => {
self.move_question(/*next=*/ false);
self.move_to_previous_question();
return;
}
KeyEvent {
@@ -1061,7 +1088,7 @@ impl BottomPaneView for RequestUserInputOverlay {
modifiers: KeyModifiers::NONE,
..
} if self.has_options() && matches!(self.focus, Focus::Options) => {
self.move_question(/*next=*/ true);
self.move_to_next_question();
return;
}
KeyEvent {
@@ -1069,7 +1096,7 @@ impl BottomPaneView for RequestUserInputOverlay {
modifiers: KeyModifiers::NONE,
..
} if self.has_options() && matches!(self.focus, Focus::Options) => {
self.move_question(/*next=*/ true);
self.move_to_next_question();
return;
}
_ => {}
@@ -1105,7 +1132,7 @@ impl BottomPaneView for RequestUserInputOverlay {
}
}
KeyCode::Char(' ') => {
self.select_current_option(/*committed=*/ true);
self.commit_current_option();
}
KeyCode::Backspace | KeyCode::Delete => {
self.clear_selection();
@@ -1119,7 +1146,7 @@ impl BottomPaneView for RequestUserInputOverlay {
KeyCode::Enter => {
let has_selection = self.selected_option_index().is_some();
if has_selection {
self.select_current_option(/*committed=*/ true);
self.commit_current_option();
}
self.go_next_or_submit();
}
@@ -1128,7 +1155,7 @@ impl BottomPaneView for RequestUserInputOverlay {
if let Some(answer) = self.current_answer_mut() {
answer.options_state.selected_idx = Some(option_idx);
}
self.select_current_option(/*committed=*/ true);
self.commit_current_option();
self.go_next_or_submit();
}
}
@@ -1158,7 +1185,7 @@ impl BottomPaneView for RequestUserInputOverlay {
if !self.handle_composer_input_result(result) {
self.pending_submission_draft = None;
if self.has_options() {
self.select_current_option(/*committed=*/ true);
self.commit_current_option();
}
self.go_next_or_submit();
}
@@ -1793,7 +1820,7 @@ mod tests {
false,
false,
);
overlay.move_question(true);
overlay.move_to_next_question();
let tips = overlay.footer_tips();
let tip_texts = tips.iter().map(|tip| tip.text.as_str()).collect::<Vec<_>>();
@@ -1844,7 +1871,7 @@ mod tests {
);
assert!(matches!(overlay.focus, Focus::Notes));
overlay.move_question(true);
overlay.move_to_next_question();
assert!(matches!(overlay.focus, Focus::Options));
assert_eq!(overlay.notes_ui_visible(), false);
@@ -1872,7 +1899,7 @@ mod tests {
.set_text_content("freeform notes".to_string(), Vec::new(), Vec::new());
overlay.composer.move_cursor_to_end();
overlay.move_question(true);
overlay.move_to_next_question();
assert!(matches!(overlay.focus, Focus::Options));
assert_eq!(overlay.notes_ui_visible(), false);
@@ -2244,12 +2271,12 @@ mod tests {
assert_eq!(overlay.answers[0].answer_committed, true);
let _ = rx.try_recv();
overlay.move_question(false);
overlay.move_to_previous_question();
overlay
.composer
.set_text_content("Edited".to_string(), Vec::new(), Vec::new());
overlay.composer.move_cursor_to_end();
overlay.move_question(true);
overlay.move_to_next_question();
assert_eq!(overlay.answers[0].answer_committed, false);
overlay.submit_answers();
@@ -2277,7 +2304,7 @@ mod tests {
let answer = overlay.current_answer_mut().expect("answer missing");
answer.options_state.selected_idx = Some(1);
}
overlay.select_current_option(false);
overlay.preview_current_option();
overlay
.composer
.set_text_content("Notes for option 2".to_string(), Vec::new(), Vec::new());
@@ -2408,7 +2435,7 @@ mod tests {
let large = "x".repeat(1_500);
overlay.composer.handle_paste(large.clone());
overlay.move_question(true);
overlay.move_to_next_question();
let draft = &overlay.answers[0].draft;
assert_eq!(draft.pending_pastes.len(), 1);
@@ -2863,7 +2890,7 @@ mod tests {
false,
false,
);
overlay.move_question(true);
overlay.move_to_next_question();
let area = Rect::new(0, 0, 120, 12);
insta::assert_snapshot!(
"request_user_input_multi_question_last",
@@ -2907,7 +2934,7 @@ mod tests {
false,
false,
);
overlay.select_current_option(false);
overlay.preview_current_option();
overlay.focus = Focus::Notes;
overlay
.composer
+21 -8
View File
@@ -5735,8 +5735,14 @@ impl ChatWidget {
});
let result: Result<ConnectorsSnapshot, String> = async {
let cache_policy = if force_refetch {
connectors::CachePolicy::ForceRefresh
} else {
connectors::CachePolicy::UseCache
};
let all_connectors =
connectors::list_all_connectors_with_options(&config, force_refetch).await?;
connectors::list_all_connectors_with_cache_policy(&config, cache_policy)
.await?;
let connectors = connectors::merge_connectors_with_accessible(
all_connectors,
accessible_connectors,
@@ -7345,10 +7351,8 @@ impl ChatWidget {
pub(crate) fn show_windows_sandbox_setup_status(&mut self) {
// While elevated sandbox setup runs, prevent typing so the user doesn't
// accidentally queue messages that will run under an unexpected mode.
self.bottom_pane.set_composer_input_enabled(
false,
Some("Input disabled until setup completes.".to_string()),
);
self.bottom_pane
.disable_composer_input(Some("Input disabled until setup completes.".to_string()));
self.bottom_pane.ensure_status_indicator();
self.bottom_pane.set_interrupt_hint_visible(false);
self.set_status(
@@ -7366,7 +7370,7 @@ impl ChatWidget {
#[cfg(target_os = "windows")]
pub(crate) fn clear_windows_sandbox_setup_status(&mut self) {
self.bottom_pane.set_composer_input_enabled(true, None);
self.bottom_pane.enable_composer_input();
self.bottom_pane.hide_status_indicator();
self.request_redraw();
}
@@ -7401,8 +7405,7 @@ impl ChatWidget {
);
}
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) fn set_feature_enabled(&mut self, feature: Feature, enabled: bool) -> bool {
fn set_feature_enabled_state(&mut self, feature: Feature, enabled: bool) -> bool {
if let Err(err) = self.config.features.set_enabled(feature, enabled) {
tracing::warn!(
error = %err,
@@ -7457,6 +7460,16 @@ impl ChatWidget {
enabled
}
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) fn enable_feature(&mut self, feature: Feature) -> bool {
self.set_feature_enabled_state(feature, true)
}
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) fn disable_feature(&mut self, feature: Feature) -> bool {
self.set_feature_enabled_state(feature, false)
}
pub(crate) fn set_full_access_warning_acknowledged(&mut self, acknowledged: bool) {
self.config.notices.hide_full_access_warning = Some(acknowledged);
}
+43 -43
View File
@@ -955,7 +955,7 @@ async fn enter_with_only_remote_images_does_not_submit_when_input_disabled() {
let remote_url = "https://example.com/remote-only.png".to_string();
chat.set_remote_image_urls(vec![remote_url.clone()]);
chat.bottom_pane
.set_composer_input_enabled(false, Some("Input disabled for test.".to_string()));
.disable_composer_input(Some("Input disabled for test.".to_string()));
chat.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
@@ -1289,7 +1289,7 @@ async fn interrupted_turn_restores_queued_messages_with_images_and_elements() {
async fn interrupted_turn_restore_keeps_active_mode_for_resubmission() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref())
.expect("expected plan collaboration mode");
@@ -2455,7 +2455,7 @@ async fn plan_implementation_popup_yes_emits_submit_message_event() {
async fn submit_user_message_with_mode_sets_coding_collaboration_mode() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let default_mode = collaboration_modes::default_mode_mask(chat.models_manager.as_ref())
.expect("expected default collaboration mode");
@@ -2481,7 +2481,7 @@ async fn submit_user_message_with_mode_sets_coding_collaboration_mode() {
async fn reasoning_selection_in_plan_mode_opens_scope_prompt_event() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref())
.expect("expected plan collaboration mode");
chat.set_collaboration_mask(plan_mask);
@@ -2508,7 +2508,7 @@ async fn reasoning_selection_in_plan_mode_opens_scope_prompt_event() {
async fn reasoning_selection_in_plan_mode_without_effort_change_does_not_open_scope_prompt_event() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref())
.expect("expected plan collaboration mode");
chat.set_collaboration_mask(plan_mask);
@@ -2543,7 +2543,7 @@ async fn reasoning_selection_in_plan_mode_matching_plan_effort_but_different_glo
{
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref())
.expect("expected plan collaboration mode");
chat.set_collaboration_mask(plan_mask);
@@ -2572,7 +2572,7 @@ async fn reasoning_selection_in_plan_mode_matching_plan_effort_but_different_glo
#[tokio::test]
async fn plan_mode_reasoning_override_is_marked_current_in_reasoning_popup() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
set_chatgpt_auth(&mut chat);
chat.set_reasoning_effort(Some(ReasoningEffortConfig::High));
chat.set_plan_mode_reasoning_effort(Some(ReasoningEffortConfig::Low));
@@ -2596,7 +2596,7 @@ async fn plan_mode_reasoning_override_is_marked_current_in_reasoning_popup() {
async fn reasoning_selection_in_plan_mode_model_switch_does_not_open_scope_prompt_event() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1-codex-max")).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref())
.expect("expected plan collaboration mode");
chat.set_collaboration_mask(plan_mask);
@@ -2861,7 +2861,7 @@ async fn plan_reasoning_scope_popup_plan_only_does_not_update_all_modes_reasonin
async fn submit_user_message_with_mode_errors_when_mode_changes_during_running_turn() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -2890,7 +2890,7 @@ async fn submit_user_message_with_mode_errors_when_mode_changes_during_running_t
async fn submit_user_message_with_mode_allows_same_mode_during_running_turn() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -2921,7 +2921,7 @@ async fn submit_user_message_with_mode_allows_same_mode_during_running_turn() {
async fn submit_user_message_with_mode_submits_when_plan_stream_is_not_active() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -2951,7 +2951,7 @@ async fn submit_user_message_with_mode_submits_when_plan_stream_is_not_active()
#[tokio::test]
async fn plan_implementation_popup_skips_replayed_turn_complete() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -2972,7 +2972,7 @@ async fn plan_implementation_popup_skips_replayed_turn_complete() {
#[tokio::test]
async fn plan_implementation_popup_shows_once_when_replay_precedes_live_turn_complete() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -3050,7 +3050,7 @@ async fn replayed_thread_rollback_emits_ordered_app_event() {
#[tokio::test]
async fn plan_implementation_popup_skips_when_messages_queued() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -3070,7 +3070,7 @@ async fn plan_implementation_popup_skips_when_messages_queued() {
#[tokio::test]
async fn plan_implementation_popup_skips_without_proposed_plan() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -3096,7 +3096,7 @@ async fn plan_implementation_popup_skips_without_proposed_plan() {
#[tokio::test]
async fn plan_implementation_popup_shows_after_proposed_plan_output() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -3117,7 +3117,7 @@ async fn plan_implementation_popup_shows_after_proposed_plan_output() {
#[tokio::test]
async fn plan_implementation_popup_skips_when_steer_follows_proposed_plan() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -3159,7 +3159,7 @@ async fn plan_implementation_popup_skips_when_steer_follows_proposed_plan() {
#[tokio::test]
async fn plan_implementation_popup_shows_after_new_plan_follows_steer() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -3208,7 +3208,7 @@ async fn plan_implementation_popup_skips_when_rate_limit_prompt_pending() {
chat.auth_manager = codex_core::test_support::auth_manager_from_auth(
CodexAuth::create_dummy_chatgpt_auth_for_testing(),
);
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -3642,7 +3642,7 @@ async fn empty_enter_during_task_does_not_queue() {
#[tokio::test]
async fn restore_thread_input_state_syncs_sleep_inhibitor_state() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_feature_enabled(Feature::PreventIdleSleep, true);
chat.enable_feature(Feature::PreventIdleSleep);
chat.restore_thread_input_state(Some(ThreadInputState {
composer: None,
@@ -3880,7 +3880,7 @@ async fn commentary_completion_restores_status_indicator_before_exec_begin() {
#[tokio::test]
async fn plan_completion_restores_status_indicator_after_streaming_plan_output() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -3975,7 +3975,7 @@ async fn unified_exec_begin_restores_working_status_snapshot() {
async fn steer_enter_queues_while_plan_stream_is_active() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -4290,7 +4290,7 @@ async fn submit_user_message_emits_structured_plugin_mentions_from_bindings() {
id: "initial".into(),
msg: EventMsg::SessionConfigured(configured),
});
chat.set_feature_enabled(Feature::Plugins, true);
chat.enable_feature(Feature::Plugins);
chat.bottom_pane.set_plugin_mentions(Some(vec![
codex_core::plugins::PluginCapabilitySummary {
config_name: "sample@test".to_string(),
@@ -4689,7 +4689,7 @@ async fn replaced_turn_clears_pending_steers_but_keeps_queued_drafts() {
async fn enter_submits_when_plan_stream_is_not_active() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -5392,7 +5392,7 @@ async fn collab_mode_shift_tab_cycles_only_when_idle() {
#[tokio::test]
async fn mode_switch_surfaces_model_change_notification_when_effective_model_changes() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let default_model = chat.current_model().to_string();
let mut plan_mask =
@@ -5431,7 +5431,7 @@ async fn mode_switch_surfaces_model_change_notification_when_effective_model_cha
#[tokio::test]
async fn mode_switch_surfaces_reasoning_change_notification_when_model_stays_same() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.3-codex")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
chat.set_reasoning_effort(Some(ReasoningEffortConfig::High));
let plan_mask = collaboration_modes::plan_mask(chat.models_manager.as_ref())
@@ -5453,7 +5453,7 @@ async fn mode_switch_surfaces_reasoning_change_notification_when_model_stays_sam
async fn collab_slash_command_opens_picker_and_updates_mode() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
chat.dispatch_command(SlashCommand::Collab);
let popup = render_bottom_popup(&chat, 80);
@@ -5509,7 +5509,7 @@ async fn collab_slash_command_opens_picker_and_updates_mode() {
#[tokio::test]
async fn plan_slash_command_switches_to_plan_mode() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let initial = chat.current_collaboration_mode().clone();
chat.dispatch_command(SlashCommand::Plan);
@@ -5527,7 +5527,7 @@ async fn plan_slash_command_switches_to_plan_mode() {
#[tokio::test]
async fn plan_slash_command_with_args_submits_prompt_in_plan_mode() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let configured = codex_protocol::protocol::SessionConfiguredEvent {
session_id: ThreadId::new(),
@@ -5667,7 +5667,7 @@ async fn experimental_mode_plan_is_ignored_on_startup() {
#[tokio::test]
async fn set_model_updates_active_collaboration_mask() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -5682,7 +5682,7 @@ async fn set_model_updates_active_collaboration_mask() {
#[tokio::test]
async fn set_reasoning_effort_updates_active_collaboration_mask() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
.expect("expected plan collaboration mask");
@@ -5700,7 +5700,7 @@ async fn set_reasoning_effort_updates_active_collaboration_mask() {
#[tokio::test]
async fn set_reasoning_effort_does_not_override_active_plan_override() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(Some("gpt-5.1")).await;
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
chat.set_plan_mode_reasoning_effort(Some(ReasoningEffortConfig::High));
let plan_mask =
collaboration_modes::mask_for_kind(chat.models_manager.as_ref(), ModeKind::Plan)
@@ -5720,7 +5720,7 @@ async fn set_reasoning_effort_does_not_override_active_plan_override() {
async fn collab_mode_is_sent_after_enabling() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(None).await;
chat.thread_id = Some(ThreadId::new());
chat.set_feature_enabled(Feature::CollaborationModes, true);
chat.enable_feature(Feature::CollaborationModes);
chat.bottom_pane
.set_composer_text("hello".to_string(), Vec::new(), Vec::new());
@@ -5771,7 +5771,7 @@ async fn collab_mode_applies_default_preset() {
#[tokio::test]
async fn user_turn_includes_personality_from_config() {
let (mut chat, _rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5.2-codex")).await;
chat.set_feature_enabled(Feature::Personality, true);
chat.enable_feature(Feature::Personality);
chat.thread_id = Some(ThreadId::new());
chat.set_model("gpt-5.2-codex");
chat.set_personality(Personality::Friendly);
@@ -7747,8 +7747,8 @@ async fn approvals_selection_popup_snapshot_windows_degraded_sandbox() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.config.notices.hide_full_access_warning = None;
chat.set_feature_enabled(Feature::WindowsSandbox, true);
chat.set_feature_enabled(Feature::WindowsSandboxElevated, false);
chat.enable_feature(Feature::WindowsSandbox);
chat.disable_feature(Feature::WindowsSandboxElevated);
chat.open_approvals_popup();
@@ -7832,8 +7832,8 @@ async fn windows_auto_mode_prompt_requests_enabling_sandbox_feature() {
async fn startup_prompts_for_windows_sandbox_when_agent_requested() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_feature_enabled(Feature::WindowsSandbox, false);
chat.set_feature_enabled(Feature::WindowsSandboxElevated, false);
chat.disable_feature(Feature::WindowsSandbox);
chat.disable_feature(Feature::WindowsSandboxElevated);
chat.maybe_prompt_windows_sandbox_enable(true);
@@ -7861,8 +7861,8 @@ async fn startup_prompts_for_windows_sandbox_when_agent_requested() {
async fn startup_does_not_prompt_for_windows_sandbox_when_not_requested() {
let (mut chat, _rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_feature_enabled(Feature::WindowsSandbox, false);
chat.set_feature_enabled(Feature::WindowsSandboxElevated, false);
chat.disable_feature(Feature::WindowsSandbox);
chat.disable_feature(Feature::WindowsSandboxElevated);
chat.maybe_prompt_windows_sandbox_enable(false);
assert!(
@@ -8108,7 +8108,7 @@ async fn disabled_slash_command_while_task_running_snapshot() {
#[tokio::test]
async fn fast_slash_command_updates_and_persists_local_service_tier() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5.3-codex")).await;
chat.set_feature_enabled(Feature::FastMode, true);
chat.enable_feature(Feature::FastMode);
chat.dispatch_command(SlashCommand::Fast);
@@ -8141,7 +8141,7 @@ async fn user_turn_carries_service_tier_after_fast_toggle() {
let (mut chat, mut rx, mut op_rx) = make_chatwidget_manual(Some("gpt-5.3-codex")).await;
chat.thread_id = Some(ThreadId::new());
set_chatgpt_auth(&mut chat);
chat.set_feature_enabled(Feature::FastMode, true);
chat.enable_feature(Feature::FastMode);
chat.dispatch_command(SlashCommand::Fast);
@@ -10034,7 +10034,7 @@ async fn stream_recovery_restores_previous_status_header() {
#[tokio::test]
async fn runtime_metrics_websocket_timing_logs_and_final_separator_sums_totals() {
let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(None).await;
chat.set_feature_enabled(Feature::RuntimeMetrics, true);
chat.enable_feature(Feature::RuntimeMetrics);
chat.on_task_started();
chat.apply_runtime_metrics_delta(RuntimeMetricsSummary {