返回 CodeWhale
config_main_host.rs
根目录 / crates / tui / src / commands / config_main_host.rs
1 //! Config commands: config, settings, mode switches, trust, logout
2
3 use crate::tui::app::StatusToastLevel;
4 use crate::tui::app::{App, AppAction, AppModeUi, SettingSelection, VimMode};
5 use anyhow::Result;
6 use codewhale_command_contract::config::{CommandWorkflowSummary, ConfigMessage, ConfigReply};
7 use codewhale_config::AppMode;
8 use codewhale_config::ProviderKind;
9 use codewhale_config::descriptors::defaults::DEFAULT_XIAOMI_MIMO_BASE_URL;
10 use codewhale_config::notifications::{
11 NotificationConfigUpdate, NotificationSetting, NotificationsConfig,
12 };
13 use codewhale_engine::reasoning_preference::ReasoningEffort;
14 use codewhale_execpolicy::ApprovalMode;
15 use codewhale_localization::{MessageId, resolve_locale, tr};
16 use codewhale_runtime::config::{
17 Config, DEFAULT_STREAM_CHUNK_TIMEOUT_SECS, DEFAULT_SUBAGENT_API_TIMEOUT_SECS,
18 DEFAULT_SUBAGENT_HEARTBEAT_TIMEOUT_SECS, MAX_STREAM_CHUNK_TIMEOUT_SECS,
19 MAX_SUBAGENT_API_TIMEOUT_SECS, MAX_SUBAGENT_HEARTBEAT_TIMEOUT_SECS, MAX_SUBAGENTS,
20 MIN_STREAM_CHUNK_TIMEOUT_SECS, MIN_SUBAGENT_API_TIMEOUT_SECS,
21 MIN_SUBAGENT_HEARTBEAT_TIMEOUT_SECS, SearchProvider, SearchProviderSource, SearchThirdParty,
22 SearchThirdPartyResolution, SearchThirdPartySource, SubagentsConfig,
23 XIAOMI_MIMO_PAY_AS_YOU_GO_BASE_URL, normalize_custom_model_id, validate_route,
24 };
25 use codewhale_runtime::config_persistence::{
26 persist_root_bool_key, persist_root_string_key, persist_subagents_bool_key,
27 persist_subagents_integer_key, persist_table_string_key, persist_table_value_key,
28 persist_unset_root_key,
29 };
30 use codewhale_runtime::settings::Settings;
31 use std::path::PathBuf;
32
33 /// Reject a preset bundle *before* anything is written, returning the message
34 /// to show, or `None` when every field can be applied.
35 ///
36 /// The bundle is persisted in one transaction and then mirrored field by field
37 /// into the live session. A per-field refusal during that mirror pass therefore
38 /// arrives *after* the file has already been rewritten — the user gets an error
39 /// and a saved file, which is the partial apply this preflight exists to make
40 /// impossible. Both refusals a field can raise are knowable up front:
41 ///
42 /// 1. A live-route key while a turn is running (#2982).
43 /// 2. A value the setter would reject, checked against a throwaway `Settings`
44 /// so the real file is never touched by the check.
45 fn preset_preflight(app: &App, fields: &[(&str, &str)]) -> Option<String> {
46 for (key, value) in fields {
47 if app.is_loading
48 && let Some(subject) = live_route_setting_subject(&key.to_lowercase())
49 {
50 return Some(app.setting_locked_message(subject));
51 }
52 if let Err(e) = Settings::default().set(key, value) {
53 return Some(format!("Failed to apply preset field {key}={value}: {e}"));
54 }
55 }
56 None
57 }
58
59 /// Apply a bundled settings preset, e.g. `/config preset calm [--save]` (#3478).
60 ///
61 /// The preset is applied to the live session through the same per-key setter a
62 /// single `/config <key> <value>` uses, so app state mirroring and (with
63 /// `--save`) persistence stay consistent. The preset name is validated before
64 /// any field is touched.
65 /// Typed effective `[workflow]`/`[goal]` facts (the config facet projects these).
66 /// Build a config reply carrying an `AppAction` converted to the contract action.
67 fn config_action_reply(message: impl Into<ConfigMessage>, action: AppAction) -> ConfigReply {
68 ConfigReply {
69 message: Some(message.into()),
70 action: crate::commands::config_host::app_action_to_config_action(action),
71 is_error: false,
72 }
73 }
74
75 pub(in crate::commands) fn workflow_summary(app: &App) -> CommandWorkflowSummary {
76 let refreshed = codewhale_engine::tools::workflow::session_workflow_config(&app.workspace);
77 let cfg = refreshed.as_ref().unwrap_or(&app.workflow_config);
78 CommandWorkflowSummary {
79 automatic: cfg.automatic,
80 auto_start_read_only: cfg.auto_start_read_only,
81 require_approval_for_writes: cfg.require_approval_for_writes,
82 max_children: cfg.max_children,
83 max_concurrent: cfg.max_concurrent,
84 max_depth: cfg.max_depth,
85 goal_max_continuations: app.goal_max_continuations,
86 goal_enforce_token_budget: app.goal_enforce_token_budget,
87 }
88 }
89
90 pub(crate) fn apply_preset(app: &mut App, name: &str, persist: bool) -> ConfigReply {
91 if name.is_empty() || name.starts_with('-') {
92 return ConfigReply::message(
93 "Usage: /config preset <name> [--save]. Available presets: calm.",
94 );
95 }
96
97 let Some(fields) = codewhale_runtime::settings::preset_fields(name) else {
98 return ConfigReply::error(format!("Unknown preset '{name}'. Available presets: calm."));
99 };
100
101 if let Some(refusal) = preset_preflight(app, fields) {
102 return ConfigReply::error(refusal);
103 }
104
105 // Persist the whole bundle atomically when requested (one load/apply/save),
106 // now that every field is known to be applicable.
107 if persist {
108 // `Settings::transact` is what makes "one load/apply/save" true against
109 // the *other* writers in this process, not just against a second preset
110 // apply: an unsynchronized load/save pair here would write back a
111 // pre-image that reverts a concurrent mode/thinking/posture write.
112 if let Err(e) = Settings::transact(|settings| settings.apply_preset(name)) {
113 return ConfigReply::error(format!("Failed to save settings: {e}"));
114 }
115 }
116
117 // Mirror the bundle into the live session via the per-key setter (the
118 // persisted write, if any, already happened atomically above, so this pass
119 // is session-only).
120 let mut applied = Vec::with_capacity(fields.len());
121 for (key, value) in fields {
122 let result = set_config_value(app, key, value, false);
123 if result.is_error {
124 let message = result
125 .message
126 .unwrap_or_else(|| ConfigMessage::literal("unknown apply error"));
127 return ConfigReply {
128 message: Some(ConfigMessage::concat(vec![
129 ConfigMessage::literal(format!(
130 "Error: Failed to apply preset field {key}={value}: "
131 )),
132 message,
133 ])),
134 action: None,
135 is_error: true,
136 };
137 }
138 applied.push(format!("{key}={value}"));
139 }
140
141 let suffix = if persist {
142 " (saved)"
143 } else {
144 " (session only — add --save to persist)"
145 };
146 ConfigReply::message(format!(
147 "Applied '{name}' transcript preset{suffix}: {}. Thinking stays visible and tool runs stay expandable.",
148 applied.join(", ")
149 ))
150 }
151
152 /// Show the current value of a single setting.
153 fn config_context_window_override(app: &App) -> Option<u32> {
154 let mut config = codewhale_plugins::providers::load_config(
155 app.config_path.clone(),
156 app.config_profile.as_deref(),
157 )
158 .ok()?;
159 let identity = app.admitted_provider_identity().ok()?;
160 config.scope_to_provider_identity(identity).ok()?;
161 config.context_window_for_provider_config(identity)
162 }
163
164 pub(crate) fn show_single_setting(app: &App, key: &str) -> ConfigReply {
165 let key = key.to_lowercase();
166 if let Some(subagent_key) = key.strip_prefix("subagents.") {
167 return show_subagents_setting(app, subagent_key);
168 }
169 if let Some(notifications_key) = key.strip_prefix("notifications.") {
170 return show_notifications_setting(app, notifications_key);
171 }
172 fn locale_display(l: codewhale_localization::Locale) -> &'static str {
173 match l {
174 codewhale_localization::Locale::En => "en",
175 codewhale_localization::Locale::ZhHans => "zh-Hans",
176 codewhale_localization::Locale::ZhHant => "zh-Hant",
177 codewhale_localization::Locale::Ja => "ja",
178 codewhale_localization::Locale::PtBr => "pt-BR",
179 codewhale_localization::Locale::Es419 => "es-419",
180 codewhale_localization::Locale::Vi => "vi",
181 codewhale_localization::Locale::Ko => "ko",
182 codewhale_localization::Locale::Ca => "ca",
183 codewhale_localization::Locale::De => "de",
184 codewhale_localization::Locale::Fr => "fr",
185 codewhale_localization::Locale::Id => "id",
186 codewhale_localization::Locale::Hi => "hi",
187 codewhale_localization::Locale::Ru => "ru",
188 codewhale_localization::Locale::Uk => "uk",
189 }
190 }
191 fn density_display(d: crate::tui::app::ComposerDensity) -> &'static str {
192 match d {
193 crate::tui::app::ComposerDensity::Compact => "compact",
194 crate::tui::app::ComposerDensity::Comfortable => "comfortable",
195 crate::tui::app::ComposerDensity::Spacious => "spacious",
196 }
197 }
198 fn spacing_display(s: crate::tui::app::TranscriptSpacing) -> &'static str {
199 match s {
200 crate::tui::app::TranscriptSpacing::Compact => "compact",
201 crate::tui::app::TranscriptSpacing::Spacious => "spacious",
202 }
203 }
204 let value = match key.as_str() {
205 "model" => {
206 if app.auto_model {
207 let mut label = "auto (auto-select model per turn)".to_string();
208 if let Some(effective) = app.last_effective_model.as_deref()
209 && effective != "auto"
210 {
211 label.push_str(&format!("; last: {effective}"));
212 }
213 Some(label)
214 } else {
215 Some(app.model.clone())
216 }
217 }
218 "provider" => Some(app.provider_identity_for_persistence().to_string()),
219 "approval_mode" | "approval" => Some(app.approval_mode.permission_chip_label().to_string()),
220 "allow_shell" | "shell" | "exec_shell" => Some(app.allow_shell.to_string()),
221 "base_url" => {
222 let config = match codewhale_plugins::providers::load_config(
223 app.config_path.clone(),
224 app.config_profile.as_deref(),
225 ) {
226 Ok(config) => config,
227 Err(err) => {
228 return ConfigReply::error(format!("Failed to load config: {err}"));
229 }
230 };
231 Some(config.active_route_base_url())
232 }
233 // `/config title` reports the config-level default, not a session's
234 // `/title` override. The latter is intentionally a separate setting
235 // and is reported by bare `/title`.
236 "title" | "window_title" | "tab_title" => Some(
237 app.title_default
238 .clone()
239 .unwrap_or_else(|| "(unset)".to_string()),
240 ),
241 "provider_url" | "provider_base_url" | "endpoint" => {
242 let config = match codewhale_plugins::providers::load_config(
243 app.config_path.clone(),
244 app.config_profile.as_deref(),
245 ) {
246 Ok(mut config) => {
247 config.provider = Some(app.provider_identity_for_persistence().to_string());
248 config
249 }
250 Err(err) => {
251 return ConfigReply::error(format!("Failed to load config: {err}"));
252 }
253 };
254 Some(config.active_route_base_url())
255 }
256 "context_window" | "context_window_tokens" => Some(format!(
257 "{} (effective {} from {})",
258 config_context_window_override(app)
259 .map_or_else(|| "not set".to_string(), |tokens| tokens.to_string()),
260 app.effective_context_window(),
261 app.effective_context_window_source().display_label(),
262 )),
263 "stream_chunk_timeout_secs" => Some(app.stream_chunk_timeout_secs.to_string()),
264 "posture_bar" => Some(app.posture_bar.as_setting().to_string()),
265 "metrics_line" => Some(app.metrics_line.as_setting().to_string()),
266 "locale" | "language" => Some(locale_display(app.ui_locale).to_string()),
267 "theme" | "ui_theme" => Some(
268 if app
269 .theme_name
270 .starts_with(codewhale_palette::USER_THEME_PREFIX)
271 {
272 app.theme_name.clone()
273 } else {
274 codewhale_palette::theme_label_for_mode(app.ui_theme.mode).to_string()
275 },
276 ),
277 "background_color" | "background" | "bg" => {
278 codewhale_palette::hex_rgb_string(app.ui_theme.surface_bg)
279 .or_else(|| Some("(default)".to_string()))
280 }
281 "auto_compact" | "compact" => {
282 Some(if app.auto_compact { "true" } else { "false" }.to_string())
283 }
284 "calm_mode" | "calm" => Some(if app.calm_mode { "true" } else { "false" }.to_string()),
285 "pet_mode" => Some(app.pet_watch.enabled.to_string()),
286 "low_motion" | "motion" => Some(if app.low_motion { "true" } else { "false" }.to_string()),
287 "fancy_animations" | "fancy" | "animations" => Some(
288 if app.fancy_animations {
289 "true"
290 } else {
291 "false"
292 }
293 .to_string(),
294 ),
295 "bracketed_paste" | "paste" => Some(
296 if app.use_bracketed_paste {
297 "true"
298 } else {
299 "false"
300 }
301 .to_string(),
302 ),
303 "paste_burst_detection" | "paste_burst" => Some(
304 if app.use_paste_burst_detection {
305 "true"
306 } else {
307 "false"
308 }
309 .to_string(),
310 ),
311 "show_thinking" | "thinking" => {
312 Some(if app.show_thinking { "true" } else { "false" }.to_string())
313 }
314 "thinking_default_expanded" | "thinking_expanded" => Some(
315 if app.thinking_default_expanded {
316 "true"
317 } else {
318 "false"
319 }
320 .to_string(),
321 ),
322 "thinking_preview_lines" | "thinking_preview" => {
323 Some(app.thinking_preview_lines.to_string())
324 }
325 "help_expand_groups" | "help_expanded" => Some(
326 if app.help_expand_groups {
327 "true"
328 } else {
329 "false"
330 }
331 .to_string(),
332 ),
333 "contextual_tips" => Some(app.behavioral_tips.enabled().to_string()),
334 "pin_last_prompt" | "pin_prompt" => {
335 Some(if app.pin_last_prompt { "true" } else { "false" }.to_string())
336 }
337 "thinking_highlight" | "reasoning_highlight" => Some(
338 if app.thinking_highlight {
339 "true"
340 } else {
341 "false"
342 }
343 .to_string(),
344 ),
345 "show_tool_details" | "tool_details" => Some(
346 if app.show_tool_details {
347 "true"
348 } else {
349 "false"
350 }
351 .to_string(),
352 ),
353 "inline_diffs" | "inline_diff" | "diffs" => {
354 Some(app.inline_diff_mode.as_setting().to_string())
355 }
356 "mode" | "default_mode" => Some(app.mode.as_setting().to_string()),
357 "max_history" | "history" => Some(app.max_input_history.to_string()),
358 "work_surface_placement" | "work_surface" | "work_rail" => {
359 Some(app.work_surface.placement.as_setting().to_string())
360 }
361 "rail_panel" | "rail" => Some(app.work_surface.panel.as_setting().to_string()),
362 "work_surface_top_height" | "work_top_height" => {
363 Some(app.work_surface.top_height.to_string())
364 }
365 "work_surface_side_width" | "work_side_width" => {
366 Some(app.work_surface.side_width.to_string())
367 }
368 "tool_collapse" | "tool_collapse_mode" | "collapse" => {
369 Some(app.tool_collapse_mode.as_setting().to_string())
370 }
371 "context_panel" | "context" | "session_panel" => {
372 Some(if app.context_panel { "true" } else { "false" }.to_string())
373 }
374 "sessions_rail" | "sessions_panel" | "session_rail" => {
375 Some(if app.sessions_rail { "true" } else { "false" }.to_string())
376 }
377 // Read the persisted value rather than reporting a hard-coded default:
378 // this setting is consumed at startup by `main`, so `App` has no live
379 // copy, and printing "false" unconditionally would misreport a user who
380 // has it on.
381 "session_auto_resume" | "auto_resume" => Some(
382 if codewhale_runtime::settings::Settings::load_persisted()
383 .map(|settings| settings.session_auto_resume)
384 .unwrap_or(false)
385 {
386 "true"
387 } else {
388 "false"
389 }
390 .to_string(),
391 ),
392 "composer_density" | "composer" => Some(density_display(app.composer_density).to_string()),
393 "composer_border" | "border" => {
394 Some(if app.composer_border { "true" } else { "false" }.to_string())
395 }
396 "composer_multiline_mode" | "multiline_mode" | "multiline" => Some(
397 if app.composer_multiline_mode {
398 "true"
399 } else {
400 "false"
401 }
402 .to_string(),
403 ),
404 "composer_vim_mode" | "vim_mode" | "vim" => Some(
405 if app.composer.vim_enabled {
406 "vim"
407 } else {
408 "normal"
409 }
410 .to_string(),
411 ),
412 "transcript_spacing" | "spacing" => {
413 Some(spacing_display(app.transcript_spacing).to_string())
414 }
415 "status_indicator" | "indicator" => Some(app.status_indicator.clone()),
416 "synchronized_output" | "sync_output" | "sync" => Some(
417 if app.synchronized_output_enabled {
418 "on"
419 } else {
420 "off"
421 }
422 .to_string(),
423 ),
424 "cost_currency" | "currency" => Some(
425 match app.cost_currency {
426 codewhale_config::pricing::CostCurrency::Usd => "usd",
427 codewhale_config::pricing::CostCurrency::Cny => "cny",
428 }
429 .to_string(),
430 ),
431 "default_model" => match saved_deepseek_default_model(app) {
432 Ok(model) => Some(model),
433 Err(error) => return ConfigReply::error(error),
434 },
435 "reasoning_effort" | "effort" => Some(
436 app.reasoning_effort
437 .as_setting_for_provider(app.api_provider)
438 .to_string(),
439 ),
440 "workspace_follow_symlinks" | "follow_symlinks" => match Settings::load() {
441 Ok(settings) => Some(format!(
442 "{} (restart required for engine tools)",
443 settings.workspace_follow_symlinks
444 )),
445 Err(err) => return config_lookup_failed(app.ui_locale, &key, err),
446 },
447 "search" | "search.provider" | "search_provider" => match load_command_config(app) {
448 Ok(config) => Some(search_provider_display(&config, app.ui_locale)),
449 Err(err) => return config_lookup_failed(app.ui_locale, &key, err),
450 },
451 "search.third_party" | "search_third_party" => match load_command_config(app) {
452 Ok(config) => Some(search_third_party_display(app, &config)),
453 Err(err) => return config_lookup_failed(app.ui_locale, &key, err),
454 },
455 "telemetry" => match load_command_config(app) {
456 Ok(config) => Some(
457 codewhale_engine::telemetry_notice::saved_preference_enabled(&config).to_string(),
458 ),
459 Err(err) => return config_lookup_failed(app.ui_locale, &key, err),
460 },
461 "prompt_suggestion" => match load_command_config(app) {
462 Ok(config) => Some(prompt_suggestion_display(&config)),
463 Err(err) => return config_lookup_failed(app.ui_locale, &key, err),
464 },
465 "auto_review.reviewer_model" => Some(match app.auto_review_reviewer_model.clone() {
466 Some(model) => model,
467 None => match load_command_config(app) {
468 Ok(config) => config
469 .auto_review
470 .and_then(|cfg| cfg.reviewer_model)
471 .unwrap_or_else(|| "auto (default)".to_string()),
472 Err(err) => return config_lookup_failed(app.ui_locale, &key, err),
473 },
474 }),
475 "notifications" => Some(notifications_summary_value(&app.notification_settings)),
476 _ => {
477 // Any spelling `/set` accepts; internal flags, actions and
478 // receipts in the schema are not settings a user can look up.
479 let known = Settings::canonical_key(&key).is_some();
480 if known {
481 Some("(see /settings for current value)".to_string())
482 } else {
483 None
484 }
485 }
486 };
487 match value {
488 Some(v) => ConfigReply::message(format!("{key} = {v}")),
489 None => ConfigReply::error(unknown_setting_message(&key)),
490 }
491 }
492
493 fn config_lookup_failed(
494 locale: codewhale_localization::Locale,
495 key: &str,
496 err: impl std::fmt::Display,
497 ) -> ConfigReply {
498 ConfigReply::error(
499 tr(locale, MessageId::ConfigLookupFailed)
500 .replace("{key}", key)
501 .replace("{error}", &format!("{err:#}")),
502 )
503 }
504
505 /// Error for `/config <key>` when `key` is not a known setting: name the
506 /// closest real key when there is one, and point at the full list.
507 fn unknown_setting_message(key: &str) -> String {
508 // Suggest only keys `/set` accepts, the same set `known` checks above
509 // (#6563).
510 let nearest = codewhale_runtime::config_keys::nearest_key(
511 key,
512 codewhale_runtime::config_keys::settings_toml_keys(),
513 );
514 match nearest {
515 Some(candidate) => format!(
516 "Unknown setting '{key}'. Did you mean `/config {candidate}`? Run `/settings text` to list every setting."
517 ),
518 None => format!("Unknown setting '{key}'. Run `/settings text` to list every setting."),
519 }
520 }
521
522 /// Typed settings facts for `/settings text` (the command renders them).
523 pub fn show_settings(
524 _app: &mut App,
525 ) -> Result<codewhale_command_contract::config::CommandSettingsReport, String> {
526 let settings = Settings::load().map_err(|e| format!("Failed to load settings: {e}"))?;
527 Ok(settings.command_report())
528 }
529
530 fn select_pet_mode(app: &mut App, enabled: bool, persist: bool) -> ConfigReply {
531 crate::tui::pet_watch::set_enabled(app, enabled);
532 if persist {
533 app.startup_defaults
534 .spawn(crate::tui::startup_defaults::StartupDefaults::pet_mode(
535 enabled,
536 ));
537 }
538 ConfigReply::message(tr(
539 app.ui_locale,
540 if enabled {
541 MessageId::PetModeOn
542 } else {
543 MessageId::PetModeOff
544 },
545 ))
546 }
547
548 fn resolve_provider_url_value(provider: ProviderKind, value: &str) -> Result<String, String> {
549 let trimmed = value.trim();
550 if trimmed.is_empty() {
551 return Err("provider_url cannot be empty".to_string());
552 }
553
554 if provider == ProviderKind::XiaomiMimo {
555 match trimmed.to_ascii_lowercase().as_str() {
556 "token" | "token-plan" | "token_plan" | "token-plan-sgp" | "sgp" => {
557 return Ok(DEFAULT_XIAOMI_MIMO_BASE_URL.to_string());
558 }
559 "payg" | "pay-go" | "paygo" | "pay-as-you-go" | "pay_as_you_go" | "api" => {
560 return Ok(XIAOMI_MIMO_PAY_AS_YOU_GO_BASE_URL.to_string());
561 }
562 _ => {}
563 }
564 }
565
566 if trimmed.contains("://") {
567 Ok(trimmed.to_string())
568 } else if provider == ProviderKind::XiaomiMimo {
569 Err("provider_url for Xiaomi MiMo must be token-plan, pay-as-you-go, or a URL".to_string())
570 } else {
571 Err("provider_url must be a URL".to_string())
572 }
573 }
574
575 fn parse_config_bool(value: &str) -> Result<bool, String> {
576 match value.trim().to_ascii_lowercase().as_str() {
577 "on" | "true" | "yes" | "1" | "enabled" => Ok(true),
578 "off" | "false" | "no" | "0" | "disabled" => Ok(false),
579 _ => Err(format!(
580 "Failed to parse boolean '{value}': expected on/off, true/false, yes/no."
581 )),
582 }
583 }
584
585 fn approval_mode_config_value(mode: ApprovalMode) -> &'static str {
586 match mode {
587 ApprovalMode::Auto => "auto",
588 ApprovalMode::Bypass => "bypass",
589 ApprovalMode::Suggest => "on-request",
590 ApprovalMode::AcceptEdits => "accept-edits",
591 ApprovalMode::Never => "never",
592 }
593 }
594
595 pub(crate) fn config_editability_audit(
596 app: &App,
597 ) -> Result<codewhale_command_contract::config::CommandConfigAuditReport, String> {
598 let config = load_command_config(app)?;
599 let config_path =
600 codewhale_runtime::config_persistence::config_toml_path(app.config_path.as_deref())
601 .map(|path| path.display().to_string())
602 .unwrap_or_else(|_| "(unresolved)".to_string());
603
604 let mut provider_config = config.clone();
605 provider_config.provider = Some(app.provider_identity_for_persistence().to_string());
606 let model = if app.auto_model {
607 "auto".to_string()
608 } else {
609 app.model.clone()
610 };
611 let saved_permission_posture = Settings::load()
612 .ok()
613 .and_then(|settings| settings.permission_posture)
614 .unwrap_or_else(|| "(unset)".to_string());
615 let configured_approval_policy = config
616 .approval_policy
617 .clone()
618 .unwrap_or_else(|| "(unset)".to_string());
619 let effective_permissions = if app.mode == AppMode::Plan {
620 "Read Only"
621 } else {
622 app.approval_mode.permission_chip_label()
623 };
624
625 let rows = [
626 (
627 "provider",
628 app.provider_identity_for_persistence().to_string(),
629 "session",
630 "/config provider <name>",
631 codewhale_command_contract::config::ConfigMessage::literal(
632 "Switches the active provider now; edit provider in config.toml for startup default.",
633 ),
634 ),
635 (
636 "model",
637 model,
638 "session",
639 "/config model <id|auto>",
640 codewhale_command_contract::config::ConfigMessage::literal(
641 "Switches the active model now; use default_text_model in config.toml for startup default.",
642 ),
643 ),
644 (
645 "effective_permissions",
646 effective_permissions.to_string(),
647 "runtime",
648 "Shift+Tab",
649 codewhale_command_contract::config::ConfigMessage::literal(
650 "Shows the effective Work permission posture; Plan remains Read Only.",
651 ),
652 ),
653 (
654 "permission_posture",
655 saved_permission_posture,
656 "TUI settings",
657 "Shift+Tab",
658 codewhale_command_contract::config::ConfigMessage::literal(
659 "Saved in settings.toml and ignored when config/requirements manage approval policy.",
660 ),
661 ),
662 (
663 "approval_policy",
664 configured_approval_policy,
665 "persisted config",
666 "/config approval_mode <auto|on-request|never> --save",
667 codewhale_command_contract::config::ConfigMessage::literal(
668 "Top-level managed policy; Full Access is not a valid value here.",
669 ),
670 ),
671 (
672 "allow_shell",
673 app.allow_shell.to_string(),
674 "runtime+persisted",
675 "/config allow_shell <true|false> --save",
676 codewhale_command_contract::config::ConfigMessage::literal(
677 "Writes top-level allow_shell and applies to subsequent turns.",
678 ),
679 ),
680 (
681 "stream_chunk_timeout_secs",
682 app.stream_chunk_timeout_secs.to_string(),
683 "runtime+persisted",
684 "/config stream_chunk_timeout_secs <0|1..3600> --save",
685 codewhale_command_contract::config::ConfigMessage::literal(
686 "Writes [stream].chunk_timeout_secs and updates the running stream timeout.",
687 ),
688 ),
689 (
690 "posture_bar",
691 app.posture_bar.as_setting().to_string(),
692 "runtime+persisted",
693 "/config posture_bar <full|compact|hidden> --save",
694 codewhale_command_contract::config::ConfigMessage::literal(
695 "Writes [tui].posture_bar; hidden gives the row to the transcript, compact keeps the posture chips only.",
696 ),
697 ),
698 (
699 "metrics_line",
700 app.metrics_line.as_setting().to_string(),
701 "runtime+persisted",
702 "/config metrics_line <full|compact|hidden> --save",
703 codewhale_command_contract::config::ConfigMessage::literal(
704 "Writes [tui].metrics_line; hidden gives the row to the transcript, compact drops secondary counts and help while keeping selected TTFT/rate readings when they fit. Choose readings with /statusline.",
705 ),
706 ),
707 (
708 "subagents.enabled",
709 subagents_config_display_value(&config, "enabled"),
710 "runtime+persisted",
711 "/config subagents on|off --save",
712 codewhale_command_contract::config::ConfigMessage::literal(
713 "Writes [subagents].enabled and updates subsequent sub-agent launches.",
714 ),
715 ),
716 (
717 "subagents.max_concurrent",
718 subagents_config_display_value(&config, "max_concurrent"),
719 "runtime+persisted",
720 "/config subagents max_concurrent <n> --save",
721 codewhale_command_contract::config::ConfigMessage::literal(
722 "Clamped with Config::max_subagents and written to [subagents].max_concurrent.",
723 ),
724 ),
725 (
726 "subagents.max_depth",
727 subagents_config_display_value(&config, "max_depth"),
728 "runtime+persisted",
729 "/config subagents max_depth <n> --save",
730 codewhale_command_contract::config::ConfigMessage::literal(
731 "Clamped to the configured spawn-depth ceiling.",
732 ),
733 ),
734 (
735 "subagents.launch_concurrency",
736 subagents_config_display_value(&config, "launch_concurrency"),
737 "runtime+persisted",
738 "/config subagents launch_concurrency <n> --save",
739 codewhale_command_contract::config::ConfigMessage::literal(
740 "Clamped to the resolved sub-agent concurrency cap.",
741 ),
742 ),
743 (
744 "subagents.api_timeout_secs",
745 subagents_config_display_value(&config, "api_timeout_secs"),
746 "runtime+persisted",
747 "/config subagents api_timeout_secs <seconds> --save",
748 codewhale_command_contract::config::ConfigMessage::literal(
749 "0 means the compiled default; non-zero values are clamped to the documented range.",
750 ),
751 ),
752 (
753 "subagents.heartbeat_timeout_secs",
754 subagents_config_display_value(&config, "heartbeat_timeout_secs"),
755 "runtime+persisted",
756 "/config subagents heartbeat_timeout_secs <seconds> --save",
757 codewhale_command_contract::config::ConfigMessage::literal(
758 "0 means the compiled default; non-zero values are clamped to the documented range.",
759 ),
760 ),
761 (
762 "base_url",
763 config.active_route_base_url(),
764 "persisted restart",
765 "/config base_url <url> --save",
766 codewhale_command_contract::config::ConfigMessage::literal(
767 "Writes top-level base_url; model clients read it on startup.",
768 ),
769 ),
770 (
771 "providers.<active>.base_url",
772 provider_config.active_route_base_url(),
773 "persisted restart",
774 "/config provider_url <url> --save",
775 codewhale_command_contract::config::ConfigMessage::literal(
776 "Writes the active provider table; model clients read it on startup.",
777 ),
778 ),
779 (
780 "providers.<active>.context_window",
781 config_context_window_override(app)
782 .map_or_else(|| "(unset)".to_string(), |tokens| tokens.to_string()),
783 "persisted restart",
784 "edit [providers.<active>] context_window = <tokens>",
785 codewhale_command_contract::config::ConfigMessage::literal(
786 "Overrides compaction, context-pressure, header, and preflight input budgets; use 262144 to cap a 1M route to 256K.",
787 ),
788 ),
789 (
790 "effective_context_window",
791 format!(
792 "{} ({})",
793 app.effective_context_window(),
794 app.effective_context_window_source().display_label(),
795 ),
796 "runtime",
797 "/config context_window",
798 codewhale_command_contract::config::ConfigMessage::literal(
799 "The shared resolved window used by every active-route budget surface.",
800 ),
801 ),
802 (
803 "mcp_config_path",
804 app.mcp_config_path.display().to_string(),
805 "persisted live reload",
806 "/config mcp_config_path <path> --save",
807 codewhale_command_contract::config::ConfigMessage::literal(
808 "Run /mcp reload to rebuild the live model-visible tool pool.",
809 ),
810 ),
811 (
812 "workspace_follow_symlinks",
813 app.workspace_follow_symlinks.to_string(),
814 "partial restart",
815 "/config workspace_follow_symlinks <true|false> --save",
816 codewhale_command_contract::config::ConfigMessage::literal(
817 "Updates TUI file completion now; engine tools require restart.",
818 ),
819 ),
820 (
821 "search.provider",
822 search_provider_display(&config, app.ui_locale),
823 "runtime+persisted",
824 "/config search.provider <name> --save",
825 codewhale_command_contract::config::ConfigMessage::keyed(
826 "config_audit_search_provider",
827 ),
828 ),
829 (
830 "search.third_party",
831 search_third_party_display(app, &config),
832 "persisted live",
833 "/config search.third_party <ask|on|off>",
834 codewhale_command_contract::config::ConfigMessage::literal(
835 "Writes [search] third_party; the next web search applies it.",
836 ),
837 ),
838 (
839 "prompt_suggestion",
840 prompt_suggestion_display(&config),
841 "runtime+persisted",
842 "/config prompt_suggestion <true|false> --save",
843 codewhale_command_contract::config::ConfigMessage::keyed(
844 "config_audit_prompt_suggestion",
845 ),
846 ),
847 (
848 "auto_review.reviewer_model",
849 app.auto_review_reviewer_model
850 .clone()
851 .or_else(|| {
852 config
853 .auto_review
854 .as_ref()
855 .and_then(|cfg| cfg.reviewer_model.clone())
856 })
857 .unwrap_or_else(|| "auto (default)".to_string()),
858 "runtime+persisted",
859 "/config auto_review.reviewer_model <model|default> --save",
860 codewhale_command_contract::config::ConfigMessage::literal(
861 "Applies to subsequent Auto-Review turns; pass default to restore catalog selection.",
862 ),
863 ),
864 (
865 "notifications",
866 notifications_summary(&config),
867 "runtime+persisted",
868 "/config notifications <method|threshold_secs|quiet|completion_sound> <value> --save",
869 codewhale_command_contract::config::ConfigMessage::keyed("config_audit_notifications"),
870 ),
871 (
872 "instructions",
873 file_only_status(config.instructions.as_ref().map(|v| !v.is_empty())),
874 "file-only restart",
875 "edit config.toml",
876 codewhale_command_contract::config::ConfigMessage::literal(
877 "Prompt layers are loaded before the first turn.",
878 ),
879 ),
880 (
881 "hooks",
882 file_only_status(config.hooks.as_ref().map(|_| true)),
883 "file-only",
884 "edit config.toml",
885 codewhale_command_contract::config::ConfigMessage::literal(
886 "Hook definitions are structured TOML, not a scalar runtime setting.",
887 ),
888 ),
889 (
890 "network",
891 file_only_status(config.network.as_ref().map(|_| true)),
892 "file-only",
893 "edit config.toml",
894 codewhale_command_contract::config::ConfigMessage::literal(
895 "Network policy is evaluated by tool dispatch and should be reviewed as TOML.",
896 ),
897 ),
898 (
899 "tools",
900 file_only_status(config.tools.as_ref().map(|_| true)),
901 "file-only restart",
902 "edit config.toml",
903 codewhale_command_contract::config::ConfigMessage::literal(
904 "Tool catalog policy is built before model/tool negotiation.",
905 ),
906 ),
907 (
908 "memory",
909 file_only_status(config.memory.as_ref().map(|_| true)),
910 "file-only restart",
911 "edit config.toml",
912 codewhale_command_contract::config::ConfigMessage::literal(
913 "Memory loading changes prompt context and is resolved at startup.",
914 ),
915 ),
916 (
917 "runtime_api",
918 file_only_status(config.runtime_api.as_ref().map(|_| true)),
919 "file-only restart",
920 "edit config.toml",
921 codewhale_command_contract::config::ConfigMessage::literal(
922 "Serve/API tuning belongs to the runtime server startup path.",
923 ),
924 ),
925 (
926 "vision_model",
927 file_only_status(config.vision_model.as_ref().map(|_| true)),
928 "file-only restart",
929 "edit config.toml",
930 codewhale_command_contract::config::ConfigMessage::literal(
931 "Image-analysis provider clients are configured outside the scalar /config editor.",
932 ),
933 ),
934 ];
935
936 Ok(
937 codewhale_command_contract::config::CommandConfigAuditReport {
938 config_path,
939 rows: rows
940 .into_iter()
941 .map(|(key, current, editability, command, note)| {
942 codewhale_command_contract::config::CommandConfigAuditRow {
943 key: key.to_string(),
944 current,
945 editability: editability.to_string(),
946 command: command.to_string(),
947 note,
948 }
949 })
950 .collect(),
951 },
952 )
953 }
954
955 fn file_only_status(configured: Option<bool>) -> String {
956 match configured {
957 Some(true) => "configured".to_string(),
958 Some(false) => "empty".to_string(),
959 None => "unset".to_string(),
960 }
961 }
962
963 fn search_provider_display(config: &Config, locale: codewhale_localization::Locale) -> String {
964 let resolved = config.search_provider_resolution();
965 let source = match resolved.source {
966 SearchProviderSource::Default => tr(locale, MessageId::ConfigDefaultValue)
967 .trim_matches(&['(', ')'][..])
968 .to_string(),
969 SearchProviderSource::Config => "config.toml".to_string(),
970 SearchProviderSource::EnvOverride => "CODEWHALE_SEARCH_PROVIDER".to_string(),
971 // Same token doctor prints: the signal is a Tavily key, not a disk
972 // pin, so never name `TAVILY_API_KEY` (the winner may have been a
973 // generic `tvly-` `[search] api_key`).
974 SearchProviderSource::TavilyKey => "tavily key".to_string(),
975 };
976 tr(locale, MessageId::ConfigCommandSource)
977 .replace("{value}", resolved.provider.as_str())
978 .replace("{source}", &source)
979 }
980
981 fn search_third_party_display(app: &App, config: &Config) -> String {
982 let persisted =
983 codewhale_runtime::config_persistence::config_toml_path(app.config_path.as_deref())
984 .ok()
985 .and_then(|path| codewhale_runtime::config::read_persisted_search_choice(&path).ok());
986 let resolved = SearchThirdPartyResolution::with_persisted(
987 persisted,
988 config.search.as_ref().and_then(|search| search.third_party),
989 config.search_consent_implied(),
990 );
991 let source = match resolved.source {
992 SearchThirdPartySource::Default => tr(app.ui_locale, MessageId::ConfigDefaultValue)
993 .trim_matches(&['(', ')'][..])
994 .to_string(),
995 SearchThirdPartySource::Config => "config.toml".to_string(),
996 SearchThirdPartySource::Implied => "implied".to_string(),
997 };
998 tr(app.ui_locale, MessageId::ConfigCommandSource)
999 .replace("{value}", resolved.value.as_str())
1000 .replace("{source}", &source)
1001 }
1002
1003 pub(crate) fn set_search_third_party(app: &mut App, value: &str) -> ConfigReply {
1004 let Some(choice) = SearchThirdParty::parse(value) else {
1005 return ConfigReply::error(ConfigMessage::keyed_with(
1006 "config_command_invalid_value",
1007 vec![
1008 (
1009 "key".to_string(),
1010 ConfigMessage::literal("search.third_party"),
1011 ),
1012 ("value".to_string(), ConfigMessage::literal(value)),
1013 (
1014 "choices".to_string(),
1015 ConfigMessage::literal("ask, on, off"),
1016 ),
1017 ],
1018 ));
1019 };
1020 let written = if choice == SearchThirdParty::Ask {
1021 codewhale_runtime::config_persistence::persist_unset_table_key(
1022 app.config_path.as_deref(),
1023 "search",
1024 "third_party",
1025 )
1026 } else {
1027 persist_table_string_key(
1028 app.config_path.as_deref(),
1029 "search",
1030 "third_party",
1031 choice.as_str(),
1032 )
1033 };
1034 match written {
1035 Ok(path) => ConfigReply::message(format!(
1036 "search.third_party = {} (saved to {}; the next web search applies it)",
1037 choice.as_str(),
1038 path.display()
1039 )),
1040 Err(err) => ConfigReply::error(ConfigMessage::keyed_with(
1041 "startup_default_not_saved",
1042 vec![
1043 (
1044 "setting".to_string(),
1045 ConfigMessage::literal("search.third_party"),
1046 ),
1047 ("error".to_string(), ConfigMessage::literal(err.to_string())),
1048 ],
1049 )),
1050 }
1051 }
1052
1053 fn prompt_suggestion_display(config: &Config) -> String {
1054 config.prompt_suggestion_enabled().to_string()
1055 }
1056
1057 fn notifications_summary(config: &Config) -> String {
1058 notifications_summary_value(&config.notifications_config())
1059 }
1060
1061 fn notifications_summary_value(notifications: &NotificationsConfig) -> String {
1062 format!(
1063 "method={} threshold={}s sound={} quiet={}",
1064 notifications.method.as_str(),
1065 notifications.threshold_secs,
1066 notifications.display(NotificationSetting::Sound),
1067 notifications.quiet
1068 )
1069 }
1070
1071 pub(crate) fn set_search_provider(app: &mut App, value: &str, persist: bool) -> ConfigReply {
1072 let Some(provider) = SearchProvider::parse(value) else {
1073 return ConfigReply::error(ConfigMessage::keyed_with(
1074 "config_command_invalid_value",
1075 vec![
1076 ("key".to_string(), ConfigMessage::literal("search.provider")),
1077 ("value".to_string(), ConfigMessage::literal(value)),
1078 (
1079 "choices".to_string(),
1080 ConfigMessage::literal(SearchProvider::names_hint()),
1081 ),
1082 ],
1083 ));
1084 };
1085
1086 let scope = if persist {
1087 match persist_table_string_key(
1088 app.config_path.as_deref(),
1089 "search",
1090 "provider",
1091 provider.as_str(),
1092 ) {
1093 Ok(path) => ConfigMessage::concat(vec![
1094 ConfigMessage::keyed("config_scope_saved"),
1095 ConfigMessage::literal(format!(" {}", path.display())),
1096 ]),
1097 Err(err) => {
1098 return ConfigReply::error(ConfigMessage::keyed_with(
1099 "startup_default_not_saved",
1100 vec![
1101 (
1102 "setting".to_string(),
1103 ConfigMessage::literal("search.provider"),
1104 ),
1105 ("error".to_string(), ConfigMessage::literal(err.to_string())),
1106 ],
1107 ));
1108 }
1109 }
1110 } else {
1111 ConfigMessage::keyed("config_scope_session")
1112 };
1113
1114 config_action_reply(
1115 ConfigMessage::keyed_with(
1116 "config_search_updated",
1117 vec![
1118 (
1119 "value".to_string(),
1120 ConfigMessage::literal(provider.as_str()),
1121 ),
1122 ("scope".to_string(), scope),
1123 ],
1124 ),
1125 AppAction::UpdateSearchProvider { provider },
1126 )
1127 }
1128
1129 fn set_prompt_suggestion(app: &mut App, value: &str, persist: bool) -> ConfigReply {
1130 let enabled = match parse_config_bool(value) {
1131 Ok(enabled) => enabled,
1132 Err(_) => {
1133 return ConfigReply::error(ConfigMessage::keyed_with(
1134 "config_command_invalid_value",
1135 vec![
1136 (
1137 "key".to_string(),
1138 ConfigMessage::literal("prompt_suggestion"),
1139 ),
1140 ("value".to_string(), ConfigMessage::literal(value)),
1141 (
1142 "choices".to_string(),
1143 ConfigMessage::literal("on, off, true, false, yes, no"),
1144 ),
1145 ],
1146 ));
1147 }
1148 };
1149 let scope = if persist {
1150 match persist_root_bool_key(app.config_path.as_deref(), "prompt_suggestion", enabled) {
1151 Ok(path) => ConfigMessage::concat(vec![
1152 ConfigMessage::keyed("config_scope_saved"),
1153 ConfigMessage::literal(format!(" {}", path.display())),
1154 ]),
1155 Err(err) => {
1156 return ConfigReply::error(ConfigMessage::keyed_with(
1157 "startup_default_not_saved",
1158 vec![
1159 (
1160 "setting".to_string(),
1161 ConfigMessage::literal("prompt_suggestion"),
1162 ),
1163 ("error".to_string(), ConfigMessage::literal(err.to_string())),
1164 ],
1165 ));
1166 }
1167 }
1168 } else {
1169 ConfigMessage::keyed("config_scope_session")
1170 };
1171 config_action_reply(
1172 ConfigMessage::keyed_with(
1173 "config_prompt_suggestion_updated",
1174 vec![
1175 (
1176 "value".to_string(),
1177 ConfigMessage::literal(enabled.to_string()),
1178 ),
1179 ("scope".to_string(), scope),
1180 ],
1181 ),
1182 AppAction::UpdatePromptSuggestion { enabled },
1183 )
1184 }
1185
1186 fn set_auto_review_reviewer_model(app: &mut App, value: &str, persist: bool) -> ConfigReply {
1187 let trimmed = value.trim();
1188 let reviewer_model = if matches!(
1189 trimmed.to_ascii_lowercase().as_str(),
1190 "default" | "auto" | "unset" | "none" | "clear"
1191 ) {
1192 None
1193 } else {
1194 if let Err(err) = codewhale_runtime::config::validate_auto_review_reviewer_model(trimmed) {
1195 return ConfigReply::error(err.to_string());
1196 }
1197 Some(trimmed.to_string())
1198 };
1199 let scope = if persist {
1200 let result = match reviewer_model.as_deref() {
1201 Some(model) => persist_table_string_key(
1202 app.config_path.as_deref(),
1203 "auto_review",
1204 "reviewer_model",
1205 model,
1206 ),
1207 None => codewhale_runtime::config_persistence::persist_unset_table_key(
1208 app.config_path.as_deref(),
1209 "auto_review",
1210 "reviewer_model",
1211 ),
1212 };
1213 match result {
1214 Ok(path) => format!("saved to {}", path.display()),
1215 Err(err) => {
1216 return ConfigReply::error(format!(
1217 "Failed to save auto_review.reviewer_model: {err}"
1218 ));
1219 }
1220 }
1221 } else {
1222 "session only".to_string()
1223 };
1224 let display_value = reviewer_model.as_deref().unwrap_or("auto (default)");
1225 config_action_reply(
1226 ConfigMessage::literal(format!(
1227 "auto_review.reviewer_model = {display_value} ({scope})"
1228 )),
1229 AppAction::SetAutoReviewReviewerModel { reviewer_model },
1230 )
1231 }
1232
1233 pub(crate) fn show_notifications_status(app: &App) -> ConfigReply {
1234 let mut lines = vec!["[notifications]".to_string()];
1235 lines.extend(NotificationSetting::ALL.into_iter().map(|setting| {
1236 format!(
1237 "{} = {}",
1238 setting.key(),
1239 app.notification_settings.display(setting)
1240 )
1241 }));
1242 ConfigReply::message(ConfigMessage::concat(vec![
1243 ConfigMessage::literal(format!("{}\n", lines.join("\n"))),
1244 ConfigMessage::keyed("config_notifications_set_hint"),
1245 ]))
1246 }
1247
1248 pub(crate) fn show_notifications_setting(app: &App, key: &str) -> ConfigReply {
1249 let Some(setting) = NotificationSetting::parse(key) else {
1250 return invalid_notification_value(app, key, key, "/config notifications status");
1251 };
1252 ConfigReply::message(format!(
1253 "notifications.{} = {}",
1254 setting.key(),
1255 app.notification_settings.display(setting)
1256 ))
1257 }
1258
1259 fn invalid_notification_value(_app: &App, key: &str, value: &str, choices: &str) -> ConfigReply {
1260 ConfigReply::error(ConfigMessage::keyed_with(
1261 "config_command_invalid_value",
1262 vec![
1263 (
1264 "key".to_string(),
1265 ConfigMessage::literal(format!("notifications.{key}")),
1266 ),
1267 ("value".to_string(), ConfigMessage::literal(value)),
1268 ("choices".to_string(), ConfigMessage::literal(choices)),
1269 ],
1270 ))
1271 }
1272
1273 pub(crate) fn set_notifications_value(
1274 app: &mut App,
1275 key: &str,
1276 value: &str,
1277 persist: bool,
1278 ) -> ConfigReply {
1279 let Some(setting) = NotificationSetting::parse(key) else {
1280 return invalid_notification_value(app, key, value, "/config notifications status");
1281 };
1282 let update = match NotificationConfigUpdate::parse(setting, value) {
1283 Ok(update) => update,
1284 Err(_) => return invalid_notification_value(app, setting.key(), value, setting.choices()),
1285 };
1286 let scope = if persist {
1287 let result =
1288 codewhale_runtime::config_persistence::config_toml_path(app.config_path.as_deref())
1289 .and_then(|path| {
1290 update.persist_for_profile(&path, app.config_profile.as_deref())?;
1291 Ok(path)
1292 });
1293 match result {
1294 Ok(path) => ConfigMessage::concat(vec![
1295 ConfigMessage::keyed("config_scope_saved"),
1296 ConfigMessage::literal(format!(" {}", path.display())),
1297 ]),
1298 Err(error) => {
1299 return ConfigReply::error(ConfigMessage::keyed_with(
1300 "startup_default_not_saved",
1301 vec![
1302 (
1303 "setting".to_string(),
1304 ConfigMessage::literal(format!("notifications.{}", setting.key())),
1305 ),
1306 (
1307 "error".to_string(),
1308 ConfigMessage::literal(error.to_string()),
1309 ),
1310 ],
1311 ));
1312 }
1313 }
1314 } else {
1315 ConfigMessage::keyed("config_scope_session")
1316 };
1317 config_action_reply(
1318 ConfigMessage::keyed_with(
1319 "config_notification_updated",
1320 vec![
1321 ("key".to_string(), ConfigMessage::literal(setting.key())),
1322 (
1323 "value".to_string(),
1324 ConfigMessage::literal(update.display()),
1325 ),
1326 ("scope".to_string(), scope),
1327 ],
1328 ),
1329 AppAction::UpdateNotification { update },
1330 )
1331 }
1332
1333 fn stream_chunk_timeout_value_label(raw: u64, resolved: u64) -> String {
1334 if raw == 0 {
1335 format!("0 (default {resolved})")
1336 } else {
1337 resolved.to_string()
1338 }
1339 }
1340
1341 fn load_command_config(app: &App) -> Result<Config, String> {
1342 codewhale_plugins::providers::load_config(
1343 app.config_path.clone(),
1344 app.config_profile.as_deref(),
1345 )
1346 .map_err(|err| format!("Failed to load config: {err}"))
1347 }
1348
1349 /// The compatibility default_model command describes saved DeepSeek config,
1350 /// independent of the active provider and one-launch environment overrides.
1351 fn saved_deepseek_default_model(app: &App) -> Result<String, String> {
1352 let path = codewhale_runtime::config_persistence::config_toml_path(app.config_path.as_deref())
1353 .map_err(|error| format!("Failed to resolve config: {error}"))?;
1354 let read = || -> anyhow::Result<String> {
1355 let store = codewhale_config::ConfigStore::load(Some(path.clone()))?;
1356 let mut config = Config::from_saved_document(
1357 store.original_body().unwrap_or(""),
1358 app.config_profile.as_deref(),
1359 )?;
1360 if app.config_profile.is_none() && codewhale_runtime::config::is_home_config_path(&path) {
1361 config.apply_saved_selection(&Settings::load_legacy_route_preferences_read_only()?);
1362 }
1363 let key = if app.admitted_provider_identity().is_ok_and(|identity| {
1364 identity.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
1365 }) {
1366 codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id
1367 } else {
1368 ProviderKind::Deepseek.as_str()
1369 };
1370 let identity = config
1371 .resolve_provider_pin_identity(key)
1372 .map_err(anyhow::Error::msg)?;
1373 anyhow::ensure!(
1374 identity.provider == ProviderKind::Deepseek,
1375 "The saved provider identity is shadowed by another route"
1376 );
1377 config
1378 .scope_to_provider_identity(&identity)
1379 .map_err(anyhow::Error::msg)?;
1380 Ok(config.default_model())
1381 };
1382 read().map_err(|error| format!("Failed to read saved model config: {error}"))
1383 }
1384
1385 pub(crate) fn subagents_status(
1386 app: &App,
1387 ) -> Result<codewhale_command_contract::config::CommandSubagentsReport, String> {
1388 let config = load_command_config(app)?;
1389 let path = codewhale_runtime::config_persistence::config_toml_path(app.config_path.as_deref())
1390 .map(|path| path.display().to_string())
1391 .unwrap_or_else(|_| "(unresolved)".to_string());
1392 let disabled_reason = config.subagents_disabled_reason();
1393 let identity = app
1394 .admitted_provider_identity()
1395 .and_then(|identity| config.verify_provider_identity(identity).map(|()| identity))
1396 .map_err(|error| error.to_string())?;
1397 let subagents = config.subagents.as_ref();
1398 let provider_subagents = config.subagent_provider_config(identity);
1399 let provider_label = identity
1400 .compatibility()
1401 .map_or(identity.key.as_str(), |row| row.label)
1402 .to_string();
1403 let limits = vec![
1404 codewhale_command_contract::config::CommandSubagentsLimit {
1405 key: "max_concurrent",
1406 raw: option_display(subagents.and_then(|cfg| cfg.max_concurrent)),
1407 global: config.max_subagents().to_string(),
1408 provider: config.max_subagents_for_provider(identity).to_string(),
1409 },
1410 codewhale_command_contract::config::CommandSubagentsLimit {
1411 key: "max_depth",
1412 raw: option_display(subagents.and_then(|cfg| cfg.max_depth)),
1413 global: config.subagent_max_spawn_depth().to_string(),
1414 provider: config
1415 .subagent_max_spawn_depth_for_provider(identity)
1416 .to_string(),
1417 },
1418 codewhale_command_contract::config::CommandSubagentsLimit {
1419 key: "launch_concurrency",
1420 raw: option_display(subagents.and_then(|cfg| cfg.launch_concurrency)),
1421 global: config.launch_concurrency().to_string(),
1422 provider: config.launch_concurrency_for_provider(identity).to_string(),
1423 },
1424 codewhale_command_contract::config::CommandSubagentsLimit {
1425 key: "api_timeout_secs",
1426 raw: option_display(subagents.and_then(|cfg| cfg.api_timeout_secs)),
1427 global: config.subagent_api_timeout_secs().to_string(),
1428 provider: config
1429 .subagent_api_timeout_secs_for_provider(identity)
1430 .to_string(),
1431 },
1432 codewhale_command_contract::config::CommandSubagentsLimit {
1433 key: "heartbeat_timeout_secs",
1434 raw: option_display(subagents.and_then(|cfg| cfg.heartbeat_timeout_secs)),
1435 global: config.subagent_heartbeat_timeout_secs().to_string(),
1436 provider: config
1437 .subagent_heartbeat_timeout_secs_for_provider(identity)
1438 .to_string(),
1439 },
1440 ];
1441 let provider_rows = provider_subagents.map(|provider| {
1442 vec![
1443 codewhale_command_contract::config::CommandSubagentsProviderRow {
1444 key: "enabled",
1445 value: provider
1446 .enabled
1447 .map(|value| value.to_string())
1448 .unwrap_or_else(|| "inherits".to_string()),
1449 },
1450 codewhale_command_contract::config::CommandSubagentsProviderRow {
1451 key: "max_concurrent",
1452 value: option_display(provider.max_concurrent),
1453 },
1454 codewhale_command_contract::config::CommandSubagentsProviderRow {
1455 key: "max_depth",
1456 value: option_display(provider.max_depth),
1457 },
1458 codewhale_command_contract::config::CommandSubagentsProviderRow {
1459 key: "launch_concurrency",
1460 value: option_display(provider.launch_concurrency),
1461 },
1462 codewhale_command_contract::config::CommandSubagentsProviderRow {
1463 key: "max_admitted",
1464 value: option_display(provider.max_admitted),
1465 },
1466 ]
1467 });
1468 Ok(codewhale_command_contract::config::CommandSubagentsReport {
1469 disabled_reason: disabled_reason.map(str::to_string),
1470 config_path: path,
1471 provider_key: identity.key.as_str().to_string(),
1472 provider_label,
1473 explicit_enabled: subagents.and_then(|cfg| cfg.enabled),
1474 limits,
1475 provider_rows,
1476 })
1477 }
1478
1479 pub(crate) fn show_subagents_setting(app: &App, key: &str) -> ConfigReply {
1480 let config = match load_command_config(app) {
1481 Ok(config) => config,
1482 Err(err) => return ConfigReply::error(err),
1483 };
1484 let Some(key) = canonical_subagents_key(key) else {
1485 return ConfigReply::error(format!(
1486 "Unknown subagents setting '{key}'. Use `/config subagents status`."
1487 ));
1488 };
1489 let identity = match app
1490 .admitted_provider_identity()
1491 .and_then(|identity| config.verify_provider_identity(identity).map(|()| identity))
1492 {
1493 Ok(identity) => identity,
1494 Err(error) => return ConfigReply::error(error),
1495 };
1496 let subagents = config.subagents.as_ref();
1497 let value = match key {
1498 "enabled" => subagents
1499 .and_then(|cfg| cfg.enabled)
1500 .map(|value| value.to_string())
1501 .unwrap_or_else(|| "default true".to_string()),
1502 "max_concurrent" => format!(
1503 "{} (resolved global {}; active provider {})",
1504 option_display(subagents.and_then(|cfg| cfg.max_concurrent)),
1505 config.max_subagents(),
1506 config.max_subagents_for_provider(identity)
1507 ),
1508 "max_depth" => format!(
1509 "{} (resolved global {}; active provider {})",
1510 option_display(subagents.and_then(|cfg| cfg.max_depth)),
1511 config.subagent_max_spawn_depth(),
1512 config.subagent_max_spawn_depth_for_provider(identity)
1513 ),
1514 "launch_concurrency" => format!(
1515 "{} (resolved global {}; active provider {})",
1516 option_display(subagents.and_then(|cfg| cfg.launch_concurrency)),
1517 config.launch_concurrency(),
1518 config.launch_concurrency_for_provider(identity)
1519 ),
1520 "api_timeout_secs" => format!(
1521 "{} (resolved global {}; active provider {})",
1522 option_display(subagents.and_then(|cfg| cfg.api_timeout_secs)),
1523 config.subagent_api_timeout_secs(),
1524 config.subagent_api_timeout_secs_for_provider(identity)
1525 ),
1526 "heartbeat_timeout_secs" => format!(
1527 "{} (resolved global {}; active provider {})",
1528 option_display(subagents.and_then(|cfg| cfg.heartbeat_timeout_secs)),
1529 config.subagent_heartbeat_timeout_secs(),
1530 config.subagent_heartbeat_timeout_secs_for_provider(identity)
1531 ),
1532 _ => unreachable!("canonical subagent key"),
1533 };
1534 ConfigReply::message(format!("subagents.{key} = {value}"))
1535 }
1536
1537 fn option_display<T: std::fmt::Display>(value: Option<T>) -> String {
1538 value
1539 .map(|value| value.to_string())
1540 .unwrap_or_else(|| "default".to_string())
1541 }
1542
1543 fn canonical_subagents_key(key: &str) -> Option<&'static str> {
1544 let normalized = key.trim().to_ascii_lowercase();
1545 let key = normalized
1546 .strip_prefix("subagents.")
1547 .unwrap_or(normalized.as_str());
1548 match key {
1549 "enabled" | "enable" => Some("enabled"),
1550 "max_concurrent" | "max_subagents" | "concurrency" | "cap" => Some("max_concurrent"),
1551 "max_depth" | "depth" | "spawn_depth" => Some("max_depth"),
1552 "launch_concurrency" | "launches" | "launch" => Some("launch_concurrency"),
1553 "api_timeout_secs" | "api_timeout" | "step_timeout_secs" => Some("api_timeout_secs"),
1554 "heartbeat_timeout_secs" | "heartbeat_timeout" | "heartbeat" => {
1555 Some("heartbeat_timeout_secs")
1556 }
1557 _ => None,
1558 }
1559 }
1560
1561 pub(crate) fn set_subagents_config_value(
1562 app: &mut App,
1563 key: &str,
1564 value: &str,
1565 persist: bool,
1566 ) -> ConfigReply {
1567 let Some(key) = canonical_subagents_key(key) else {
1568 return ConfigReply::error(format!(
1569 "Unknown subagents setting '{key}'. Use `/config subagents status`."
1570 ));
1571 };
1572 let mut config = match load_command_config(app) {
1573 Ok(config) => config,
1574 Err(err) => return ConfigReply::error(err),
1575 };
1576 let identity = match app.admitted_provider_identity().and_then(|identity| {
1577 config
1578 .verify_provider_identity(identity)
1579 .map(|()| identity.clone())
1580 }) {
1581 Ok(identity) => identity,
1582 Err(error) => return ConfigReply::error(error),
1583 };
1584 let current_max_subagents = config.max_subagents() as u64;
1585 let subagents = config
1586 .subagents
1587 .get_or_insert_with(SubagentsConfig::default);
1588
1589 let mut note = None;
1590 let save_result = match key {
1591 "enabled" => {
1592 let enabled = match parse_config_bool(value) {
1593 Ok(enabled) => enabled,
1594 Err(err) => return ConfigReply::error(err),
1595 };
1596 subagents.enabled = Some(enabled);
1597 if persist {
1598 Some(persist_subagents_bool_key(
1599 app.config_path.as_deref(),
1600 "enabled",
1601 enabled,
1602 ))
1603 } else {
1604 None
1605 }
1606 }
1607 "max_concurrent" => {
1608 let raw = match parse_subagents_u64(key, value) {
1609 Ok(raw) => raw,
1610 Err(err) => return ConfigReply::error(err),
1611 };
1612 let clamped = raw.min(MAX_SUBAGENTS as u64);
1613 if clamped != raw {
1614 note = Some(format!("clamped from {raw} to {clamped}"));
1615 }
1616 subagents.max_concurrent = Some(clamped as usize);
1617 if persist {
1618 Some(persist_subagents_integer_key(
1619 app.config_path.as_deref(),
1620 "max_concurrent",
1621 clamped,
1622 ))
1623 } else {
1624 None
1625 }
1626 }
1627 "max_depth" => {
1628 let raw = match parse_subagents_u64(key, value) {
1629 Ok(raw) => raw,
1630 Err(err) => return ConfigReply::error(err),
1631 };
1632 let ceiling = u64::from(codewhale_config::MAX_SPAWN_DEPTH_CEILING);
1633 let clamped = raw.min(ceiling);
1634 if clamped != raw {
1635 note = Some(format!("clamped from {raw} to {clamped}"));
1636 }
1637 subagents.max_depth = Some(clamped as u32);
1638 if persist {
1639 Some(persist_subagents_integer_key(
1640 app.config_path.as_deref(),
1641 "max_depth",
1642 clamped,
1643 ))
1644 } else {
1645 None
1646 }
1647 }
1648 "launch_concurrency" => {
1649 let raw = match parse_subagents_u64(key, value) {
1650 Ok(raw) => raw,
1651 Err(err) => return ConfigReply::error(err),
1652 };
1653 let clamped = raw.clamp(1, current_max_subagents);
1654 if clamped != raw {
1655 note = Some(format!("clamped from {raw} to {clamped}"));
1656 }
1657 subagents.launch_concurrency = Some(clamped as usize);
1658 if persist {
1659 Some(persist_subagents_integer_key(
1660 app.config_path.as_deref(),
1661 "launch_concurrency",
1662 clamped,
1663 ))
1664 } else {
1665 None
1666 }
1667 }
1668 "api_timeout_secs" => {
1669 let raw = match parse_subagents_u64(key, value) {
1670 Ok(raw) => raw,
1671 Err(err) => return ConfigReply::error(err),
1672 };
1673 let stored = if raw == 0 {
1674 0
1675 } else {
1676 raw.clamp(MIN_SUBAGENT_API_TIMEOUT_SECS, MAX_SUBAGENT_API_TIMEOUT_SECS)
1677 };
1678 if stored != raw {
1679 note = Some(format!("clamped from {raw} to {stored}"));
1680 }
1681 subagents.api_timeout_secs = Some(stored);
1682 if persist {
1683 Some(persist_subagents_integer_key(
1684 app.config_path.as_deref(),
1685 "api_timeout_secs",
1686 stored,
1687 ))
1688 } else {
1689 None
1690 }
1691 }
1692 "heartbeat_timeout_secs" => {
1693 let raw = match parse_subagents_u64(key, value) {
1694 Ok(raw) => raw,
1695 Err(err) => return ConfigReply::error(err),
1696 };
1697 let stored = if raw == 0 {
1698 0
1699 } else {
1700 raw.clamp(
1701 MIN_SUBAGENT_HEARTBEAT_TIMEOUT_SECS,
1702 MAX_SUBAGENT_HEARTBEAT_TIMEOUT_SECS,
1703 )
1704 };
1705 if stored != raw {
1706 note = Some(format!("clamped from {raw} to {stored}"));
1707 }
1708 subagents.heartbeat_timeout_secs = Some(stored);
1709 if persist {
1710 Some(persist_subagents_integer_key(
1711 app.config_path.as_deref(),
1712 "heartbeat_timeout_secs",
1713 stored,
1714 ))
1715 } else {
1716 None
1717 }
1718 }
1719 _ => unreachable!("canonical subagent key"),
1720 };
1721
1722 let save_suffix = if let Some(result) = save_result {
1723 match result {
1724 Ok(path) => format!("saved to {}", path.display()),
1725 Err(err) => return ConfigReply::error(format!("Failed to save: {err}")),
1726 }
1727 } else {
1728 "session only, add --save to persist".to_string()
1729 };
1730
1731 if key == "max_concurrent" {
1732 app.max_subagents = config.max_subagents_for_provider(&identity);
1733 }
1734 let display_value = subagents_config_display_value(&config, key);
1735 let note = note.map(|note| format!("; {note}")).unwrap_or_default();
1736 config_action_reply(
1737 format!(
1738 "subagents.{key} = {display_value} ({save_suffix}; runtime updated for subsequent turns{note})"
1739 ),
1740 subagents_runtime_action(&identity, &config),
1741 )
1742 }
1743
1744 fn parse_subagents_u64(key: &str, value: &str) -> Result<u64, String> {
1745 value
1746 .trim()
1747 .parse::<u64>()
1748 .map_err(|_| format!("subagents.{key} must be a whole number"))
1749 }
1750
1751 fn subagents_config_display_value(config: &Config, key: &str) -> String {
1752 let subagents = config.subagents.as_ref();
1753 match key {
1754 "enabled" => subagents
1755 .and_then(|cfg| cfg.enabled)
1756 .map(|value| value.to_string())
1757 .unwrap_or_else(|| "default true".to_string()),
1758 "max_concurrent" => {
1759 if subagents.and_then(|cfg| cfg.max_concurrent) == Some(0) {
1760 "0 (disabled)".to_string()
1761 } else {
1762 config.max_subagents().to_string()
1763 }
1764 }
1765 "max_depth" => {
1766 if subagents.and_then(|cfg| cfg.max_depth) == Some(0) {
1767 "0 (agent tool disabled)".to_string()
1768 } else {
1769 config.subagent_max_spawn_depth().to_string()
1770 }
1771 }
1772 "launch_concurrency" => config.launch_concurrency().to_string(),
1773 "api_timeout_secs" => {
1774 let raw = subagents.and_then(|cfg| cfg.api_timeout_secs);
1775 if raw == Some(0) {
1776 format!("0 (default {DEFAULT_SUBAGENT_API_TIMEOUT_SECS})")
1777 } else {
1778 config.subagent_api_timeout_secs().to_string()
1779 }
1780 }
1781 "heartbeat_timeout_secs" => {
1782 let raw = subagents.and_then(|cfg| cfg.heartbeat_timeout_secs);
1783 if raw == Some(0) {
1784 format!("0 (default {DEFAULT_SUBAGENT_HEARTBEAT_TIMEOUT_SECS})")
1785 } else {
1786 config.subagent_heartbeat_timeout_secs().to_string()
1787 }
1788 }
1789 _ => unreachable!("canonical subagent key"),
1790 }
1791 }
1792
1793 fn subagents_runtime_action(
1794 identity: &codewhale_runtime::config::ProviderIdentity,
1795 config: &Config,
1796 ) -> AppAction {
1797 let max_subagents = config
1798 .max_subagents_for_provider(identity)
1799 .clamp(1, MAX_SUBAGENTS);
1800 AppAction::UpdateSubagentRuntimeConfig {
1801 enabled: config.subagents_enabled_for_provider(identity),
1802 max_subagents,
1803 launch_concurrency: config.launch_concurrency_for_provider(identity),
1804 max_spawn_depth: config.subagent_max_spawn_depth_for_provider(identity),
1805 api_timeout_secs: config.subagent_api_timeout_secs_for_provider(identity),
1806 heartbeat_timeout_secs: config.subagent_heartbeat_timeout_secs_for_provider(identity),
1807 }
1808 }
1809
1810 /// The subject a live-route key belongs to, or `None` if the key does not touch
1811 /// the route the engine is currently acting on.
1812 ///
1813 /// This is the single list the #2982 turn lock is enforced from. It exists
1814 /// because the lock used to live in the *selectors* — the Tab cycle, the
1815 /// pickers, the hotbar — while `/set <key> <value>` and `/config <key> <value>`
1816 /// reached the same live state through a different door. A slash command is
1817 /// reachable mid-turn (the composer accepts Shift+Enter and the slash menu while
1818 /// `is_loading`), so during a running turn `/set model …` could swap the route
1819 /// out from under the engine and persist it.
1820 ///
1821 /// `default_mode` is deliberately absent: it is a restart default that
1822 /// `set_config_value` explicitly does *not* apply to the live session, so
1823 /// refusing it would lock a key that cannot affect the turn. `mode` and the
1824 /// approval keys are absent too: the engine applies a posture change at its
1825 /// next step boundary in the running turn.
1826 fn live_route_setting_subject(key: &str) -> Option<MessageId> {
1827 match key {
1828 // `default_model` is not merely a startup default: for the DeepSeek
1829 // routes `set_config_value` installs it as the live model.
1830 "model" | "default_model" => Some(MessageId::SettingSubjectModel),
1831 "reasoning_effort" | "effort" => Some(MessageId::SettingSubjectThinking),
1832 "provider" => Some(MessageId::SettingSubjectProvider),
1833 _ => None,
1834 }
1835 }
1836
1837 /// Modify a setting at runtime
1838 pub fn set_config_value(app: &mut App, key: &str, value: &str, persist: bool) -> ConfigReply {
1839 let key = key.to_lowercase();
1840 if let Some(subagent_key) = key.strip_prefix("subagents.") {
1841 return set_subagents_config_value(app, subagent_key, value, persist);
1842 }
1843 if let Some(notifications_key) = key.strip_prefix("notifications.") {
1844 return set_notifications_value(app, notifications_key, value, persist);
1845 }
1846
1847 // Refuse before *anything* — before the disk write, and before the live
1848 // `App` mutation each arm performs. Placing the check at the top is what
1849 // makes it central: every caller of this function (`/set`, `/config k v`,
1850 // the preset mirror, the schema-driven config editor, the runtime
1851 // `ConfigUpdated` event) inherits it, and none of them can half-apply.
1852 if let Some(subject) = live_route_setting_subject(key.as_str())
1853 && app.is_loading
1854 {
1855 return ConfigReply::error(app.setting_locked_message(subject));
1856 }
1857
1858 match key.as_str() {
1859 "pet_mode" => {
1860 let enabled = match parse_config_bool(value) {
1861 Ok(enabled) => enabled,
1862 Err(_) => {
1863 return ConfigReply::error(ConfigMessage::keyed_with(
1864 "config_command_invalid_value",
1865 vec![
1866 ("key".to_string(), ConfigMessage::literal(key.clone())),
1867 ("value".to_string(), ConfigMessage::literal(value)),
1868 ("choices".to_string(), ConfigMessage::literal("on/off")),
1869 ],
1870 ));
1871 }
1872 };
1873 // /whale and the settings editor share the ordered background writer.
1874 // A failed save is reported by the existing warning mailbox.
1875 return select_pet_mode(app, enabled, persist);
1876 }
1877 "contextual_tips" => {
1878 let enabled = match parse_config_bool(value) {
1879 Ok(enabled) => enabled,
1880 Err(_) => {
1881 return ConfigReply::error(ConfigMessage::keyed_with(
1882 "config_command_invalid_value",
1883 vec![
1884 ("key".to_string(), ConfigMessage::literal(key.clone())),
1885 ("value".to_string(), ConfigMessage::literal(value)),
1886 ("choices".to_string(), ConfigMessage::literal("on/off")),
1887 ],
1888 ));
1889 }
1890 };
1891 // Apply the opt-out even when the settings file cannot be read
1892 // or saved. Only the existing single-key transaction may claim
1893 // persistence; a failure leaves the live preference in effect.
1894 app.set_contextual_tips_enabled(enabled);
1895 if persist && let Err(error) = persist_single_setting(&key, &enabled.to_string()) {
1896 let toast = tr(app.ui_locale, MessageId::ContextualTipsNotSaved)
1897 .replace("{error}", &error.to_string());
1898 app.push_status_toast(toast, crate::tui::app::StatusToastLevel::Error, Some(8_000));
1899 return ConfigReply::error(ConfigMessage::keyed_with(
1900 "contextual_tips_not_saved",
1901 vec![(
1902 "error".to_string(),
1903 ConfigMessage::literal(error.to_string()),
1904 )],
1905 ));
1906 }
1907 let scope_key = if persist {
1908 "config_scope_saved"
1909 } else {
1910 "config_scope_session"
1911 };
1912 return ConfigReply::message(ConfigMessage::concat(vec![
1913 ConfigMessage::literal(format!("contextual_tips = {enabled} (")),
1914 ConfigMessage::keyed(scope_key),
1915 ConfigMessage::literal(")"),
1916 ]));
1917 }
1918 "telemetry" => {
1919 if !persist {
1920 return ConfigReply::error(
1921 "Telemetry is a durable privacy preference. Change it in /settings or add --save.",
1922 );
1923 }
1924 let enabled = match parse_config_bool(value) {
1925 Ok(enabled) => enabled,
1926 Err(err) => return ConfigReply::error(err),
1927 };
1928 let applied = codewhale_engine::telemetry_notice::apply_persistent_preference(
1929 app.config_path.clone(),
1930 enabled,
1931 );
1932 let message = applied.message(app.ui_locale);
1933 return if applied.is_error() {
1934 ConfigReply {
1935 message: Some(ConfigMessage::literal(message)),
1936 action: None,
1937 is_error: true,
1938 }
1939 } else {
1940 ConfigReply::message(message)
1941 };
1942 }
1943 "default_model" => {
1944 let value = value.trim();
1945 let value = if value.is_empty()
1946 || matches!(
1947 value.to_ascii_lowercase().as_str(),
1948 "none" | "default" | "(default)"
1949 ) {
1950 codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL
1951 } else {
1952 value
1953 };
1954 if matches!(app.api_provider, ProviderKind::Deepseek) {
1955 return set_config_value(app, "model", value, persist);
1956 }
1957 if !persist {
1958 return ConfigReply::error(format!(
1959 "default_model is the DeepSeek startup fallback and cannot change the active {} session. Use /model for the current provider, or add --save to change only future DeepSeek sessions.",
1960 app.api_provider.as_str()
1961 ));
1962 }
1963 let saved = match load_command_config(app) {
1964 Ok(config) => config,
1965 Err(err) => return ConfigReply::error(err),
1966 };
1967 let identity = match saved.builtin_provider_identity(ProviderKind::Deepseek) {
1968 Ok(identity) => identity,
1969 Err(error) => return ConfigReply::error(error),
1970 };
1971 let model = if value.eq_ignore_ascii_case("auto") {
1972 "auto".to_string()
1973 } else {
1974 // Route-aware, matching POST /v1/config: a custom DeepSeek
1975 // endpoint owns its model namespace, so an id declared for the
1976 // saved DeepSeek route validates verbatim before the catalog
1977 // normalization runs.
1978 if codewhale_runtime::config::configured_model_for_route(
1979 &saved,
1980 ProviderKind::Deepseek,
1981 identity.key.as_str(),
1982 &saved.base_url_for_route(&identity),
1983 value.trim(),
1984 )
1985 .is_some()
1986 {
1987 value.trim().to_string()
1988 } else {
1989 let Ok(resolved) =
1990 codewhale_config::route::resolve_model(ProviderKind::Deepseek, value, None)
1991 else {
1992 return ConfigReply::error(format!("Invalid DeepSeek model '{value}'."));
1993 };
1994 let model = resolved.wire_id;
1995 if let Err(error) = validate_route(ProviderKind::Deepseek, &model) {
1996 return ConfigReply::error(error);
1997 }
1998 model
1999 }
2000 };
2001 return match codewhale_runtime::config_persistence::persist_provider_model_key(
2002 app.config_path.as_deref(),
2003 &identity,
2004 &model,
2005 ) {
2006 Ok(path) => ConfigReply::message(format!(
2007 "default_model = {model} (saved to {}); DeepSeek fallback only — active {}/{} is unchanged",
2008 path.display(),
2009 app.api_provider.as_str(),
2010 app.model_display_label()
2011 )),
2012 Err(error) => ConfigReply::error(format!("Failed to save model: {error}")),
2013 };
2014 }
2015 "model" => {
2016 // Route-aware: a custom DeepSeek (or other) endpoint owns its model
2017 // namespace. Provider-only normalization would reject a non-DeepSeek
2018 // id that the live session is already allowed to use via `/model`.
2019 // OpenCode Go stays protocol-strict even on a custom host.
2020 let auto_select = value.trim().eq_ignore_ascii_case("auto");
2021 let model = if auto_select {
2022 "auto".to_string()
2023 } else if app.api_provider == ProviderKind::OpencodeGo {
2024 let Ok(resolved) =
2025 codewhale_config::route::resolve_model(app.api_provider, value, None)
2026 else {
2027 return ConfigReply::error(format!(
2028 "Invalid model '{value}' for provider {}.",
2029 app.api_provider.as_str()
2030 ));
2031 };
2032 let model = resolved.wire_id;
2033 if let Err(reason) = validate_route(app.api_provider, &model) {
2034 return ConfigReply::error(reason);
2035 }
2036 model
2037 } else if app.accepts_custom_model_ids()
2038 || (app.api_provider != ProviderKind::OpenaiCodex
2039 && app.configured_models.iter().any(|row| {
2040 row.id == value.trim()
2041 && row.matches_route(
2042 app.provider_identity_for_persistence(),
2043 &app.active_route_base_url,
2044 )
2045 }))
2046 {
2047 let Some(model) = normalize_custom_model_id(value) else {
2048 return ConfigReply::error(format!(
2049 "Invalid model '{value}' for provider {}.",
2050 app.api_provider.as_str()
2051 ));
2052 };
2053 model
2054 } else {
2055 let Ok(resolved) =
2056 codewhale_config::route::resolve_model(app.api_provider, value, None)
2057 else {
2058 return ConfigReply::error(format!(
2059 "Invalid model '{value}' for provider {}.",
2060 app.api_provider.as_str()
2061 ));
2062 };
2063 let model = resolved.wire_id;
2064 if let Err(reason) = validate_route(app.api_provider, &model) {
2065 return ConfigReply::error(reason);
2066 }
2067 model
2068 };
2069 let saved = if persist {
2070 match codewhale_engine::route_preferences::persist_provider_selection(
2071 app.config_path.as_deref(),
2072 match app.admitted_provider_identity() {
2073 Ok(identity) => identity,
2074 Err(error) => return ConfigReply::error(error),
2075 },
2076 Some(&model),
2077 ) {
2078 Ok((path, _)) => Some(path),
2079 Err(error) => {
2080 return ConfigReply::error(format!("Failed to save model: {error}"));
2081 }
2082 }
2083 } else {
2084 None
2085 };
2086 app.set_model_selection(model.clone());
2087 app.update_model_compaction_budget();
2088 app.last_billed_input_tokens = None;
2089 app.session.last_prompt_tokens = None;
2090 app.session.last_completion_tokens = None;
2091 crate::tui::ui::maybe_warn_context_pressure(app);
2092 let mut message = if model == "auto" {
2093 format!(
2094 "model = auto (auto-select model per turn; thinking = {})",
2095 app.reasoning_effort_display_label()
2096 )
2097 } else {
2098 format!("model = {model}")
2099 };
2100 if let Some(path) = saved {
2101 message.push_str(&format!(" (saved to {})", path.display()));
2102 }
2103 return config_action_reply(
2104 message,
2105 AppAction::UpdateCompaction(app.compaction_config()),
2106 );
2107 }
2108 "provider" => {
2109 let value = value.trim();
2110 let Some(row) = codewhale_config::descriptors::compatibility_for_selector(value) else {
2111 return ConfigReply::error(format!(
2112 "Unknown provider '{value}'. Use: {}.",
2113 ProviderKind::names_hint()
2114 ));
2115 };
2116 if app
2117 .provider_identity
2118 .as_ref()
2119 .is_some_and(|identity| identity.key.as_str() == row.id)
2120 {
2121 return ConfigReply::message(format!("provider = {}", row.id));
2122 }
2123 return config_action_reply(
2124 format!("provider = {}", row.id),
2125 AppAction::SwitchProvider {
2126 provider: row.id.into(),
2127 model: None,
2128 },
2129 );
2130 }
2131 "approval_mode" | "approval_policy" | "approval" => {
2132 let use_tui_default = matches!(
2133 value
2134 .trim()
2135 .to_ascii_lowercase()
2136 .replace([' ', '_'], "-")
2137 .as_str(),
2138 "default" | "tui-default" | "use-tui-default"
2139 );
2140 if use_tui_default {
2141 if !persist {
2142 return ConfigReply::error(
2143 "Removing the config approval override requires --save.",
2144 );
2145 }
2146 let control = match load_command_config(app) {
2147 Ok(config) => config.approval_policy_control(
2148 app.config_path.as_deref(),
2149 app.config_profile.as_deref(),
2150 &app.workspace,
2151 ),
2152 Err(err) => return ConfigReply::error(err),
2153 };
2154 if !matches!(
2155 control,
2156 codewhale_runtime::config::ApprovalPolicyControl::RootConfig
2157 | codewhale_runtime::config::ApprovalPolicyControl::Unset
2158 ) {
2159 return ConfigReply::error(format!(
2160 "Approval posture is controlled by {}; change that source first.",
2161 control.label()
2162 ));
2163 }
2164 return match persist_unset_root_key(app.config_path.as_deref(), "approval_policy") {
2165 Ok(path) => {
2166 let saved_mode = Settings::load_persisted()
2167 .ok()
2168 .and_then(|settings| settings.permission_posture)
2169 .as_deref()
2170 .and_then(ApprovalMode::from_config_value)
2171 .unwrap_or(ApprovalMode::AcceptEdits);
2172 app.set_agent_approval_posture(saved_mode);
2173 app.clear_saved_approval_policy_lock();
2174 config_action_reply(
2175 format!(
2176 "approval_policy removed from {}; new sessions use the TUI {} default",
2177 path.display(),
2178 saved_mode.permission_chip_label()
2179 ),
2180 AppAction::ApprovalPolicyPersisted { policy: None },
2181 )
2182 }
2183 Err(err) => ConfigReply::error(format!("Failed to save: {err}")),
2184 };
2185 }
2186 let control = match load_command_config(app) {
2187 Ok(config) => config.approval_policy_control(
2188 app.config_path.as_deref(),
2189 app.config_profile.as_deref(),
2190 &app.workspace,
2191 ),
2192 Err(err) => return ConfigReply::error(err),
2193 };
2194 let control_allows_change = if persist {
2195 control.editable_root()
2196 } else {
2197 matches!(
2198 control,
2199 codewhale_runtime::config::ApprovalPolicyControl::Unset
2200 )
2201 };
2202 if !control_allows_change {
2203 return ConfigReply::error(format!(
2204 "Approval posture is controlled by {}; {}.",
2205 control.label(),
2206 if matches!(
2207 control,
2208 codewhale_runtime::config::ApprovalPolicyControl::RootConfig
2209 ) {
2210 "save a new config value or choose Use TUI permission default"
2211 } else {
2212 "change that source first"
2213 }
2214 ));
2215 }
2216 let mode = ApprovalMode::from_config_value(value);
2217 return match mode {
2218 Some(ApprovalMode::Auto) if app.auto_review_disabled => ConfigReply::error(
2219 "Auto-Review is disabled by managed configuration (`auto_review.disabled = true`)",
2220 ),
2221 Some(ApprovalMode::Bypass)
2222 if persist
2223 && matches!(
2224 control,
2225 codewhale_runtime::config::ApprovalPolicyControl::RootConfig
2226 ) =>
2227 {
2228 match app.adopt_root_approval_posture(ApprovalMode::Bypass) {
2229 Ok(()) => config_action_reply(
2230 "approval_mode = Full Access (saved as the TUI permission posture; removed the root approval_policy override)",
2231 AppAction::ApprovalPolicyPersisted { policy: None },
2232 ),
2233 Err(reason) => {
2234 ConfigReply::error(format!("Failed to save Full Access: {reason}"))
2235 }
2236 }
2237 }
2238 Some(ApprovalMode::Bypass) if persist => ConfigReply::error(
2239 "Full Access is saved as the TUI permission posture, not as a top-level approval_policy. Remove the controlling policy first.",
2240 ),
2241 Some(m) => {
2242 if persist {
2243 let saved = approval_mode_config_value(m);
2244 match persist_root_string_key(
2245 app.config_path.as_deref(),
2246 "approval_policy",
2247 saved,
2248 ) {
2249 Ok(path) => {
2250 app.set_agent_approval_posture(m);
2251 app.mark_approval_policy_locked();
2252 config_action_reply(
2253 format!(
2254 "approval_mode = {} (saved to {} as approval_policy = \"{}\")",
2255 m.permission_chip_label(),
2256 path.display(),
2257 saved
2258 ),
2259 AppAction::ApprovalPolicyPersisted {
2260 policy: Some(saved.to_string()),
2261 },
2262 )
2263 }
2264 Err(err) => ConfigReply::error(format!("Failed to save: {err}")),
2265 }
2266 } else {
2267 app.set_agent_approval_posture(m);
2268 config_action_reply(
2269 format!(
2270 "approval_mode = {} (session only, add --save to persist)",
2271 m.permission_chip_label()
2272 ),
2273 AppAction::ModeChanged(app.mode),
2274 )
2275 }
2276 }
2277 None => ConfigReply::error(
2278 "Invalid approval_mode. Use: auto-review/auto, ask/suggest/on-request, full-access, never/deny",
2279 ),
2280 };
2281 }
2282 "allow_shell" | "shell" | "exec_shell" => {
2283 let control = match load_command_config(app) {
2284 Ok(config) => config.allow_shell_control(
2285 app.config_path.as_deref(),
2286 app.config_profile.as_deref(),
2287 &app.workspace,
2288 ),
2289 Err(err) => return ConfigReply::error(err),
2290 };
2291 if !control.editable_root() {
2292 return ConfigReply::error(format!(
2293 "Shell access is controlled by {}; change that source first.",
2294 control.label()
2295 ));
2296 }
2297 let enabled = match parse_config_bool(value) {
2298 Ok(enabled) => enabled,
2299 Err(err) => return ConfigReply::error(err),
2300 };
2301 let suffix = if persist {
2302 match persist_root_bool_key(app.config_path.as_deref(), "allow_shell", enabled) {
2303 Ok(path) => format!(
2304 " ({})",
2305 app.tr(MessageId::ConfigSavedTo)
2306 .replace("{path}", &path.display().to_string())
2307 ),
2308 Err(err) => return ConfigReply::error(format!("Failed to save: {err}")),
2309 }
2310 } else {
2311 format!(" ({})", app.tr(MessageId::ConfigSessionOnlyHint))
2312 };
2313 app.set_agent_shell_access(enabled);
2314 let mode_hint = if enabled {
2315 app.tr(MessageId::ConfigAllowShellEnabledHint).replace(
2316 "{chord}",
2317 &crate::tui::shell_key_routing::display_chord(
2318 crate::tui::shell_key_routing::binding(
2319 crate::tui::shell_key_routing::ShellBindingId::PermissionCycle,
2320 )
2321 .footer_chord,
2322 ),
2323 )
2324 } else {
2325 app.tr(MessageId::ConfigAllowShellDisabledHint)
2326 .replace("{command}", "`/config allow_shell true`")
2327 };
2328 return ConfigReply::message(format!("allow_shell = {enabled}{suffix}. {mode_hint}"));
2329 }
2330 "mcp_config_path" | "mcp" => {
2331 if value.trim().is_empty() {
2332 return ConfigReply::error("mcp_config_path cannot be empty");
2333 }
2334 let next_path = PathBuf::from(expand_tilde(value));
2335 let path_changed = next_path != app.mcp_config_path;
2336 let reload_note = if path_changed {
2337 "; run /mcp reload to rebuild the live tool pool"
2338 } else {
2339 ""
2340 };
2341 // Persist before touching live state (C01-08): a failed save
2342 // must leave the session exactly as it was, not report failure
2343 // over a path and reload flag that already moved.
2344 let saved_to = if persist {
2345 match persist_root_string_key(app.config_path.as_deref(), "mcp_config_path", value)
2346 {
2347 Ok(path) => Some(path),
2348 Err(err) => return ConfigReply::error(format!("Failed to save: {err}")),
2349 }
2350 } else {
2351 None
2352 };
2353 app.mcp_config_path = next_path;
2354 if path_changed {
2355 app.mcp_reload_required = true;
2356 }
2357 let message = match saved_to {
2358 Some(path) => format!(
2359 "mcp_config_path = {} (saved to {}){}",
2360 app.mcp_config_path.display(),
2361 path.display(),
2362 reload_note
2363 ),
2364 None => format!(
2365 "mcp_config_path = {} (session only){}",
2366 app.mcp_config_path.display(),
2367 reload_note
2368 ),
2369 };
2370 return ConfigReply::message(message);
2371 }
2372 "title" | "window_title" | "tab_title" => {
2373 // Keep the config setter under the same terminal-control and
2374 // bidi/zero-width policy as `/title` and `/rename`. Persist the
2375 // normalized value too, so a restart cannot reintroduce bytes the
2376 // live session already discarded.
2377 let sanitized = codewhale_engine::session_manager::sanitize_session_title(value);
2378 let value = sanitized.trim();
2379 if value.is_empty() {
2380 return ConfigReply::error(
2381 "title cannot be empty; use /title off to clear a session title",
2382 );
2383 }
2384 if value.chars().count() > 100 {
2385 return ConfigReply::error("Title too long (max 100 characters)");
2386 }
2387 let suffix = if persist {
2388 match persist_root_string_key(app.config_path.as_deref(), "title", value) {
2389 Ok(path) => format!(" (saved to {})", path.display()),
2390 Err(err) => return ConfigReply::error(format!("Failed to save: {err}")),
2391 }
2392 } else {
2393 " (session only, add --save to persist)".to_string()
2394 };
2395 app.title_default = Some(value.to_string());
2396 app.needs_redraw = true;
2397 return ConfigReply::message(format!(
2398 "title = {value}{suffix} — terminal window titles now read [\"{value}\"] … until /title overrides this session"
2399 ));
2400 }
2401 // `base_url` is the older spelling. It used to write a top-level key
2402 // that every DeepSeek-family route inherited; it now writes the
2403 // active route's own `[providers.<name>]` table like `provider_url`
2404 // (#6394).
2405 url_key @ ("base_url" | "provider_url" | "provider_base_url" | "endpoint") => {
2406 let value = match resolve_provider_url_value(app.api_provider, value) {
2407 Ok(value) => value,
2408 Err(err) => return ConfigReply::error(err),
2409 };
2410 if persist {
2411 match codewhale_runtime::config_persistence::persist_route_base_url(
2412 app.config_path.as_deref(),
2413 match app.admitted_provider_identity() {
2414 Ok(identity) => identity,
2415 Err(error) => return ConfigReply::error(error),
2416 },
2417 &value,
2418 ) {
2419 Ok(path) => {
2420 return ConfigReply::message(format!(
2421 "{url_key} = {value} for {} (saved to {}; restart required)",
2422 app.api_provider.as_str(),
2423 path.display()
2424 ));
2425 }
2426 Err(err) => return ConfigReply::error(format!("Failed to save: {err}")),
2427 }
2428 }
2429 return ConfigReply::error(format!(
2430 "{url_key} must be saved with --save; client base URL is loaded from config on startup. Restart and re-open your session after saving."
2431 ));
2432 }
2433 // The two bottom-chrome rows' size presets (`tui.posture_bar`,
2434 // `tui.metrics_line`, #5950). Live on the next frame; `--save`
2435 // writes the owning `[tui]` table. `/statusline` composes what is in a row;
2436 // this only decides whether and how much of it paints.
2437 row_key @ ("posture_bar" | "metrics_line") => {
2438 let Some(preset) = codewhale_runtime::config::ChromeRowPreset::from_setting(value)
2439 else {
2440 return ConfigReply::error(ConfigMessage::keyed_with(
2441 "config_command_invalid_value",
2442 vec![
2443 ("key".to_string(), ConfigMessage::literal(row_key)),
2444 ("value".to_string(), ConfigMessage::literal(value)),
2445 (
2446 "choices".to_string(),
2447 ConfigMessage::literal(
2448 codewhale_runtime::config::ChromeRowPreset::SETTINGS.join(", "),
2449 ),
2450 ),
2451 ],
2452 ));
2453 };
2454 let value = preset.as_setting();
2455 let scope = if persist {
2456 let saved = codewhale_runtime::config_persistence::config_toml_path(
2457 app.config_path.as_deref(),
2458 )
2459 .and_then(|path| {
2460 codewhale_runtime::config_persistence::mutate_config_document(&path, |doc| {
2461 // Profiles replace the whole TUI table on load. Edit its
2462 // existing owner without creating an empty override that
2463 // would reset the other inherited display settings.
2464 let mut segments = Vec::new();
2465 if let Some(profile) = app.config_profile.as_deref() {
2466 let table = doc
2467 .get("profiles")
2468 .and_then(|v| v.get(profile))
2469 .and_then(toml_edit::Item::as_table_like)
2470 .ok_or_else(|| {
2471 anyhow::anyhow!("active profile is missing or malformed")
2472 })?;
2473 if table.contains_key("tui") {
2474 segments.extend(["profiles", profile]);
2475 }
2476 }
2477 segments.extend(["tui", row_key]);
2478 codewhale_runtime::config_persistence::set_document_value(
2479 doc, &segments, value,
2480 )
2481 })?;
2482 Ok(path)
2483 });
2484 match saved {
2485 Ok(path) => ConfigMessage::concat(vec![
2486 ConfigMessage::keyed("config_scope_saved"),
2487 ConfigMessage::literal(format!(" {}", path.display())),
2488 ]),
2489 Err(error) => {
2490 return ConfigReply::error(ConfigMessage::keyed_with(
2491 "startup_default_not_saved",
2492 vec![
2493 ("setting".to_string(), ConfigMessage::literal(row_key)),
2494 (
2495 "error".to_string(),
2496 ConfigMessage::literal(error.to_string()),
2497 ),
2498 ],
2499 ));
2500 }
2501 }
2502 } else {
2503 ConfigMessage::keyed("config_scope_session")
2504 };
2505 if row_key == "posture_bar" {
2506 app.posture_bar = preset;
2507 } else {
2508 app.metrics_line = preset;
2509 }
2510 app.needs_redraw = true;
2511 return ConfigReply::message(ConfigMessage::concat(vec![
2512 ConfigMessage::literal(format!("{row_key} = {value} (")),
2513 scope,
2514 ConfigMessage::literal(")"),
2515 ]));
2516 }
2517 "stream_chunk_timeout_secs" => {
2518 let raw = match value.trim().parse::<u64>() {
2519 Ok(value) => value,
2520 Err(_) => {
2521 return ConfigReply::error("stream_chunk_timeout_secs must be a whole number");
2522 }
2523 };
2524 if raw != 0
2525 && !(MIN_STREAM_CHUNK_TIMEOUT_SECS..=MAX_STREAM_CHUNK_TIMEOUT_SECS).contains(&raw)
2526 {
2527 return ConfigReply::error(format!(
2528 "stream_chunk_timeout_secs must be 0 or {MIN_STREAM_CHUNK_TIMEOUT_SECS}..={MAX_STREAM_CHUNK_TIMEOUT_SECS}"
2529 ));
2530 }
2531 let resolved = if raw == 0 {
2532 DEFAULT_STREAM_CHUNK_TIMEOUT_SECS
2533 } else {
2534 raw
2535 };
2536 let value_label = stream_chunk_timeout_value_label(raw, resolved);
2537 if persist {
2538 match persist_table_value_key(
2539 app.config_path.as_deref(),
2540 "stream",
2541 "chunk_timeout_secs",
2542 (raw as i64).into(), // validated above: at most 3600
2543 ) {
2544 Ok(path) => {
2545 // Live state moves only with the engine action and
2546 // only after the save landed (C01-08).
2547 app.stream_chunk_timeout_secs = resolved;
2548 return config_action_reply(
2549 format!(
2550 "stream_chunk_timeout_secs = {value_label} (saved to {}; affects subsequent turns in this session)",
2551 path.display()
2552 ),
2553 AppAction::UpdateStreamChunkTimeout(resolved),
2554 );
2555 }
2556 Err(err) => return ConfigReply::error(format!("Failed to save: {err}")),
2557 }
2558 }
2559 app.stream_chunk_timeout_secs = resolved;
2560 return config_action_reply(
2561 format!(
2562 "stream_chunk_timeout_secs = {value_label} (session only; affects subsequent turns in this session)"
2563 ),
2564 AppAction::UpdateStreamChunkTimeout(resolved),
2565 );
2566 }
2567 "search" | "search.provider" | "search_provider" => {
2568 return set_search_provider(app, value, persist);
2569 }
2570 "search.third_party" | "search_third_party" => {
2571 return set_search_third_party(app, value);
2572 }
2573 "prompt_suggestion" => return set_prompt_suggestion(app, value, persist),
2574 "auto_review.reviewer_model" => {
2575 return set_auto_review_reviewer_model(app, value, persist);
2576 }
2577 _ => {}
2578 }
2579
2580 // This copy exists to validate the value and to project it onto live `App`
2581 // state. It is deliberately *not* what gets saved: see
2582 // [`persist_single_setting`].
2583 let mut settings = match Settings::load_persisted() {
2584 Ok(s) => s,
2585 Err(e) if !persist => {
2586 app.show_command_result(
2587 format!("Settings unavailable; applying session-only override ({e})"),
2588 StatusToastLevel::Warning,
2589 );
2590 Settings::default()
2591 }
2592 Err(e) => return ConfigReply::error(format!("Failed to load settings: {e}")),
2593 };
2594
2595 if let Err(e) = settings.set(&key, value) {
2596 return ConfigReply::error(format!("{e}"));
2597 }
2598 // Runtime/environment constraints are an effective projection, not saved
2599 // preferences. Keep the persisted copy pristine so NO_ANIMATIONS or a
2600 // terminal quirk cannot become permanent during an unrelated edit.
2601 let mut effective_settings = settings.clone();
2602 effective_settings.apply_env_overrides();
2603
2604 let mut action = None;
2605 match key.as_str() {
2606 "auto_compact" | "compact" => {
2607 app.auto_compact = settings.auto_compact;
2608 app.auto_compact_user_configured = true;
2609 action = Some(AppAction::UpdateCompaction(app.compaction_config()));
2610 }
2611 "auto_compact_threshold" | "auto_compact_threshold_percent" => {
2612 app.auto_compact = true;
2613 app.auto_compact_user_configured = true;
2614 app.auto_compact_threshold_percent = settings.auto_compact_threshold_percent;
2615 app.update_model_compaction_budget();
2616 action = Some(AppAction::UpdateCompaction(app.compaction_config()));
2617 }
2618 "calm_mode" | "calm" => {
2619 app.calm_mode = settings.calm_mode;
2620 app.mark_history_updated();
2621 }
2622 "whale_name" | "whale_color" | "whale_colour" => {
2623 app.pet_watch.apply_identity(
2624 settings.whale_name.as_deref(),
2625 settings.whale_color.as_deref(),
2626 );
2627 app.needs_redraw = true;
2628 }
2629 "low_motion" | "motion" => {
2630 app.low_motion = effective_settings.low_motion;
2631 app.needs_redraw = true;
2632 }
2633 "fancy_animations" | "fancy" | "animations" => {
2634 app.fancy_animations = effective_settings.fancy_animations;
2635 app.needs_redraw = true;
2636 }
2637 "focus_texture" | "texture" => {
2638 app.focus_texture =
2639 crate::tui::focus_texture::FocusTextureMode::parse(&settings.focus_texture)
2640 .unwrap_or_default();
2641 app.needs_redraw = true;
2642 }
2643 "work_surface_placement" | "work_surface" | "work_rail" => {
2644 app.work_surface.placement = crate::tui::work_surface::WorkSurfacePlacement::parse(
2645 &settings.work_surface_placement,
2646 );
2647 app.work_surface.focused = false;
2648 app.work_surface.last_area = None;
2649 app.needs_redraw = true;
2650 }
2651 "rail_panel" | "rail" => {
2652 app.work_surface.panel =
2653 crate::tui::work_surface::RailPanel::parse(&settings.rail_panel);
2654 app.needs_redraw = true;
2655 }
2656 "work_surface_top_height" | "work_top_height" => {
2657 app.work_surface.top_height = settings.work_surface_top_height;
2658 app.needs_redraw = true;
2659 }
2660 "work_surface_side_width" | "work_side_width" => {
2661 app.work_surface.side_width = settings.work_surface_side_width;
2662 app.needs_redraw = true;
2663 }
2664 "bracketed_paste" | "paste" => {
2665 app.use_bracketed_paste = settings.bracketed_paste;
2666 app.needs_redraw = true;
2667 }
2668 "status_indicator" | "indicator" => {
2669 app.status_indicator = settings.status_indicator.clone();
2670 app.needs_redraw = true;
2671 }
2672 "synchronized_output" | "sync_output" | "sync" => {
2673 app.synchronized_output_enabled = effective_settings.synchronized_output_enabled();
2674 app.needs_redraw = true;
2675 }
2676 "show_thinking" | "thinking" => {
2677 app.show_thinking = settings.show_thinking;
2678 app.mark_history_updated();
2679 }
2680 "thinking_default_expanded" | "thinking_expanded" => {
2681 app.thinking_default_expanded = settings.thinking_default_expanded;
2682 app.mark_history_updated();
2683 }
2684 "thinking_preview_lines" | "thinking_preview" => {
2685 app.thinking_preview_lines = settings.thinking_preview_lines;
2686 app.mark_history_updated();
2687 }
2688 "help_expand_groups" | "help_expanded" => {
2689 app.help_expand_groups = settings.help_expand_groups;
2690 app.needs_redraw = true;
2691 }
2692 "pin_last_prompt" | "pin_prompt" => {
2693 app.pin_last_prompt = settings.pin_last_prompt;
2694 app.needs_redraw = true;
2695 }
2696 "thinking_highlight" | "reasoning_highlight" => {
2697 app.thinking_highlight = settings.thinking_highlight;
2698 app.mark_history_updated();
2699 }
2700 "show_tool_details" | "tool_details" => {
2701 app.show_tool_details = settings.show_tool_details;
2702 app.mark_history_updated();
2703 }
2704 "inline_diffs" | "inline_diff" | "diffs" => {
2705 app.inline_diff_mode =
2706 codewhale_runtime::settings::InlineDiffMode::parse(&settings.inline_diffs);
2707 app.mark_history_updated();
2708 app.needs_redraw = true;
2709 }
2710 "locale" | "language" => {
2711 app.ui_locale = resolve_locale(&settings.locale);
2712 app.mark_history_updated();
2713 app.needs_redraw = true;
2714 }
2715 "theme" | "ui_theme" | "background_color" | "background" | "bg" => {
2716 // Theme previews reload persisted settings for each cursor move.
2717 // Keep a session-only background overlay live unless this command
2718 // is itself updating (or clearing) the background.
2719 let background_color_override = if matches!(key.as_str(), "theme" | "ui_theme") {
2720 app.background_color_override
2721 } else {
2722 settings
2723 .background_color
2724 .as_deref()
2725 .and_then(codewhale_palette::parse_hex_rgb_color)
2726 };
2727 let background_setting =
2728 background_color_override.and_then(codewhale_palette::hex_rgb_string);
2729 let (theme_name, theme_id, ui_theme) = match codewhale_palette::resolve_theme_setting(
2730 &settings.theme,
2731 background_setting.as_deref(),
2732 ) {
2733 Ok(resolved) => resolved,
2734 Err(error) => {
2735 return ConfigReply::error(format!("Failed to apply theme: {error}"));
2736 }
2737 };
2738 app.background_color_override = background_color_override;
2739 app.theme_id = theme_id;
2740 app.theme_name = theme_name;
2741 app.ui_theme = ui_theme;
2742 app.needs_redraw = true;
2743 }
2744 "cost_currency" | "currency" => {
2745 app.cost_currency =
2746 codewhale_config::pricing::CostCurrency::from_setting(&settings.cost_currency)
2747 .unwrap_or(codewhale_config::pricing::CostCurrency::Usd);
2748 app.needs_redraw = true;
2749 }
2750 key @ ("mini_window.keep_header"
2751 | "mini_window.keep_input"
2752 | "mini_window.keep_todo"
2753 | "mini_window.keep_sidebar"
2754 | "mini_window.keep_footer") => {
2755 let field = key.strip_prefix("mini_window.").unwrap_or(key);
2756 let value = match parse_config_bool(value) {
2757 Ok(value) => value,
2758 Err(err) => return ConfigReply::error(err),
2759 };
2760 // Persist first: a failed save leaves the live layout as it was
2761 // (C01-08).
2762 if persist
2763 && let Err(err) =
2764 codewhale_runtime::config_persistence::persist_mini_window_bool_key(
2765 app.config_path.as_deref(),
2766 field,
2767 value,
2768 )
2769 {
2770 return ConfigReply::error(format!("Failed to persist: {err}"));
2771 }
2772 match field {
2773 "keep_header" => app.mini_window.keep_header = value,
2774 "keep_input" => app.mini_window.keep_input = value,
2775 "keep_todo" => app.mini_window.keep_todo = value,
2776 "keep_sidebar" => app.mini_window.keep_sidebar = value,
2777 "keep_footer" => app.mini_window.keep_footer = value,
2778 _ => unreachable!("mini_window field matched above"),
2779 }
2780 app.needs_redraw = true;
2781 }
2782 "composer_density" | "composer" => {
2783 app.composer_density =
2784 crate::tui::app::ComposerDensity::from_setting(&settings.composer_density);
2785 app.needs_redraw = true;
2786 }
2787 "composer_border" | "border" => {
2788 app.composer_border = settings.composer_border;
2789 app.needs_redraw = true;
2790 }
2791 "composer_multiline_mode" | "multiline_mode" | "multiline" => {
2792 app.composer_multiline_mode = settings.composer_multiline_mode;
2793 app.needs_redraw = true;
2794 }
2795 "composer_vim_mode" | "vim_mode" | "vim" => {
2796 app.composer.vim_enabled = settings.composer_vim_mode == "vim";
2797 app.composer.vim_mode = if app.composer.vim_enabled {
2798 VimMode::Normal
2799 } else {
2800 VimMode::Insert
2801 };
2802 app.composer.vim_pending_d = false;
2803 app.needs_redraw = true;
2804 }
2805 "paste_burst_detection" | "paste_burst" => {
2806 app.use_paste_burst_detection = settings.paste_burst_detection;
2807 if !app.use_paste_burst_detection {
2808 app.paste_burst.clear_after_explicit_paste();
2809 }
2810 }
2811 "mention_menu_limit" | "mention_limit" => {
2812 app.mention_menu_limit = settings.mention_menu_limit;
2813 app.composer.mention_completion_cache = None;
2814 app.composer.mention_discovery.invalidate();
2815 app.needs_redraw = true;
2816 }
2817 "mention_menu_behavior" | "mention_behavior" | "mention_menu" => {
2818 app.mention_menu_behavior = settings.mention_menu_behavior.clone();
2819 app.composer.mention_completion_cache = None;
2820 app.composer.mention_discovery.invalidate();
2821 app.needs_redraw = true;
2822 }
2823 "mention_walk_depth" | "mention_depth" | "completions_walk_depth" => {
2824 app.mention_walk_depth = settings.mention_walk_depth;
2825 app.composer.mention_completion_cache = None;
2826 app.composer.mention_discovery.invalidate();
2827 app.needs_redraw = true;
2828 }
2829 "workspace_follow_symlinks" | "follow_symlinks" => {
2830 // Persist first: a failed save leaves the live value as it was
2831 // (C01-08).
2832 if persist && let Err(e) = persist_single_setting(&key, value) {
2833 return ConfigReply::error(format!("Failed to save: {e}"));
2834 }
2835 app.workspace_follow_symlinks = settings.workspace_follow_symlinks;
2836 app.composer.mention_completion_cache = None;
2837 app.composer.mention_discovery.invalidate();
2838 app.needs_redraw = true;
2839 // Engine tools use EngineConfig which is fixed at startup
2840 return ConfigReply::message(if persist {
2841 format!(
2842 "workspace_follow_symlinks = {} (saved; restart required for engine tools)",
2843 settings.workspace_follow_symlinks
2844 )
2845 } else {
2846 format!(
2847 "workspace_follow_symlinks = {} (session only for UI; restart required for engine tools)",
2848 settings.workspace_follow_symlinks
2849 )
2850 });
2851 }
2852 "transcript_spacing" | "spacing" => {
2853 app.transcript_spacing =
2854 crate::tui::app::TranscriptSpacing::from_setting(&settings.transcript_spacing);
2855 app.mark_history_updated();
2856 }
2857 "tool_collapse" | "tool_collapse_mode" | "collapse" => {
2858 app.tool_collapse_mode =
2859 crate::tui::app::ToolCollapseMode::from_setting(&settings.tool_collapse_mode);
2860 app.expanded_tool_runs.clear();
2861 app.mark_history_updated();
2862 }
2863 // `default_mode` is a restart default, not a live mode switch. The
2864 // `/mode` command owns synchronized session transitions.
2865 "default_mode" => {}
2866 "mode" => {
2867 let mode = AppMode::from_setting(&settings.default_mode);
2868 app.set_mode(mode);
2869 action = Some(AppAction::ModeChanged(mode));
2870 }
2871 "max_history" | "history" => {
2872 app.max_input_history = settings.max_input_history;
2873 }
2874 "reasoning_effort" | "effort" => {
2875 app.reasoning_effort_preference = settings
2876 .reasoning_effort
2877 .as_deref()
2878 .map(ReasoningEffort::from_setting);
2879 app.reasoning_effort = app.reasoning_effort_preference.map_or_else(
2880 || {
2881 if app.auto_model {
2882 ReasoningEffort::Auto
2883 } else {
2884 ReasoningEffort::default()
2885 }
2886 },
2887 |requested| {
2888 if app.auto_model {
2889 requested
2890 } else {
2891 requested.normalize_for_provider(app.api_provider)
2892 }
2893 },
2894 );
2895 app.invalidate_route_receipts_for_reasoning_change();
2896 app.update_model_compaction_budget();
2897 action = Some(AppAction::UpdateCompaction(app.compaction_config()));
2898 }
2899 "context_panel" | "context" | "session_panel" => {
2900 app.context_panel = settings.context_panel;
2901 app.needs_redraw = true;
2902 }
2903 "sessions_rail" | "sessions_panel" | "session_rail" => {
2904 app.sessions_rail = settings.sessions_rail;
2905 app.needs_redraw = true;
2906 }
2907 _ => {}
2908 }
2909
2910 let display_value = match key.as_str() {
2911 "default_mode" | "mode" => settings.default_mode.clone(),
2912 "cost_currency" | "currency" => settings.cost_currency.clone(),
2913 "theme" | "ui_theme" => settings.theme.clone(),
2914 "synchronized_output" | "sync_output" | "sync" => settings.synchronized_output.clone(),
2915 "background_color" | "background" | "bg" => settings
2916 .background_color
2917 .clone()
2918 .unwrap_or_else(|| "default".to_string()),
2919 "reasoning_effort" | "effort" => settings.reasoning_effort.as_deref().map_or_else(
2920 || "config/default".to_string(),
2921 |value| {
2922 ReasoningEffort::from_setting_for_provider(value, app.api_provider)
2923 .as_setting_for_provider(app.api_provider)
2924 .to_string()
2925 },
2926 ),
2927 "composer_vim_mode" | "vim_mode" | "vim" => settings.composer_vim_mode.clone(),
2928 "composer_multiline_mode" | "multiline_mode" | "multiline" => {
2929 settings.composer_multiline_mode.to_string()
2930 }
2931 "low_motion" | "motion" => settings.low_motion.to_string(),
2932 "fancy_animations" | "fancy" | "animations" => settings.fancy_animations.to_string(),
2933 _ => value.to_string(),
2934 };
2935
2936 let message = if persist {
2937 if let Err(e) = persist_single_setting(&key, value) {
2938 // C01-08: the projection above already changed live state (and
2939 // some arms validate only while projecting, so saving first could
2940 // persist a value that never applied). Report exactly that partial
2941 // effect, and keep the action so the engine matches the UI instead
2942 // of silently diverging from it.
2943 return ConfigReply {
2944 message: Some(ConfigMessage::literal(format!(
2945 "Error: {key} = {display_value} applies to this session only; saving failed: {e}"
2946 ))),
2947 action: action.and_then(crate::commands::config_host::app_action_to_config_action),
2948 is_error: true,
2949 };
2950 }
2951 format!("{key} = {display_value} (saved)")
2952 } else {
2953 format!("{key} = {display_value} (session only, add --save to persist)")
2954 };
2955 ConfigReply {
2956 message: Some(ConfigMessage::literal(message)),
2957 action: action.and_then(crate::commands::config_host::app_action_to_config_action),
2958 is_error: false,
2959 }
2960 }
2961
2962 /// Persist exactly the one key `/set --save` changed.
2963 ///
2964 /// `/set` loads a `Settings` copy up front to validate the value and to project
2965 /// it onto live `App` state, and a lot of `App` mutation happens in between. That
2966 /// copy is a stale snapshot by the time we get here, so saving *it* would write
2967 /// back every other field as it looked before — reverting any mode, thinking,
2968 /// model, or permission write that landed in the meantime. Re-applying the single
2969 /// key inside [`Settings::transact`] persists the user's actual edit and nothing
2970 /// else. `Settings::set` is the same normalizer the copy above already accepted
2971 /// the value through, so this cannot fail for a value that validated.
2972 fn persist_single_setting(key: &str, value: &str) -> anyhow::Result<()> {
2973 Settings::transact(|settings| settings.set(key, value))
2974 }
2975
2976 pub fn switch_mode(app: &mut App, mode: AppMode) -> String {
2977 switch_mode_with_status(app, mode).0
2978 }
2979
2980 /// Returns the user-facing sentence and whether live mode moved (the caller
2981 /// emits `AppAction::ModeChanged` only for the latter).
2982 ///
2983 /// The three outcomes read differently on purpose. Before the typed
2984 /// [`SettingSelection`], a refusal and a same-mode selection that *did* persist
2985 /// the startup default both came back as "Already in X mode." — so the one case
2986 /// where `/mode` had written something looked exactly like the case where it had
2987 /// written nothing.
2988 fn switch_mode_with_status(app: &mut App, mode: AppMode) -> (String, bool) {
2989 match app.select_mode(mode) {
2990 SettingSelection::Changed => (
2991 format!(
2992 "Switched to {} mode.",
2993 mode.display_name_localized(app.ui_locale)
2994 ),
2995 true,
2996 ),
2997 SettingSelection::PersistedSame => (app.mode_startup_default_receipt(mode), false),
2998 SettingSelection::Refused => (
2999 app.setting_locked_message(MessageId::SettingSubjectMode),
3000 false,
3001 ),
3002 }
3003 }
3004
3005 pub(crate) async fn set_workspace_trust(app: &mut App, trusted: bool, save: bool) -> Result<()> {
3006 if !save {
3007 app.trust_mode = trusted;
3008 return Ok(());
3009 }
3010 // Revocation restricts live file access even if the saved decision cannot be updated.
3011 if !trusted {
3012 app.trust_mode = false;
3013 }
3014 let workspace = app.workspace.clone();
3015 #[cfg(test)]
3016 let ticket = crate::test_support::env_scope_ticket();
3017 tokio::task::spawn_blocking(move || {
3018 #[cfg(test)]
3019 let _membership = crate::test_support::join_env_scope(ticket);
3020 codewhale_runtime::config::set_workspace_trust(&workspace, trusted)
3021 })
3022 .await??;
3023 app.trust_mode = trusted;
3024 Ok(())
3025 }
3026
3027 /// What `/trust on|off [--save]` just did, for the transcript. The toast
3028 /// alone fades, and the footer does not show trust mode, so without this
3029 /// line the command appeared to do nothing.
3030 pub(crate) fn trust_change_note(trusted: bool, save: bool) -> String {
3031 let session = if trusted {
3032 "Trust mode is on for this session: file tools may now reach files outside this folder. `/trust off` turns it off."
3033 } else {
3034 "Trust mode is off for this session: it no longer lets file tools reach files outside this folder."
3035 };
3036 let saved = match (save, trusted) {
3037 (false, _) => return session.to_string(),
3038 (true, true) => {
3039 "Saved for this folder: its project skills, commands, hooks, MCP servers and context are trusted in later sessions too."
3040 }
3041 (true, false) => {
3042 "Saved for this folder: its project skills, commands, hooks, MCP servers and context are no longer trusted."
3043 }
3044 };
3045 format!("{session}\n{saved}")
3046 }
3047
3048 pub(crate) fn expand_tilde(raw: &str) -> String {
3049 if let Some(rest) = raw.strip_prefix("~/")
3050 && let Some(home) = codewhale_paths::user_home()
3051 {
3052 return home.join(rest).to_string_lossy().into_owned();
3053 } else if raw == "~"
3054 && let Some(home) = codewhale_paths::user_home()
3055 {
3056 return home.to_string_lossy().into_owned();
3057 }
3058 raw.to_string()
3059 }
3060
3061 #[cfg(test)]
3062 mod tests {
3063 use super::*;
3064 use crate::commands::CommandResult;
3065 use crate::test_support::{EnvVarGuard, TestEnvLock, lock_test_env};
3066 use crate::tui::app::OnboardingState;
3067 use crate::tui::app::{App, TuiOptions};
3068 use codewhale_config::notifications::NotificationMethod;
3069 use codewhale_runtime::config::Config;
3070 use std::env;
3071
3072 /// Invoke the portable `/logout` handler through a real capability envelope
3073 /// and convert the contract result back, mirroring the host registration.
3074 fn logout_command(app: &mut App) -> CommandResult {
3075 let result = crate::commands::groups::config::config::logout(
3076 app.command_contexts_with_config(None)
3077 .contexts(crate::commands::groups::config::config::LOGIN_CAPS),
3078 None,
3079 );
3080 CommandResult {
3081 message: result.message,
3082 action: result
3083 .action
3084 .map(crate::commands::config_host::config_action_to_app_action),
3085 is_error: result.is_error,
3086 }
3087 }
3088
3089 /// Invoke the portable `/trust` handler through a real capability envelope
3090 /// and convert the contract result back, mirroring the host registration.
3091 fn trust_command(app: &mut App, arg: Option<&str>) -> CommandResult {
3092 let result = crate::commands::groups::config::config::trust(
3093 app.command_contexts_with_config(None)
3094 .contexts(crate::commands::groups::config::config::TRUST_CAPS),
3095 arg,
3096 );
3097 CommandResult {
3098 message: result.message,
3099 action: result
3100 .action
3101 .map(crate::commands::config_host::config_action_to_app_action),
3102 is_error: result.is_error,
3103 }
3104 }
3105 /// Invoke the portable `/mode` handler through the real MODE_POLICY
3106 /// envelope and convert the contract result back.
3107 fn mode_command(app: &mut App, arg: Option<&str>) -> CommandResult {
3108 let result = crate::commands::groups::config::config::mode(
3109 app.command_contexts_with_config(None)
3110 .contexts(crate::commands::groups::config::config::MODE_CAPS),
3111 arg,
3112 );
3113 CommandResult {
3114 message: result.message,
3115 action: result
3116 .action
3117 .map(crate::commands::config_host::config_action_to_app_action),
3118 is_error: result.is_error,
3119 }
3120 }
3121 /// Invoke the portable `/workbar` handler through the real WORK_SURFACE
3122 /// envelope and convert the contract result back.
3123 fn workbar_command(app: &mut App, arg: Option<&str>) -> CommandResult {
3124 let result = crate::commands::groups::config::config::workbar(
3125 app.command_contexts_with_config(None)
3126 .contexts(crate::commands::groups::config::config::WORK_SURFACE_CAPS),
3127 arg,
3128 );
3129 CommandResult {
3130 message: result.message,
3131 action: result
3132 .action
3133 .map(crate::commands::config_host::config_action_to_app_action),
3134 is_error: result.is_error,
3135 }
3136 }
3137 /// Invoke the portable `/whale` handler through the real PET envelope and
3138 /// convert the contract result back.
3139 fn whale_command(app: &mut App, arg: Option<&str>) -> CommandResult {
3140 let result = crate::commands::groups::config::config::whale(
3141 app.command_contexts_with_config(None)
3142 .contexts(crate::commands::groups::config::config::WHALE_CAPS),
3143 arg,
3144 );
3145 CommandResult {
3146 message: result.message,
3147 action: result
3148 .action
3149 .map(crate::commands::config_host::config_action_to_app_action),
3150 is_error: result.is_error,
3151 }
3152 }
3153 /// Invoke the portable `/theme` handler through the real CONFIG envelope
3154 /// and convert the contract result back.
3155 fn theme_command(app: &mut App, arg: Option<&str>) -> CommandResult {
3156 let result = crate::commands::groups::config::config::theme(
3157 app.command_contexts_with_config(None)
3158 .contexts(crate::commands::groups::config::config::CONFIG_PRESENTATION_CAPS),
3159 arg,
3160 );
3161 CommandResult {
3162 message: result.message,
3163 action: result
3164 .action
3165 .map(crate::commands::config_host::config_action_to_app_action),
3166 is_error: result.is_error,
3167 }
3168 }
3169 /// Invoke the portable `/config` handler through the real CONFIG envelope
3170 /// and convert the contract result back.
3171 fn config_command(app: &mut App, arg: Option<&str>) -> CommandResult {
3172 let result = crate::commands::groups::config::config::config(
3173 app.command_contexts_with_config(None)
3174 .contexts(crate::commands::groups::config::config::CONFIG_CAPS),
3175 arg,
3176 );
3177 CommandResult {
3178 message: result.message,
3179 action: result
3180 .action
3181 .map(crate::commands::config_host::config_action_to_app_action),
3182 is_error: result.is_error,
3183 }
3184 }
3185 /// Invoke the portable `/settings` handler through the real CONFIG envelope.
3186 fn settings_command(app: &mut App, arg: Option<&str>) -> CommandResult {
3187 let result = crate::commands::groups::config::config::settings(
3188 app.command_contexts_with_config(None)
3189 .contexts(crate::commands::groups::config::config::CONFIG_PRESENTATION_CAPS),
3190 arg,
3191 );
3192 CommandResult {
3193 message: result.message,
3194 action: result
3195 .action
3196 .map(crate::commands::config_host::config_action_to_app_action),
3197 is_error: result.is_error,
3198 }
3199 }
3200 /// Invoke the portable `/config` handler (editor routing) through the CONFIG
3201 /// envelope for the legacy `show_config` tests.
3202 fn show_config(app: &mut App, arg: Option<&str>) -> CommandResult {
3203 let result = crate::commands::groups::config::config::config(
3204 app.command_contexts_with_config(None)
3205 .contexts(crate::commands::groups::config::config::CONFIG_CAPS),
3206 arg,
3207 );
3208 CommandResult {
3209 message: result.message,
3210 action: result
3211 .action
3212 .map(crate::commands::config_host::config_action_to_app_action),
3213 is_error: result.is_error,
3214 }
3215 }
3216 fn set_config_value(app: &mut App, key: &str, value: &str, persist: bool) -> CommandResult {
3217 let locale = app.ui_locale;
3218 crate::commands::config_host::render_config_reply(
3219 super::set_config_value(app, key, value, persist),
3220 locale,
3221 )
3222 }
3223
3224 fn show_single_setting(app: &App, key: &str) -> CommandResult {
3225 let locale = app.ui_locale;
3226 crate::commands::config_host::render_config_reply(
3227 super::show_single_setting(app, key),
3228 locale,
3229 )
3230 }
3231 use std::fs;
3232 use std::path::Path;
3233 use std::path::PathBuf;
3234 use std::time::{SystemTime, UNIX_EPOCH};
3235
3236 struct EnvGuard {
3237 _vars: Vec<EnvVarGuard>,
3238 _lock: TestEnvLock,
3239 }
3240
3241 impl EnvGuard {
3242 fn new(home: &Path) -> Self {
3243 let lock = lock_test_env();
3244 let config_path = home.join(".deepseek").join("config.toml");
3245 let vars = vec![
3246 EnvVarGuard::set("HOME", home),
3247 EnvVarGuard::set("USERPROFILE", home),
3248 EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale")),
3249 EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"),
3250 EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", config_path),
3251 EnvVarGuard::remove("CODEWHALE_ALLOW_SHELL"),
3252 EnvVarGuard::remove("DEEPSEEK_ALLOW_SHELL"),
3253 EnvVarGuard::remove("DEEPSEEK_APPROVAL_POLICY"),
3254 EnvVarGuard::remove("NO_ANIMATIONS"),
3255 EnvVarGuard::remove("TERM_PROGRAM"),
3256 EnvVarGuard::remove("PTYXIS_VERSION"),
3257 EnvVarGuard::remove("CODEWHALE_SEARCH_PROVIDER"),
3258 EnvVarGuard::remove("DEEPSEEK_SEARCH_PROVIDER"),
3259 EnvVarGuard::remove("TAVILY_API_KEY"),
3260 ];
3261 Self {
3262 _vars: vars,
3263 _lock: lock,
3264 }
3265 }
3266 }
3267
3268 fn create_test_app_with_config(config: &Config) -> App {
3269 let options = TuiOptions {
3270 model: "test-model".to_string(),
3271 // Keep command tests independent from the developer's saved
3272 // `default_mode` setting: with `false`, App::new starts in the
3273 // saved mode, so a machine with `default_mode = "yolo"` flips
3274 // `allow_shell` on and breaks the allow_shell assertions.
3275 start_in_agent_mode: true,
3276 skip_onboarding: false,
3277 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
3278 };
3279 let mut app = App::new(options, config);
3280 // App::new folds in saved TUI settings from the developer machine.
3281 // Pin command tests back to DeepSeek semantics so model aliases are
3282 // not normalized through a provider selected in an interactive run.
3283 app.model = "test-model".to_string();
3284 app.auto_model = false;
3285 app.api_provider = codewhale_config::ProviderKind::Deepseek;
3286 app.model_ids_passthrough = false;
3287 app
3288 }
3289
3290 fn create_test_app() -> App {
3291 create_test_app_with_config(&Config::default())
3292 }
3293
3294 #[test]
3295 fn contextual_tips_disable_only_guidance_and_keep_session_cap() {
3296 use crate::tui::app::{StatusToast, StatusToastKind, StatusToastLevel};
3297 use crate::tui::behavioral_tips::BehavioralTip;
3298
3299 let temp = tempfile::tempdir().unwrap();
3300 let _guard = EnvGuard::new(temp.path());
3301 let mut app = create_test_app();
3302 app.status_toasts.clear();
3303 assert!(app.maybe_show_behavioral_tip(BehavioralTip::McpValidation));
3304 app.push_status_toast("warning receipt", StatusToastLevel::Warning, None);
3305 app.push_status_toast("error receipt", StatusToastLevel::Error, None);
3306 app.sticky_status = Some(StatusToast::context_pressure(
3307 "context warning",
3308 codewhale_runtime::context_budget::PressureLevel::High,
3309 ));
3310
3311 let result = crate::commands::execute("/config contextual_tips off", &mut app);
3312 assert!(!result.is_error);
3313 assert!(!app.behavioral_tips.enabled());
3314 assert_eq!(
3315 app.status_toasts
3316 .iter()
3317 .map(|toast| toast.text.as_str())
3318 .collect::<Vec<_>>(),
3319 ["warning receipt", "error receipt"]
3320 );
3321 assert!(matches!(
3322 app.sticky_status.as_ref().unwrap().kind,
3323 StatusToastKind::ContextPressure(_)
3324 ));
3325 assert!(!app.maybe_show_behavioral_tip(BehavioralTip::McpValidation));
3326
3327 assert!(!crate::commands::execute("/config contextual_tips on", &mut app).is_error);
3328 assert!(app.behavioral_tips.enabled());
3329 assert!(
3330 !app.maybe_show_behavioral_tip(BehavioralTip::McpValidation),
3331 "reenabling must not reset the session cap"
3332 );
3333 }
3334
3335 #[test]
3336 fn contextual_tips_command_persists_and_reports_failed_save() {
3337 let temp = tempfile::tempdir().unwrap();
3338 let _guard = EnvGuard::new(temp.path());
3339 let mut app = create_test_app();
3340 Settings::transact(|settings| {
3341 settings.theme = "terminal".into();
3342 settings
3343 .behavioral_tip_impressions
3344 .insert("planning_mode".into(), 2);
3345 Ok(())
3346 })
3347 .unwrap();
3348
3349 let result = crate::commands::execute("/config contextual_tips off --save", &mut app);
3350 assert!(!result.is_error);
3351 let saved = Settings::load_persisted().unwrap();
3352 assert!(!saved.contextual_tips);
3353 assert_eq!(saved.theme, "terminal");
3354 assert_eq!(
3355 saved.behavioral_tip_impressions.get("planning_mode"),
3356 Some(&2)
3357 );
3358 assert!(
3359 !create_test_app().behavioral_tips.enabled(),
3360 "restart must load the saved opt-out"
3361 );
3362
3363 assert!(!crate::commands::execute("/config contextual_tips on --save", &mut app).is_error);
3364 assert!(create_test_app().behavioral_tips.enabled());
3365 assert_eq!(
3366 Settings::load_persisted()
3367 .unwrap()
3368 .behavioral_tip_impressions
3369 .get("planning_mode"),
3370 Some(&2)
3371 );
3372 let path = Settings::path().unwrap();
3373 let before = fs::read(&path).unwrap();
3374 assert!(
3375 crate::commands::execute("/config contextual_tips invalid --save", &mut app).is_error
3376 );
3377 assert_eq!(fs::read(&path).unwrap(), before);
3378 assert!(app.behavioral_tips.enabled());
3379
3380 let malformed = "contextual_tips = [private_fixture_payload\n";
3381 fs::write(&path, malformed).unwrap();
3382 let failed = crate::commands::execute("/config contextual_tips off --save", &mut app);
3383 assert!(failed.is_error);
3384 assert!(
3385 !app.behavioral_tips.enabled(),
3386 "failed persistence still honors the session opt-out"
3387 );
3388 assert_eq!(fs::read_to_string(path).unwrap(), malformed);
3389 let message = failed.message.unwrap();
3390 assert!(message.contains("could not be saved"), "{message}");
3391 assert!(
3392 !message.contains("private_fixture_payload"),
3393 "parse errors must not echo settings contents"
3394 );
3395 assert!(message.ends_with(&app.status_toasts.back().unwrap().text));
3396 }
3397
3398 #[test]
3399 fn config_unknown_setting_suggests_nearest_key() {
3400 let mut app = create_test_app();
3401 let result = config_command(&mut app, Some("auto_compcat"));
3402 assert!(result.is_error);
3403 let text = result.message.as_deref().unwrap_or_default();
3404 assert!(
3405 text.contains("Did you mean `/config auto_compact`?"),
3406 "{text}"
3407 );
3408 assert!(text.contains("/settings text"), "{text}");
3409
3410 let result = config_command(&mut app, Some("zzqqxxyy"));
3411 assert!(result.is_error);
3412 let text = result.message.as_deref().unwrap_or_default();
3413 assert!(!text.contains("Did you mean"), "{text}");
3414 assert!(text.contains("/settings text"), "{text}");
3415
3416 // Internal flags, actions and retired schema defs are not settings a
3417 // user can look up, and are never suggested.
3418 for internal in ["feature_intro_shown", "mcp_open", "fast_model"] {
3419 let result = config_command(&mut app, Some(internal));
3420 assert!(result.is_error, "{internal}: {:?}", result.message);
3421 let text = result.message.as_deref().unwrap_or_default();
3422 assert!(!text.contains(&format!("`/config {internal}`")), "{text}");
3423 }
3424 }
3425
3426 #[test]
3427 fn config_workflow_and_goal_explain_the_effective_tables() {
3428 let mut app = create_test_app();
3429 for token in ["workflow", "goal"] {
3430 let result = config_command(&mut app, Some(token));
3431 assert!(
3432 result.action.is_none(),
3433 "{token} must not spend a model turn"
3434 );
3435 let text = result.message.as_deref().unwrap_or_default();
3436 assert!(
3437 text.contains("require_approval_for_writes"),
3438 "{token}: {text}"
3439 );
3440 assert!(text.contains("max_continuations"), "{token}: {text}");
3441 }
3442 }
3443
3444 #[test]
3445 fn title_config_reports_the_default_not_the_session_override() {
3446 let config = {
3447 let __cw_config_init_0_0 =
3448 Some(" workspace\u{1b}]0;ignored\u{7}\u{202e}-default ".to_string());
3449 let mut __cw_config_init_0_value: Config = Config::default();
3450 __cw_config_init_0_value.title = __cw_config_init_0_0;
3451 __cw_config_init_0_value
3452 };
3453 let mut app = create_test_app_with_config(&config);
3454 assert_eq!(
3455 app.title_default.as_deref(),
3456 Some("workspace]0;ignored-default")
3457 );
3458 app.window_title = Some("session-override".to_string());
3459
3460 let shown = show_single_setting(&app, "title");
3461
3462 assert_eq!(
3463 shown.message.as_deref(),
3464 Some("title = workspace]0;ignored-default")
3465 );
3466 }
3467
3468 #[test]
3469 fn title_config_normalizes_the_live_and_persisted_default() {
3470 let dir = tempfile::tempdir().expect("isolated config dir");
3471 let config_path = dir.path().join("config.toml");
3472 let mut app = create_test_app();
3473 app.config_path = Some(config_path.clone());
3474
3475 let result = set_config_value(
3476 &mut app,
3477 "title",
3478 " Ev\u{1b}]0;PWNED\u{7}il\u{202e} Beta ",
3479 true,
3480 );
3481
3482 assert!(!result.is_error, "{:?}", result.message);
3483 assert_eq!(app.title_default.as_deref(), Some("Ev]0;PWNEDil Beta"));
3484 assert!(app.needs_redraw);
3485 let loaded = codewhale_plugins::providers::load_config(Some(config_path), None)
3486 .expect("reload saved config");
3487 assert_eq!(loaded.title.as_deref(), Some("Ev]0;PWNEDil Beta"));
3488 }
3489
3490 /// The shipped preset must survive its own preflight, or `/config preset
3491 /// calm` would be refused for a reason the user cannot act on.
3492 #[test]
3493 fn the_shipped_preset_passes_its_own_preflight() {
3494 let app = create_test_app();
3495 let fields =
3496 codewhale_runtime::settings::preset_fields("calm").expect("the calm preset exists");
3497 assert_eq!(preset_preflight(&app, fields), None);
3498 }
3499
3500 /// A field the setter would reject must be caught *before* the transaction
3501 /// opens. Previously the bundle was saved first and the per-field mirror
3502 /// pass then failed, leaving the user with an error message and a rewritten
3503 /// settings file.
3504 #[test]
3505 fn preset_preflight_refuses_an_invalid_field_before_any_write() {
3506 let app = create_test_app();
3507 let refusal = preset_preflight(&app, &[("calm_mode", "true"), ("low_motion", "banana")])
3508 .expect("an invalid value must be refused");
3509 assert!(
3510 refusal.contains("low_motion"),
3511 "the refusal must name the offending field, got {refusal:?}"
3512 );
3513 }
3514
3515 /// A preset carrying a live-route key is refused whole while a turn runs,
3516 /// rather than saving the bundle and then failing on that one field.
3517 #[test]
3518 fn preset_preflight_refuses_a_live_route_field_while_a_turn_runs() {
3519 let mut app = create_test_app();
3520 app.is_loading = true;
3521 let bundle = [("calm_mode", "true"), ("reasoning_effort", "high")];
3522 let refusal =
3523 preset_preflight(&app, &bundle).expect("a live-route field must be refused mid-turn");
3524 assert!(
3525 refusal.contains("locked while a turn is running"),
3526 "got {refusal:?}"
3527 );
3528
3529 app.is_loading = false;
3530 assert_eq!(
3531 preset_preflight(&app, &bundle),
3532 None,
3533 "the same bundle must apply once the turn ends"
3534 );
3535 }
3536
3537 /// The refusal list is the contract for #2982 on the slash surfaces. Keep
3538 /// restart-only `default_mode` out of it, and mode and permissions, which
3539 /// the engine applies at its next step boundary mid-turn.
3540 #[test]
3541 fn live_route_key_list_covers_every_route_mutating_alias() {
3542 for key in [
3543 "model",
3544 "default_model",
3545 "reasoning_effort",
3546 "effort",
3547 "provider",
3548 ] {
3549 assert!(
3550 live_route_setting_subject(key).is_some(),
3551 "{key} mutates the active route and must be locked mid-turn"
3552 );
3553 }
3554 for key in [
3555 "default_mode",
3556 "mode",
3557 "approval_mode",
3558 "approval_policy",
3559 "approval",
3560 "theme",
3561 "calm_mode",
3562 "rail_panel",
3563 ] {
3564 assert!(
3565 live_route_setting_subject(key).is_none(),
3566 "{key} does not mutate the active route and must stay settable"
3567 );
3568 }
3569 }
3570
3571 #[test]
3572 fn config_preset_calm_applies_bundle_to_session_and_keeps_evidence() {
3573 let mut app = create_test_app();
3574 app.calm_mode = false;
3575 app.show_thinking = true;
3576 app.show_tool_details = true;
3577 app.fancy_animations = true;
3578
3579 let result = config_command(&mut app, Some("preset calm"));
3580 let message = result.message.unwrap_or_default();
3581 assert!(
3582 message.contains("calm"),
3583 "summary should name the preset: {message}"
3584 );
3585
3586 assert!(app.calm_mode);
3587 assert!(!app.show_tool_details);
3588 assert!(app.low_motion);
3589 assert!(!app.fancy_animations);
3590 assert_eq!(
3591 app.tool_collapse_mode,
3592 crate::tui::app::ToolCollapseMode::Calm
3593 );
3594 assert_eq!(
3595 app.transcript_spacing,
3596 crate::tui::app::TranscriptSpacing::Compact
3597 );
3598 // Evidence preserved: thinking is not hidden by the preset.
3599 assert!(app.show_thinking, "calm preset must not hide thinking");
3600 }
3601
3602 #[test]
3603 fn config_preset_unknown_name_reports_error() {
3604 let mut app = create_test_app();
3605 let result = config_command(&mut app, Some("preset turbo"));
3606 let message = result.message.unwrap_or_default();
3607 assert!(
3608 message.to_lowercase().contains("unknown preset"),
3609 "expected unknown-preset error, got: {message}"
3610 );
3611 }
3612
3613 #[test]
3614 fn config_preset_save_without_name_reports_usage() {
3615 let mut app = create_test_app();
3616 let result = config_command(&mut app, Some("preset --save"));
3617 let message = result.message.unwrap_or_default();
3618 assert!(
3619 message.contains("Usage: /config preset"),
3620 "expected usage hint, got: {message}"
3621 );
3622 assert!(!result.is_error);
3623 }
3624
3625 #[test]
3626 fn work_surface_config_applies_live_and_accepts_bottom() {
3627 let mut app = create_test_app();
3628
3629 let result = set_config_value(&mut app, "work_surface_placement", "left", false);
3630 assert!(!result.is_error, "{:?}", result.message);
3631 assert_eq!(
3632 app.work_surface.placement,
3633 crate::tui::work_surface::WorkSurfacePlacement::Left
3634 );
3635 let shown = show_single_setting(&app, "work_surface_placement");
3636 assert_eq!(
3637 shown.message.as_deref(),
3638 Some("work_surface_placement = left")
3639 );
3640
3641 let result = set_config_value(&mut app, "work_surface_placement", "bottom", false);
3642 assert!(!result.is_error, "{:?}", result.message);
3643 assert_eq!(
3644 app.work_surface.placement,
3645 crate::tui::work_surface::WorkSurfacePlacement::Bottom
3646 );
3647 }
3648
3649 #[test]
3650 fn rail_command_on_restores_default_bottom_placement() {
3651 let mut app = create_test_app();
3652 app.work_surface.placement = crate::tui::work_surface::WorkSurfacePlacement::Off;
3653
3654 let result = workbar_command(&mut app, Some("on"));
3655
3656 assert!(!result.is_error);
3657 assert_eq!(
3658 app.work_surface.placement,
3659 crate::tui::work_surface::WorkSurfacePlacement::Bottom
3660 );
3661 let message = result.message.unwrap_or_default();
3662 assert!(message.contains("bottom placement"), "got: {message}");
3663 }
3664
3665 #[test]
3666 fn whale_command_selects_the_main_view_without_taking_composer_focus() {
3667 let mut app = create_test_app();
3668 app.onboarding = crate::tui::app::OnboardingState::None;
3669 app.redaction_gate = false;
3670 app.input = "kept draft".into();
3671 app.pet_watch.detach_for_test();
3672
3673 let on = whale_command(&mut app, None);
3674 assert!(!on.is_error);
3675 assert!(app.pet_watch.enabled);
3676 assert!(crate::tui::pet_watch::is_open(&app));
3677 assert_eq!(
3678 on.message.as_deref(),
3679 Some(&*tr(app.ui_locale, MessageId::PetModeOn))
3680 );
3681 assert!(app.view_stack.is_empty());
3682 // Repeating `on` leaves the composer in the same shell focus.
3683 assert!(!whale_command(&mut app, Some(" ON ")).is_error);
3684 assert!(app.pet_watch.enabled);
3685 assert!(crate::tui::pet_watch::is_open(&app));
3686
3687 let off = whale_command(&mut app, Some("off"));
3688 assert!(!off.is_error);
3689 assert!(!app.pet_watch.enabled);
3690 assert!(!crate::tui::pet_watch::is_open(&app));
3691 assert!(app.view_stack.is_empty());
3692 assert_eq!(app.input, "kept draft");
3693 assert_eq!(
3694 off.message.as_deref(),
3695 Some(&*tr(app.ui_locale, MessageId::PetModeOff))
3696 );
3697
3698 // Bare /whale toggles back on; removed verbs are refused with usage.
3699 assert!(!whale_command(&mut app, None).is_error);
3700 assert!(app.pet_watch.enabled);
3701 for removed in ["bogus", "status", "sound on", "export", "avatar"] {
3702 assert!(whale_command(&mut app, Some(removed)).is_error, "{removed}");
3703 }
3704 assert!(app.pet_watch.enabled);
3705 }
3706
3707 #[test]
3708 fn whale_still_name_and_colour_reach_this_terminal_s_whale() {
3709 let mut app = create_test_app();
3710 app.pet_watch.detach_for_test();
3711 assert!(!whale_command(&mut app, Some("still")).is_error);
3712 assert!(app.pet_watch.still());
3713 assert!(!whale_command(&mut app, Some("name Moby")).is_error);
3714 assert_eq!(app.pet_watch.name(), Some("Moby"));
3715 assert!(!whale_command(&mut app, Some("color #7fb2e0")).is_error);
3716 assert_eq!(app.pet_watch.color(), Some([0x7f, 0xb2, 0xe0]));
3717 assert!(!whale_command(&mut app, Some("color default")).is_error);
3718 assert_eq!(app.pet_watch.color(), None);
3719 assert!(!whale_command(&mut app, Some("still")).is_error);
3720 assert!(!app.pet_watch.still());
3721 }
3722
3723 #[test]
3724 fn pet_is_an_unlisted_alias_that_runs_whale() {
3725 let mut app = create_test_app();
3726 app.onboarding = crate::tui::app::OnboardingState::None;
3727 app.redaction_gate = false;
3728 app.pet_watch.detach_for_test();
3729 assert!(!crate::commands::execute("/pet", &mut app).is_error);
3730 assert!(app.pet_watch.enabled);
3731 assert!(!crate::commands::execute("/PET still", &mut app).is_error);
3732 assert!(app.pet_watch.still());
3733 assert!(!crate::commands::execute("/whale", &mut app).is_error);
3734 assert!(!app.pet_watch.enabled);
3735 let infos = crate::commands::command_infos();
3736 assert!(infos.iter().any(|info| info.name == "whale"));
3737 assert!(
3738 infos
3739 .iter()
3740 .all(|info| info.name != "pet" && !info.aliases.contains(&"pet")),
3741 "/pet is not listed"
3742 );
3743 }
3744
3745 #[test]
3746 fn rail_command_reports_narrow_terminal_top_fallback() {
3747 let mut app = create_test_app();
3748 app.work_surface.placement = crate::tui::work_surface::WorkSurfacePlacement::Left;
3749 // A 60-column host is below the side-rail floor, so the effective
3750 // placement falls back to top; the status must say so rather than
3751 // claim a left workbar renders.
3752 let _ = crate::tui::work_surface::height(&mut app, 60, 24, u16::MAX);
3753
3754 let result = workbar_command(&mut app, None);
3755
3756 assert!(!result.is_error);
3757 let message = result.message.unwrap_or_default();
3758 assert!(message.contains("left placement"), "got: {message}");
3759 assert!(message.contains("showing top for now"), "got: {message}");
3760 }
3761
3762 #[test]
3763 fn rail_command_off_never_claims_visibility() {
3764 let mut app = create_test_app();
3765
3766 let result = workbar_command(&mut app, Some("off"));
3767
3768 assert!(!result.is_error);
3769 assert_eq!(
3770 app.work_surface.placement,
3771 crate::tui::work_surface::WorkSurfacePlacement::Off
3772 );
3773 let message = result.message.unwrap_or_default();
3774 assert!(message.contains("Workbar is off"), "got: {message}");
3775 assert!(
3776 !message.contains("Workbar is visible"),
3777 "the readout must never claim a hidden surface renders: {message}"
3778 );
3779 }
3780
3781 #[test]
3782 fn rail_command_rejects_retired_auto_mode() {
3783 let mut app = create_test_app();
3784
3785 let result = workbar_command(&mut app, Some("auto"));
3786
3787 assert!(result.is_error);
3788 assert!(
3789 result
3790 .message
3791 .as_deref()
3792 .unwrap_or_default()
3793 .contains("Usage: /workbar")
3794 );
3795 }
3796
3797 #[test]
3798 fn test_mode_yolo_hints_shift_tab_and_zidong_aliases_auto() {
3799 for legacy in ["yolo", "bypass", "4"] {
3800 let mut app = create_test_app();
3801 let _ = mode_command(&mut app, Some("agent"));
3802 let before_approval = app.approval_mode;
3803 let before_trust = app.trust_mode;
3804 let before_shell = app.allow_shell;
3805 let result = mode_command(&mut app, Some(legacy));
3806 assert!(
3807 result
3808 .message
3809 .as_deref()
3810 .unwrap_or_default()
3811 .contains("Shift+Tab"),
3812 "expected Shift+Tab hint for /mode {legacy}, got {:?}",
3813 result.message
3814 );
3815 assert_eq!(result.action, None);
3816 assert!(!app.yolo);
3817 assert_eq!(app.approval_mode, before_approval);
3818 assert_eq!(app.trust_mode, before_trust);
3819 assert_eq!(app.allow_shell, before_shell);
3820 }
3821
3822 let mut app = create_test_app();
3823 let zidong = crate::commands::execute("/zidong", &mut app);
3824 let auto = crate::commands::execute("/auto", &mut app);
3825 assert_eq!(zidong.action, auto.action);
3826 assert!(!app.yolo);
3827 }
3828
3829 #[test]
3830 fn test_mode_switch_command_accepts_names_and_numbers() {
3831 let mut app = create_test_app();
3832 let _ = mode_command(&mut app, Some("agent"));
3833 assert_eq!(app.mode, AppMode::Agent);
3834 let result = mode_command(&mut app, Some("2"));
3835 assert_eq!(result.action, Some(AppAction::ModeChanged(AppMode::Plan)));
3836 assert_eq!(app.mode, AppMode::Plan);
3837 let result = mode_command(&mut app, Some("act"));
3838 assert_eq!(result.action, Some(AppAction::ModeChanged(AppMode::Agent)));
3839 assert_eq!(app.mode, AppMode::Agent);
3840 let result = crate::commands::execute("/jihua", &mut app);
3841 assert!(!result.is_error);
3842 assert_eq!(result.action, Some(AppAction::ModeChanged(AppMode::Plan)));
3843 assert_eq!(app.mode, AppMode::Plan);
3844 let _ = mode_command(&mut app, Some("plan"));
3845 assert_eq!(app.mode, AppMode::Plan);
3846 let result = mode_command(&mut app, Some("3"));
3847 assert_eq!(result.action, Some(AppAction::ModeChanged(AppMode::Agent)));
3848 assert_eq!(app.mode, AppMode::Agent);
3849 let result = mode_command(&mut app, Some("5"));
3850 assert!(result.is_error);
3851 assert_eq!(app.mode, AppMode::Agent);
3852 let result = mode_command(&mut app, Some("9"));
3853 assert!(result.is_error);
3854 assert_eq!(app.mode, AppMode::Agent);
3855 let result = mode_command(&mut app, Some("4"));
3856 assert!(result.action.is_none());
3857 assert_eq!(app.mode, AppMode::Agent);
3858 assert!(!app.yolo);
3859 assert!(
3860 result
3861 .message
3862 .as_deref()
3863 .is_some_and(|message| message.contains("Full Access is a permission posture")),
3864 "{:?}",
3865 result.message
3866 );
3867 }
3868
3869 #[test]
3870 fn test_mode_without_arg_opens_picker() {
3871 let mut app = create_test_app();
3872 let result = mode_command(&mut app, None);
3873 assert!(result.message.is_none());
3874 assert!(matches!(result.action, Some(AppAction::OpenModePicker)));
3875 }
3876
3877 #[test]
3878 fn test_mode_rejects_unknown_value() {
3879 let mut app = create_test_app();
3880 let prior = app.mode;
3881 let result = mode_command(&mut app, Some("fast"));
3882 assert!(!result.is_error);
3883 assert!(matches!(
3884 result.action,
3885 Some(AppAction::SetConversationMode { ref id }) if id == "fast"
3886 ));
3887 assert_eq!(app.mode, prior);
3888
3889 let invalid = mode_command(&mut app, Some("fast mode"));
3890 assert!(invalid.is_error);
3891 assert!(invalid.message.unwrap().contains("Usage: /mode"));
3892 }
3893
3894 #[test]
3895 fn test_mode_plan_artifact_subcommands_route_to_open_plan_artifact() {
3896 let mut app = create_test_app();
3897 let initial_mode = app.mode;
3898 for (input, expected) in [
3899 ("plan view", "view"),
3900 ("plan show", "view"),
3901 ("plan save", "save"),
3902 ("plan edit", "edit"),
3903 ("plan build", "build"),
3904 ("plan run", "build"),
3905 ] {
3906 let result = mode_command(&mut app, Some(input));
3907 assert!(!result.is_error, "{input}");
3908 assert_eq!(
3909 result.action,
3910 Some(AppAction::OpenPlanArtifact {
3911 arg: Some(expected.to_string()),
3912 }),
3913 "{input}"
3914 );
3915 assert_eq!(app.mode, initial_mode, "{input}");
3916 }
3917 let invalid = mode_command(&mut app, Some("plan unknown"));
3918 assert!(invalid.is_error);
3919 assert!(invalid.action.is_none());
3920 assert!(
3921 invalid
3922 .message
3923 .unwrap()
3924 .contains("Usage: /mode plan [view|save|edit|build]")
3925 );
3926 }
3927
3928 #[test]
3929 fn test_show_config_defaults_to_native() {
3930 let mut app = create_test_app();
3931 app.session.total_tokens = 1234;
3932 let result = show_config(&mut app, None);
3933 assert!(result.message.is_none());
3934 assert!(matches!(result.action, Some(AppAction::OpenConfigView)));
3935 }
3936
3937 #[test]
3938 fn test_show_config_native_opens_config_view() {
3939 let mut app = create_test_app();
3940 let result = show_config(&mut app, Some("native"));
3941 assert!(result.message.is_none());
3942 assert!(matches!(result.action, Some(AppAction::OpenConfigView)));
3943 }
3944
3945 #[test]
3946 fn test_show_config_tui_and_web_open_the_same_config_view() {
3947 let mut app = create_test_app();
3948 for arg in ["tui", "web", "TUI", " Web "] {
3949 let result = show_config(&mut app, Some(arg));
3950 assert!(result.message.is_none(), "{arg}");
3951 assert!(
3952 matches!(result.action, Some(AppAction::OpenConfigView)),
3953 "{arg}"
3954 );
3955 }
3956 }
3957
3958 #[test]
3959 fn test_show_config_non_editor_token_is_a_key_lookup() {
3960 // `tui`/`web`/`native` open the config view; every other single token is
3961 // a `/config <key>` lookup (unknown keys fail as settings, not editors).
3962 let mut app = create_test_app();
3963 let result = show_config(&mut app, Some("zzqqxxyy"));
3964 assert!(result.is_error);
3965 assert!(result.message.unwrap().contains("Unknown setting"));
3966 }
3967
3968 #[test]
3969 fn test_show_settings_loads_from_file() {
3970 let _lock = lock_test_env();
3971 let mut app = create_test_app();
3972 let report = show_settings(&mut app).expect("settings facts load");
3973 // Settings should load (may use defaults if file doesn't exist)
3974 assert!(!report.rows.is_empty());
3975 assert!(!report.config_file.is_empty());
3976 }
3977
3978 #[test]
3979 fn settings_command_opens_typed_editor_and_preserves_text_mode() {
3980 let _lock = lock_test_env();
3981 let mut app = create_test_app();
3982
3983 let modal = settings_command(&mut app, None);
3984 assert!(modal.message.is_none());
3985 assert!(matches!(modal.action, Some(AppAction::OpenConfigView)));
3986
3987 let text = settings_command(&mut app, Some("text"));
3988 let message = text.message.as_deref().expect("settings diagnostic text");
3989 assert!(message.contains("Settings:"), "{message}");
3990 assert!(
3991 message.contains("model defaults: config.toml"),
3992 "{message}"
3993 );
3994 assert!(!message.contains("provider_models:"), "{message}");
3995 assert!(message.contains("Config file:"), "{message}");
3996 assert!(text.action.is_none());
3997 }
3998
3999 #[test]
4000 fn config_model_updates_app_state() {
4001 let mut app = create_test_app();
4002 let _old_model = app.model.clone();
4003 let result = config_command(&mut app, Some("model deepseek-v4-flash"));
4004 assert!(result.message.is_some());
4005 let msg = result.message.unwrap();
4006 assert!(msg.contains("model = deepseek-v4-flash"));
4007 assert_eq!(app.model, "deepseek-v4-flash");
4008 assert!(matches!(
4009 result.action,
4010 Some(AppAction::UpdateCompaction(_))
4011 ));
4012 }
4013
4014 #[test]
4015 fn config_model_rejects_foreign_model_for_direct_provider() {
4016 let mut app = create_test_app();
4017 app.api_provider = ProviderKind::Zai;
4018 app.model = codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string();
4019
4020 let result = set_config_value(&mut app, "model", "deepseek-v4-pro", false);
4021
4022 assert!(result.is_error);
4023 assert_eq!(
4024 app.model,
4025 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL
4026 );
4027 assert!(result.action.is_none());
4028 let message = result.message.as_deref().expect("rejection message");
4029 assert!(
4030 message.contains("not compatible with provider 'zai'")
4031 || message.contains("not served by direct provider zai"),
4032 "unexpected rejection message: {message}"
4033 );
4034 assert!(message.contains("deepseek-v4-pro"), "{message}");
4035 }
4036
4037 #[test]
4038 fn config_model_auto_preserves_explicit_thinking() {
4039 let mut app = create_test_app();
4040 app.reasoning_effort = ReasoningEffort::Off;
4041 app.reasoning_effort_preference = Some(ReasoningEffort::Off);
4042
4043 let result = config_command(&mut app, Some("model auto"));
4044
4045 assert!(result.message.is_some());
4046 assert!(app.auto_model);
4047 assert_eq!(app.model, "auto");
4048 assert_eq!(app.reasoning_effort, ReasoningEffort::Off);
4049 assert!(
4050 result
4051 .message
4052 .as_deref()
4053 .is_some_and(|message| message.contains("thinking = off"))
4054 );
4055 assert!(app.last_effective_model.is_none());
4056 assert!(app.last_effective_reasoning_effort.is_none());
4057 }
4058
4059 #[test]
4060 fn config_model_auto_releases_implicit_fixed_model_thinking() {
4061 let mut app = create_test_app();
4062 app.reasoning_effort = ReasoningEffort::Max;
4063 app.reasoning_effort_preference = None;
4064
4065 let result = config_command(&mut app, Some("model auto"));
4066
4067 assert!(result.message.is_some());
4068 assert!(app.auto_model);
4069 assert_eq!(app.reasoning_effort, ReasoningEffort::Auto);
4070 assert_eq!(app.reasoning_effort_preference, None);
4071 assert!(
4072 result
4073 .message
4074 .as_deref()
4075 .is_some_and(|message| message.contains("thinking = auto"))
4076 );
4077 }
4078
4079 #[test]
4080 fn config_reasoning_effort_applies_while_model_routing_is_auto() {
4081 let mut app = create_test_app();
4082 app.set_model_selection("auto".to_string());
4083 app.reasoning_effort = ReasoningEffort::Auto;
4084 app.reasoning_effort_preference = None;
4085
4086 let result = set_config_value(&mut app, "reasoning_effort", "low", false);
4087
4088 assert!(!result.is_error);
4089 assert_eq!(app.reasoning_effort, ReasoningEffort::Low);
4090 assert_eq!(app.reasoning_effort_preference, Some(ReasoningEffort::Low));
4091 assert!(matches!(
4092 result.action,
4093 Some(AppAction::UpdateCompaction(_))
4094 ));
4095 }
4096
4097 #[test]
4098 fn config_default_model_cannot_replace_a_non_deepseek_live_route() {
4099 let temp_root = tempfile::tempdir().expect("isolated configuration");
4100 let _guard = EnvGuard::new(temp_root.path());
4101 let config_path =
4102 codewhale_runtime::config_persistence::config_toml_path(None).expect("config path");
4103 fs::create_dir_all(config_path.parent().expect("config directory")).expect("mkdir");
4104 fs::write(
4105 &config_path,
4106 "provider = 'zai'\n[providers.zai]\nmodel = 'GLM-5.2'\n",
4107 )
4108 .expect("config");
4109 let mut app = create_test_app();
4110 app.api_provider = ProviderKind::Zai;
4111 app.model = codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string();
4112 app.auto_model = false;
4113
4114 let session_only = set_config_value(&mut app, "default_model", "deepseek-v4-flash", false);
4115
4116 assert!(session_only.is_error);
4117 assert_eq!(
4118 app.model,
4119 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL
4120 );
4121 assert!(session_only.action.is_none());
4122 assert!(
4123 session_only
4124 .message
4125 .as_deref()
4126 .is_some_and(|message| message.contains("DeepSeek startup fallback"))
4127 );
4128
4129 let saved = set_config_value(&mut app, "default_model", "deepseek-v4-flash", true);
4130
4131 assert!(!saved.is_error);
4132 assert_eq!(
4133 app.model,
4134 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL
4135 );
4136 assert!(saved.action.is_none());
4137 assert!(
4138 saved
4139 .message
4140 .as_deref()
4141 .is_some_and(|message| message.contains("active zai/GLM-5.2 is unchanged"))
4142 );
4143 let persisted: toml::Value =
4144 toml::from_str(&fs::read_to_string(&config_path).expect("saved config")).expect("toml");
4145 assert_eq!(
4146 persisted["providers"]["deepseek"]["model"].as_str(),
4147 Some("deepseek-v4-flash")
4148 );
4149 assert_eq!(persisted["provider"].as_str(), Some("zai"));
4150 assert_eq!(
4151 saved_deepseek_default_model(&app).expect("saved value"),
4152 "deepseek-v4-flash"
4153 );
4154 assert!(
4155 Settings::load_persisted()
4156 .expect("settings")
4157 .default_model
4158 .is_none()
4159 );
4160 }
4161
4162 #[test]
4163 fn saved_automatic_model_selection_round_trips_every_provider_route() {
4164 let temp_root = tempfile::tempdir().expect("isolated configuration");
4165 let _guard = EnvGuard::new(temp_root.path());
4166 let config_path = codewhale_runtime::config_persistence::config_toml_path(None).unwrap();
4167 fs::create_dir_all(config_path.parent().unwrap()).unwrap();
4168 for (provider, selector, table, initial) in [
4169 (
4170 ProviderKind::Deepseek,
4171 "deepseek",
4172 "deepseek",
4173 "deepseek-v4-pro",
4174 ),
4175 (
4176 ProviderKind::Deepseek,
4177 "deepseek-cn",
4178 "deepseek_cn",
4179 "deepseek-v4-pro",
4180 ),
4181 (ProviderKind::Zai, "zai", "zai", "GLM-5.3"),
4182 ] {
4183 fs::write(
4184 &config_path,
4185 format!("provider = '{selector}'\n[providers.{table}]\nmodel = '{initial}'\n"),
4186 )
4187 .unwrap();
4188 let mut app = create_test_app();
4189 app.set_provider_identity(provider, selector);
4190 app.model = initial.to_string();
4191 app.auto_model = false;
4192 let result = set_config_value(&mut app, "model", "auto", true);
4193 assert!(!result.is_error, "{:?}", result.message);
4194 assert!(app.auto_model);
4195 assert!(
4196 result
4197 .message
4198 .as_deref()
4199 .is_some_and(|m| m.contains("saved"))
4200 );
4201 let persisted: toml::Value =
4202 toml::from_str(&fs::read_to_string(&config_path).unwrap()).unwrap();
4203 assert_eq!(
4204 persisted["providers"][table]["model"].as_str(),
4205 Some("auto")
4206 );
4207 let loaded =
4208 codewhale_plugins::providers::load_config(Some(config_path.clone()), None).unwrap();
4209 assert_eq!(
4210 loaded.default_model(),
4211 "auto",
4212 "{selector} must consume its saved choice"
4213 );
4214 }
4215 }
4216
4217 #[test]
4218 fn config_default_model_save_accepts_models_declared_for_the_deepseek_route() {
4219 let temp_root = tempfile::tempdir().expect("isolated configuration");
4220 let _guard = EnvGuard::new(temp_root.path());
4221 // The declaration matches on the saved DeepSeek route's base URL; keep
4222 // ambient endpoint overrides out of the comparison.
4223 let _base_url_env = [
4224 EnvVarGuard::remove("CODEWHALE_BASE_URL"),
4225 EnvVarGuard::remove("DEEPSEEK_BASE_URL"),
4226 ];
4227 let config_path =
4228 codewhale_runtime::config_persistence::config_toml_path(None).expect("config path");
4229 fs::create_dir_all(config_path.parent().expect("config directory")).expect("mkdir");
4230 fs::write(
4231 &config_path,
4232 "provider = 'zai'\n[providers.zai]\nmodel = 'GLM-5.2'\n[providers.deepseek]\nbase_url = 'https://my-gateway.example/v1'\n[[custom_models]]\nprovider = 'deepseek'\nbase_url = 'https://my-gateway.example/v1'\nid = 'my-llm'\n",
4233 )
4234 .expect("config");
4235
4236 let mut app = create_test_app();
4237 app.api_provider = ProviderKind::Zai;
4238 app.model = codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string();
4239 app.auto_model = false;
4240
4241 let result = set_config_value(&mut app, "default_model", "my-llm", true);
4242
4243 assert!(!result.is_error, "{:?}", result.message);
4244 let persisted: toml::Value =
4245 toml::from_str(&fs::read_to_string(&config_path).expect("saved config")).expect("toml");
4246 assert_eq!(
4247 persisted["providers"]["deepseek"]["model"].as_str(),
4248 Some("my-llm")
4249 );
4250 // The same id on a different DeepSeek endpoint is not declared for the
4251 // saved route and must still be rejected by catalog normalization.
4252 fs::write(
4253 &config_path,
4254 "provider = 'zai'\n[providers.zai]\nmodel = 'GLM-5.2'\n[providers.deepseek]\nbase_url = 'https://other-gateway.example/v1'\n[[custom_models]]\nprovider = 'deepseek'\nbase_url = 'https://my-gateway.example/v1'\nid = 'my-llm'\n",
4255 )
4256 .expect("config");
4257 let rejected = set_config_value(&mut app, "default_model", "my-llm", true);
4258 assert!(rejected.is_error, "{:?}", rejected.message);
4259 }
4260
4261 #[test]
4262 fn saved_model_display_uses_the_same_profile_root_precedence_as_startup() {
4263 let temp_root = tempfile::tempdir().unwrap();
4264 let _guard = EnvGuard::new(temp_root.path());
4265 let path = codewhale_runtime::config_persistence::config_toml_path(None).unwrap();
4266 fs::create_dir_all(path.parent().unwrap()).unwrap();
4267 let mut app = create_test_app();
4268 app.config_path = Some(path.clone());
4269 app.config_profile = Some("pro".to_string());
4270 for field in ["default_text_model", "model"] {
4271 fs::write(&path, format!("route_preferences_version = 1\nprovider = 'deepseek'\n[providers.deepseek]\nmodel = 'deepseek-v4-flash'\n[profiles.pro]\n{field} = 'deepseek-v4-pro'\n")).unwrap();
4272 let configured =
4273 Config::from_saved_document(&fs::read_to_string(&path).unwrap(), Some("pro"))
4274 .unwrap();
4275 assert_eq!(configured.default_model(), "deepseek-v4-pro");
4276 assert_eq!(
4277 saved_deepseek_default_model(&app).unwrap(),
4278 configured.default_model()
4279 );
4280 }
4281 }
4282
4283 #[test]
4284 fn config_reasoning_effort_uses_codex_provider_labels() {
4285 let temp_root = env::temp_dir().join(format!(
4286 "codewhale-tui-codex-effort-config-test-{}",
4287 std::process::id()
4288 ));
4289 fs::create_dir_all(&temp_root).unwrap();
4290 let _guard = EnvGuard::new(&temp_root);
4291 let mut app = create_test_app();
4292 app.api_provider = ProviderKind::OpenaiCodex;
4293 app.reasoning_effort = ReasoningEffort::High;
4294
4295 let result = set_config_value(&mut app, "reasoning_effort", "off", false);
4296
4297 assert_eq!(app.reasoning_effort, ReasoningEffort::Low);
4298 assert_eq!(app.reasoning_effort_preference, Some(ReasoningEffort::Off));
4299 assert_eq!(
4300 result.message.as_deref(),
4301 Some("reasoning_effort = low (session only, add --save to persist)")
4302 );
4303
4304 let result = set_config_value(&mut app, "reasoning_effort", "xhigh", false);
4305
4306 // `xhigh` stopped collapsing into `Max` when the ladder gave it a rung.
4307 assert_eq!(app.reasoning_effort, ReasoningEffort::XHigh);
4308 assert_eq!(
4309 result.message.as_deref(),
4310 Some("reasoning_effort = xhigh (session only, add --save to persist)")
4311 );
4312 }
4313
4314 #[test]
4315 fn config_fancy_animations_keeps_ghostty_full_motion() {
4316 let temp_root = env::temp_dir().join(format!(
4317 "codewhale-tui-ghostty-fancy-config-test-{}",
4318 std::process::id()
4319 ));
4320 fs::create_dir_all(&temp_root).unwrap();
4321 let _guard = EnvGuard::new(&temp_root);
4322 let _tmux = EnvVarGuard::remove("TMUX");
4323 let _sty = EnvVarGuard::remove("STY");
4324 let _tilix_id = EnvVarGuard::remove("TILIX_ID");
4325 let _terminator_uuid = EnvVarGuard::remove("TERMINATOR_UUID");
4326 // Neutralize the SSH markers: production intentionally caps motion
4327 // over SSH, and the suite routinely runs inside one.
4328 let _ssh_client = EnvVarGuard::remove("SSH_CLIENT");
4329 let _ssh_connection = EnvVarGuard::remove("SSH_CONNECTION");
4330 let _ssh_tty = EnvVarGuard::remove("SSH_TTY");
4331 let prev_term_program = env::var_os("TERM_PROGRAM");
4332 // Safety: test-only environment mutation guarded by EnvGuard's lock.
4333 unsafe {
4334 env::set_var("TERM_PROGRAM", "Ghostty");
4335 }
4336
4337 let mut app = create_test_app();
4338 assert!(app.fancy_animations);
4339 assert!(!app.constrained_frame_rate);
4340
4341 let result = set_config_value(&mut app, "fancy_animations", "true", false);
4342
4343 assert!(!result.is_error);
4344 assert!(
4345 app.fancy_animations,
4346 "Ghostty must keep authored motion enabled"
4347 );
4348 assert_eq!(
4349 result.message.as_deref(),
4350 Some("fancy_animations = true (session only, add --save to persist)")
4351 );
4352
4353 // Safety: cleanup under EnvGuard's lock.
4354 unsafe {
4355 match prev_term_program {
4356 Some(v) => env::set_var("TERM_PROGRAM", v),
4357 None => env::remove_var("TERM_PROGRAM"),
4358 }
4359 }
4360 }
4361
4362 #[test]
4363 fn config_model_accepts_future_deepseek_model_id() {
4364 let mut app = create_test_app();
4365 let result = config_command(&mut app, Some("model deepseek-v4"));
4366 assert!(result.message.is_some());
4367 let msg = result.message.unwrap();
4368 assert!(msg.contains("model = deepseek-v4"));
4369 assert_eq!(app.model, "deepseek-v4");
4370 }
4371
4372 #[test]
4373 fn config_model_with_save_flag() {
4374 let temp_root = tempfile::tempdir().expect("isolated settings dir");
4375 let _guard = EnvGuard::new(temp_root.path());
4376 let mut app = create_test_app();
4377 let result = config_command(&mut app, Some("model deepseek-v4-flash --save"));
4378 assert!(!result.is_error, "{:?}", result.message);
4379 assert_eq!(app.model, "deepseek-v4-flash");
4380 let config_path =
4381 codewhale_runtime::config_persistence::config_toml_path(app.config_path.as_deref())
4382 .expect("config path");
4383 let persisted: toml::Value =
4384 toml::from_str(&fs::read_to_string(config_path).expect("saved config")).expect("toml");
4385 assert_eq!(persisted["provider"].as_str(), Some("deepseek"));
4386 assert_eq!(
4387 persisted["providers"]["deepseek"]["model"].as_str(),
4388 Some("deepseek-v4-flash")
4389 );
4390 assert!(
4391 Settings::load_persisted()
4392 .expect("settings")
4393 .provider_models
4394 .is_none()
4395 );
4396 }
4397
4398 #[test]
4399 fn failed_model_save_keeps_the_live_selection() {
4400 let temp_root = tempfile::tempdir().expect("isolated config");
4401 let _guard = EnvGuard::new(temp_root.path());
4402 let mut app = create_test_app();
4403 let previous = app.model.clone();
4404 let blocked_path = temp_root.path().join("config-directory");
4405 fs::create_dir(&blocked_path).expect("blocked config path");
4406 app.config_path = Some(blocked_path);
4407
4408 let result = config_command(&mut app, Some("model deepseek-v4-flash --save"));
4409
4410 assert!(result.is_error);
4411 assert!(result.action.is_none());
4412 assert_eq!(app.model, previous);
4413 }
4414
4415 #[test]
4416 fn hosted_ollama_model_saves_keep_the_legacy_provider_slot() {
4417 use crate::tui::app::PendingRouteSave;
4418 use crate::tui::views::route_save_prompt::RouteSaveChoice;
4419
4420 let temp_root = tempfile::tempdir().expect("isolated config");
4421 let _guard = EnvGuard::new(temp_root.path());
4422 let config_path = temp_root.path().join(".codewhale/config.toml");
4423 fs::create_dir_all(config_path.parent().expect("config parent")).expect("config home");
4424 fs::write(
4425 &config_path,
4426 "provider = \"ollama\"\n[providers.ollama]\nbase_url = \"https://ollama.com/v1\"\nmodel = \"original:cloud\"\napi_key_env = \"TEST_OLLAMA_KEY\"\n",
4427 )
4428 .expect("legacy hosted config");
4429 let mut app = create_test_app();
4430 app.config_path = Some(config_path.clone());
4431 app.set_provider_identity_record(
4432 codewhale_plugins::providers::load_config(Some(config_path.clone()), None)
4433 .expect("captured hosted config")
4434 .active_provider_identity()
4435 .expect("captured hosted identity"),
4436 );
4437 app.active_route_base_url = "https://ollama.com/v1".to_string();
4438 app.model_ids_passthrough = true;
4439
4440 for (index, model) in ["live:cloud", "pending:cloud", "command:cloud"]
4441 .into_iter()
4442 .enumerate()
4443 {
4444 app.model = model.to_string();
4445 match index {
4446 0 => {
4447 let receipt = app
4448 .try_save_live_route_as_startup_default()
4449 .expect("remember live hosted route");
4450 assert!(receipt.contains("ollama-cloud/live:cloud"), "{receipt}");
4451 }
4452 1 => {
4453 app.pending_route_save = Some(PendingRouteSave {
4454 provider_identity: "ollama-cloud".to_string(),
4455 model: model.to_string(),
4456 fleet: None,
4457 });
4458 let receipt = app.apply_route_save_choice(RouteSaveChoice::SaveAsDefault);
4459 assert!(receipt.starts_with("Remembered "), "{receipt}");
4460 }
4461 _ => {
4462 let result = set_config_value(&mut app, "model", model, true);
4463 assert!(!result.is_error, "{:?}", result.message);
4464 }
4465 }
4466 let saved: toml::Value =
4467 toml::from_str(&fs::read_to_string(&config_path).expect("saved config"))
4468 .expect("valid config");
4469 assert_eq!(saved["provider"].as_str(), Some("ollama"));
4470 assert_eq!(saved["providers"]["ollama"]["model"].as_str(), Some(model));
4471 assert_eq!(
4472 saved["providers"]["ollama"]["base_url"].as_str(),
4473 Some("https://ollama.com/v1")
4474 );
4475 assert_eq!(
4476 saved["providers"]["ollama"]["api_key_env"].as_str(),
4477 Some("TEST_OLLAMA_KEY")
4478 );
4479 assert!(saved["providers"].get("ollama_cloud").is_none());
4480 assert!(saved["providers"].get("ollama-cloud").is_none());
4481 assert_eq!(app.provider_identity_for_persistence(), "ollama-cloud");
4482 assert_eq!(app.provider_id_for_persistence(), Some("ollama"));
4483 }
4484 }
4485
4486 #[test]
4487 fn config_default_mode_normal_save_reports_normalized_value() {
4488 let nanos = SystemTime::now()
4489 .duration_since(UNIX_EPOCH)
4490 .unwrap()
4491 .as_nanos();
4492 let temp_root = env::temp_dir().join(format!(
4493 "codewhale-tui-default-mode-test-{}-{}",
4494 std::process::id(),
4495 nanos
4496 ));
4497 fs::create_dir_all(&temp_root).unwrap();
4498 let _guard = EnvGuard::new(&temp_root);
4499
4500 let mut app = create_test_app();
4501 let result = config_command(&mut app, Some("default_mode normal --save"));
4502 let msg = result.message.unwrap();
4503 assert_eq!(msg, "default_mode = agent (saved)");
4504 assert_eq!(app.mode, AppMode::Agent);
4505
4506 let settings_path = Settings::path().unwrap();
4507 let saved = fs::read_to_string(settings_path).unwrap();
4508 assert!(saved.contains("default_mode = \"agent\""));
4509 }
4510
4511 #[test]
4512 fn config_command_cost_currency_save_persists_value() {
4513 let nanos = SystemTime::now()
4514 .duration_since(UNIX_EPOCH)
4515 .unwrap()
4516 .as_nanos();
4517 let temp_root = env::temp_dir().join(format!(
4518 "codewhale-tui-cost-currency-test-{}-{}",
4519 std::process::id(),
4520 nanos
4521 ));
4522 fs::create_dir_all(&temp_root).unwrap();
4523 let _guard = EnvGuard::new(&temp_root);
4524
4525 let mut app = create_test_app();
4526 let result = config_command(&mut app, Some("cost_currency cny --save"));
4527 let msg = result.message.unwrap();
4528
4529 assert_eq!(msg, "cost_currency = cny (saved)");
4530 assert_eq!(
4531 app.cost_currency,
4532 codewhale_config::pricing::CostCurrency::Cny
4533 );
4534
4535 let settings_path = Settings::path().unwrap();
4536 let saved = fs::read_to_string(settings_path).unwrap();
4537 assert!(saved.contains("cost_currency = \"cny\""));
4538 }
4539
4540 #[test]
4541 fn config_command_base_url_save_persists_value() {
4542 let nanos = SystemTime::now()
4543 .duration_since(UNIX_EPOCH)
4544 .unwrap()
4545 .as_nanos();
4546 let temp_root = env::temp_dir().join(format!(
4547 "deepseek-tui-base-url-test-{}-{}",
4548 std::process::id(),
4549 nanos
4550 ));
4551 fs::create_dir_all(&temp_root).unwrap();
4552 let _guard = EnvGuard::new(&temp_root);
4553
4554 let mut app = create_test_app();
4555 let result = config_command(
4556 &mut app,
4557 Some("base_url https://example.internal.local/v1 --save"),
4558 );
4559 let msg = result.message.unwrap();
4560 let saved_path = codewhale_runtime::config_persistence::config_toml_path(None).unwrap();
4561 let saved = fs::read_to_string(&saved_path).unwrap();
4562
4563 // The active DeepSeek route's own table, not a top-level key (#6394).
4564 assert_eq!(
4565 msg,
4566 format!(
4567 "base_url = https://example.internal.local/v1 for deepseek (saved to {}; restart required)",
4568 saved_path.display()
4569 )
4570 );
4571 let table: toml::Table = toml::from_str(&saved).unwrap();
4572 assert_eq!(
4573 table["providers"]["deepseek"]["base_url"].as_str(),
4574 Some("https://example.internal.local/v1")
4575 );
4576 assert!(table.get("base_url").is_none(), "{saved}");
4577 }
4578
4579 #[test]
4580 fn config_command_provider_emits_switch_action() {
4581 let mut app = create_test_app();
4582 let result = config_command(&mut app, Some("provider openrouter"));
4583
4584 assert!(!result.is_error);
4585 assert_eq!(result.message.as_deref(), Some("provider = openrouter"));
4586 match result.action {
4587 Some(AppAction::SwitchProvider { provider, model }) => {
4588 assert_eq!(provider.as_str(), ProviderKind::Openrouter.as_str());
4589 assert_eq!(model, None);
4590 }
4591 other => panic!("expected SwitchProvider action, got {other:?}"),
4592 }
4593 }
4594
4595 #[test]
4596 fn config_command_provider_rejects_unknown_provider() {
4597 let mut app = create_test_app();
4598 // "anthropic" became a real provider in #3014; probe with an id that
4599 // stays unknown.
4600 let result = config_command(&mut app, Some("provider not-a-provider"));
4601 assert!(result.is_error);
4602 let msg = result.message.unwrap();
4603 assert!(msg.contains("Unknown provider 'not-a-provider'"));
4604 assert!(msg.contains("openrouter"));
4605 assert!(msg.contains("xiaomi-mimo"));
4606 }
4607
4608 #[test]
4609 fn config_command_allow_shell_enables_agent_shell_session_only() {
4610 let mut app = create_test_app();
4611 assert!(!app.allow_shell);
4612
4613 let result = config_command(&mut app, Some("allow_shell true"));
4614 assert!(!result.is_error);
4615 assert!(app.allow_shell);
4616 let msg = result.message.unwrap();
4617
4618 assert!(msg.contains("allow_shell = true"));
4619 assert!(msg.contains("session only"));
4620 assert!(msg.contains("Work mode"));
4621 assert!(msg.contains("approval gating"));
4622 assert!(msg.contains("next turn"));
4623 assert!(msg.contains("Full Access (Shift+Tab) also enables shell and auto-approves"));
4624 }
4625
4626 #[test]
4627 fn config_command_allow_shell_save_persists_root_boolean() {
4628 let temp_root = tempfile::tempdir().expect("isolated config dir");
4629 let _guard = EnvGuard::new(temp_root.path());
4630
4631 let config_path = temp_root.path().join("custom-config.toml");
4632
4633 let mut app = create_test_app();
4634 app.config_path = Some(config_path.clone());
4635 let result = config_command(&mut app, Some("allow_shell true --save"));
4636 let msg = result.message.unwrap();
4637 let saved = fs::read_to_string(&config_path).unwrap();
4638
4639 assert!(app.allow_shell);
4640 assert_eq!(
4641 msg,
4642 format!(
4643 "allow_shell = true (saved to {}). Work mode will expose shell on the next turn with approval gating. Full Access (Shift+Tab) also enables shell and auto-approves.",
4644 config_path.display()
4645 )
4646 );
4647 assert!(saved.contains("allow_shell = true"));
4648 }
4649
4650 #[test]
4651 fn config_command_allow_shell_rejects_invalid_boolean() {
4652 let mut app = create_test_app();
4653 let result = config_command(&mut app, Some("allow_shell maybe"));
4654 assert!(result.is_error);
4655 assert!(!app.allow_shell);
4656 let msg = result.message.unwrap();
4657 assert!(msg.contains("Failed to parse boolean 'maybe'"));
4658 }
4659
4660 #[test]
4661 fn config_command_cannot_bypass_project_shell_constraint() {
4662 let temp_root = env::temp_dir().join(format!(
4663 "codewhale-project-shell-control-test-{}",
4664 std::process::id()
4665 ));
4666 fs::create_dir_all(temp_root.join(".deepseek")).unwrap();
4667 let _guard = EnvGuard::new(&temp_root);
4668 let root_config = temp_root.join(".deepseek").join("config.toml");
4669 fs::write(&root_config, "# user root\n").unwrap();
4670 let workspace = temp_root.join("workspace");
4671 fs::create_dir_all(workspace.join(codewhale_config::CODEWHALE_APP_DIR)).unwrap();
4672 fs::write(
4673 workspace
4674 .join(codewhale_config::CODEWHALE_APP_DIR)
4675 .join("config.toml"),
4676 "allow_shell = false\n",
4677 )
4678 .unwrap();
4679 let mut app = create_test_app();
4680 app.config_path = Some(root_config.clone());
4681 app.workspace = workspace;
4682 app.set_agent_shell_access(false);
4683
4684 let result = config_command(&mut app, Some("allow_shell true --save"));
4685
4686 assert!(result.is_error, "{:?}", result.message);
4687 assert!(!app.allow_shell);
4688 assert!(
4689 result
4690 .message
4691 .as_deref()
4692 .is_some_and(|message| message.contains("project configuration"))
4693 );
4694 assert!(
4695 !fs::read_to_string(root_config)
4696 .unwrap()
4697 .contains("allow_shell")
4698 );
4699 }
4700
4701 #[test]
4702 fn config_command_cannot_bypass_environment_shell_constraint() {
4703 let temp_root = env::temp_dir().join(format!(
4704 "codewhale-env-shell-control-test-{}",
4705 std::process::id()
4706 ));
4707 fs::create_dir_all(temp_root.join(".deepseek")).unwrap();
4708 let _guard = EnvGuard::new(&temp_root);
4709 let config_path = temp_root.join(".deepseek").join("config.toml");
4710 fs::write(&config_path, "# root\n").unwrap();
4711 // Safety: EnvGuard holds the process-wide environment lock and restores
4712 // this variable on drop.
4713 unsafe { env::set_var("DEEPSEEK_ALLOW_SHELL", "false") };
4714 let config =
4715 codewhale_plugins::providers::load_config(Some(config_path.clone()), None).unwrap();
4716 let mut app = create_test_app_with_config(&config);
4717 app.config_path = Some(config_path);
4718 app.set_agent_shell_access(false);
4719
4720 let result = config_command(&mut app, Some("allow_shell true"));
4721
4722 assert!(result.is_error, "{:?}", result.message);
4723 assert!(!app.allow_shell);
4724 assert!(
4725 result
4726 .message
4727 .as_deref()
4728 .is_some_and(|message| message.contains("DEEPSEEK_ALLOW_SHELL"))
4729 );
4730 }
4731
4732 #[test]
4733 fn config_command_cannot_bypass_project_or_environment_approval() {
4734 let temp_root = env::temp_dir().join(format!(
4735 "codewhale-external-approval-control-test-{}",
4736 std::process::id()
4737 ));
4738 fs::create_dir_all(temp_root.join(".deepseek")).unwrap();
4739 let _guard = EnvGuard::new(&temp_root);
4740 let root_config = temp_root.join(".deepseek").join("config.toml");
4741 fs::write(&root_config, "# root\n").unwrap();
4742 let workspace = temp_root.join("workspace");
4743 fs::create_dir_all(workspace.join(codewhale_config::CODEWHALE_APP_DIR)).unwrap();
4744 fs::write(
4745 workspace
4746 .join(codewhale_config::CODEWHALE_APP_DIR)
4747 .join("config.toml"),
4748 "approval_policy = \"never\"\n",
4749 )
4750 .unwrap();
4751 let mut app = create_test_app();
4752 app.config_path = Some(root_config.clone());
4753 app.workspace = workspace;
4754 app.set_agent_approval_posture(ApprovalMode::Never);
4755
4756 let project_result = config_command(&mut app, Some("approval_mode full-access"));
4757 assert!(project_result.is_error, "{:?}", project_result.message);
4758 assert_eq!(app.approval_mode, ApprovalMode::Never);
4759
4760 // Move outside the project and make the environment the controlling
4761 // source for the second half of the regression.
4762 app.workspace = temp_root.join("clean-workspace");
4763 fs::create_dir_all(&app.workspace).unwrap();
4764 // Safety: EnvGuard holds the process-wide environment lock and restores
4765 // this variable on drop.
4766 unsafe { env::set_var("DEEPSEEK_APPROVAL_POLICY", "never") };
4767 let env_result = config_command(&mut app, Some("approval_mode auto"));
4768 assert!(env_result.is_error, "{:?}", env_result.message);
4769 assert_eq!(app.approval_mode, ApprovalMode::Never);
4770 assert!(
4771 env_result
4772 .message
4773 .as_deref()
4774 .is_some_and(|message| message.contains("DEEPSEEK_APPROVAL_POLICY"))
4775 );
4776 }
4777
4778 #[test]
4779 fn config_command_shell_choice_survives_plan_round_trip() {
4780 let mut app = create_test_app();
4781 app.set_agent_approval_posture(ApprovalMode::Bypass);
4782
4783 let result = config_command(&mut app, Some("allow_shell true"));
4784
4785 assert!(!result.is_error, "{:?}", result.message);
4786 app.set_mode(AppMode::Plan);
4787 assert!(!app.allow_shell);
4788 app.set_mode(AppMode::Agent);
4789 assert!(app.allow_shell);
4790 assert_eq!(app.approval_mode, ApprovalMode::Bypass);
4791 }
4792
4793 #[test]
4794 fn config_command_subagents_off_save_persists_and_updates_runtime() {
4795 let temp_root = env::temp_dir().join(format!(
4796 "codewhale-subagents-off-save-test-{}",
4797 std::process::id()
4798 ));
4799 fs::create_dir_all(&temp_root).unwrap();
4800 let config_path = temp_root.join("custom-config.toml");
4801
4802 let mut app = create_test_app();
4803 app.config_path = Some(config_path.clone());
4804 let result = config_command(&mut app, Some("subagents off --save"));
4805 let msg = result.message.unwrap();
4806 let saved = fs::read_to_string(&config_path).unwrap();
4807
4808 assert!(!result.is_error);
4809 assert!(msg.contains("subagents.enabled = false"));
4810 assert!(msg.contains("saved to"));
4811 assert!(saved.contains("[subagents]"));
4812 assert!(saved.contains("enabled = false"));
4813 match result.action {
4814 Some(AppAction::UpdateSubagentRuntimeConfig { enabled, .. }) => {
4815 assert!(!enabled);
4816 }
4817 other => panic!("expected subagent runtime update, got {other:?}"),
4818 }
4819 }
4820
4821 #[test]
4822 fn config_command_subagents_depth_save_clamps_to_ceiling() {
4823 let temp_root = env::temp_dir().join(format!(
4824 "codewhale-subagents-depth-save-test-{}",
4825 std::process::id()
4826 ));
4827 fs::create_dir_all(&temp_root).unwrap();
4828 let config_path = temp_root.join("custom-config.toml");
4829
4830 let mut app = create_test_app();
4831 app.config_path = Some(config_path.clone());
4832 let result = config_command(&mut app, Some("subagents max_depth 99 --save"));
4833 let msg = result.message.unwrap();
4834 let saved = fs::read_to_string(&config_path).unwrap();
4835 let ceiling = 99;
4836
4837 assert!(!result.is_error);
4838 assert!(msg.contains(&format!("subagents.max_depth = {ceiling}")));
4839 assert!(!msg.contains("clamped"));
4840 assert!(saved.contains(&format!("max_depth = {ceiling}")));
4841 match result.action {
4842 Some(AppAction::UpdateSubagentRuntimeConfig {
4843 max_spawn_depth, ..
4844 }) => {
4845 assert_eq!(max_spawn_depth, ceiling);
4846 }
4847 other => panic!("expected subagent runtime update, got {other:?}"),
4848 }
4849 }
4850
4851 #[test]
4852 fn config_command_subagents_status_shows_raw_and_resolved_values() {
4853 let temp_root = env::temp_dir().join(format!(
4854 "codewhale-subagents-status-test-{}",
4855 std::process::id()
4856 ));
4857 fs::create_dir_all(&temp_root).unwrap();
4858 let config_path = temp_root.join("custom-config.toml");
4859 fs::write(
4860 &config_path,
4861 r#"
4862 [subagents]
4863 enabled = true
4864 max_concurrent = 2
4865 max_depth = 0
4866 launch_concurrency = 5
4867 api_timeout_secs = 0
4868 heartbeat_timeout_secs = 1
4869 "#,
4870 )
4871 .unwrap();
4872
4873 let mut app = create_test_app();
4874 app.config_path = Some(config_path);
4875 let result = config_command(&mut app, Some("subagents status"));
4876 let msg = result.message.unwrap();
4877
4878 assert!(!result.is_error);
4879 assert!(msg.contains("Sub-agents: disabled (subagents.max_depth=0)"));
4880 assert!(msg.contains("Active provider: deepseek"));
4881 assert!(
4882 msg.contains("subagents.max_concurrent = 2 (resolved global 2; active provider 2)")
4883 );
4884 assert!(
4885 msg.contains("subagents.launch_concurrency = 5 (resolved global 2; active provider 2)")
4886 );
4887 assert!(
4888 msg.contains(
4889 "subagents.api_timeout_secs = 0 (resolved global 600; active provider 600)"
4890 )
4891 );
4892 assert!(msg.contains(
4893 "subagents.heartbeat_timeout_secs = 1 (resolved global 630; active provider 630)"
4894 ));
4895 assert!(msg.contains("subagents.providers.deepseek = inherits global"));
4896 }
4897
4898 #[test]
4899 fn config_command_audit_lists_editability_and_current_values() {
4900 let temp_root = env::temp_dir().join(format!(
4901 "codewhale-config-audit-test-{}",
4902 std::process::id()
4903 ));
4904 fs::create_dir_all(&temp_root).unwrap();
4905 // Hermetic: the audit reads Settings::load(); without this guard the
4906 // developer's real saved permission_posture leaks in and the
4907 // "(unset)" assertion below becomes machine-dependent.
4908 let _guard = EnvGuard::new(&temp_root);
4909 let config_path = temp_root.join("custom-config.toml");
4910 fs::write(
4911 &config_path,
4912 r#"
4913 base_url = "https://api.from-config.local/v1"
4914 instructions = ["~/global.md"]
4915 prompt_suggestion = true
4916
4917 [subagents]
4918 enabled = false
4919 max_concurrent = 4
4920
4921 [search]
4922 provider = "bing"
4923
4924 [notifications]
4925 method = "osc9"
4926 threshold_secs = 45
4927 quiet = true
4928 completion_sound = "off"
4929 "#,
4930 )
4931 .unwrap();
4932
4933 let mut app = create_test_app();
4934 app.config_path = Some(config_path.clone());
4935 app.approval_mode = ApprovalMode::Never;
4936 app.stream_chunk_timeout_secs = 45;
4937
4938 let result = config_command(&mut app, Some("audit"));
4939 let msg = result.message.unwrap();
4940
4941 assert!(!result.is_error);
4942 assert!(msg.contains("Config editability audit"));
4943 assert!(msg.contains(&format!("Config path: {}", config_path.display())));
4944 assert!(msg.contains("effective_permissions | Never | runtime"));
4945 assert!(msg.contains("permission_posture | (unset) | TUI settings"));
4946 assert!(msg.contains("approval_policy | (unset) | persisted config"));
4947 assert!(msg.contains("stream_chunk_timeout_secs | 45 | runtime+persisted"));
4948 assert!(msg.contains("subagents.enabled | false | runtime+persisted"));
4949 assert!(msg.contains("subagents.max_concurrent | 4 | runtime+persisted"));
4950 assert!(msg.contains("base_url | https://api.from-config.local/v1 | persisted restart"));
4951 assert!(msg.contains("providers.<active>.context_window | (unset) | persisted restart"));
4952 assert!(msg.contains("effective_context_window |"), "{msg}");
4953 assert!(msg.contains("| runtime | /config context_window"), "{msg}");
4954 assert!(msg.contains("instructions | configured | file-only restart"));
4955 assert!(msg.contains("network | unset | file-only"));
4956 assert!(
4957 msg.contains("search.provider | bing (source: config.toml) | runtime+persisted"),
4958 "{msg}"
4959 );
4960 assert!(
4961 msg.contains("prompt_suggestion | true | runtime+persisted"),
4962 "{msg}"
4963 );
4964 assert!(
4965 msg.contains(
4966 "notifications | method=osc9 threshold=45s sound=legacy quiet=true | runtime+persisted"
4967 ),
4968 "{msg}"
4969 );
4970
4971 app.mode = AppMode::Plan;
4972 let plan_msg = config_command(&mut app, Some("audit"))
4973 .message
4974 .expect("Plan audit message");
4975 assert!(
4976 plan_msg.contains("effective_permissions | Read Only | runtime"),
4977 "{plan_msg}"
4978 );
4979 }
4980
4981 #[test]
4982 fn config_command_shows_search_prompt_suggestion_and_notifications() {
4983 let temp_root = env::temp_dir().join(format!(
4984 "codewhale-config-discovery-show-{}",
4985 std::process::id()
4986 ));
4987 fs::create_dir_all(&temp_root).unwrap();
4988 let _guard = EnvGuard::new(&temp_root);
4989 let config_path = temp_root.join("custom-config.toml");
4990 fs::write(
4991 &config_path,
4992 r#"
4993 prompt_suggestion = true
4994
4995 [search]
4996 provider = "tavily"
4997
4998 [notifications]
4999 method = "bel"
5000 threshold_secs = 12
5001 quiet = false
5002 completion_sound = "bell"
5003 "#,
5004 )
5005 .unwrap();
5006
5007 let mut app = create_test_app();
5008 app.config_path = Some(config_path.clone());
5009 // This fixture starts App with defaults; seed its current Config view
5010 // as the real constructor does before asking a live-session query.
5011 app.notification_settings =
5012 codewhale_plugins::providers::load_config(Some(config_path), None)
5013 .unwrap()
5014 .notifications_config();
5015
5016 let search = config_command(&mut app, Some("search.provider"));
5017 assert!(!search.is_error, "{:?}", search.message);
5018 assert_eq!(
5019 search.message.as_deref(),
5020 Some("search.provider = tavily (source: config.toml)")
5021 );
5022
5023 let suggestion = config_command(&mut app, Some("prompt_suggestion"));
5024 assert!(!suggestion.is_error, "{:?}", suggestion.message);
5025 assert_eq!(
5026 suggestion.message.as_deref(),
5027 Some("prompt_suggestion = true")
5028 );
5029
5030 let notifications = config_command(&mut app, Some("notifications"));
5031 let notifications_msg = notifications.message.expect("notifications status");
5032 assert!(!notifications.is_error, "{notifications_msg}");
5033 assert!(
5034 notifications_msg.contains("method = bel"),
5035 "{notifications_msg}"
5036 );
5037 assert!(
5038 notifications_msg.contains("threshold_secs = 12"),
5039 "{notifications_msg}"
5040 );
5041 assert!(
5042 notifications_msg.contains("completion_sound = bell"),
5043 "{notifications_msg}"
5044 );
5045 }
5046
5047 #[test]
5048 fn unparseable_config_reports_lookup_failure_not_unknown_setting() {
5049 let temp_root = tempfile::tempdir().expect("isolated config dir");
5050 let _guard = EnvGuard::new(temp_root.path());
5051 let config_path = temp_root.path().join("custom-config.toml");
5052 fs::write(&config_path, "search = [unterminated").unwrap();
5053
5054 let mut app = create_test_app();
5055 app.config_path = Some(config_path);
5056
5057 let result = show_single_setting(&app, "search");
5058 assert!(result.is_error, "{:?}", result.message);
5059 let message = result.message.expect("lookup failure message");
5060 assert!(message.contains("Failed to load config"), "{message}");
5061 assert!(!message.contains("Unknown setting"), "{message}");
5062 }
5063
5064 #[test]
5065 fn allow_shell_reply_follows_the_ui_locale() {
5066 let temp_root = tempfile::tempdir().expect("isolated config dir");
5067 let _guard = EnvGuard::new(temp_root.path());
5068 let config_path = temp_root.path().join("custom-config.toml");
5069 fs::write(&config_path, "").unwrap();
5070
5071 let mut app = create_test_app();
5072 app.config_path = Some(config_path);
5073 let mut replies = Vec::new();
5074 for locale in [
5075 codewhale_localization::Locale::En,
5076 codewhale_localization::Locale::ZhHans,
5077 ] {
5078 app.ui_locale = locale;
5079 for value in ["true", "false"] {
5080 let result = set_config_value(&mut app, "allow_shell", value, false);
5081 assert!(!result.is_error, "{:?}", result.message);
5082 replies.push(result.message.expect("allow_shell reply"));
5083 }
5084 }
5085 assert_ne!(replies[0], replies[2]);
5086 assert_ne!(replies[1], replies[3]);
5087 }
5088
5089 #[test]
5090 fn config_command_shows_autodetected_tavily_key_source() {
5091 let temp_root = tempfile::tempdir().expect("isolated config dir");
5092 let _guard = EnvGuard::new(temp_root.path());
5093 let config_path = temp_root.path().join("custom-config.toml");
5094 fs::write(
5095 &config_path,
5096 r#"
5097 [search]
5098 api_key = "tvly-autodetected"
5099 "#,
5100 )
5101 .unwrap();
5102
5103 let mut app = create_test_app();
5104 app.config_path = Some(config_path);
5105
5106 let search = config_command(&mut app, Some("search.provider"));
5107 assert!(!search.is_error, "{:?}", search.message);
5108 let message = search.message.expect("search provider display");
5109 assert_eq!(message, "search.provider = tavily (source: tavily key)");
5110 assert!(
5111 !message.contains("TAVILY_API_KEY"),
5112 "a generic `tvly-` key must not be reported as the env var: {message}"
5113 );
5114 }
5115
5116 #[test]
5117 fn config_command_sets_search_prompt_suggestion_and_notifications() {
5118 let temp_root = tempfile::tempdir().expect("isolated config dir");
5119 let _guard = EnvGuard::new(temp_root.path());
5120 let config_path = temp_root.path().join("custom-config.toml");
5121
5122 let mut app = create_test_app();
5123 app.config_path = Some(config_path.clone());
5124
5125 let search = config_command(&mut app, Some("search.provider duckduckgo --save"));
5126 assert!(!search.is_error, "{:?}", search.message);
5127 match search.action {
5128 Some(AppAction::UpdateSearchProvider { provider }) => {
5129 assert_eq!(provider, SearchProvider::DuckDuckGo);
5130 }
5131 other => panic!("expected UpdateSearchProvider, got {other:?}"),
5132 }
5133
5134 let suggestion = config_command(&mut app, Some("prompt_suggestion true --save"));
5135 assert!(!suggestion.is_error, "{:?}", suggestion.message);
5136 match suggestion.action {
5137 Some(AppAction::UpdatePromptSuggestion { enabled }) => assert!(enabled),
5138 other => panic!("expected UpdatePromptSuggestion, got {other:?}"),
5139 }
5140
5141 let notifications = config_command(&mut app, Some("notifications method osc9 --save"));
5142 assert!(!notifications.is_error, "{:?}", notifications.message);
5143 match notifications.action {
5144 Some(AppAction::UpdateNotification {
5145 update: NotificationConfigUpdate::Method(method),
5146 }) => assert_eq!(method, NotificationMethod::Osc9),
5147 other => panic!("expected UpdateNotification method, got {other:?}"),
5148 }
5149
5150 let saved = fs::read_to_string(&config_path).unwrap();
5151 assert!(saved.contains("provider = \"duckduckgo\""), "{saved}");
5152 assert!(saved.contains("prompt_suggestion = true"), "{saved}");
5153 assert!(saved.contains("method = \"osc9\""), "{saved}");
5154
5155 let loaded = codewhale_plugins::providers::load_config(Some(config_path), None)
5156 .expect("reloaded config");
5157 assert_eq!(loaded.search_provider(), SearchProvider::DuckDuckGo);
5158 assert!(loaded.prompt_suggestion_enabled());
5159 assert_eq!(
5160 loaded.notifications_config().method,
5161 NotificationMethod::Osc9
5162 );
5163 }
5164
5165 #[test]
5166 fn config_command_reads_and_writes_search_third_party() {
5167 let temp_root = tempfile::tempdir().expect("isolated config dir");
5168 let _guard = EnvGuard::new(temp_root.path());
5169 let _firecrawl = EnvVarGuard::remove("FIRECRAWL_API_KEY");
5170 let _search_key = EnvVarGuard::remove("CODEWHALE_SEARCH_API_KEY");
5171 let config_path = temp_root.path().join("custom-config.toml");
5172 let mut app = create_test_app();
5173 app.config_path = Some(config_path.clone());
5174
5175 let shown = config_command(&mut app, Some("search.third_party"));
5176 assert!(!shown.is_error, "{:?}", shown.message);
5177 let message = shown.message.expect("search.third_party display");
5178 assert!(message.starts_with("search.third_party = ask"), "{message}");
5179
5180 let off = config_command(&mut app, Some("search.third_party off"));
5181 assert!(!off.is_error, "{:?}", off.message);
5182 let message = off.message.expect("search.third_party reply");
5183 assert!(message.contains("search.third_party = off"), "{message}");
5184 let saved = fs::read_to_string(&config_path).unwrap();
5185 assert!(saved.contains("third_party = \"off\""), "{saved}");
5186 let shown = config_command(&mut app, Some("search_third_party"))
5187 .message
5188 .expect("display after save");
5189 assert!(
5190 shown.starts_with("search_third_party = off") && shown.contains("config.toml"),
5191 "{shown}"
5192 );
5193
5194 let invalid = config_command(&mut app, Some("search.third_party sometimes"));
5195 assert!(invalid.is_error, "{:?}", invalid.message);
5196 assert!(
5197 fs::read_to_string(&config_path)
5198 .unwrap()
5199 .contains("third_party = \"off\"")
5200 );
5201
5202 let ask = config_command(&mut app, Some("search.third_party ask"));
5203 assert!(!ask.is_error, "{:?}", ask.message);
5204 assert!(
5205 !fs::read_to_string(&config_path)
5206 .unwrap()
5207 .contains("third_party")
5208 );
5209 }
5210
5211 #[test]
5212 fn session_only_notification_commands_emit_composable_field_deltas() {
5213 let temp_root = tempfile::tempdir().expect("isolated config dir");
5214 let _guard = EnvGuard::new(temp_root.path());
5215 let config_path = temp_root.path().join("custom-config.toml");
5216 fs::write(
5217 &config_path,
5218 "[notifications]\nmethod = \"bel\"\nthreshold_secs = 12\nquiet = false\n",
5219 )
5220 .expect("persisted notification config");
5221
5222 let mut app = create_test_app();
5223 app.config_path = Some(config_path);
5224 let mut live = NotificationsConfig {
5225 threshold_secs: 12,
5226 ..NotificationsConfig::default()
5227 };
5228
5229 for command in ["notifications method osc9", "notifications quiet true"] {
5230 let result = config_command(&mut app, Some(command));
5231 assert!(!result.is_error, "{:?}", result.message);
5232 let Some(AppAction::UpdateNotification { update }) = result.action else {
5233 panic!("expected notification field delta for {command}");
5234 };
5235 live.apply_update(update).unwrap();
5236 }
5237
5238 assert_eq!(live.method, NotificationMethod::Osc9);
5239 assert!(live.quiet);
5240 assert_eq!(live.threshold_secs, 12);
5241 }
5242
5243 #[test]
5244 fn config_command_rejects_invalid_search_and_notification_values() {
5245 let mut app = create_test_app();
5246 let search = config_command(&mut app, Some("search.provider not-a-backend"));
5247 assert!(search.is_error);
5248 let search_msg = search.message.unwrap();
5249 assert!(
5250 search_msg.contains("Can't use 'not-a-backend' for search.provider"),
5251 "{search_msg}"
5252 );
5253 assert!(search_msg.contains("firecrawl"), "{search_msg}");
5254
5255 let notifications = config_command(&mut app, Some("notifications method semaphore"));
5256 assert!(notifications.is_error);
5257 let notifications_msg = notifications.message.unwrap();
5258 assert!(
5259 notifications_msg.contains("Can't use 'semaphore' for notifications.method"),
5260 "{notifications_msg}"
5261 );
5262 assert!(notifications_msg.contains("osc9"), "{notifications_msg}");
5263 }
5264
5265 #[test]
5266 fn config_context_window_query_shows_override_and_effective_source() {
5267 let temp_root = env::temp_dir().join(format!(
5268 "codewhale-context-window-query-test-{}",
5269 std::process::id()
5270 ));
5271 fs::create_dir_all(&temp_root).unwrap();
5272 let _guard = EnvGuard::new(&temp_root);
5273 let config_path = temp_root.join("custom-config.toml");
5274 fs::write(
5275 &config_path,
5276 r#"
5277 provider = "moonshot"
5278 [providers.moonshot]
5279 model = "kimi-k3"
5280 context_window = 262144
5281 "#,
5282 )
5283 .unwrap();
5284 let mut app = create_test_app();
5285 app.config_path = Some(config_path);
5286 app.set_provider_identity_record(
5287 codewhale_runtime::config::Config::default()
5288 .resolve_provider_identity(ProviderKind::Moonshot.as_str())
5289 .expect("captured fixture provider"),
5290 );
5291 app.model = "kimi-k3".to_string();
5292 app.active_route_limits = Some(codewhale_config::route::RouteLimits {
5293 context_tokens: Some(262_144),
5294 ..Default::default()
5295 });
5296 app.active_context_window =
5297 Some(codewhale_engine::route_runtime::ContextWindowResolution {
5298 tokens: 262_144,
5299 source: codewhale_engine::route_runtime::ContextWindowSource::Configured,
5300 });
5301 app.active_context_window_source =
5302 codewhale_engine::route_runtime::ContextWindowSource::Configured;
5303
5304 let result = config_command(&mut app, Some("context_window"));
5305 let message = result.message.expect("context window message");
5306
5307 assert!(!result.is_error, "{message}");
5308 assert!(
5309 message.contains("262144 (effective 262144 from configured)"),
5310 "{message}"
5311 );
5312 }
5313
5314 #[test]
5315 fn config_command_base_url_without_save_requires_save() {
5316 let _lock = lock_test_env();
5317 let mut app = create_test_app();
5318 let result = config_command(&mut app, Some("base_url https://example.internal.local/v1"));
5319 assert!(result.is_error);
5320 let msg = result.message.unwrap();
5321
5322 assert!(
5323 msg.contains("base_url must be saved with --save"),
5324 "got {msg}"
5325 );
5326 }
5327
5328 #[test]
5329 fn config_command_base_url_reads_current_value_from_config() {
5330 let nanos = SystemTime::now()
5331 .duration_since(UNIX_EPOCH)
5332 .unwrap()
5333 .as_nanos();
5334 let temp_root = env::temp_dir().join(format!(
5335 "deepseek-tui-base-url-show-test-{}-{}",
5336 std::process::id(),
5337 nanos
5338 ));
5339 fs::create_dir_all(&temp_root).unwrap();
5340 let _guard = EnvGuard::new(&temp_root);
5341
5342 let config_path = temp_root.join(".deepseek").join("config.toml");
5343 fs::create_dir_all(config_path.parent().unwrap()).unwrap();
5344 fs::write(
5345 &config_path,
5346 "base_url = \"https://api.from-config.local/v1\"\n",
5347 )
5348 .unwrap();
5349
5350 let mut app = create_test_app();
5351 let result = config_command(&mut app, Some("base_url"));
5352 let msg = result.message.unwrap();
5353
5354 assert_eq!(msg, "base_url = https://api.from-config.local/v1");
5355 }
5356
5357 #[test]
5358 fn config_command_base_url_reads_current_value_from_app_config_path() {
5359 let temp_root = env::temp_dir().join(format!(
5360 "deepseek-tui-base-url-app-config-path-test-{}",
5361 std::process::id()
5362 ));
5363 fs::create_dir_all(&temp_root).unwrap();
5364
5365 let config_path = temp_root.join("custom-config.toml");
5366 fs::write(
5367 &config_path,
5368 "base_url = \"https://api.from-app-path.local/v1\"\n",
5369 )
5370 .unwrap();
5371
5372 let mut app = create_test_app();
5373 app.config_path = Some(config_path.clone());
5374 let result = config_command(&mut app, Some("base_url"));
5375 let msg = result.message.unwrap();
5376
5377 assert_eq!(msg, "base_url = https://api.from-app-path.local/v1");
5378 }
5379
5380 #[test]
5381 fn config_command_base_url_save_persists_to_app_config_path() {
5382 let temp_root = env::temp_dir().join(format!(
5383 "deepseek-tui-base-url-save-app-path-test-{}",
5384 std::process::id()
5385 ));
5386 fs::create_dir_all(&temp_root).unwrap();
5387
5388 let config_path = temp_root.join("custom-config.toml");
5389
5390 let mut app = create_test_app();
5391 app.config_path = Some(config_path.clone());
5392 let result = config_command(
5393 &mut app,
5394 Some("base_url https://example.session.local/v1 --save"),
5395 );
5396 let msg = result.message.unwrap();
5397 let saved = fs::read_to_string(&config_path).unwrap();
5398
5399 assert_eq!(
5400 msg,
5401 format!(
5402 "base_url = https://example.session.local/v1 for deepseek (saved to {}; restart required)",
5403 config_path.display()
5404 )
5405 );
5406 let table: toml::Table = toml::from_str(&saved).unwrap();
5407 assert_eq!(
5408 table["providers"]["deepseek"]["base_url"].as_str(),
5409 Some("https://example.session.local/v1")
5410 );
5411 }
5412
5413 #[test]
5414 fn config_command_stream_chunk_timeout_session_query_uses_live_value() {
5415 let _lock = lock_test_env();
5416 let mut app = create_test_app();
5417
5418 let result = config_command(&mut app, Some("stream_chunk_timeout_secs 90"));
5419 assert!(!result.is_error);
5420 assert_eq!(app.stream_chunk_timeout_secs, 90);
5421 assert!(matches!(
5422 result.action,
5423 Some(AppAction::UpdateStreamChunkTimeout(90))
5424 ));
5425
5426 let query = config_command(&mut app, Some("stream_chunk_timeout_secs"));
5427 assert_eq!(
5428 query.message.as_deref(),
5429 Some("stream_chunk_timeout_secs = 90")
5430 );
5431 }
5432
5433 #[test]
5434 fn failed_save_leaves_live_config_state_untouched() {
5435 // C01-08: a `--save` that cannot write must not report failure over
5436 // live state that already moved.
5437 let temp = tempfile::tempdir().unwrap();
5438 let _guard = EnvGuard::new(temp.path());
5439 let blocker = temp.path().join("not-a-directory");
5440 fs::write(&blocker, "a file where the config directory should be").unwrap();
5441 let mut app = create_test_app();
5442 app.config_path = Some(blocker.join("config.toml"));
5443 let mcp_before = app.mcp_config_path.clone();
5444 app.mcp_reload_required = false;
5445 let timeout_before = app.stream_chunk_timeout_secs;
5446
5447 let result = set_config_value(&mut app, "mcp_config_path", "/elsewhere/mcp.json", true);
5448 assert!(result.is_error, "{:?}", result.message);
5449 assert_eq!(app.mcp_config_path, mcp_before);
5450 assert!(!app.mcp_reload_required);
5451
5452 let next_timeout = if timeout_before == 120 { "121" } else { "120" };
5453 let result = set_config_value(&mut app, "stream_chunk_timeout_secs", next_timeout, true);
5454 assert!(result.is_error, "{:?}", result.message);
5455 assert!(
5456 result.action.is_none(),
5457 "no engine update for an unsaved value"
5458 );
5459 assert_eq!(app.stream_chunk_timeout_secs, timeout_before);
5460 }
5461
5462 #[test]
5463 fn config_command_stream_chunk_timeout_save_overrides_canonical_value() {
5464 let nanos = SystemTime::now()
5465 .duration_since(UNIX_EPOCH)
5466 .unwrap()
5467 .as_nanos();
5468 let temp_root = env::temp_dir().join(format!(
5469 "codewhale-tui-stream-timeout-test-{}-{}",
5470 std::process::id(),
5471 nanos
5472 ));
5473 fs::create_dir_all(&temp_root).unwrap();
5474 let _guard = EnvGuard::new(&temp_root);
5475
5476 let config_path = temp_root.join("custom-config.toml");
5477 fs::write(
5478 &config_path,
5479 "[stream]\nchunk_timeout_secs=45\n[tui]\nstream_chunk_timeout_secs=30\n",
5480 )
5481 .unwrap();
5482 let mut app = create_test_app();
5483 app.config_path = Some(config_path.clone());
5484
5485 let result = config_command(&mut app, Some("stream_chunk_timeout_secs 120 --save"));
5486 let msg = result.message.unwrap();
5487 let saved = fs::read_to_string(&config_path).unwrap();
5488
5489 assert_eq!(
5490 msg,
5491 format!(
5492 "stream_chunk_timeout_secs = 120 (saved to {}; affects subsequent turns in this session)",
5493 config_path.display()
5494 )
5495 );
5496 let reopened: Config = toml::from_str(&saved).unwrap();
5497 assert_eq!(
5498 reopened.stream_chunk_timeout_secs(),
5499 120,
5500 "saved value must survive reopening when a canonical value already existed"
5501 );
5502 assert_eq!(
5503 reopened.tui.unwrap().stream_chunk_timeout_secs,
5504 Some(30),
5505 "legacy compatibility input is preserved"
5506 );
5507 assert_eq!(app.stream_chunk_timeout_secs, 120);
5508 assert!(matches!(
5509 result.action,
5510 Some(AppAction::UpdateStreamChunkTimeout(120))
5511 ));
5512 }
5513
5514 /// The bottom-chrome row presets (#5950) apply on the next frame and
5515 /// `--save` writes the `[tui]` key; an unknown preset names the three.
5516 #[test]
5517 fn config_command_row_presets_apply_live_and_persist_to_tui_table() {
5518 use codewhale_runtime::config::ChromeRowPreset;
5519 let nanos = SystemTime::now()
5520 .duration_since(UNIX_EPOCH)
5521 .unwrap()
5522 .as_nanos();
5523 let temp_root = env::temp_dir().join(format!(
5524 "codewhale-tui-row-presets-test-{}-{}",
5525 std::process::id(),
5526 nanos
5527 ));
5528 fs::create_dir_all(&temp_root).unwrap();
5529 let _guard = EnvGuard::new(&temp_root);
5530 let config_path = temp_root.join("custom-config.toml");
5531 let mut app = create_test_app();
5532 app.config_path = Some(config_path.clone());
5533 assert_eq!(app.posture_bar, ChromeRowPreset::Full);
5534 assert_eq!(app.metrics_line, ChromeRowPreset::Compact);
5535
5536 let live = config_command(&mut app, Some("posture_bar compact"));
5537 assert!(!live.is_error, "{live:?}");
5538 assert_eq!(app.posture_bar, ChromeRowPreset::Compact);
5539 assert_eq!(
5540 live.message.as_deref(),
5541 Some("posture_bar = compact (SESSION)")
5542 );
5543 assert_eq!(
5544 config_command(&mut app, Some("posture_bar"))
5545 .message
5546 .as_deref(),
5547 Some("posture_bar = compact")
5548 );
5549
5550 let saved = config_command(&mut app, Some("metrics_line HIDDEN --save"));
5551 assert!(!saved.is_error, "{saved:?}");
5552 assert_eq!(app.metrics_line, ChromeRowPreset::Hidden);
5553 let body = fs::read_to_string(&config_path).unwrap();
5554 assert!(body.contains("[tui]"), "{body}");
5555 assert!(body.contains("metrics_line = \"hidden\""), "{body}");
5556 assert!(
5557 !body.contains("posture_bar"),
5558 "session-only value must not be saved: {body}"
5559 );
5560
5561 let bad = config_command(&mut app, Some("metrics_line tiny"));
5562 assert!(bad.is_error);
5563 assert!(
5564 bad.message
5565 .as_deref()
5566 .is_some_and(|m| m.contains("metrics_line. Try: full, compact, hidden")),
5567 "{bad:?}"
5568 );
5569 assert_eq!(
5570 app.metrics_line,
5571 ChromeRowPreset::Hidden,
5572 "a bad value changes nothing"
5573 );
5574 }
5575
5576 #[test]
5577 fn row_preset_save_failure_preserves_live_state_and_uses_current_locale() {
5578 let temp = tempfile::tempdir().unwrap();
5579 let _guard = EnvGuard::new(temp.path());
5580 let path = temp.path().join("config.toml");
5581 // A directory in place of the file fails on every supported OS.
5582 fs::create_dir(&path).unwrap();
5583 let mut app = create_test_app();
5584 app.config_path = Some(path);
5585 app.ui_locale = codewhale_localization::Locale::ZhHans;
5586 let before = (app.posture_bar, app.metrics_line);
5587 for key in ["posture_bar", "metrics_line"] {
5588 let result = config_command(&mut app, Some(&format!("{key} hidden --save")));
5589 assert!(result.is_error, "{result:?}");
5590 assert!(result.message.unwrap().contains("未能保存"));
5591 assert_eq!((app.posture_bar, app.metrics_line), before);
5592 let invalid = config_command(&mut app, Some(&format!("{key} tiny")));
5593 assert!(invalid.is_error);
5594 assert_eq!(
5595 invalid.message,
5596 CommandResult::error(
5597 tr(app.ui_locale, MessageId::ConfigCommandInvalidValue)
5598 .replace("{key}", key)
5599 .replace("{value}", "tiny")
5600 .replace("{choices}", "full, compact, hidden")
5601 )
5602 .message
5603 );
5604 }
5605 // A session-only change needs no writable file and uses the new locale.
5606 let result = config_command(&mut app, Some("posture_bar compact"));
5607 assert!(!result.is_error);
5608 assert_eq!(
5609 result.message.as_deref(),
5610 Some("posture_bar = compact (会话)")
5611 );
5612 }
5613
5614 #[test]
5615 fn row_preset_saved_in_active_profile_reloads_without_resetting_other_rows() {
5616 use codewhale_runtime::config::ChromeRowPreset;
5617 let temp = tempfile::tempdir().unwrap();
5618 let _guard = EnvGuard::new(temp.path());
5619 let path = temp.path().join("selected.toml");
5620 for owns_tui in [false, true] {
5621 let mut body = "# Keep this comment\n[tui]\nposture_bar = \"full\"\nmetrics_line = \"hidden\"\n[profiles.\"work.team\"]\nmax_subagents = 4\n".to_string();
5622 if owns_tui {
5623 body.push_str("[profiles.\"work.team\".tui]\nposture_bar = \"hidden\"\nmetrics_line = \"compact\"\n");
5624 }
5625 fs::write(&path, body).unwrap();
5626 let config =
5627 codewhale_plugins::providers::load_config(Some(path.clone()), Some("work.team"))
5628 .unwrap();
5629 let mut app = create_test_app_with_config(&config);
5630 app.config_path = Some(path.clone());
5631 app.config_profile = Some("work.team".to_string());
5632 let metrics_before = app.metrics_line;
5633 let result = config_command(&mut app, Some("posture_bar compact --save"));
5634 assert!(!result.is_error, "{result:?}");
5635 assert_eq!(app.posture_bar, ChromeRowPreset::Compact);
5636 let reloaded =
5637 codewhale_plugins::providers::load_config(Some(path.clone()), Some("work.team"))
5638 .unwrap();
5639 let restarted = create_test_app_with_config(&reloaded);
5640 assert_eq!(restarted.posture_bar, app.posture_bar);
5641 assert_eq!(restarted.metrics_line, metrics_before);
5642 let saved = fs::read_to_string(&path).unwrap();
5643 assert!(saved.starts_with("# Keep this comment"));
5644 let document: toml::Value = toml::from_str(&saved).unwrap();
5645 assert_eq!(
5646 document["profiles"]["work.team"].get("tui").is_some(),
5647 owns_tui
5648 );
5649 if owns_tui {
5650 assert_eq!(document["tui"]["posture_bar"].as_str(), Some("full"));
5651 }
5652 }
5653 }
5654
5655 #[test]
5656 fn config_command_stream_chunk_timeout_rejects_invalid_input() {
5657 let _lock = lock_test_env();
5658 let mut app = create_test_app();
5659
5660 let text = config_command(&mut app, Some("stream_chunk_timeout_secs abc"));
5661 assert!(text.is_error);
5662 assert!(
5663 text.message
5664 .unwrap()
5665 .contains("stream_chunk_timeout_secs must be a whole number")
5666 );
5667
5668 let high = config_command(&mut app, Some("stream_chunk_timeout_secs 3601"));
5669 assert!(high.is_error);
5670 assert!(
5671 high.message
5672 .unwrap()
5673 .contains("stream_chunk_timeout_secs must be 0 or 1..=3600")
5674 );
5675 }
5676
5677 #[test]
5678 fn config_command_stream_chunk_timeout_zero_reports_effective_default() {
5679 let _lock = lock_test_env();
5680 let mut app = create_test_app();
5681
5682 let result = config_command(&mut app, Some("stream_chunk_timeout_secs 0"));
5683
5684 assert!(!result.is_error);
5685 assert_eq!(
5686 app.stream_chunk_timeout_secs,
5687 DEFAULT_STREAM_CHUNK_TIMEOUT_SECS
5688 );
5689 assert_eq!(
5690 result.message.as_deref(),
5691 Some(
5692 "stream_chunk_timeout_secs = 0 (default 900) (session only; affects subsequent turns in this session)"
5693 )
5694 );
5695 assert!(matches!(
5696 result.action,
5697 Some(AppAction::UpdateStreamChunkTimeout(
5698 DEFAULT_STREAM_CHUNK_TIMEOUT_SECS
5699 ))
5700 ));
5701 }
5702
5703 #[test]
5704 fn config_command_provider_url_token_plan_persists_provider_base_url() {
5705 let temp_root = env::temp_dir().join(format!(
5706 "codewhale-provider-url-save-app-path-test-{}",
5707 std::process::id()
5708 ));
5709 fs::create_dir_all(&temp_root).unwrap();
5710
5711 let config_path = temp_root.join("custom-config.toml");
5712
5713 let mut app = create_test_app();
5714 app.set_provider_identity_record(
5715 codewhale_runtime::config::Config::default()
5716 .resolve_provider_identity(ProviderKind::XiaomiMimo.as_str())
5717 .expect("captured fixture provider"),
5718 );
5719 app.config_path = Some(config_path.clone());
5720 let result = config_command(&mut app, Some("provider_url token-plan --save"));
5721 let msg = result.message.unwrap();
5722 let saved = fs::read_to_string(&config_path).unwrap();
5723
5724 assert_eq!(
5725 msg,
5726 format!(
5727 "provider_url = {} for xiaomi-mimo (saved to {}; restart required)",
5728 DEFAULT_XIAOMI_MIMO_BASE_URL,
5729 config_path.display()
5730 )
5731 );
5732 assert!(saved.contains("[providers.xiaomi_mimo]"));
5733 assert!(saved.contains(&format!("base_url = \"{DEFAULT_XIAOMI_MIMO_BASE_URL}\"")));
5734 }
5735
5736 #[test]
5737 fn config_command_provider_url_without_save_requires_save() {
5738 let _lock = lock_test_env();
5739 let mut app = create_test_app();
5740 app.api_provider = ProviderKind::XiaomiMimo;
5741 let result = config_command(&mut app, Some("provider_url token-plan"));
5742 assert!(result.is_error);
5743 let msg = result.message.unwrap();
5744
5745 assert!(
5746 msg.contains("provider_url must be saved with --save"),
5747 "got {msg}"
5748 );
5749 }
5750
5751 #[test]
5752 fn theme_command_accepts_grayscale_arg() {
5753 let nanos = SystemTime::now()
5754 .duration_since(UNIX_EPOCH)
5755 .unwrap()
5756 .as_nanos();
5757 let temp_root = env::temp_dir().join(format!(
5758 "codewhale-tui-theme-command-test-{}-{}",
5759 std::process::id(),
5760 nanos
5761 ));
5762 fs::create_dir_all(&temp_root).unwrap();
5763 let _guard = EnvGuard::new(&temp_root);
5764
5765 let mut app = create_test_app();
5766 let result = theme_command(&mut app, Some("grayscale"));
5767
5768 assert_eq!(result.message.unwrap(), "theme = grayscale (saved)");
5769 assert_eq!(app.theme_id, codewhale_palette::ThemeId::Grayscale);
5770 assert_eq!(app.ui_theme.mode, codewhale_palette::PaletteMode::Grayscale);
5771 assert!(app.needs_redraw);
5772 }
5773
5774 #[test]
5775 fn theme_command_underwater_alias_selects_the_underwater_theme() {
5776 let nanos = SystemTime::now()
5777 .duration_since(UNIX_EPOCH)
5778 .unwrap()
5779 .as_nanos();
5780 let temp_root = env::temp_dir().join(format!(
5781 "codewhale-tui-theme-underwater-test-{}-{}",
5782 std::process::id(),
5783 nanos
5784 ));
5785 fs::create_dir_all(&temp_root).unwrap();
5786 let _guard = EnvGuard::new(&temp_root);
5787
5788 let mut app = create_test_app();
5789 for alias in ["underwater", "Deepsea", "deep-sea", "ombre"] {
5790 let result = theme_command(&mut app, Some(alias));
5791 assert!(!result.is_error, "{alias}: {:?}", result.message);
5792 assert_eq!(
5793 result.message.as_deref(),
5794 Some("theme = underwater (saved)"),
5795 "{alias}"
5796 );
5797 assert_eq!(
5798 app.theme_id,
5799 codewhale_palette::ThemeId::Underwater,
5800 "{alias}"
5801 );
5802 assert_eq!(app.ui_theme.name, "underwater", "{alias}");
5803 assert!(
5804 crate::tui::ocean::OceanRamp::for_theme(&app.ui_theme).is_some(),
5805 "{alias}: the underwater theme owns the painted field"
5806 );
5807 }
5808 }
5809
5810 #[test]
5811 fn underwater_theme_selection_updates_live_state_and_persists_one_field() {
5812 let temp_root = env::temp_dir().join(format!(
5813 "codewhale-tui-underwater-selection-test-{}-{}",
5814 std::process::id(),
5815 SystemTime::now()
5816 .duration_since(UNIX_EPOCH)
5817 .expect("clock")
5818 .as_nanos()
5819 ));
5820 fs::create_dir_all(temp_root.join(".deepseek")).expect("settings dir");
5821 let _guard = EnvGuard::new(&temp_root);
5822 fs::write(
5823 temp_root.join(".deepseek").join("settings.toml"),
5824 "theme = \"light\"\nmax_input_history = 77\n",
5825 )
5826 .expect("seed settings");
5827
5828 let mut app = create_test_app();
5829 let result = set_config_value(&mut app, "theme", "underwater", true);
5830
5831 assert!(!result.is_error, "{:?}", result.message);
5832 assert_eq!(app.theme_id, codewhale_palette::ThemeId::Underwater);
5833 let persisted = Settings::load_persisted().expect("persisted selection");
5834 assert_eq!(persisted.theme, "underwater");
5835 assert_eq!(
5836 persisted.max_input_history, 77,
5837 "the theme save must not overwrite unrelated settings"
5838 );
5839 }
5840
5841 #[test]
5842 fn custom_theme_selection_keeps_the_raw_selector_in_live_app_state() {
5843 let temp_root = env::temp_dir().join(format!(
5844 "codewhale-tui-custom-theme-selection-test-{}-{}",
5845 std::process::id(),
5846 SystemTime::now()
5847 .duration_since(UNIX_EPOCH)
5848 .expect("clock")
5849 .as_nanos()
5850 ));
5851 let _guard = EnvGuard::new(&temp_root);
5852 let themes = temp_root.join(".codewhale").join("themes");
5853 fs::create_dir_all(&themes).expect("themes dir");
5854 fs::write(
5855 themes.join("midnight.json"),
5856 r##"{"schema_version":1,"base":"dark","colors":{"accent_primary":"#123456"}}"##,
5857 )
5858 .expect("theme overlay");
5859
5860 let mut app = create_test_app();
5861 let result = set_config_value(&mut app, "theme", "custom:midnight", false);
5862
5863 assert!(!result.is_error, "{:?}", result.message);
5864 assert_eq!(app.theme_name, "custom:midnight");
5865 assert_eq!(app.theme_id, codewhale_palette::ThemeId::Whale);
5866 assert_eq!(
5867 app.ui_theme.accent_primary,
5868 ratatui::style::Color::Rgb(0x12, 0x34, 0x56)
5869 );
5870 }
5871
5872 #[test]
5873 fn invalid_theme_name_changes_nothing() {
5874 let temp_root = env::temp_dir().join(format!(
5875 "codewhale-tui-theme-preflight-test-{}-{}",
5876 std::process::id(),
5877 SystemTime::now()
5878 .duration_since(UNIX_EPOCH)
5879 .expect("clock")
5880 .as_nanos()
5881 ));
5882 fs::create_dir_all(temp_root.join(".deepseek")).expect("settings dir");
5883 let _guard = EnvGuard::new(&temp_root);
5884 fs::write(
5885 temp_root.join(".deepseek").join("settings.toml"),
5886 "theme = \"light\"\n",
5887 )
5888 .expect("seed settings");
5889
5890 let mut app = create_test_app();
5891 let original_theme = app.theme_id;
5892 let result = set_config_value(&mut app, "theme", "kelp", true);
5893
5894 assert!(result.is_error);
5895 assert_eq!(app.theme_id, original_theme);
5896 let persisted = Settings::load_persisted().expect("unchanged persisted settings");
5897 assert_eq!(persisted.theme, "light");
5898 }
5899
5900 #[test]
5901 fn explicit_default_background_override_survives_theme_preview() {
5902 let temp_root =
5903 crate::test_support::test_scratch_dir("codewhale-tui-background-override-test");
5904 fs::create_dir_all(temp_root.join(".deepseek")).expect("settings dir");
5905 let _guard = EnvGuard::new(&temp_root);
5906 fs::write(
5907 temp_root.join(".deepseek").join("settings.toml"),
5908 "theme = \"solarized-light\"\nbackground_color = \"#fdf6e3\"\n",
5909 )
5910 .expect("seed settings");
5911
5912 let mut app = create_test_app();
5913 let explicit_base3 = ratatui::style::Color::Rgb(0xfd, 0xf6, 0xe3);
5914 assert_eq!(app.background_color_override, Some(explicit_base3));
5915
5916 let result = set_config_value(&mut app, "theme", "dark", false);
5917
5918 assert!(!result.is_error, "{:?}", result.message);
5919 assert_eq!(app.theme_id, codewhale_palette::ThemeId::Whale);
5920 assert_eq!(app.background_color_override, Some(explicit_base3));
5921 assert_eq!(app.ui_theme.surface_bg, explicit_base3);
5922 assert!(
5923 crate::tui::ocean::OceanRamp::for_theme(&app.ui_theme).is_none(),
5924 "only the underwater theme owns a painted field"
5925 );
5926 }
5927
5928 #[test]
5929 fn underwater_theme_keeps_its_field_under_a_background_override() {
5930 let temp_root = env::temp_dir().join(format!(
5931 "codewhale-tui-underwater-override-test-{}-{}",
5932 std::process::id(),
5933 SystemTime::now()
5934 .duration_since(UNIX_EPOCH)
5935 .expect("clock")
5936 .as_nanos()
5937 ));
5938 fs::create_dir_all(temp_root.join(".deepseek")).expect("settings dir");
5939 let _guard = EnvGuard::new(&temp_root);
5940
5941 let mut app = create_test_app();
5942 let custom = ratatui::style::Color::Rgb(0x1a, 0x1b, 0x26);
5943 let background = set_config_value(&mut app, "background_color", "#1a1b26", false);
5944 assert!(!background.is_error, "{:?}", background.message);
5945
5946 let preview = set_config_value(&mut app, "theme", "underwater", false);
5947 assert!(!preview.is_error, "{:?}", preview.message);
5948 assert_eq!(app.theme_id, codewhale_palette::ThemeId::Underwater);
5949 assert_eq!(app.background_color_override, Some(custom));
5950 assert_eq!(app.ui_theme.surface_bg, custom);
5951 assert!(
5952 crate::tui::ocean::OceanRamp::for_theme(&app.ui_theme).is_some(),
5953 "the underwater theme's field survives a background override"
5954 );
5955 }
5956
5957 #[test]
5958 fn session_only_background_override_survives_theme_preview() {
5959 let temp_root =
5960 crate::test_support::test_scratch_dir("codewhale-tui-session-background-test");
5961 fs::create_dir_all(temp_root.join(".deepseek")).expect("settings dir");
5962 let _guard = EnvGuard::new(&temp_root);
5963 fs::write(
5964 temp_root.join(".deepseek").join("settings.toml"),
5965 "theme = \"solarized-light\"\n",
5966 )
5967 .expect("seed settings");
5968
5969 let mut app = create_test_app();
5970 let custom = ratatui::style::Color::Rgb(0x1a, 0x1b, 0x26);
5971 let background = set_config_value(&mut app, "background_color", "#1a1b26", false);
5972 assert!(!background.is_error, "{:?}", background.message);
5973 assert_eq!(app.background_color_override, Some(custom));
5974
5975 let preview = set_config_value(&mut app, "theme", "dark", false);
5976 assert!(!preview.is_error, "{:?}", preview.message);
5977 assert_eq!(app.background_color_override, Some(custom));
5978 assert_eq!(app.ui_theme.surface_bg, custom);
5979
5980 let solarized_preview = set_config_value(&mut app, "theme", "solarized-light", false);
5981 assert!(
5982 !solarized_preview.is_error,
5983 "{:?}",
5984 solarized_preview.message
5985 );
5986 assert_eq!(app.background_color_override, Some(custom));
5987 assert_eq!(app.ui_theme.surface_bg, custom);
5988 assert!(crate::tui::ocean::OceanRamp::for_theme(&app.ui_theme).is_none());
5989
5990 let saved_theme = set_config_value(&mut app, "theme", "dark", true);
5991 assert!(!saved_theme.is_error, "{:?}", saved_theme.message);
5992 assert_eq!(app.background_color_override, Some(custom));
5993 assert_eq!(app.ui_theme.surface_bg, custom);
5994 let persisted = Settings::load_persisted().expect("persisted settings");
5995 assert_eq!(persisted.theme, "dark");
5996 assert_eq!(
5997 persisted.background_color, None,
5998 "saving a theme must not persist the session-only background"
5999 );
6000 }
6001
6002 #[test]
6003 fn set_theme_save_updates_live_app_and_persists() {
6004 let nanos = SystemTime::now()
6005 .duration_since(UNIX_EPOCH)
6006 .unwrap()
6007 .as_nanos();
6008 let temp_root = env::temp_dir().join(format!(
6009 "codewhale-tui-theme-save-test-{}-{}",
6010 std::process::id(),
6011 nanos
6012 ));
6013 fs::create_dir_all(&temp_root).unwrap();
6014 let _guard = EnvGuard::new(&temp_root);
6015
6016 let mut app = create_test_app();
6017 let result = config_command(&mut app, Some("theme grayscale --save"));
6018 let msg = result.message.unwrap();
6019
6020 assert_eq!(msg, "theme = grayscale (saved)");
6021 assert_eq!(app.ui_theme.mode, codewhale_palette::PaletteMode::Grayscale);
6022
6023 let settings_path = Settings::path().unwrap();
6024 let saved = fs::read_to_string(settings_path).unwrap();
6025 assert!(saved.contains("theme = \"grayscale\""));
6026 }
6027
6028 #[test]
6029 fn unrelated_save_does_not_persist_no_animations_runtime_overlay() {
6030 let temp_root = env::temp_dir().join(format!(
6031 "codewhale-no-animations-save-test-{}-{}",
6032 std::process::id(),
6033 SystemTime::now()
6034 .duration_since(UNIX_EPOCH)
6035 .expect("clock")
6036 .as_nanos()
6037 ));
6038 fs::create_dir_all(temp_root.join(".deepseek")).expect("settings dir");
6039 let _guard = EnvGuard::new(&temp_root);
6040 fs::write(
6041 temp_root.join(".deepseek").join("settings.toml"),
6042 "low_motion = false\nfancy_animations = true\ntheme = \"system\"\n",
6043 )
6044 .expect("seed settings");
6045 // Safety: test-only environment mutation is serialized by EnvGuard.
6046 unsafe {
6047 env::set_var("NO_ANIMATIONS", "1");
6048 }
6049
6050 let mut app = create_test_app();
6051 assert!(app.low_motion, "runtime overlay should reduce motion");
6052 assert!(
6053 !app.fancy_animations,
6054 "runtime overlay should disable ocean animations"
6055 );
6056
6057 let result = set_config_value(&mut app, "theme", "grayscale", true);
6058 assert!(!result.is_error, "{:?}", result.message);
6059 let saved = Settings::load_persisted().expect("persisted settings");
6060 assert_eq!(saved.theme, "grayscale");
6061 assert!(
6062 !saved.low_motion,
6063 "NO_ANIMATIONS must not become a saved preference"
6064 );
6065 assert!(
6066 saved.fancy_animations,
6067 "NO_ANIMATIONS must not overwrite the saved animation preference"
6068 );
6069 assert!(app.low_motion);
6070 assert!(!app.fancy_animations);
6071 }
6072
6073 #[test]
6074 fn preset_save_does_not_persist_runtime_environment_overlays() {
6075 let temp_root = env::temp_dir().join(format!(
6076 "codewhale-preset-env-overlay-test-{}-{}",
6077 std::process::id(),
6078 SystemTime::now()
6079 .duration_since(UNIX_EPOCH)
6080 .expect("clock")
6081 .as_nanos()
6082 ));
6083 fs::create_dir_all(temp_root.join(".deepseek")).expect("settings dir");
6084 let _guard = EnvGuard::new(&temp_root);
6085 fs::write(
6086 temp_root.join(".deepseek").join("settings.toml"),
6087 "low_motion = false\nfancy_animations = true\nsynchronized_output = \"auto\"\n",
6088 )
6089 .expect("seed settings");
6090 // NO_ANIMATIONS exercises the reported path. Ptyxis supplies an
6091 // unrelated effective-only field, making an accidental
6092 // apply_env_overrides()+save observable even though the calm preset
6093 // intentionally selects reduced motion itself.
6094 unsafe {
6095 env::set_var("NO_ANIMATIONS", "1");
6096 env::set_var("PTYXIS_VERSION", "50.0");
6097 }
6098
6099 let mut app = create_test_app();
6100 let result = config_command(&mut app, Some("preset calm --save"));
6101 assert!(!result.is_error, "{:?}", result.message);
6102
6103 let saved = Settings::load_persisted().expect("persisted settings");
6104 assert!(saved.low_motion, "calm preset should save reduced motion");
6105 assert!(
6106 !saved.fancy_animations,
6107 "calm preset should save static ocean chrome"
6108 );
6109 assert_eq!(
6110 saved.synchronized_output, "auto",
6111 "Ptyxis runtime override must not leak into a preset save"
6112 );
6113 }
6114
6115 #[test]
6116 fn config_approval_mode_valid_values() {
6117 let dir = tempfile::tempdir().expect("isolated config dir");
6118 let mut app = create_test_app();
6119 app.config_path = Some(dir.path().join("config.toml"));
6120 // Test auto
6121 let result = config_command(&mut app, Some("approval_mode auto"));
6122 assert!(result.message.is_some());
6123 assert_eq!(app.approval_mode, ApprovalMode::Auto);
6124
6125 // Test suggest
6126 let result = config_command(&mut app, Some("approval_mode suggest"));
6127 assert!(result.message.is_some());
6128 assert_eq!(app.approval_mode, ApprovalMode::Suggest);
6129
6130 // Test never
6131 let result = config_command(&mut app, Some("approval_mode never"));
6132 assert!(result.message.is_some());
6133 assert_eq!(app.approval_mode, ApprovalMode::Never);
6134 }
6135
6136 #[test]
6137 fn config_key_and_value_split_on_any_whitespace() {
6138 let dir = tempfile::tempdir().expect("isolated config dir");
6139 let mut app = create_test_app();
6140 app.config_path = Some(dir.path().join("config.toml"));
6141 let result = config_command(&mut app, Some("approval_mode\tauto"));
6142 assert!(!result.is_error, "{:?}", result.message);
6143 assert_eq!(app.approval_mode, ApprovalMode::Auto);
6144 let result = config_command(&mut app, Some("approval_mode\u{3000}never"));
6145 assert!(!result.is_error, "{:?}", result.message);
6146 assert_eq!(app.approval_mode, ApprovalMode::Never);
6147 }
6148
6149 #[test]
6150 fn config_approval_mode_save_persists_top_level_policy() {
6151 let temp_root = env::temp_dir().join(format!(
6152 "codewhale-approval-policy-save-test-{}",
6153 std::process::id()
6154 ));
6155 fs::create_dir_all(&temp_root).unwrap();
6156 let _guard = EnvGuard::new(&temp_root);
6157 let config_path = temp_root.join("custom-config.toml");
6158
6159 let mut app = create_test_app();
6160 app.config_path = Some(config_path.clone());
6161 let result = config_command(&mut app, Some("approval_mode suggest --save"));
6162 let msg = result.message.unwrap();
6163 let saved = fs::read_to_string(&config_path).unwrap();
6164
6165 assert!(!result.is_error);
6166 assert_eq!(app.approval_mode, ApprovalMode::Suggest);
6167 assert_eq!(
6168 msg,
6169 format!(
6170 "approval_mode = Ask (saved to {} as approval_policy = \"on-request\")",
6171 config_path.display()
6172 )
6173 );
6174 assert!(saved.contains("approval_policy = \"on-request\""));
6175
6176 let loaded =
6177 codewhale_plugins::providers::load_config(Some(config_path.clone()), None).unwrap();
6178 assert_eq!(loaded.approval_policy.as_deref(), Some("on-request"));
6179
6180 let mut restarted = create_test_app_with_config(&loaded);
6181 restarted.config_path = Some(config_path.clone());
6182 assert!(restarted.approval_policy_locked());
6183 assert!(!restarted.approval_policy_requirements_managed());
6184 let changed = config_command(&mut restarted, Some("approval_mode auto --save"));
6185 assert!(!changed.is_error, "{:?}", changed.message);
6186 assert_eq!(
6187 changed.action,
6188 Some(AppAction::ApprovalPolicyPersisted {
6189 policy: Some("auto".to_string())
6190 })
6191 );
6192 assert_eq!(restarted.approval_mode, ApprovalMode::Auto);
6193 let reloaded = codewhale_plugins::providers::load_config(Some(config_path), None).unwrap();
6194 assert_eq!(reloaded.approval_policy.as_deref(), Some("auto"));
6195 }
6196
6197 #[test]
6198 fn config_approval_policy_can_return_to_saved_tui_permission_default() {
6199 let temp_root = env::temp_dir().join(format!(
6200 "codewhale-approval-policy-tui-default-test-{}",
6201 std::process::id()
6202 ));
6203 fs::create_dir_all(temp_root.join(".deepseek")).unwrap();
6204 let _guard = EnvGuard::new(&temp_root);
6205 let config_path = temp_root.join("custom-config.toml");
6206 fs::write(&config_path, "# keep\napproval_policy = \"auto\"\n").unwrap();
6207 fs::write(
6208 temp_root.join(".deepseek").join("settings.toml"),
6209 "permission_posture = \"full-access\"\n",
6210 )
6211 .unwrap();
6212 let loaded =
6213 codewhale_plugins::providers::load_config(Some(config_path.clone()), None).unwrap();
6214 let mut app = create_test_app_with_config(&loaded);
6215 app.config_path = Some(config_path.clone());
6216
6217 let result = set_config_value(&mut app, "approval_policy", "use-tui-default", true);
6218
6219 assert!(!result.is_error, "{:?}", result.message);
6220 assert_eq!(app.approval_mode, ApprovalMode::Bypass);
6221 assert!(!app.approval_policy_locked());
6222 assert_eq!(
6223 result.action,
6224 Some(AppAction::ApprovalPolicyPersisted { policy: None })
6225 );
6226 let saved = fs::read_to_string(config_path).unwrap();
6227 assert!(saved.contains("# keep"));
6228 assert!(!saved.contains("approval_policy"));
6229 }
6230
6231 #[test]
6232 fn config_approval_policy_full_access_adopts_tui_posture_and_releases_root_override() {
6233 let temp_root = env::temp_dir().join(format!(
6234 "codewhale-approval-policy-full-access-test-{}",
6235 std::process::id()
6236 ));
6237 fs::create_dir_all(temp_root.join(".deepseek")).unwrap();
6238 let _guard = EnvGuard::new(&temp_root);
6239 let config_path = temp_root.join("custom-config.toml");
6240 fs::write(&config_path, "# keep\napproval_policy = \"on-request\"\n").unwrap();
6241 fs::write(
6242 temp_root.join(".deepseek").join("settings.toml"),
6243 "permission_posture = \"ask\"\n",
6244 )
6245 .unwrap();
6246 let loaded =
6247 codewhale_plugins::providers::load_config(Some(config_path.clone()), None).unwrap();
6248 let mut app = create_test_app_with_config(&loaded);
6249 app.config_path = Some(config_path.clone());
6250 // The production constructor receives the path up front and marks a
6251 // user-owned root policy editable. This focused fixture attaches the
6252 // path after construction, so mirror that resolved ownership here.
6253 app.mark_approval_policy_locked();
6254 assert!(app.approval_policy_locked());
6255
6256 let result = set_config_value(&mut app, "approval_policy", "full-access", true);
6257
6258 assert!(!result.is_error, "{:?}", result.message);
6259 assert_eq!(app.approval_mode, ApprovalMode::Bypass);
6260 assert!(!app.approval_policy_locked());
6261 assert_eq!(
6262 result.action,
6263 Some(AppAction::ApprovalPolicyPersisted { policy: None })
6264 );
6265 let saved_config = fs::read_to_string(config_path).unwrap();
6266 assert!(saved_config.contains("# keep"));
6267 assert!(!saved_config.contains("approval_policy"));
6268 let saved_settings = Settings::load_persisted().expect("saved TUI settings");
6269 assert_eq!(
6270 saved_settings.permission_posture.as_deref(),
6271 Some("full-access")
6272 );
6273 }
6274
6275 #[test]
6276 fn config_approval_mode_invalid_value() {
6277 let dir = tempfile::tempdir().expect("isolated config dir");
6278 let mut app = create_test_app();
6279 app.config_path = Some(dir.path().join("config.toml"));
6280 let result = config_command(&mut app, Some("approval_mode invalid"));
6281 assert!(result.message.is_some());
6282 let msg = result.message.unwrap();
6283 assert!(msg.contains("Invalid approval_mode"));
6284 }
6285
6286 #[test]
6287 fn config_without_save_flag() {
6288 let _lock = lock_test_env();
6289 let mut app = create_test_app();
6290 let result = config_command(&mut app, Some("auto_compact true"));
6291 assert!(result.message.is_some());
6292 let msg = result.message.unwrap();
6293 assert!(msg.contains("(session only"));
6294 }
6295
6296 #[test]
6297 fn config_threshold_enables_and_updates_live_auto_compaction() {
6298 let _lock = lock_test_env();
6299 let mut app = create_test_app();
6300 app.auto_compact = false;
6301 app.auto_compact_user_configured = false;
6302
6303 let result = config_command(&mut app, Some("auto_compact_threshold_percent 65"));
6304
6305 assert!(!result.is_error, "{:?}", result.message);
6306 assert!(app.auto_compact);
6307 assert!(app.auto_compact_user_configured);
6308 assert_eq!(app.auto_compact_threshold_percent, 65.0);
6309 assert_eq!(
6310 app.compact_threshold,
6311 codewhale_engine::route_budget::compaction_threshold_for_route_at_percent(
6312 app.api_provider,
6313 app.effective_model_for_budget(),
6314 app.active_route_limits,
6315 65.0,
6316 )
6317 );
6318 assert!(matches!(
6319 result.action,
6320 Some(AppAction::UpdateCompaction(_))
6321 ));
6322 }
6323
6324 #[test]
6325 fn config_composer_border_updates_live_app() {
6326 let _lock = lock_test_env();
6327 let mut app = create_test_app();
6328 app.composer_border = true;
6329
6330 let result = config_command(&mut app, Some("composer_border false"));
6331
6332 assert!(result.message.is_some());
6333 assert!(!app.composer_border);
6334 assert!(app.needs_redraw);
6335 }
6336
6337 #[test]
6338 fn config_composer_multiline_mode_updates_live_app() {
6339 let _lock = lock_test_env();
6340 let mut app = create_test_app();
6341 app.composer_multiline_mode = false;
6342
6343 let result = config_command(&mut app, Some("composer_multiline_mode true"));
6344
6345 assert!(!result.is_error, "{:?}", result.message);
6346 assert!(app.composer_multiline_mode);
6347 assert!(app.needs_redraw);
6348 }
6349
6350 /// `/trust on` and `/trust off` printed nothing (0.10.1 tutorial, lesson
6351 /// 3). Each change now has a line that says what it did and how to undo
6352 /// it, and only `--save` claims anything was saved.
6353 #[test]
6354 fn trust_change_note_says_what_changed() {
6355 let on = trust_change_note(true, false);
6356 assert!(on.starts_with("Trust mode is on for this session"), "{on}");
6357 assert!(on.contains("/trust off"), "{on}");
6358 let off = trust_change_note(false, false);
6359 assert!(
6360 off.starts_with("Trust mode is off for this session"),
6361 "{off}"
6362 );
6363 for note in [&on, &off] {
6364 assert!(!note.contains("Saved"), "{note}");
6365 }
6366 let saved_on = trust_change_note(true, true);
6367 assert!(
6368 saved_on.starts_with(&on) && saved_on.contains("are trusted in later sessions"),
6369 "{saved_on}"
6370 );
6371 let saved_off = trust_change_note(false, true);
6372 assert!(
6373 saved_off.starts_with(&off) && saved_off.contains("are no longer trusted"),
6374 "{saved_off}"
6375 );
6376 }
6377
6378 #[tokio::test]
6379 async fn trust_only_persists_with_save() {
6380 let tmp = tempfile::tempdir().unwrap();
6381 let _guard = EnvGuard::new(tmp.path());
6382 let config_path = tmp.path().join("config.toml");
6383 let _config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", &config_path);
6384 let workspace = tmp.path().join("workspace");
6385 let commands = workspace.join(".claude/commands");
6386 let skills = workspace.join(".claude/skills/review-example");
6387 fs::create_dir_all(&commands).unwrap();
6388 fs::create_dir_all(&skills).unwrap();
6389 fs::write(commands.join("review-example.md"), "Review the example").unwrap();
6390 fs::write(
6391 skills.join("SKILL.md"),
6392 "---\nname: review-example\ndescription: Review the example\n---\nRead the example.",
6393 )
6394 .unwrap();
6395 let mut app = create_test_app();
6396 app.workspace = workspace.clone();
6397 app.trust_mode = false;
6398 for trusted in [false, true, false] {
6399 if trusted || app.trust_mode {
6400 let result = trust_command(
6401 &mut app,
6402 Some(if trusted { "on --save" } else { "off --save" }),
6403 );
6404 assert_eq!(
6405 result.action,
6406 Some(AppAction::SetWorkspaceTrust {
6407 trusted,
6408 save: true
6409 })
6410 );
6411 set_workspace_trust(&mut app, trusted, true).await.unwrap();
6412 }
6413 let saved = fs::read(&config_path).ok();
6414 for session_trusted in [true, false] {
6415 let result =
6416 trust_command(&mut app, Some(if session_trusted { "on" } else { "off" }));
6417 assert_eq!(
6418 result.action,
6419 Some(AppAction::SetWorkspaceTrust {
6420 trusted: session_trusted,
6421 save: false
6422 })
6423 );
6424 set_workspace_trust(&mut app, session_trusted, false)
6425 .await
6426 .unwrap();
6427 assert_eq!(app.trust_mode, session_trusted);
6428 assert_eq!(
6429 fs::read(&config_path).ok(),
6430 saved,
6431 "session toggle must not write config"
6432 );
6433 assert_eq!(
6434 codewhale_runtime::config::is_workspace_trusted(&workspace),
6435 trusted
6436 );
6437 }
6438 app.trust_mode = trusted;
6439 assert!(trust_command(&mut app, Some("on --typo")).is_error);
6440 assert_eq!(
6441 codewhale_runtime::config::is_workspace_trusted(&workspace),
6442 trusted
6443 );
6444 crate::commands::user_registry::with_registry_for_workspace(
6445 Some(&workspace),
6446 |registry| {
6447 assert_eq!(registry.get("review-example").is_some(), trusted);
6448 },
6449 );
6450 assert_eq!(
6451 codewhale_skills::discover_in_workspace(&workspace)
6452 .get("review-example")
6453 .is_some(),
6454 trusted
6455 );
6456 }
6457 // A failed write must not grant trust in memory.
6458 fs::create_dir_all(tmp.path().join("bad-config")).unwrap();
6459 let _bad_config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", tmp.path().join("bad-config"));
6460 assert!(set_workspace_trust(&mut app, true, true).await.is_err());
6461 assert!(!app.trust_mode);
6462 app.trust_mode = true;
6463 assert!(set_workspace_trust(&mut app, false, true).await.is_err());
6464 assert!(!app.trust_mode);
6465 }
6466
6467 #[test]
6468 fn test_trust_status_default_lists_state() {
6469 let mut app = create_test_app();
6470 let result = trust_command(&mut app, None);
6471 let msg = result.message.expect("status message");
6472 assert!(msg.contains("Workspace trust mode"));
6473 }
6474
6475 #[test]
6476 fn test_trust_add_requires_path() {
6477 let mut app = create_test_app();
6478 let result = trust_command(&mut app, Some("add"));
6479 let msg = result.message.expect("error message");
6480 assert!(msg.starts_with("Error:"), "got {msg:?}");
6481 }
6482
6483 #[test]
6484 fn test_logout_starts_account_logout_without_clearing_api_key_state() {
6485 let temp_root = crate::test_support::test_scratch_dir("codewhale-tui-logout-test");
6486 fs::create_dir_all(&temp_root).unwrap();
6487 let _guard = EnvGuard::new(&temp_root);
6488
6489 let config_path = temp_root.join(".deepseek").join("config.toml");
6490 fs::create_dir_all(config_path.parent().unwrap()).unwrap();
6491 fs::write(&config_path, "api_key = \"test-key\"\n").unwrap();
6492
6493 let mut app = create_test_app();
6494 app.onboarding = OnboardingState::None;
6495 app.onboarding_needs_api_key = false;
6496 app.onboarding_missing_key_recovery = false;
6497 let result = logout_command(&mut app);
6498 assert!(!result.is_error);
6499 assert!(result.message.is_none());
6500 assert_eq!(app.onboarding, OnboardingState::None);
6501 assert!(!app.onboarding_needs_api_key);
6502 assert!(!app.onboarding_missing_key_recovery);
6503 assert_eq!(result.action, Some(AppAction::StartAccountLogout));
6504
6505 let updated = fs::read_to_string(config_path).unwrap();
6506 assert_eq!(updated, "api_key = \"test-key\"\n");
6507 }
6508
6509 #[test]
6510 fn logout_preserves_named_custom_provider_keys() {
6511 let temp_root = crate::test_support::test_scratch_dir("codewhale-custom-logout-test");
6512 fs::create_dir_all(&temp_root).unwrap();
6513 let _guard = EnvGuard::new(&temp_root);
6514 let config_path = temp_root.join(".deepseek").join("config.toml");
6515 fs::create_dir_all(config_path.parent().unwrap()).unwrap();
6516 fs::write(
6517 &config_path,
6518 "[providers.custom-a]\napi_key = \"a-key\"\n\n[providers.custom-b]\napi_key = \"b-key\"\n",
6519 )
6520 .unwrap();
6521 let mut app = create_test_app();
6522 app.set_provider_identity(ProviderKind::Custom, "custom-a");
6523
6524 let result = logout_command(&mut app);
6525
6526 assert!(!result.is_error);
6527 assert!(result.message.is_none());
6528 assert_eq!(result.action, Some(AppAction::StartAccountLogout));
6529 assert_eq!(app.provider_identity_for_persistence(), "custom-a");
6530 let updated = fs::read_to_string(config_path).unwrap();
6531 assert_eq!(
6532 updated,
6533 "[providers.custom-a]\napi_key = \"a-key\"\n\n[providers.custom-b]\napi_key = \"b-key\"\n"
6534 );
6535 }
6536
6537 #[test]
6538 fn named_custom_provider_url_write_fails_closed() {
6539 let mut app = create_test_app();
6540 app.set_provider_identity(ProviderKind::Custom, "custom-a");
6541
6542 let result = config_command(
6543 &mut app,
6544 Some("provider_url http://127.0.0.1:18181/v1 --save"),
6545 );
6546 let message = result.message.expect("error message");
6547
6548 assert!(result.is_error);
6549 assert!(result.action.is_none());
6550 assert!(
6551 message.contains("[providers.custom-a]") && message.contains("missing"),
6552 "{message}"
6553 );
6554 }
6555
6556 #[test]
6557 fn config_command_auto_review_reviewer_model_gets_sets_unsets_and_rejects_invalid() {
6558 let nanos = SystemTime::now()
6559 .duration_since(UNIX_EPOCH)
6560 .unwrap()
6561 .as_nanos();
6562 let temp_root = env::temp_dir().join(format!(
6563 "codewhale-ar-reviewer-model-test-{}-{}",
6564 std::process::id(),
6565 nanos
6566 ));
6567 fs::create_dir_all(&temp_root).unwrap();
6568 let _guard = EnvGuard::new(&temp_root);
6569 let config_path = temp_root.join(".codewhale").join("config.toml");
6570 fs::create_dir_all(config_path.parent().unwrap()).unwrap();
6571 fs::write(&config_path, "").unwrap();
6572
6573 let mut app = create_test_app();
6574 app.config_path = Some(config_path.clone());
6575
6576 let initial = config_command(&mut app, Some("auto_review.reviewer_model"));
6577 assert!(!initial.is_error);
6578 assert!(
6579 initial
6580 .message
6581 .as_deref()
6582 .unwrap_or_default()
6583 .contains("auto (default)")
6584 );
6585
6586 let set_saved = config_command(
6587 &mut app,
6588 Some("auto_review.reviewer_model claude-sonnet-5-5 --save"),
6589 );
6590 assert!(!set_saved.is_error, "{:?}", set_saved.message);
6591 assert_eq!(
6592 set_saved.action,
6593 Some(AppAction::SetAutoReviewReviewerModel {
6594 reviewer_model: Some("claude-sonnet-5-5".to_string())
6595 })
6596 );
6597 let saved_toml = fs::read_to_string(&config_path).unwrap();
6598 assert!(
6599 saved_toml.contains("reviewer_model = \"claude-sonnet-5-5\""),
6600 "{saved_toml}"
6601 );
6602 app.auto_review_reviewer_model = Some("claude-sonnet-5-5".to_string());
6603
6604 let invalid = config_command(&mut app, Some("auto_review.reviewer_model bad model"));
6605 assert!(invalid.is_error);
6606 assert!(invalid.action.is_none());
6607
6608 let reset_saved =
6609 config_command(&mut app, Some("auto_review.reviewer_model default --save"));
6610 assert!(!reset_saved.is_error, "{:?}", reset_saved.message);
6611 assert_eq!(
6612 reset_saved.action,
6613 Some(AppAction::SetAutoReviewReviewerModel {
6614 reviewer_model: None
6615 })
6616 );
6617 let after_unset = fs::read_to_string(&config_path).unwrap();
6618 assert!(!after_unset.contains("reviewer_model"), "{after_unset}");
6619 }
6620 }
6621
6621 lines RUST