| 1 | use crate::tui::app::AppAction; |
| 2 | use crate::tui::views::ModalKind; |
| 3 | use codewhale_config::ProviderKind; |
| 4 | use codewhale_engine::reasoning_preference::ReasoningEffort; |
| 5 | |
| 6 | use super::CommandResult; |
| 7 | |
| 8 | #[cfg(test)] |
| 9 | mod tests { |
| 10 | use super::*; |
| 11 | fn model(app: &mut App, arg: Option<&str>) -> CommandResult { |
| 12 | crate::commands::execute(&format!("/model {}", arg.unwrap_or_default()), app) |
| 13 | } |
| 14 | use crate::tui::app::{App, TuiOptions, TurnCacheRecord}; |
| 15 | use crate::tui::history::HistoryCell; |
| 16 | use codewhale_engine::client::PromptInspection; |
| 17 | use codewhale_localization::Locale; |
| 18 | use codewhale_models::Message; |
| 19 | use codewhale_models::Role; |
| 20 | use codewhale_runtime::config::Config; |
| 21 | use std::ffi::OsString; |
| 22 | use std::path::PathBuf; |
| 23 | use std::time::Instant; |
| 24 | use tempfile::TempDir; |
| 25 | |
| 26 | struct SettingsPathGuard { |
| 27 | _tmp: TempDir, |
| 28 | previous: Option<OsString>, |
| 29 | _lock: crate::test_support::TestEnvLock, |
| 30 | } |
| 31 | |
| 32 | impl SettingsPathGuard { |
| 33 | fn new() -> Self { |
| 34 | let lock = crate::test_support::lock_test_env(); |
| 35 | let tmp = TempDir::new().expect("settings tempdir"); |
| 36 | let config_path = tmp.path().join(".deepseek").join("config.toml"); |
| 37 | std::fs::create_dir_all(config_path.parent().expect("config parent")) |
| 38 | .expect("config dir"); |
| 39 | let previous = std::env::var_os("DEEPSEEK_CONFIG_PATH"); |
| 40 | // Safety: test-only environment mutation guarded by a global mutex. |
| 41 | unsafe { |
| 42 | std::env::set_var("DEEPSEEK_CONFIG_PATH", &config_path); |
| 43 | } |
| 44 | Self { |
| 45 | _tmp: tmp, |
| 46 | previous, |
| 47 | _lock: lock, |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | impl Drop for SettingsPathGuard { |
| 53 | fn drop(&mut self) { |
| 54 | // Safety: test-only environment mutation guarded by a global mutex. |
| 55 | unsafe { |
| 56 | if let Some(previous) = self.previous.take() { |
| 57 | std::env::set_var("DEEPSEEK_CONFIG_PATH", previous); |
| 58 | } else { |
| 59 | std::env::remove_var("DEEPSEEK_CONFIG_PATH"); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | fn create_test_app() -> App { |
| 66 | let options = TuiOptions { |
| 67 | skills_dir: PathBuf::from("/tmp/test-skills"), |
| 68 | ..crate::tui::test_support::test_tui_options(PathBuf::from("/tmp/test-workspace")) |
| 69 | }; |
| 70 | let mut app = App::new(options, &Config::default()); |
| 71 | app.ui_locale = codewhale_localization::Locale::En; |
| 72 | app.api_provider = codewhale_config::ProviderKind::Deepseek; |
| 73 | app.model = "deepseek-v4-pro".to_string(); |
| 74 | app.auto_model = false; |
| 75 | app.model_ids_passthrough = false; |
| 76 | app |
| 77 | } |
| 78 | |
| 79 | #[test] |
| 80 | fn profile_command_localizes_replies_and_preserves_switch_action() { |
| 81 | let _env = crate::test_support::lock_test_env(); |
| 82 | for (locale, usage, switching) in [ |
| 83 | ( |
| 84 | Locale::En, |
| 85 | "Usage: /profile <name>", |
| 86 | "Switching to profile 'work'...", |
| 87 | ), |
| 88 | ( |
| 89 | Locale::ZhHans, |
| 90 | "用法:/profile <name>", |
| 91 | "正在切换到配置文件 'work'...", |
| 92 | ), |
| 93 | ( |
| 94 | Locale::De, |
| 95 | "Verwendung: /profile <name>", |
| 96 | "Wechsle zum Profil 'work'...", |
| 97 | ), |
| 98 | ] { |
| 99 | let mut app = create_test_app(); |
| 100 | app.ui_locale = locale; |
| 101 | let previous_profile = app.config_profile.clone(); |
| 102 | |
| 103 | for command in ["/profile", "/profile "] { |
| 104 | let result = crate::commands::execute(command, &mut app); |
| 105 | assert!(result.is_error, "{locale:?}: {command:?}"); |
| 106 | assert!(result.action.is_none(), "{locale:?}: {command:?}"); |
| 107 | let message = result.message.expect("profile usage"); |
| 108 | assert!(message.contains(usage), "{locale:?}: {message}"); |
| 109 | assert!(message.contains("~/.codewhale/config.toml"), "{message}"); |
| 110 | assert!(message.contains("[profiles]"), "{message}"); |
| 111 | } |
| 112 | |
| 113 | let result = crate::commands::execute("/profile work ", &mut app); |
| 114 | assert!(!result.is_error, "{locale:?}"); |
| 115 | assert_eq!(result.message.as_deref(), Some(switching), "{locale:?}"); |
| 116 | assert!(matches!( |
| 117 | result.action, |
| 118 | Some(AppAction::SwitchProfile { profile }) if profile == "work" |
| 119 | )); |
| 120 | assert_eq!(app.config_profile, previous_profile, "{locale:?}"); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | #[test] |
| 125 | fn effort_alias_rejects_unknown_input_without_committing_an_effort() { |
| 126 | let mut app = create_test_app(); |
| 127 | let before = app.reasoning_effort; |
| 128 | let invalid = crate::commands::execute("/thinking imaginary-tier", &mut app); |
| 129 | assert!(invalid.is_error); |
| 130 | assert!(invalid.message.unwrap().contains("Usage: /effort")); |
| 131 | assert_eq!(app.reasoning_effort, before); |
| 132 | let receipt = crate::commands::execute("/effort high", &mut app); |
| 133 | assert!(!receipt.is_error); |
| 134 | assert_eq!(receipt.message.as_deref(), Some("Effort set to high")); |
| 135 | assert_eq!(app.reasoning_effort, ReasoningEffort::High); |
| 136 | } |
| 137 | |
| 138 | #[test] |
| 139 | fn effort_reports_work_receipt_failure_and_preserves_effort() { |
| 140 | let _home = crate::test_support::SealedHome::new(); |
| 141 | let mut app = create_test_app(); |
| 142 | app.runtime_services.work = Some(codewhale_engine::work_graph::new_shared_work_runtime( |
| 143 | app.todos.clone(), |
| 144 | app.plan_state.clone(), |
| 145 | )); |
| 146 | let before = app.reasoning_effort; |
| 147 | assert_ne!(before, ReasoningEffort::High); |
| 148 | |
| 149 | let previous_preference = app.reasoning_effort_preference; |
| 150 | let todos = app.todos.clone(); |
| 151 | let todo_guard = todos.try_lock().expect("lock todos"); |
| 152 | let named_failed = crate::commands::execute("/effort high", &mut app); |
| 153 | assert!(named_failed.is_error); |
| 154 | assert!( |
| 155 | named_failed |
| 156 | .message |
| 157 | .as_deref() |
| 158 | .is_some_and(|msg| msg.contains("Work receipt failed")), |
| 159 | "{:?}", |
| 160 | named_failed.message |
| 161 | ); |
| 162 | assert_eq!(app.reasoning_effort, before); |
| 163 | |
| 164 | let cycle_failed = crate::commands::execute("/thinking", &mut app); |
| 165 | assert!(cycle_failed.is_error); |
| 166 | assert!( |
| 167 | cycle_failed |
| 168 | .message |
| 169 | .as_deref() |
| 170 | .is_some_and(|msg| msg.contains("Work receipt failed")), |
| 171 | "{:?}", |
| 172 | cycle_failed.message |
| 173 | ); |
| 174 | assert_eq!(app.reasoning_effort, before); |
| 175 | assert_eq!(app.reasoning_effort_preference, previous_preference); |
| 176 | drop(todo_guard); |
| 177 | |
| 178 | let named_ok = crate::commands::execute("/effort high", &mut app); |
| 179 | assert!(!named_ok.is_error); |
| 180 | assert_eq!(named_ok.message.as_deref(), Some("Effort set to high")); |
| 181 | assert_eq!(app.reasoning_effort, ReasoningEffort::High); |
| 182 | |
| 183 | let cycle_ok = crate::commands::execute("/effort", &mut app); |
| 184 | assert!(!cycle_ok.is_error); |
| 185 | assert!( |
| 186 | cycle_ok |
| 187 | .message |
| 188 | .as_deref() |
| 189 | .is_some_and(|msg| msg.starts_with("Effort: high → ")), |
| 190 | "{:?}", |
| 191 | cycle_ok.message |
| 192 | ); |
| 193 | assert_ne!(app.reasoning_effort, ReasoningEffort::High); |
| 194 | } |
| 195 | |
| 196 | #[test] |
| 197 | fn test_clear_resets_all_state() { |
| 198 | let mut app = create_test_app(); |
| 199 | // Set up some state |
| 200 | app.history.push(HistoryCell::User { |
| 201 | content: "test".to_string(), |
| 202 | }); |
| 203 | app.api_messages_mut().push(Message { |
| 204 | role: Role::User, |
| 205 | content: vec![], |
| 206 | }); |
| 207 | app.session.total_conversation_tokens = 100; |
| 208 | app.tool_log.push("test".to_string()); |
| 209 | app.current_session_id = Some("existing-session".to_string()); |
| 210 | app.session_artifacts |
| 211 | .push(codewhale_runtime::artifacts::ArtifactRecord { |
| 212 | id: "art_call_big".to_string(), |
| 213 | kind: codewhale_runtime::artifacts::ArtifactKind::ToolOutput, |
| 214 | session_id: "existing-session".to_string(), |
| 215 | tool_call_id: "call-big".to_string(), |
| 216 | tool_name: "exec_shell".to_string(), |
| 217 | created_at: chrono::Utc::now(), |
| 218 | byte_size: 128, |
| 219 | preview: "tool output".to_string(), |
| 220 | storage_path: PathBuf::from("/tmp/tool_outputs/call-big.txt"), |
| 221 | }); |
| 222 | |
| 223 | let result = crate::commands::execute("/clear", &mut app); |
| 224 | assert!(result.message.is_some()); |
| 225 | assert!(app.history.is_empty()); |
| 226 | assert!(app.api_messages.is_empty()); |
| 227 | assert_eq!(app.session.total_conversation_tokens, 0); |
| 228 | assert!(app.tool_log.is_empty()); |
| 229 | assert!(app.tool_cells.is_empty()); |
| 230 | assert!(app.tool_details_by_cell.is_empty()); |
| 231 | assert!(app.session_artifacts.is_empty()); |
| 232 | // The App mints the next session id itself so the engine and every |
| 233 | // checkpoint/autosave share one id (no orphaned checkpoint). |
| 234 | let next_id = app |
| 235 | .current_session_id |
| 236 | .clone() |
| 237 | .expect("/clear claims the next session id"); |
| 238 | assert_ne!(next_id, "existing-session"); |
| 239 | assert!(app.session_write_receipt.is_some()); |
| 240 | assert!(app.session_write_owner.is_some()); |
| 241 | assert_eq!( |
| 242 | app.offline_queue_lease.as_ref().unwrap().session_id(), |
| 243 | next_id |
| 244 | ); |
| 245 | assert!(uuid::Uuid::parse_str(&next_id).is_ok(), "{next_id}"); |
| 246 | match result.action { |
| 247 | Some(AppAction::SyncSession { |
| 248 | session_id, |
| 249 | messages, |
| 250 | .. |
| 251 | }) => { |
| 252 | assert_eq!(session_id.as_deref(), Some(next_id.as_str())); |
| 253 | assert!(messages.is_empty()); |
| 254 | } |
| 255 | other => panic!("expected SyncSession, got {other:?}"), |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn clear_is_all_or_nothing_when_work_state_is_busy() { |
| 261 | let mut app = create_test_app(); |
| 262 | app.history.push(HistoryCell::User { |
| 263 | content: "keep me".to_string(), |
| 264 | }); |
| 265 | app.api_messages_mut().push(Message { |
| 266 | role: Role::User, |
| 267 | content: vec![], |
| 268 | }); |
| 269 | app.current_session_id = Some("current-session".to_string()); |
| 270 | let plan_state = app.plan_state.clone(); |
| 271 | let _held = plan_state.try_lock().expect("hold plan lock"); |
| 272 | |
| 273 | let result = crate::commands::execute("/clear", &mut app); |
| 274 | |
| 275 | assert!(result.is_error); |
| 276 | assert!(result.action.is_none()); |
| 277 | assert_eq!(app.history.len(), 1); |
| 278 | assert_eq!(app.api_messages.len(), 1); |
| 279 | assert_eq!(app.current_session_id.as_deref(), Some("current-session")); |
| 280 | assert!(result.message.as_deref().is_some_and(|message| { |
| 281 | message.contains("Nothing cleared") && message.contains("busy") |
| 282 | })); |
| 283 | } |
| 284 | |
| 285 | #[test] |
| 286 | fn clear_rejects_an_active_turn_without_mutating_session_state() { |
| 287 | let mut app = create_test_app(); |
| 288 | app.history.push(HistoryCell::User { |
| 289 | content: "keep active turn".to_string(), |
| 290 | }); |
| 291 | app.api_messages_mut().push(Message { |
| 292 | role: Role::User, |
| 293 | content: vec![], |
| 294 | }); |
| 295 | app.current_session_id = Some("active-session".to_string()); |
| 296 | app.is_loading = true; |
| 297 | app.runtime_turn_status = Some("in_progress".to_string()); |
| 298 | |
| 299 | let result = crate::commands::execute("/clear", &mut app); |
| 300 | |
| 301 | assert!(result.is_error); |
| 302 | assert!(result.action.is_none()); |
| 303 | assert_eq!(app.history.len(), 1); |
| 304 | assert_eq!(app.api_messages.len(), 1); |
| 305 | assert_eq!(app.current_session_id.as_deref(), Some("active-session")); |
| 306 | } |
| 307 | |
| 308 | #[test] |
| 309 | fn clear_resets_session_telemetry() { |
| 310 | let mut app = create_test_app(); |
| 311 | app.session.total_tokens = 234; |
| 312 | app.session.total_conversation_tokens = 123; |
| 313 | app.session.session_cost = 0.42; |
| 314 | app.session.session_cost_cny = 3.05; |
| 315 | app.session.subagent_cost = 0.11; |
| 316 | app.session.subagent_cost_cny = 0.80; |
| 317 | app.session.subagent_usage_sources.insert( |
| 318 | codewhale_engine::cost_status::usage_source_fingerprint("response-test"), |
| 319 | ); |
| 320 | app.session.displayed_cost_high_water = 0.53; |
| 321 | app.session.displayed_cost_high_water_cny = 3.85; |
| 322 | app.session.last_prompt_cache_hit_tokens = Some(70); |
| 323 | app.session.last_prompt_cache_miss_tokens = Some(30); |
| 324 | app.session.last_reasoning_replay_tokens = Some(12); |
| 325 | app.session.total_cache_write_tokens = 99; |
| 326 | app.session.last_warmup_key = None; |
| 327 | app.session.last_tool_catalog = Some(Vec::new()); |
| 328 | app.session.last_base_url = Some("https://api.deepseek.com".to_string()); |
| 329 | app.session.last_cache_inspection = Some(PromptInspection { |
| 330 | base_static_prefix_hash: "base".to_string(), |
| 331 | full_request_prefix_hash: "full".to_string(), |
| 332 | tool_catalog_hash: String::new(), |
| 333 | layers: Vec::new(), |
| 334 | }); |
| 335 | app.push_turn_cache_record(TurnCacheRecord { |
| 336 | provider: None, |
| 337 | provider_identity: None, |
| 338 | model: None, |
| 339 | auto_model: false, |
| 340 | input_tokens: 100, |
| 341 | output_tokens: 25, |
| 342 | cache_hit_tokens: Some(70), |
| 343 | cache_miss_tokens: Some(30), |
| 344 | reasoning_replay_tokens: Some(12), |
| 345 | cache_write_tokens: None, |
| 346 | reasoning_tokens: None, |
| 347 | cost_audit: None, |
| 348 | recorded_at: Instant::now(), |
| 349 | }); |
| 350 | |
| 351 | crate::commands::execute("/clear", &mut app); |
| 352 | |
| 353 | assert_eq!(app.session.total_tokens, 0); |
| 354 | assert_eq!(app.session.total_conversation_tokens, 0); |
| 355 | assert_eq!(app.session.session_cost, 0.0); |
| 356 | assert_eq!(app.session.session_cost_cny, 0.0); |
| 357 | assert_eq!(app.session.subagent_cost, 0.0); |
| 358 | assert_eq!(app.session.subagent_cost_cny, 0.0); |
| 359 | assert!(app.session.subagent_usage_sources.is_empty()); |
| 360 | assert_eq!(app.session.displayed_cost_high_water, 0.0); |
| 361 | assert_eq!(app.session.displayed_cost_high_water_cny, 0.0); |
| 362 | assert_eq!(app.session.last_prompt_cache_hit_tokens, None); |
| 363 | assert_eq!(app.session.last_prompt_cache_miss_tokens, None); |
| 364 | assert_eq!(app.session.last_reasoning_replay_tokens, None); |
| 365 | assert_eq!(app.session.total_cache_write_tokens, 0); |
| 366 | assert!(app.session.turn_cache_history.is_empty()); |
| 367 | assert_eq!(app.session.last_cache_inspection, None); |
| 368 | assert_eq!(app.session.last_warmup_key, None); |
| 369 | assert_eq!(app.session.last_tool_catalog, None); |
| 370 | assert_eq!(app.session.last_base_url, None); |
| 371 | } |
| 372 | |
| 373 | #[test] |
| 374 | fn test_exit_returns_quit_action() { |
| 375 | let result = crate::commands::execute("/exit", &mut create_test_app()); |
| 376 | assert!(result.message.is_none()); |
| 377 | assert!(matches!(result.action, Some(AppAction::Quit))); |
| 378 | } |
| 379 | |
| 380 | #[test] |
| 381 | fn test_model_change_updates_state() { |
| 382 | let _settings = SettingsPathGuard::new(); |
| 383 | let mut app = create_test_app(); |
| 384 | let old_model = app.model.clone(); |
| 385 | let result = model(&mut app, Some("deepseek-v4-flash")); |
| 386 | assert!(result.message.is_some()); |
| 387 | let msg = result.message.unwrap(); |
| 388 | assert!(msg.contains(&old_model)); |
| 389 | assert!(msg.contains("deepseek-v4-flash")); |
| 390 | assert!(matches!( |
| 391 | result.action, |
| 392 | Some(AppAction::UpdateCompaction(_)) |
| 393 | )); |
| 394 | assert_eq!(app.model, "deepseek-v4-flash"); |
| 395 | assert_eq!(app.session.last_prompt_tokens, None); |
| 396 | assert_eq!(app.session.last_completion_tokens, None); |
| 397 | } |
| 398 | |
| 399 | #[test] |
| 400 | fn model_command_preserves_active_kimi_code_endpoint_for_bare_k3() { |
| 401 | let _settings = SettingsPathGuard::new(); |
| 402 | let mut app = create_test_app(); |
| 403 | app.set_provider_identity(codewhale_config::ProviderKind::Moonshot, "moonshot"); |
| 404 | app.model_ids_passthrough = true; |
| 405 | app.active_route_base_url = |
| 406 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL.to_string(); |
| 407 | app.active_context_window_override = None; |
| 408 | |
| 409 | let result = model( |
| 410 | &mut app, |
| 411 | Some(codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL), |
| 412 | ); |
| 413 | |
| 414 | assert!( |
| 415 | !result.is_error, |
| 416 | "Kimi Code K3 route should resolve: {result:?}" |
| 417 | ); |
| 418 | assert_eq!( |
| 419 | app.model, |
| 420 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL |
| 421 | ); |
| 422 | assert_eq!( |
| 423 | app.active_route_limits |
| 424 | .and_then(|limits| limits.context_tokens), |
| 425 | Some(u64::from( |
| 426 | codewhale_models::KIMI_CODE_K3_CONTEXT_WINDOW_TOKENS |
| 427 | )) |
| 428 | ); |
| 429 | |
| 430 | // Switching to the direct platform endpoint requires the direct model |
| 431 | // id (`kimi-k3`); bare `k3` is fail-closed (#4687). |
| 432 | app.active_route_base_url = |
| 433 | codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL.to_string(); |
| 434 | let rejected = model( |
| 435 | &mut app, |
| 436 | Some(codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL), |
| 437 | ); |
| 438 | assert!( |
| 439 | rejected.is_error, |
| 440 | "bare k3 on direct Moonshot must fail closed: {rejected:?}" |
| 441 | ); |
| 442 | |
| 443 | let direct = model( |
| 444 | &mut app, |
| 445 | Some(codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL), |
| 446 | ); |
| 447 | assert!( |
| 448 | !direct.is_error, |
| 449 | "direct Moonshot kimi-k3 remains valid: {direct:?}" |
| 450 | ); |
| 451 | assert_ne!( |
| 452 | app.active_route_limits |
| 453 | .and_then(|limits| limits.context_tokens), |
| 454 | Some(u64::from( |
| 455 | codewhale_models::KIMI_CODE_K3_CONTEXT_WINDOW_TOKENS |
| 456 | )) |
| 457 | ); |
| 458 | } |
| 459 | |
| 460 | #[test] |
| 461 | fn model_command_is_session_local_until_explicitly_saved() { |
| 462 | let _settings = SettingsPathGuard::new(); |
| 463 | let mut app = create_test_app(); |
| 464 | |
| 465 | let result = model(&mut app, Some("deepseek-v4-flash")); |
| 466 | |
| 467 | assert!(result.message.is_some()); |
| 468 | assert_eq!( |
| 469 | app.provider_models.get("deepseek").map(String::as_str), |
| 470 | Some("deepseek-v4-flash") |
| 471 | ); |
| 472 | // The live session changed and the save decision is pending — the |
| 473 | // route-save prompt owns persistence now. |
| 474 | let pending = app.pending_route_save.as_ref().expect("pending save"); |
| 475 | assert_eq!(pending.provider_identity, "deepseek"); |
| 476 | assert_eq!(pending.model, "deepseek-v4-flash"); |
| 477 | |
| 478 | // NOTHING was written to settings: no scoped model, no default |
| 479 | // provider, no default model. The message says the change is |
| 480 | // session-only. |
| 481 | let settings = codewhale_runtime::settings::Settings::load().expect("load settings"); |
| 482 | assert_eq!( |
| 483 | settings |
| 484 | .provider_models |
| 485 | .as_ref() |
| 486 | .and_then(|models| models.get("deepseek")), |
| 487 | None |
| 488 | ); |
| 489 | assert_eq!(settings.default_provider.as_deref(), None); |
| 490 | assert_eq!(settings.default_model.as_deref(), None); |
| 491 | assert!( |
| 492 | result |
| 493 | .message |
| 494 | .as_deref() |
| 495 | .unwrap_or_default() |
| 496 | .contains("session only"), |
| 497 | "the receipt must say the change is temporary: {:?}", |
| 498 | result.message |
| 499 | ); |
| 500 | } |
| 501 | |
| 502 | #[test] |
| 503 | fn model_command_does_not_mutate_shared_default_provider() { |
| 504 | // Regression for #3227, strengthened: a `/model` change must not drag |
| 505 | // the global `default_provider` onto it AND must not write the scoped |
| 506 | // model either — the change is session-local until the user explicitly |
| 507 | // saves it via the route-save prompt. |
| 508 | let _settings = SettingsPathGuard::new(); |
| 509 | let startup_config = |
| 510 | codewhale_runtime::config::home_config_path().expect("isolated startup config"); |
| 511 | let startup_before = std::fs::read(&startup_config).ok(); |
| 512 | { |
| 513 | let seed = { |
| 514 | let __cw_config_init_0_0 = Some("deepseek".to_string()); |
| 515 | let mut __cw_config_init_0_value: codewhale_runtime::settings::Settings = |
| 516 | Default::default(); |
| 517 | __cw_config_init_0_value.default_provider = __cw_config_init_0_0; |
| 518 | __cw_config_init_0_value |
| 519 | }; |
| 520 | seed.save().expect("seed settings"); |
| 521 | } |
| 522 | let mut app = create_test_app(); |
| 523 | app.set_provider_identity_record( |
| 524 | codewhale_runtime::config::Config::default() |
| 525 | .resolve_provider_identity(codewhale_config::ProviderKind::Zai.as_str()) |
| 526 | .expect("captured fixture provider"), |
| 527 | ); |
| 528 | app.model_ids_passthrough = false; |
| 529 | app.model = codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL.to_string(); |
| 530 | app.auto_model = false; |
| 531 | |
| 532 | let result = model(&mut app, Some("GLM-5.2")); |
| 533 | assert!(result.message.is_some(), "expected a model-changed message"); |
| 534 | assert!(!result.is_error, "GLM-5.2 is valid on Z.ai"); |
| 535 | |
| 536 | let settings = codewhale_runtime::settings::Settings::load().expect("load settings"); |
| 537 | // Neither canonical startup config nor the legacy archive changes. |
| 538 | assert_eq!(std::fs::read(startup_config).ok(), startup_before); |
| 539 | assert_eq!(settings.default_provider.as_deref(), Some("deepseek")); |
| 540 | // No scoped entry was written either — session-local. |
| 541 | assert_eq!( |
| 542 | settings |
| 543 | .provider_models |
| 544 | .as_ref() |
| 545 | .and_then(|models| models.get("zai")), |
| 546 | None |
| 547 | ); |
| 548 | // The in-memory route changed and the decision is pending. |
| 549 | assert_eq!(app.model, "GLM-5.2"); |
| 550 | let pending = app.pending_route_save.as_ref().expect("pending save"); |
| 551 | assert_eq!(pending.provider_identity, "zai"); |
| 552 | } |
| 553 | |
| 554 | #[test] |
| 555 | fn model_command_keeps_glm_53_as_its_own_wire_id() { |
| 556 | let _settings = SettingsPathGuard::new(); |
| 557 | let mut app = create_test_app(); |
| 558 | app.set_provider_identity_record( |
| 559 | codewhale_runtime::config::Config::default() |
| 560 | .resolve_provider_identity(codewhale_config::ProviderKind::Zai.as_str()) |
| 561 | .expect("captured fixture provider"), |
| 562 | ); |
| 563 | app.model_ids_passthrough = false; |
| 564 | app.model = codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL.to_string(); |
| 565 | app.auto_model = false; |
| 566 | |
| 567 | let result = model(&mut app, Some("glm-5.3")); |
| 568 | |
| 569 | assert!(!result.is_error, "GLM-5.3 is valid on Z.ai: {result:?}"); |
| 570 | assert_eq!( |
| 571 | app.model, |
| 572 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_MODEL |
| 573 | ); |
| 574 | assert_eq!( |
| 575 | app.provider_models.get("zai").map(String::as_str), |
| 576 | Some(codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_MODEL) |
| 577 | ); |
| 578 | assert_eq!( |
| 579 | app.pending_route_save |
| 580 | .as_ref() |
| 581 | .map(|pending| pending.model.as_str()), |
| 582 | Some(codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_MODEL) |
| 583 | ); |
| 584 | } |
| 585 | |
| 586 | #[test] |
| 587 | fn two_sessions_keep_independent_provider_model_routes() { |
| 588 | // #3227: two App instances sharing one settings/config path. A is on |
| 589 | // Z.ai/GLM; B switches to DeepSeek and picks a DeepSeek model. B must |
| 590 | // build a DeepSeek route (not Z.ai + a DeepSeek model), A must stay on |
| 591 | // Z.ai/GLM, and neither session's `/model` may flip the shared global |
| 592 | // default provider out from under the other. |
| 593 | let _settings = SettingsPathGuard::new(); |
| 594 | |
| 595 | // Terminal A: Z.ai / GLM. |
| 596 | let mut app_a = create_test_app(); |
| 597 | app_a.api_provider = codewhale_config::ProviderKind::Zai; |
| 598 | app_a.model_ids_passthrough = false; |
| 599 | app_a.model = codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL.to_string(); |
| 600 | app_a.auto_model = false; |
| 601 | let result_a = model(&mut app_a, Some("GLM-5.2")); |
| 602 | assert!(!result_a.is_error, "GLM-5.2 is valid on Z.ai"); |
| 603 | assert_eq!(app_a.api_provider, codewhale_config::ProviderKind::Zai); |
| 604 | assert_eq!(app_a.model, "GLM-5.2"); |
| 605 | |
| 606 | // Terminal B: DeepSeek / deepseek-v4-flash. |
| 607 | let mut app_b = create_test_app(); |
| 608 | app_b.api_provider = codewhale_config::ProviderKind::Deepseek; |
| 609 | app_b.model_ids_passthrough = false; |
| 610 | app_b.model = "deepseek-v4-pro".to_string(); |
| 611 | app_b.auto_model = false; |
| 612 | let result_b = model(&mut app_b, Some("deepseek-v4-flash")); |
| 613 | assert!(!result_b.is_error, "deepseek-v4-flash is valid on DeepSeek"); |
| 614 | |
| 615 | // B's route is a coherent DeepSeek route — never Z.ai + a DeepSeek model. |
| 616 | assert_eq!(app_b.api_provider, codewhale_config::ProviderKind::Deepseek); |
| 617 | assert_eq!(app_b.model, "deepseek-v4-flash"); |
| 618 | |
| 619 | // A is untouched by B's selection — still Z.ai / GLM. |
| 620 | assert_eq!(app_a.api_provider, codewhale_config::ProviderKind::Zai); |
| 621 | assert_eq!(app_a.model, "GLM-5.2"); |
| 622 | |
| 623 | // Shared settings: NOTHING was written by either `/model` — both |
| 624 | // changes are session-local with a pending save decision, and the |
| 625 | // global default provider was never flipped. |
| 626 | let settings = codewhale_runtime::settings::Settings::load().expect("load settings"); |
| 627 | assert_eq!(settings.default_provider.as_deref(), None); |
| 628 | assert_eq!(settings.provider_models, None); |
| 629 | // Both sessions carry their own pending save decisions. |
| 630 | assert_eq!( |
| 631 | app_a.pending_route_save.as_ref().map(|p| p.model.as_str()), |
| 632 | Some("GLM-5.2") |
| 633 | ); |
| 634 | assert_eq!( |
| 635 | app_b.pending_route_save.as_ref().map(|p| p.model.as_str()), |
| 636 | Some("deepseek-v4-flash") |
| 637 | ); |
| 638 | } |
| 639 | |
| 640 | #[test] |
| 641 | fn model_command_rejects_model_foreign_to_active_provider() { |
| 642 | // #3227: a DeepSeek model id requested while the session is on Z.ai is |
| 643 | // rejected locally with a precise diagnostic, before any network call. |
| 644 | let _settings = SettingsPathGuard::new(); |
| 645 | let mut app = create_test_app(); |
| 646 | app.api_provider = codewhale_config::ProviderKind::Zai; |
| 647 | app.model_ids_passthrough = false; |
| 648 | app.model = codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL.to_string(); |
| 649 | app.auto_model = false; |
| 650 | app.provider_models.clear(); |
| 651 | |
| 652 | let result = model(&mut app, Some("deepseek-v4-pro")); |
| 653 | |
| 654 | assert!(result.is_error, "expected a local rejection"); |
| 655 | let msg = result.message.expect("error message"); |
| 656 | assert!(msg.contains("deepseek-v4-pro"), "names the model: {msg}"); |
| 657 | assert!(msg.contains("zai"), "names the provider: {msg}"); |
| 658 | // The session route is unchanged — still Z.ai / GLM. |
| 659 | assert_eq!(app.api_provider, codewhale_config::ProviderKind::Zai); |
| 660 | assert_eq!( |
| 661 | app.model, |
| 662 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL |
| 663 | ); |
| 664 | } |
| 665 | |
| 666 | #[test] |
| 667 | fn model_switch_clears_turn_cache_history() { |
| 668 | let _settings = SettingsPathGuard::new(); |
| 669 | let mut app = create_test_app(); |
| 670 | // Keep the assertion independent of the developer's saved default model. |
| 671 | app.auto_model = false; |
| 672 | app.model = "deepseek-v4-pro".to_string(); |
| 673 | app.push_turn_cache_record(TurnCacheRecord { |
| 674 | provider: None, |
| 675 | provider_identity: None, |
| 676 | model: None, |
| 677 | auto_model: false, |
| 678 | input_tokens: 100, |
| 679 | output_tokens: 25, |
| 680 | cache_hit_tokens: Some(70), |
| 681 | cache_miss_tokens: Some(30), |
| 682 | reasoning_replay_tokens: Some(12), |
| 683 | cache_write_tokens: None, |
| 684 | reasoning_tokens: None, |
| 685 | cost_audit: None, |
| 686 | recorded_at: Instant::now(), |
| 687 | }); |
| 688 | |
| 689 | let result = model(&mut app, Some("deepseek-v4-flash")); |
| 690 | |
| 691 | assert!(result.message.is_some()); |
| 692 | assert!(app.session.turn_cache_history.is_empty()); |
| 693 | } |
| 694 | |
| 695 | #[test] |
| 696 | fn model_reset_same_model_keeps_turn_cache_history() { |
| 697 | let _settings = SettingsPathGuard::new(); |
| 698 | let mut app = create_test_app(); |
| 699 | app.auto_model = false; |
| 700 | app.model = "deepseek-v4-pro".to_string(); |
| 701 | app.push_turn_cache_record(TurnCacheRecord { |
| 702 | provider: None, |
| 703 | provider_identity: None, |
| 704 | model: None, |
| 705 | auto_model: false, |
| 706 | input_tokens: 100, |
| 707 | output_tokens: 25, |
| 708 | cache_hit_tokens: Some(70), |
| 709 | cache_miss_tokens: Some(30), |
| 710 | reasoning_replay_tokens: Some(12), |
| 711 | cache_write_tokens: None, |
| 712 | reasoning_tokens: None, |
| 713 | cost_audit: None, |
| 714 | recorded_at: Instant::now(), |
| 715 | }); |
| 716 | |
| 717 | let result = model(&mut app, Some("deepseek-v4-pro")); |
| 718 | |
| 719 | assert!(result.message.is_some()); |
| 720 | assert_eq!(app.session.turn_cache_history.len(), 1); |
| 721 | } |
| 722 | |
| 723 | #[test] |
| 724 | fn test_model_auto_enables_auto_thinking() { |
| 725 | let _settings = SettingsPathGuard::new(); |
| 726 | let mut app = create_test_app(); |
| 727 | app.reasoning_effort = ReasoningEffort::Off; |
| 728 | app.reasoning_effort_preference = None; |
| 729 | |
| 730 | let result = model(&mut app, Some("auto")); |
| 731 | |
| 732 | assert!(result.message.is_some()); |
| 733 | assert!(app.auto_model); |
| 734 | assert_eq!(app.model, "auto"); |
| 735 | assert_eq!(app.reasoning_effort, ReasoningEffort::Auto); |
| 736 | assert!(app.last_effective_model.is_none()); |
| 737 | assert!(app.last_effective_reasoning_effort.is_none()); |
| 738 | } |
| 739 | |
| 740 | #[test] |
| 741 | fn test_model_auto_preserves_raw_explicit_thinking() { |
| 742 | let _settings = SettingsPathGuard::new(); |
| 743 | let mut app = create_test_app(); |
| 744 | app.api_provider = ProviderKind::OpenaiCodex; |
| 745 | app.auto_model = false; |
| 746 | app.reasoning_effort = ReasoningEffort::Low; |
| 747 | app.reasoning_effort_preference = Some(ReasoningEffort::Off); |
| 748 | |
| 749 | let result = model(&mut app, Some("auto")); |
| 750 | |
| 751 | assert!(result.message.is_some()); |
| 752 | assert!(app.auto_model); |
| 753 | assert_eq!(app.model, "auto"); |
| 754 | assert_eq!(app.reasoning_effort, ReasoningEffort::Off); |
| 755 | assert_eq!(app.reasoning_effort_preference, Some(ReasoningEffort::Off)); |
| 756 | } |
| 757 | |
| 758 | #[test] |
| 759 | fn test_model_change_accepts_future_deepseek_model() { |
| 760 | let _settings = SettingsPathGuard::new(); |
| 761 | let mut app = create_test_app(); |
| 762 | let result = model(&mut app, Some("deepseek-v4")); |
| 763 | assert!(result.message.is_some()); |
| 764 | let msg = result.message.unwrap(); |
| 765 | assert!(msg.contains("deepseek-v4")); |
| 766 | assert_eq!(app.model, "deepseek-v4"); |
| 767 | assert!(matches!( |
| 768 | result.action, |
| 769 | Some(AppAction::UpdateCompaction(_)) |
| 770 | )); |
| 771 | } |
| 772 | |
| 773 | #[test] |
| 774 | fn test_model_change_accepts_custom_id_for_openai_compatible_provider() { |
| 775 | let _settings = SettingsPathGuard::new(); |
| 776 | let mut app = create_test_app(); |
| 777 | app.api_provider = codewhale_config::ProviderKind::Openai; |
| 778 | app.model_ids_passthrough = true; |
| 779 | |
| 780 | let result = model(&mut app, Some("opencode-go/glm-5.1")); |
| 781 | |
| 782 | assert!(result.message.is_some()); |
| 783 | assert_eq!(app.model, "opencode-go/glm-5.1"); |
| 784 | assert!(!app.auto_model); |
| 785 | assert!(matches!( |
| 786 | result.action, |
| 787 | Some(AppAction::UpdateCompaction(_)) |
| 788 | )); |
| 789 | } |
| 790 | |
| 791 | #[test] |
| 792 | fn test_model_change_accepts_custom_id_for_custom_base_url() { |
| 793 | let _settings = SettingsPathGuard::new(); |
| 794 | let mut app = create_test_app(); |
| 795 | app.model_ids_passthrough = true; |
| 796 | |
| 797 | let result = model(&mut app, Some("opencode-go/kimi-k2.6")); |
| 798 | |
| 799 | assert!(result.message.is_some()); |
| 800 | assert_eq!(app.model, "opencode-go/kimi-k2.6"); |
| 801 | assert!(matches!( |
| 802 | result.action, |
| 803 | Some(AppAction::UpdateCompaction(_)) |
| 804 | )); |
| 805 | } |
| 806 | |
| 807 | #[test] |
| 808 | fn test_model_change_rejects_invalid_model() { |
| 809 | let mut app = create_test_app(); |
| 810 | let result = model(&mut app, Some("gpt-4")); |
| 811 | assert!(result.message.is_some()); |
| 812 | let msg = result.message.unwrap(); |
| 813 | assert!(msg.contains("Invalid model")); |
| 814 | assert!(msg.contains("active provider")); |
| 815 | assert!(msg.contains("deepseek")); |
| 816 | assert!(!msg.contains("Common DeepSeek models")); |
| 817 | assert!(result.action.is_none()); |
| 818 | } |
| 819 | |
| 820 | #[test] |
| 821 | fn model_command_rejects_saved_model_from_other_provider() { |
| 822 | let mut app = create_test_app(); |
| 823 | app.api_provider = codewhale_config::ProviderKind::Deepseek; |
| 824 | app.provider_models |
| 825 | .insert("moonshot".to_string(), "kimi-k2.6".to_string()); |
| 826 | |
| 827 | let result = model(&mut app, Some("kimi-k2.6")); |
| 828 | |
| 829 | let message = result.message.expect("invalid model message"); |
| 830 | assert!(message.contains("Invalid model")); |
| 831 | assert!(message.contains("active provider")); |
| 832 | assert!(result.action.is_none()); |
| 833 | assert_eq!(app.api_provider, codewhale_config::ProviderKind::Deepseek); |
| 834 | assert_eq!(app.model, "deepseek-v4-pro"); |
| 835 | } |
| 836 | |
| 837 | #[test] |
| 838 | fn test_model_without_args_opens_picker() { |
| 839 | let mut app = create_test_app(); |
| 840 | let result = model(&mut app, None); |
| 841 | assert_eq!(result.message, None); |
| 842 | assert_eq!(result.action, Some(AppAction::OpenModelPicker)); |
| 843 | } |
| 844 | |
| 845 | #[test] |
| 846 | fn test_models_triggers_fetch_action() { |
| 847 | let mut app = create_test_app(); |
| 848 | let result = crate::commands::execute("/models", &mut app); |
| 849 | assert!(result.message.is_none()); |
| 850 | assert!(matches!(result.action, Some(AppAction::FetchModels))); |
| 851 | } |
| 852 | |
| 853 | #[test] |
| 854 | fn model_refresh_dispatches_models_dev_catalog_action() { |
| 855 | let mut app = create_test_app(); |
| 856 | let result = model(&mut app, Some("refresh")); |
| 857 | assert!(result.message.is_none()); |
| 858 | assert!(matches!( |
| 859 | result.action, |
| 860 | Some(AppAction::RefreshModelsDevCatalog) |
| 861 | )); |
| 862 | } |
| 863 | |
| 864 | #[test] |
| 865 | fn test_subagents_pushes_view_and_sets_status() { |
| 866 | let mut app = create_test_app(); |
| 867 | let result = crate::commands::execute("/subagents", &mut app); |
| 868 | assert!(result.message.is_none()); |
| 869 | assert!(matches!(result.action, Some(AppAction::ListSubAgents))); |
| 870 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::SubAgents)); |
| 871 | assert_eq!( |
| 872 | app.visible_notice_text(), |
| 873 | Some("Finding this session's agents...".to_string()) |
| 874 | ); |
| 875 | } |
| 876 | |
| 877 | #[test] |
| 878 | fn provider_link_metadata_marks_custom_routes_as_configuration_owned() { |
| 879 | let links = |
| 880 | codewhale_config::provider::provider_for_kind(codewhale_config::ProviderKind::Custom) |
| 881 | .credential_help(); |
| 882 | |
| 883 | assert_eq!( |
| 884 | links.acquisition, |
| 885 | codewhale_config::provider::CredentialAcquisition::Configuration |
| 886 | ); |
| 887 | assert_eq!(links.docs_url, None); |
| 888 | assert_eq!(links.credential_url, None); |
| 889 | } |
| 890 | } |
| 891 |