| 1 | use super::*; |
| 2 | |
| 3 | use crate::test_support::EnvVarGuard; |
| 4 | |
| 5 | use crate::test_support::env_scope_ticket; |
| 6 | |
| 7 | use crate::test_support::join_env_scope; |
| 8 | |
| 9 | use crate::test_support::lock_test_env; |
| 10 | |
| 11 | use std::collections::HashMap; |
| 12 | |
| 13 | use std::env; |
| 14 | |
| 15 | use std::ffi::OsString; |
| 16 | |
| 17 | use std::sync::mpsc; |
| 18 | |
| 19 | use std::time::Duration; |
| 20 | |
| 21 | use std::time::SystemTime; |
| 22 | |
| 23 | use super::test_support::*; |
| 24 | use std::time::UNIX_EPOCH; |
| 25 | |
| 26 | #[test] |
| 27 | fn requirements_check_implicit_approval_and_sandbox_defaults() { |
| 28 | let temp = tempfile::tempdir().expect("tempdir"); |
| 29 | let path = temp.path().join("requirements.toml"); |
| 30 | let mut config = Config { |
| 31 | requirements_path: Some(path.display().to_string()), |
| 32 | ..Config::default() |
| 33 | }; |
| 34 | |
| 35 | fs::write(&path, "allowed_approval_policies = ['never']\n").unwrap(); |
| 36 | let error = apply_requirements(&mut config).expect_err("default approval must be checked"); |
| 37 | assert!(error.to_string().contains("approval_policy 'on-request'")); |
| 38 | config.approval_policy = Some("never".into()); |
| 39 | apply_requirements(&mut config).expect("explicit allowed policy"); |
| 40 | |
| 41 | fs::write(&path, "allowed_sandbox_modes = ['read-only']\n").unwrap(); |
| 42 | let error = apply_requirements(&mut config).expect_err("default sandbox must be checked"); |
| 43 | assert!(error.to_string().contains("sandbox_mode 'workspace-write'")); |
| 44 | config.sandbox_mode = Some("read-only".into()); |
| 45 | apply_requirements(&mut config).expect("explicit allowed sandbox"); |
| 46 | |
| 47 | config.approval_policy = None; |
| 48 | config.sandbox_mode = None; |
| 49 | fs::write( |
| 50 | &path, |
| 51 | "allowed_approval_policies = ['ON-REQUEST']\nallowed_sandbox_modes = ['WORKSPACE-WRITE']\n", |
| 52 | ) |
| 53 | .unwrap(); |
| 54 | apply_requirements(&mut config).expect("allowed implicit defaults"); |
| 55 | config.yolo = Some(true); |
| 56 | apply_requirements(&mut config).expect("managed approvals prevent the YOLO override"); |
| 57 | fs::write(&path, "allowed_sandbox_modes = ['workspace-write']\n").unwrap(); |
| 58 | apply_requirements(&mut config).expect("managed sandbox prevents the YOLO override"); |
| 59 | config.approval_policy = Some("full-access".into()); |
| 60 | let error = |
| 61 | apply_requirements(&mut config).expect_err("full access changes the sandbox default"); |
| 62 | assert!( |
| 63 | error |
| 64 | .to_string() |
| 65 | .contains("sandbox_mode 'danger-full-access'") |
| 66 | ); |
| 67 | } |
| 68 | |
| 69 | #[test] |
| 70 | fn requirements_accept_equivalent_approval_aliases() { |
| 71 | let temp = tempfile::tempdir().expect("tempdir"); |
| 72 | let path = temp.path().join("requirements.toml"); |
| 73 | let mut config = Config { |
| 74 | requirements_path: Some(path.display().to_string()), |
| 75 | ..Config::default() |
| 76 | }; |
| 77 | for alias in ["untrusted", "ask", "suggest", "ON-REQUEST"] { |
| 78 | fs::write(&path, format!("allowed_approval_policies = ['{alias}']\n")).unwrap(); |
| 79 | for policy in [None, Some("on-request"), Some("ask")] { |
| 80 | config.approval_policy = policy.map(str::to_string); |
| 81 | apply_requirements(&mut config).expect("equivalent approval mode is allowed"); |
| 82 | } |
| 83 | config.approval_policy = Some("full-access".into()); |
| 84 | assert!( |
| 85 | apply_requirements(&mut config).is_err(), |
| 86 | "{alias} must not allow bypass" |
| 87 | ); |
| 88 | } |
| 89 | fs::write(&path, "allowed_approval_policies = ['unknown']\n").unwrap(); |
| 90 | config.approval_policy = None; |
| 91 | assert!( |
| 92 | apply_requirements(&mut config).is_err(), |
| 93 | "unknown is not the default" |
| 94 | ); |
| 95 | config.approval_policy = Some("other-unknown".into()); |
| 96 | assert!( |
| 97 | apply_requirements(&mut config).is_err(), |
| 98 | "unknown modes must not compare equal" |
| 99 | ); |
| 100 | config.approval_policy = Some("UNKNOWN".into()); |
| 101 | apply_requirements(&mut config).expect("unparsed policies retain literal comparison"); |
| 102 | } |
| 103 | |
| 104 | #[test] |
| 105 | fn legacy_hosted_ollama_migration_keeps_the_existing_table_and_endpoint() { |
| 106 | let _lock = lock_test_env(); |
| 107 | let home = tempfile::tempdir().unwrap(); |
| 108 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 109 | let _overrides: Vec<_> = [ |
| 110 | "CODEWHALE_CONFIG_PATH", |
| 111 | "DEEPSEEK_CONFIG_PATH", |
| 112 | "CODEWHALE_PROVIDER", |
| 113 | "DEEPSEEK_PROVIDER", |
| 114 | "CODEWHALE_MODEL", |
| 115 | "DEEPSEEK_MODEL", |
| 116 | "DEEPSEEK_DEFAULT_TEXT_MODEL", |
| 117 | "OLLAMA_MODEL", |
| 118 | "OLLAMA_CLOUD_MODEL", |
| 119 | "OLLAMA_BASE_URL", |
| 120 | "OLLAMA_CLOUD_BASE_URL", |
| 121 | ] |
| 122 | .into_iter() |
| 123 | .map(EnvVarGuard::remove) |
| 124 | .collect(); |
| 125 | let path = home.path().join("config.toml"); |
| 126 | fs::write(&path, "provider = 'ollama'\n[providers.ollama]\nbase_url = 'https://ollama.com/v1'\nmodel = 'old-model'\n").unwrap(); |
| 127 | fs::write( |
| 128 | home.path().join("settings.toml"), |
| 129 | "default_provider = 'ollama'\n[provider_models]\nollama-cloud = 'remembered-model'\n", |
| 130 | ) |
| 131 | .unwrap(); |
| 132 | let before = Config::load(None, None).unwrap(); |
| 133 | assert_eq!( |
| 134 | before.active_provider_identity().unwrap().provider, |
| 135 | ProviderKind::OllamaCloud |
| 136 | ); |
| 137 | assert_eq!(before.default_model(), "remembered-model"); |
| 138 | crate::config_persistence::persist_root_bool_key(Some(&path), "allow_shell", false).unwrap(); |
| 139 | let after = Config::load(None, None).unwrap(); |
| 140 | assert_eq!( |
| 141 | after.active_provider_identity().unwrap().provider, |
| 142 | ProviderKind::OllamaCloud |
| 143 | ); |
| 144 | assert_eq!(after.default_model(), "remembered-model"); |
| 145 | assert_eq!(after.active_route_base_url(), "https://ollama.com/v1"); |
| 146 | assert_eq!( |
| 147 | after.active_provider_identity().unwrap().persisted_id(), |
| 148 | Some("ollama") |
| 149 | ); |
| 150 | let doc: toml::Value = toml::from_str(&fs::read_to_string(path).unwrap()).unwrap(); |
| 151 | assert_eq!(doc["provider"].as_str(), Some("ollama")); |
| 152 | assert_eq!( |
| 153 | doc["providers"]["ollama"]["model"].as_str(), |
| 154 | Some("remembered-model") |
| 155 | ); |
| 156 | assert!(doc["providers"].get("ollama_cloud").is_none()); |
| 157 | } |
| 158 | |
| 159 | #[test] |
| 160 | fn malformed_config_error_omits_secret_contents_and_keys() { |
| 161 | let dir = tempfile::tempdir().expect("tempdir"); |
| 162 | let path = dir.path().join("config.toml"); |
| 163 | let secret = "cw-secret-tui-config-4507"; |
| 164 | fs::write( |
| 165 | &path, |
| 166 | format!("[providers.xai]\napi_key = \"{secret}\" trailing-junk\n"), |
| 167 | ) |
| 168 | .expect("write malformed config"); |
| 169 | |
| 170 | let error = Config::load(Some(path), None).expect_err("malformed config must fail"); |
| 171 | let diagnostic = format!("{error:#}"); |
| 172 | assert!(!diagnostic.contains(secret), "{diagnostic}"); |
| 173 | assert!(!diagnostic.contains("api_key"), "{diagnostic}"); |
| 174 | assert!( |
| 175 | diagnostic.contains("file contents were omitted"), |
| 176 | "{diagnostic}" |
| 177 | ); |
| 178 | } |
| 179 | |
| 180 | #[test] |
| 181 | fn config_parse_error_names_unknown_key_and_table() { |
| 182 | let error = Config::from_saved_document("[skills]\nbogus_key = 1\n", None) |
| 183 | .expect_err("unknown key in [skills] must fail"); |
| 184 | let diagnostic = format!("{error:#}"); |
| 185 | assert!(diagnostic.contains("bogus_key"), "{diagnostic}"); |
| 186 | assert!(diagnostic.contains("skills"), "{diagnostic}"); |
| 187 | assert!( |
| 188 | diagnostic.contains("file contents were omitted"), |
| 189 | "{diagnostic}" |
| 190 | ); |
| 191 | } |
| 192 | |
| 193 | #[test] |
| 194 | fn config_parse_error_syntax_error_reports_line_without_leaking_secret() { |
| 195 | let error = Config::from_saved_document("api_key = \"sk-SECRET-VALUE-123\"\n[broken\n", None) |
| 196 | .expect_err("TOML syntax error must fail"); |
| 197 | let diagnostic = format!("{error:#}"); |
| 198 | assert!(!diagnostic.contains("SECRET"), "{diagnostic}"); |
| 199 | assert!(diagnostic.contains("line 2"), "{diagnostic}"); |
| 200 | assert!( |
| 201 | diagnostic.contains("file contents were omitted"), |
| 202 | "{diagnostic}" |
| 203 | ); |
| 204 | } |
| 205 | |
| 206 | #[test] |
| 207 | fn config_parse_error_wrong_type_names_key_without_leaking_secret() { |
| 208 | let error = Config::from_saved_document( |
| 209 | "[skills]\nlisting_budget_fraction = \"sk-SECRET-VALUE-123\"\n", |
| 210 | None, |
| 211 | ) |
| 212 | .expect_err("wrong value type in [skills] must fail"); |
| 213 | let diagnostic = format!("{error:#}"); |
| 214 | assert!(!diagnostic.contains("SECRET"), "{diagnostic}"); |
| 215 | assert!( |
| 216 | diagnostic.contains("skills.listing_budget_fraction"), |
| 217 | "{diagnostic}" |
| 218 | ); |
| 219 | assert!( |
| 220 | diagnostic.contains("file contents were omitted"), |
| 221 | "{diagnostic}" |
| 222 | ); |
| 223 | } |
| 224 | |
| 225 | fn assert_config_error_is_opaque(source: &str, leaked: &[&str]) -> String { |
| 226 | let error = Config::from_saved_document(source, None).expect_err("config must fail"); |
| 227 | let diagnostic = format!("{error:#}"); |
| 228 | for needle in leaked { |
| 229 | assert!(!diagnostic.contains(needle), "{diagnostic}"); |
| 230 | } |
| 231 | assert!(!diagnostic.contains('\u{1b}'), "{diagnostic}"); |
| 232 | assert!(!diagnostic.contains('\n'), "{diagnostic}"); |
| 233 | assert!(diagnostic.len() < 300, "{diagnostic}"); |
| 234 | assert!( |
| 235 | diagnostic.contains("file contents were omitted"), |
| 236 | "{diagnostic}" |
| 237 | ); |
| 238 | diagnostic |
| 239 | } |
| 240 | |
| 241 | #[test] |
| 242 | fn config_parse_error_names_unknown_key_under_profile_table() { |
| 243 | let diagnostic = |
| 244 | assert_config_error_is_opaque("[profiles.work.skills]\nbogus_key = 1\n", &["SECRET"]); |
| 245 | assert!(diagnostic.contains("bogus_key"), "{diagnostic}"); |
| 246 | assert!(diagnostic.contains("profiles.work.skills"), "{diagnostic}"); |
| 247 | } |
| 248 | |
| 249 | #[test] |
| 250 | fn config_parse_error_hides_secret_shaped_profile_name_on_wrong_type() { |
| 251 | let diagnostic = assert_config_error_is_opaque( |
| 252 | "[profiles.\"sk-proj-abcdefghijklmnopqrstuvwxyz0123456789\".skills]\nlisting_budget_fraction = \"x\"\n", |
| 253 | &["sk-proj", "abcdefghijkl"], |
| 254 | ); |
| 255 | assert!(!diagnostic.contains("invalid value for"), "{diagnostic}"); |
| 256 | } |
| 257 | |
| 258 | #[test] |
| 259 | fn config_parse_error_hides_secret_shaped_profile_name_on_unknown_key() { |
| 260 | assert_config_error_is_opaque( |
| 261 | "[profiles.\"sk-proj-abcdefghijklmnopqrstuvwxyz0123456789\".skills]\nbogus = 1\n", |
| 262 | &["sk-proj", "abcdefghijkl"], |
| 263 | ); |
| 264 | } |
| 265 | |
| 266 | #[test] |
| 267 | fn config_parse_error_hides_control_character_key() { |
| 268 | let diagnostic = assert_config_error_is_opaque( |
| 269 | "[skills]\n\"evil\\u001b[2Jx\" = 1\n\"a\\nFAKE: line two\" = 2\n", |
| 270 | &["evil", "FAKE"], |
| 271 | ); |
| 272 | assert!(!diagnostic.contains("unknown setting \""), "{diagnostic}"); |
| 273 | } |
| 274 | |
| 275 | #[test] |
| 276 | fn config_parse_error_hides_bare_hex_and_oversized_keys() { |
| 277 | assert_config_error_is_opaque( |
| 278 | "[skills]\nabcdef0123456789abcdef0123456789 = 1\n", |
| 279 | &["abcdef0123456789"], |
| 280 | ); |
| 281 | let long_key = "k".repeat(5000); |
| 282 | assert_config_error_is_opaque(&format!("[skills]\n{long_key} = 1\n"), &["kkkkkkkk"]); |
| 283 | let long_profile = "p".repeat(3000); |
| 284 | assert_config_error_is_opaque( |
| 285 | &format!("[profiles.{long_profile}.skills]\nlisting_budget_fraction = \"x\"\n"), |
| 286 | &["pppppppp"], |
| 287 | ); |
| 288 | } |
| 289 | |
| 290 | #[test] |
| 291 | fn config_parse_error_hides_unprefixed_secret_shaped_keys() { |
| 292 | for key in [ |
| 293 | "Zq8kLm2Pv9Xw4Rt7Yb3Nc6Hd1Jf5Gs0A", |
| 294 | "zq8klm2pv9xw4rt7yb3nc6hd1jf5gs0a", |
| 295 | "Bogus_Key", |
| 296 | ] { |
| 297 | let error = Config::from_saved_document(&format!("[skills]\n{key} = 1\n"), None) |
| 298 | .expect_err("unknown key in [skills] must fail"); |
| 299 | let diagnostic = format!("{error:#}"); |
| 300 | assert!(!diagnostic.contains(key), "{diagnostic}"); |
| 301 | assert!( |
| 302 | diagnostic.contains("unknown setting in [skills]"), |
| 303 | "{diagnostic}" |
| 304 | ); |
| 305 | assert!( |
| 306 | diagnostic.contains("file contents were omitted"), |
| 307 | "{diagnostic}" |
| 308 | ); |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | #[test] |
| 313 | fn config_parse_error_syntax_branch_hides_key_path_of_overflowing_integer() { |
| 314 | let diagnostic = assert_config_error_is_opaque( |
| 315 | "[other.\"sk-proj-abcdefghijklmnopqrstuvwxyz0123456789\"]\nbig = 99999999999999999999\n", |
| 316 | &["sk-proj", "abcdefghijkl", "big"], |
| 317 | ); |
| 318 | assert!(diagnostic.contains("line 2"), "{diagnostic}"); |
| 319 | let diagnostic = |
| 320 | assert_config_error_is_opaque("hunter2 = 99999999999999999999\n", &["hunter2"]); |
| 321 | assert!(diagnostic.contains("line 1"), "{diagnostic}"); |
| 322 | } |
| 323 | |
| 324 | #[test] |
| 325 | fn config_parse_error_syntax_branch_hides_control_character_and_oversized_table_names() { |
| 326 | assert_config_error_is_opaque( |
| 327 | "[other.\"evil\\u001b[2Jy\\nFORGED: line\"]\nbig = 99999999999999999999\n", |
| 328 | &["evil", "FORGED"], |
| 329 | ); |
| 330 | let long_table = "t".repeat(3000); |
| 331 | assert_config_error_is_opaque( |
| 332 | &format!("[other.{long_table}]\nbig = 99999999999999999999\n"), |
| 333 | &["tttttttt"], |
| 334 | ); |
| 335 | } |
| 336 | |
| 337 | #[test] |
| 338 | fn config_parse_error_unprintable_unknown_key_is_not_called_invalid_value() { |
| 339 | let diagnostic = assert_config_error_is_opaque("[skills]\n\"has space\" = 1\n", &["has space"]); |
| 340 | assert!(diagnostic.contains("unknown setting"), "{diagnostic}"); |
| 341 | assert!(!diagnostic.contains("invalid value"), "{diagnostic}"); |
| 342 | assert!(diagnostic.contains("[skills]"), "{diagnostic}"); |
| 343 | } |
| 344 | |
| 345 | #[test] |
| 346 | fn legacy_root_environment_replacement_requires_exact_id_and_refuses_prior_snapshot() { |
| 347 | let _lock = lock_test_env(); |
| 348 | let _base = EnvVarGuard::set("CODEWHALE_BASE_URL", "http://127.0.0.1:18191/v1"); |
| 349 | let _model = EnvVarGuard::set("CODEWHALE_MODEL", "prepared-model"); |
| 350 | let _headers = EnvVarGuard::set("CODEWHALE_HTTP_HEADERS", "X-Prepared=one"); |
| 351 | let mut config = Config::from_saved_document( |
| 352 | r#"provider = "custom" |
| 353 | base_url = "http://127.0.0.1:18190/v1" |
| 354 | api_key = "original-file-key" |
| 355 | default_text_model = "original-model" |
| 356 | "#, |
| 357 | None, |
| 358 | ) |
| 359 | .unwrap(); |
| 360 | let captured = config.active_provider_identity().unwrap(); |
| 361 | assert_eq!(captured.persisted_id(), None); |
| 362 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 363 | let prepared = config.active_provider_identity().unwrap(); |
| 364 | assert_eq!(prepared.persisted_id(), Some("custom")); |
| 365 | assert_eq!(config.default_model(), "prepared-model"); |
| 366 | assert_eq!(config.active_route_base_url(), "http://127.0.0.1:18191/v1"); |
| 367 | assert_eq!( |
| 368 | config.http_headers().get("X-Prepared").map(String::as_str), |
| 369 | Some("one") |
| 370 | ); |
| 371 | assert!(config.verify_provider_identity(&captured).is_err()); |
| 372 | assert!( |
| 373 | config |
| 374 | .resolve_persisted_provider_identity(Some("custom"), None) |
| 375 | .is_err() |
| 376 | ); |
| 377 | assert_eq!(config.active_route_api_key().unwrap(), ""); |
| 378 | } |
| 379 | |
| 380 | #[test] |
| 381 | fn scoped_hosted_ollama_retains_legacy_leaf_and_refuses_replaced_endpoint() { |
| 382 | let _lock = lock_test_env(); |
| 383 | let _env = EnvVarGuard::remove("OLLAMA_BASE_URL"); |
| 384 | let mut config = Config::from_saved_document( |
| 385 | r#"provider = "deepseek" |
| 386 | [providers.ollama] |
| 387 | base_url = "https://ollama.com/v1" |
| 388 | model = "held-model" |
| 389 | "#, |
| 390 | None, |
| 391 | ) |
| 392 | .unwrap(); |
| 393 | let captured = config.resolve_provider_identity("ollama").unwrap(); |
| 394 | config.scope_to_provider_identity(&captured).unwrap(); |
| 395 | assert_eq!(config.active_provider_identity().unwrap(), captured); |
| 396 | assert_eq!(config.default_model(), "held-model"); |
| 397 | config.providers.as_mut().unwrap().ollama.base_url = Some("http://localhost:11434/v1".into()); |
| 398 | assert!(config.active_provider_identity().is_err()); |
| 399 | assert!(config.verify_provider_identity(&captured).is_err()); |
| 400 | let explicit = config.resolve_provider_identity("ollama-cloud").unwrap(); |
| 401 | assert_eq!(explicit.persisted_id(), Some("ollama-cloud")); |
| 402 | assert!(!explicit.migrated_legacy_ollama_cloud_route); |
| 403 | } |
| 404 | |
| 405 | #[test] |
| 406 | fn api_provider_metadata_helpers_follow_config_provider_metadata() { |
| 407 | let config = Config::default(); |
| 408 | let rows = codewhale_config::descriptors::provider_compatibility(); |
| 409 | assert_eq!(rows.len(), 53); |
| 410 | for row in rows { |
| 411 | if matches!(row.kind, ProviderKind::Antigravity | ProviderKind::Custom) { |
| 412 | assert!(config.resolve_provider_selection_identity(row.id).is_err()); |
| 413 | continue; |
| 414 | } |
| 415 | let identity = config |
| 416 | .resolve_provider_selection_identity(row.id) |
| 417 | .expect("released admitted selection"); |
| 418 | assert_eq!(identity.provider, row.kind); |
| 419 | assert_eq!(identity.key.as_str(), row.id); |
| 420 | assert!( |
| 421 | identity |
| 422 | .compatibility() |
| 423 | .is_some_and(|actual| std::ptr::eq(actual, row)) |
| 424 | ); |
| 425 | assert_eq!( |
| 426 | identity.provider.provider().env_vars(), |
| 427 | row.kind.provider().env_vars() |
| 428 | ); |
| 429 | } |
| 430 | let cn = config |
| 431 | .resolve_provider_selection_identity("deepseek-cn") |
| 432 | .unwrap(); |
| 433 | assert_eq!(cn.provider, ProviderKind::Deepseek); |
| 434 | assert_eq!(cn.key.as_str(), "deepseek-cn"); |
| 435 | assert_eq!( |
| 436 | cn.compatibility().unwrap().base_url, |
| 437 | DEFAULT_DEEPSEEKCN_BASE_URL |
| 438 | ); |
| 439 | } |
| 440 | |
| 441 | #[test] |
| 442 | fn retired_antigravity_is_not_selectable_but_has_an_actionable_tombstone() { |
| 443 | for identity in ["antigravity", "agy"] { |
| 444 | assert_eq!(ProviderKind::parse(identity), None, "{identity}"); |
| 445 | } |
| 446 | assert!(!ProviderKind::all().contains(&ProviderKind::Antigravity)); |
| 447 | assert!( |
| 448 | !codewhale_config::provider::providers_sorted_for_display() |
| 449 | .iter() |
| 450 | .map(|provider| provider.kind()) |
| 451 | .collect::<Vec<_>>() |
| 452 | .contains(&ProviderKind::Antigravity) |
| 453 | ); |
| 454 | |
| 455 | for identity in ["antigravity", "agy"] { |
| 456 | assert!(is_legacy_antigravity_identity(identity), "{identity}"); |
| 457 | let config = Config { |
| 458 | provider: Some(identity.to_string()), |
| 459 | ..Config::default() |
| 460 | }; |
| 461 | let error = config |
| 462 | .validate() |
| 463 | .expect_err("a persisted legacy selection must fail before runtime setup") |
| 464 | .to_string(); |
| 465 | assert!(error.contains("non-runnable"), "{identity}: {error}"); |
| 466 | assert!( |
| 467 | error.contains("auth clear --provider antigravity"), |
| 468 | "{identity}: {error}" |
| 469 | ); |
| 470 | assert!(error.contains("provider `google`"), "{identity}: {error}"); |
| 471 | assert!(error.contains("GEMINI_API_KEY"), "{identity}: {error}"); |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | #[test] |
| 476 | fn retired_antigravity_env_selection_is_refused_with_the_tombstone() { |
| 477 | let _guard = lock_test_env(); |
| 478 | let _deepseek_provider = EnvVarGuard::remove("DEEPSEEK_PROVIDER"); |
| 479 | for identity in ["antigravity", "agy"] { |
| 480 | let _provider = EnvVarGuard::set("CODEWHALE_PROVIDER", identity); |
| 481 | let mut config = Config::default(); |
| 482 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 483 | let error = config |
| 484 | .validate() |
| 485 | .expect_err("CODEWHALE_PROVIDER must not select the tombstone") |
| 486 | .to_string(); |
| 487 | assert!(error.contains("non-runnable"), "{identity}: {error}"); |
| 488 | assert!(error.contains("GEMINI_API_KEY"), "{identity}: {error}"); |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | #[test] |
| 493 | fn every_api_provider_variant_resolves_base_url_without_panicking() { |
| 494 | let rows = codewhale_config::descriptors::provider_compatibility(); |
| 495 | assert_eq!(rows.len(), 53); |
| 496 | for row in rows { |
| 497 | assert!(!row.base_url.is_empty(), "{} default base is empty", row.id); |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | #[test] |
| 502 | fn provider_config_key_follows_config_provider_metadata() { |
| 503 | let config = Config::default(); |
| 504 | for row in codewhale_config::descriptors::provider_compatibility() { |
| 505 | if matches!(row.kind, ProviderKind::Antigravity | ProviderKind::Custom) { |
| 506 | continue; |
| 507 | } |
| 508 | let identity = config.resolve_provider_selection_identity(row.id).unwrap(); |
| 509 | if row.id == ProviderKind::Deepseek.as_str() { |
| 510 | assert!(provider_config_key(&identity).is_err()); |
| 511 | } else { |
| 512 | assert_eq!(provider_config_key(&identity).unwrap(), row.config_key); |
| 513 | } |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | #[test] |
| 518 | fn deepseek_api_key_reads_metadata_env_vars_for_newer_providers() -> Result<()> { |
| 519 | let _lock = lock_test_env(); |
| 520 | let _source = EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 521 | let cases = [ |
| 522 | (ProviderKind::Zai, "ZAI_API_KEY", "zai-env-key"), |
| 523 | (ProviderKind::Stepfun, "STEPFUN_API_KEY", "stepfun-env-key"), |
| 524 | (ProviderKind::Minimax, "MINIMAX_API_KEY", "minimax-env-key"), |
| 525 | ( |
| 526 | ProviderKind::MinimaxAnthropic, |
| 527 | "MINIMAX_API_KEY", |
| 528 | "minimax-env-key", |
| 529 | ), |
| 530 | ( |
| 531 | ProviderKind::Deepinfra, |
| 532 | "DEEPINFRA_API_KEY", |
| 533 | "deepinfra-env-key", |
| 534 | ), |
| 535 | (ProviderKind::Sakana, "FUGU_API_KEY", "fugu-env-key"), |
| 536 | ( |
| 537 | ProviderKind::Together, |
| 538 | "TOGETHER_API_KEY", |
| 539 | "together-env-key", |
| 540 | ), |
| 541 | (ProviderKind::Qianfan, "QIANFAN_API_KEY", "qianfan-env-key"), |
| 542 | ( |
| 543 | ProviderKind::OpencodeGo, |
| 544 | "OPENCODE_GO_API_KEY", |
| 545 | "opencode-go-env-key", |
| 546 | ), |
| 547 | ]; |
| 548 | let _env_guards: Vec<_> = cases |
| 549 | .iter() |
| 550 | .map(|(_, var, value)| EnvVarGuard::set(var, value)) |
| 551 | .collect(); |
| 552 | |
| 553 | for (provider, _, expected_key) in cases { |
| 554 | let config = Config { |
| 555 | provider: Some(provider.as_str().to_string()), |
| 556 | ..Config::default() |
| 557 | }; |
| 558 | |
| 559 | assert_eq!(config.active_route_api_key()?, expected_key); |
| 560 | } |
| 561 | |
| 562 | Ok(()) |
| 563 | } |
| 564 | |
| 565 | #[test] |
| 566 | fn goal_max_continuations_loads_from_goal_table() -> Result<()> { |
| 567 | // Absent table → unlimited by default (#5052). |
| 568 | let config: Config = toml::from_str("")?; |
| 569 | assert_eq!( |
| 570 | config.goal_max_continuations(), |
| 571 | crate::goal_loop::DEFAULT_MAX_GOAL_CONTINUATIONS |
| 572 | ); |
| 573 | assert_eq!(config.goal_max_continuations(), 0); |
| 574 | assert_eq!(config.goal_continuation_delay_seconds(), 0); |
| 575 | // enforce_token_budget defaults off: budgets stay advisory (#6013). |
| 576 | assert!(!config.goal_enforce_token_budget()); |
| 577 | |
| 578 | // Explicit backstop override. |
| 579 | let config: Config = toml::from_str( |
| 580 | r#" |
| 581 | [goal] |
| 582 | max_continuations = 25 |
| 583 | continuation_delay_seconds = 300 |
| 584 | "#, |
| 585 | )?; |
| 586 | assert_eq!(config.goal_max_continuations(), 25); |
| 587 | assert_eq!(config.goal_continuation_delay_seconds(), 300); |
| 588 | |
| 589 | // 0 = unlimited; token/time budgets are telemetry only. |
| 590 | let config: Config = toml::from_str( |
| 591 | r#" |
| 592 | [goal] |
| 593 | max_continuations = 0 |
| 594 | "#, |
| 595 | )?; |
| 596 | assert_eq!(config.goal_max_continuations(), 0); |
| 597 | |
| 598 | // Opt a set token budget into a hard stop (#6013). |
| 599 | let config: Config = toml::from_str( |
| 600 | r#" |
| 601 | [goal] |
| 602 | enforce_token_budget = true |
| 603 | "#, |
| 604 | )?; |
| 605 | assert!(config.goal_enforce_token_budget()); |
| 606 | assert_eq!(config.goal_continuation_delay_seconds(), 0); |
| 607 | |
| 608 | // Bound accidental giant cadences; this remains a turn loop, not a |
| 609 | // replacement for durable low-frequency automations. |
| 610 | let config: Config = toml::from_str( |
| 611 | r#" |
| 612 | [goal] |
| 613 | continuation_delay_seconds = 999999999 |
| 614 | "#, |
| 615 | )?; |
| 616 | assert_eq!( |
| 617 | config.goal_continuation_delay_seconds(), |
| 618 | crate::goal_loop::MAX_GOAL_CONTINUATION_DELAY_SECONDS |
| 619 | ); |
| 620 | |
| 621 | Ok(()) |
| 622 | } |
| 623 | |
| 624 | #[test] |
| 625 | fn reasoning_only_config_loads_from_table() -> Result<()> { |
| 626 | // Absent table → built-in defaults. |
| 627 | let config: Config = toml::from_str("")?; |
| 628 | assert_eq!( |
| 629 | config.reasoning_only_max_reprompts(), |
| 630 | crate::config::DEFAULT_REASONING_ONLY_REPROMPTS |
| 631 | ); |
| 632 | assert_eq!( |
| 633 | config.reasoning_only_reprompt_message(), |
| 634 | crate::config::DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE |
| 635 | ); |
| 636 | |
| 637 | // Explicit max_reprompts override. |
| 638 | let config: Config = toml::from_str( |
| 639 | r#" |
| 640 | [reasoning_only] |
| 641 | max_reprompts = 10 |
| 642 | "#, |
| 643 | )?; |
| 644 | assert_eq!(config.reasoning_only_max_reprompts(), 10); |
| 645 | assert_eq!( |
| 646 | config.reasoning_only_reprompt_message(), |
| 647 | crate::config::DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE |
| 648 | ); |
| 649 | |
| 650 | // Explicit reprompt_message override. |
| 651 | let config: Config = toml::from_str( |
| 652 | r#" |
| 653 | [reasoning_only] |
| 654 | max_reprompts = 5 |
| 655 | reprompt_message = "tu n'as rien a dire" |
| 656 | "#, |
| 657 | )?; |
| 658 | assert_eq!(config.reasoning_only_max_reprompts(), 5); |
| 659 | assert_eq!( |
| 660 | config.reasoning_only_reprompt_message(), |
| 661 | "tu n'as rien a dire" |
| 662 | ); |
| 663 | |
| 664 | // 0 = disable automatic recovery. |
| 665 | let config: Config = toml::from_str( |
| 666 | r#" |
| 667 | [reasoning_only] |
| 668 | max_reprompts = 0 |
| 669 | "#, |
| 670 | )?; |
| 671 | assert_eq!(config.reasoning_only_max_reprompts(), 0); |
| 672 | assert_eq!( |
| 673 | config.reasoning_only_reprompt_message(), |
| 674 | crate::config::DEFAULT_REASONING_ONLY_REPROMPT_MESSAGE |
| 675 | ); |
| 676 | |
| 677 | Ok(()) |
| 678 | } |
| 679 | |
| 680 | #[test] |
| 681 | fn modelstudio_coding_plan_mode_resolves_the_official_chat_base_url() { |
| 682 | // The picker represents Coding Plan as the primary Model Studio provider |
| 683 | // plus a mode, rather than switching to the legacy Coding Plan identity. |
| 684 | // Keep this config-resolution seam covered: chat-route reasoning support |
| 685 | // relies on receiving this exact official URL downstream. |
| 686 | let config: Config = toml::from_str( |
| 687 | r#" |
| 688 | provider = "modelstudio-token-plan" |
| 689 | |
| 690 | [providers.modelstudio_token_plan] |
| 691 | mode = "coding-plan" |
| 692 | "#, |
| 693 | ) |
| 694 | .expect("Coding Plan mode should parse"); |
| 695 | |
| 696 | assert_eq!( |
| 697 | config.active_provider_identity().unwrap().provider, |
| 698 | ProviderKind::ModelstudioTokenPlan |
| 699 | ); |
| 700 | assert_eq!( |
| 701 | config.active_route_base_url(), |
| 702 | DEFAULT_MODELSTUDIO_CODING_PLAN_BASE_URL |
| 703 | ); |
| 704 | } |
| 705 | |
| 706 | #[test] |
| 707 | fn provider_context_scenario() -> Result<()> { |
| 708 | // Scenario consolidation of: provider_context_window_loads_from_provider_table, provider_context_window_zero_is_invalid |
| 709 | // from provider_context_window_loads_from_provider_table |
| 710 | { |
| 711 | let config: Config = toml::from_str( |
| 712 | r#" |
| 713 | provider = "openai" |
| 714 | |
| 715 | [providers.openai] |
| 716 | model = "qwen3.7" |
| 717 | context_window = 1000000 |
| 718 | "#, |
| 719 | )?; |
| 720 | |
| 721 | config.validate()?; |
| 722 | assert_eq!( |
| 723 | config.context_window_for_provider_config( |
| 724 | &config.test_identity_for_kind(ProviderKind::Openai) |
| 725 | ), |
| 726 | Some(1_000_000) |
| 727 | ); |
| 728 | } |
| 729 | // from provider_context_window_zero_is_invalid |
| 730 | { |
| 731 | let config: Config = toml::from_str( |
| 732 | r#" |
| 733 | [providers.openai] |
| 734 | context_window = 0 |
| 735 | "#, |
| 736 | ) |
| 737 | .expect("zero is syntactically valid TOML"); |
| 738 | |
| 739 | let err = config |
| 740 | .validate() |
| 741 | .expect_err("zero context_window should be rejected"); |
| 742 | assert!(err.to_string().contains("providers.openai.context_window")); |
| 743 | } |
| 744 | Ok(()) |
| 745 | } |
| 746 | |
| 747 | #[test] |
| 748 | fn context_window_edits_preserve_the_regional_and_migrated_provider_tables() -> Result<()> { |
| 749 | let directory = tempfile::tempdir()?; |
| 750 | let path = directory.path().join("config.toml"); |
| 751 | for (provider, selected, sibling, endpoint) in [ |
| 752 | ("siliconflow-cn", "siliconflow_cn", "siliconflow", ""), |
| 753 | ( |
| 754 | "ollama", |
| 755 | "ollama", |
| 756 | "ollama_cloud", |
| 757 | "base_url = 'https://ollama.com/v1'", |
| 758 | ), |
| 759 | ] { |
| 760 | fs::write( |
| 761 | &path, |
| 762 | format!( |
| 763 | "provider = '{provider}'\n[providers.{selected}]\n{endpoint}\n[providers.{sibling}.model_context_windows]\nmodel = 16384\n" |
| 764 | ), |
| 765 | )?; |
| 766 | let config = Config::from_saved_document(&fs::read_to_string(&path)?, None)?; |
| 767 | let identity = config |
| 768 | .active_provider_identity() |
| 769 | .map_err(anyhow::Error::msg)?; |
| 770 | assert_eq!(identity.config_table_key()?, selected); |
| 771 | for tokens in [Some(65_536), None] { |
| 772 | crate::config_persistence::persist_provider_model_context_window( |
| 773 | Some(&path), |
| 774 | None, |
| 775 | &identity, |
| 776 | "model", |
| 777 | tokens, |
| 778 | )?; |
| 779 | let document: toml::Value = toml::from_str(&fs::read_to_string(&path)?)?; |
| 780 | assert_eq!( |
| 781 | document["providers"][selected] |
| 782 | .get("model_context_windows") |
| 783 | .and_then(|table| table.get("model")) |
| 784 | .and_then(toml::Value::as_integer), |
| 785 | tokens.map(i64::from) |
| 786 | ); |
| 787 | assert_eq!( |
| 788 | document["providers"][sibling]["model_context_windows"]["model"].as_integer(), |
| 789 | Some(16_384) |
| 790 | ); |
| 791 | } |
| 792 | } |
| 793 | Ok(()) |
| 794 | } |
| 795 | |
| 796 | #[test] |
| 797 | fn context_window_edits_are_scoped_to_the_selected_profile() -> Result<()> { |
| 798 | let dir = tempfile::tempdir()?; |
| 799 | let path = dir.path().join("config.toml"); |
| 800 | let raw = r#" |
| 801 | [providers.openai.model_context_windows] |
| 802 | first = 8192 |
| 803 | second = 16384 |
| 804 | [profiles.work] |
| 805 | provider = "gateway" |
| 806 | [profiles.work.providers.gateway] |
| 807 | kind = "openai-compatible" |
| 808 | base_url = "https://gateway.example/v1" |
| 809 | "#; |
| 810 | fs::write(&path, raw)?; |
| 811 | let profile = Some("work"); |
| 812 | let load = || Config::from_saved_document(&fs::read_to_string(&path)?, profile); |
| 813 | let config = load()?; |
| 814 | let gateway = config |
| 815 | .active_provider_identity() |
| 816 | .map_err(anyhow::Error::msg)?; |
| 817 | let openai = config.test_identity_for_kind(ProviderKind::Openai); |
| 818 | for identity in [&gateway, &openai] { |
| 819 | for tokens in [Some(32768), None] { |
| 820 | crate::config_persistence::persist_provider_model_context_window( |
| 821 | Some(&path), |
| 822 | profile, |
| 823 | identity, |
| 824 | "first", |
| 825 | tokens, |
| 826 | )?; |
| 827 | let loaded = load()?; |
| 828 | let windows = loaded.model_context_windows_for(identity); |
| 829 | assert_eq!(windows.and_then(|w| w.get("first")).copied(), tokens); |
| 830 | if identity == &openai { |
| 831 | assert_eq!(windows.and_then(|w| w.get("second")).copied(), Some(16384)); |
| 832 | } |
| 833 | } |
| 834 | } |
| 835 | let base = Config::from_saved_document(&fs::read_to_string(&path)?, None)?; |
| 836 | assert_eq!( |
| 837 | base.model_context_windows_for(&openai).unwrap()["first"], |
| 838 | 8192 |
| 839 | ); |
| 840 | |
| 841 | let legacy = "provider = 'custom'\nbase_url = 'https://legacy.example/v1'\n[profiles.work]\n[profiles.other]\n"; |
| 842 | fs::write(&path, legacy)?; |
| 843 | let identity = load()? |
| 844 | .active_provider_identity() |
| 845 | .map_err(anyhow::Error::msg)?; |
| 846 | assert!(identity.persisted_id().is_none()); |
| 847 | let error = crate::config_persistence::persist_provider_model_context_window( |
| 848 | Some(&path), |
| 849 | profile, |
| 850 | &identity, |
| 851 | "first", |
| 852 | Some(32768), |
| 853 | ) |
| 854 | .unwrap_err(); |
| 855 | assert!(error.to_string().contains("select a named provider")); |
| 856 | assert_eq!(fs::read_to_string(&path)?, legacy); |
| 857 | Ok(()) |
| 858 | } |
| 859 | |
| 860 | #[test] |
| 861 | fn model_context_windows_load_isolate_and_validate() -> Result<()> { |
| 862 | // A gateway fronting heterogeneous models: slash and dotted wire ids both |
| 863 | // land as exact keys of the provider's own table (#6108). |
| 864 | let config: Config = toml::from_str( |
| 865 | r#" |
| 866 | provider = "command_code" |
| 867 | |
| 868 | [providers.command_code] |
| 869 | kind = "openai-compatible" |
| 870 | base_url = "https://gateway.example/v1" |
| 871 | model = "qwen3.5-flash" |
| 872 | context_window = 204800 |
| 873 | |
| 874 | [providers.command_code.model_context_windows] |
| 875 | "qwen3.5-flash" = 131072 |
| 876 | "MiniMaxAI/MiniMax-M2.5" = 1000000 |
| 877 | |
| 878 | [providers.openai.model_context_windows] |
| 879 | "qwen3.5-flash" = 64000 |
| 880 | "#, |
| 881 | )?; |
| 882 | |
| 883 | config.validate()?; |
| 884 | |
| 885 | let custom = config |
| 886 | .model_context_windows_for(&config.test_identity_for_kind(ProviderKind::Custom)) |
| 887 | .expect("custom provider table resolves by selected provider name"); |
| 888 | assert_eq!(custom.get("qwen3.5-flash"), Some(&131_072)); |
| 889 | assert_eq!(custom.get("MiniMaxAI/MiniMax-M2.5"), Some(&1_000_000)); |
| 890 | |
| 891 | // Per-provider isolation: the same wire id under another provider is a |
| 892 | // different override, and untouched providers have no table at all. |
| 893 | assert_eq!( |
| 894 | config |
| 895 | .model_context_windows_for(&config.test_identity_for_kind(ProviderKind::Openai)) |
| 896 | .and_then(|table| table.get("qwen3.5-flash").copied()), |
| 897 | Some(64_000) |
| 898 | ); |
| 899 | assert!( |
| 900 | config |
| 901 | .model_context_windows_for(&config.test_identity_for_kind(ProviderKind::Moonshot)) |
| 902 | .is_none() |
| 903 | ); |
| 904 | |
| 905 | // A zero entry fails validation with the full key path in the error. |
| 906 | let zeroed: Config = toml::from_str( |
| 907 | r#" |
| 908 | [providers.openai.model_context_windows] |
| 909 | "qwen3.5-flash" = 0 |
| 910 | "#, |
| 911 | ) |
| 912 | .expect("zero is syntactically valid TOML"); |
| 913 | let err = zeroed |
| 914 | .validate() |
| 915 | .expect_err("zero per-model context window must be rejected"); |
| 916 | assert!( |
| 917 | err.to_string().contains("model_context_windows"), |
| 918 | "unexpected error: {err}" |
| 919 | ); |
| 920 | Ok(()) |
| 921 | } |
| 922 | |
| 923 | #[test] |
| 924 | fn negative_retry_delay_is_invalid() { |
| 925 | let config: Config = toml::from_str( |
| 926 | r#" |
| 927 | [retry] |
| 928 | jitter = false |
| 929 | max_delay = -1.0 |
| 930 | "#, |
| 931 | ) |
| 932 | .expect("a negative delay is syntactically valid TOML"); |
| 933 | |
| 934 | let err = config |
| 935 | .validate() |
| 936 | .expect_err("a negative retry delay should be rejected"); |
| 937 | assert!(err.to_string().contains("[retry] max_delay"), "{err}"); |
| 938 | } |
| 939 | |
| 940 | #[test] |
| 941 | fn opencode_go_context_window_zero_is_invalid() { |
| 942 | let config: Config = toml::from_str( |
| 943 | r#" |
| 944 | [providers.opencode_go] |
| 945 | context_window = 0 |
| 946 | "#, |
| 947 | ) |
| 948 | .expect("zero is syntactically valid TOML"); |
| 949 | |
| 950 | let err = config |
| 951 | .validate() |
| 952 | .expect_err("zero OpenCode Go context_window should be rejected"); |
| 953 | assert!( |
| 954 | err.to_string() |
| 955 | .contains("providers.opencode_go.context_window") |
| 956 | ); |
| 957 | } |
| 958 | |
| 959 | #[test] |
| 960 | fn missing_provider_api_key_message_uses_provider_metadata() -> Result<()> { |
| 961 | let message = missing_provider_api_key_message( |
| 962 | &Config::default().test_identity_for_kind(ProviderKind::Zai), |
| 963 | )?; |
| 964 | |
| 965 | assert!(message.contains("Zhipu AI / Z.ai API key not found")); |
| 966 | assert!(message.contains("https://z.ai/model-api")); |
| 967 | assert!(message.contains("ZAI_API_KEY / Z_AI_API_KEY")); |
| 968 | assert!(message.contains("[providers.zai] api_key")); |
| 969 | |
| 970 | Ok(()) |
| 971 | } |
| 972 | |
| 973 | #[test] |
| 974 | fn opencode_zen_missing_credentials_never_mentions_codex_oauth() -> Result<()> { |
| 975 | let message = missing_provider_api_key_message( |
| 976 | &Config::default().test_identity_for_kind(ProviderKind::OpencodeZen), |
| 977 | )?; |
| 978 | assert!(message.contains("OpenCode Zen API key not found")); |
| 979 | assert!(message.contains("OPENCODE_ZEN_API_KEY")); |
| 980 | assert!(message.contains("OPENCODE_API_KEY")); |
| 981 | assert!(message.contains("[providers.opencode_zen]")); |
| 982 | assert!(!message.contains("codex login")); |
| 983 | assert!(!message.contains("ChatGPT")); |
| 984 | assert!(!message.contains("auth.json")); |
| 985 | Ok(()) |
| 986 | } |
| 987 | |
| 988 | // GHSA-72w5-pf8h-xfp4 — regression: `allow_shell` must be opt-in. |
| 989 | #[test] |
| 990 | fn allow_shell_defaults_to_false_when_unset() { |
| 991 | let config = Config::default(); |
| 992 | assert_eq!(config.allow_shell, None, "default Config has no opt-in set"); |
| 993 | assert!( |
| 994 | !config.allow_shell(), |
| 995 | "Config::allow_shell() must default to false when no opt-in is recorded" |
| 996 | ); |
| 997 | } |
| 998 | |
| 999 | // The interactive default is shell-on (approval-gated). Both interactive |
| 1000 | // startup and the durable Agent permission baseline (app.rs) read this single |
| 1001 | // method so the default cannot drift between launch modes; an explicit opt-out |
| 1002 | // is still honored. |
| 1003 | #[test] |
| 1004 | fn interactive_allow_shell_defaults_to_true_but_honors_explicit_opt_out() { |
| 1005 | let default_config = Config::default(); |
| 1006 | assert!( |
| 1007 | default_config.interactive_allow_shell(), |
| 1008 | "interactive Agent sessions expose shell by default so approvals can gate commands" |
| 1009 | ); |
| 1010 | |
| 1011 | let opted_out = Config { |
| 1012 | allow_shell: Some(false), |
| 1013 | ..Config::default() |
| 1014 | }; |
| 1015 | assert!( |
| 1016 | !opted_out.interactive_allow_shell(), |
| 1017 | "explicit allow_shell = false still hides shell in interactive sessions" |
| 1018 | ); |
| 1019 | |
| 1020 | let opted_in = Config { |
| 1021 | allow_shell: Some(true), |
| 1022 | ..Config::default() |
| 1023 | }; |
| 1024 | assert!(opted_in.interactive_allow_shell()); |
| 1025 | } |
| 1026 | |
| 1027 | #[test] |
| 1028 | fn prompt_suggestion_scenario() { |
| 1029 | // Scenario consolidation of: prompt_suggestion_defaults_to_false, prompt_suggestion_enabled_when_set_true |
| 1030 | // from prompt_suggestion_defaults_to_false |
| 1031 | { |
| 1032 | let config = Config::default(); |
| 1033 | assert_eq!( |
| 1034 | config.prompt_suggestion, None, |
| 1035 | "default Config must not opt in" |
| 1036 | ); |
| 1037 | assert!( |
| 1038 | !config.prompt_suggestion_enabled(), |
| 1039 | "prompt_suggestion must be opt-in (default off)" |
| 1040 | ); |
| 1041 | } |
| 1042 | // from prompt_suggestion_enabled_when_set_true |
| 1043 | { |
| 1044 | let config = Config { |
| 1045 | prompt_suggestion: Some(true), |
| 1046 | ..Default::default() |
| 1047 | }; |
| 1048 | assert!(config.prompt_suggestion_enabled()); |
| 1049 | } |
| 1050 | } |
| 1051 | |
| 1052 | #[test] |
| 1053 | fn config_loads_sibling_permissions_into_exec_policy_engine() { |
| 1054 | let dir = tempfile::tempdir().expect("tempdir"); |
| 1055 | let config_path = dir.path().join("config.toml"); |
| 1056 | fs::write(&config_path, "model = \"deepseek-v4-pro\"\n").expect("write config"); |
| 1057 | fs::write( |
| 1058 | dir.path().join(codewhale_config::PERMISSIONS_FILE_NAME), |
| 1059 | r#" |
| 1060 | [[rules]] |
| 1061 | tool = "exec_shell" |
| 1062 | command = "cargo test" |
| 1063 | "#, |
| 1064 | ) |
| 1065 | .expect("write permissions"); |
| 1066 | |
| 1067 | let config = Config::load(Some(config_path), None).expect("load config"); |
| 1068 | let decision = config |
| 1069 | .exec_policy_engine |
| 1070 | .check(codewhale_execpolicy::ExecPolicyContext { |
| 1071 | command: "cargo test --workspace", |
| 1072 | cwd: dir.path().to_string_lossy().as_ref(), |
| 1073 | tool: Some("exec_shell"), |
| 1074 | path: None, |
| 1075 | ask_for_approval: codewhale_execpolicy::AskForApproval::OnFailure, |
| 1076 | sandbox_mode: None, |
| 1077 | }) |
| 1078 | .expect("check permission"); |
| 1079 | |
| 1080 | assert!(decision.allow); |
| 1081 | assert!(decision.requires_approval); |
| 1082 | assert_eq!( |
| 1083 | decision.matched_rule.as_deref(), |
| 1084 | Some("tool=exec_shell command=cargo test") |
| 1085 | ); |
| 1086 | } |
| 1087 | |
| 1088 | #[test] |
| 1089 | fn config_loads_sibling_permissions_when_config_file_is_absent() { |
| 1090 | let dir = tempfile::tempdir().expect("tempdir"); |
| 1091 | let config_path = dir.path().join("config.toml"); |
| 1092 | fs::write( |
| 1093 | dir.path().join(codewhale_config::PERMISSIONS_FILE_NAME), |
| 1094 | r#" |
| 1095 | [[rules]] |
| 1096 | tool = "exec_shell" |
| 1097 | command = "npm test" |
| 1098 | "#, |
| 1099 | ) |
| 1100 | .expect("write permissions"); |
| 1101 | |
| 1102 | let config = Config::load(Some(config_path), None).expect("load config"); |
| 1103 | let decision = config |
| 1104 | .exec_policy_engine |
| 1105 | .check(codewhale_execpolicy::ExecPolicyContext { |
| 1106 | command: "npm test -- --runInBand", |
| 1107 | cwd: dir.path().to_string_lossy().as_ref(), |
| 1108 | tool: Some("exec_shell"), |
| 1109 | path: None, |
| 1110 | ask_for_approval: codewhale_execpolicy::AskForApproval::OnFailure, |
| 1111 | sandbox_mode: None, |
| 1112 | }) |
| 1113 | .expect("check permission"); |
| 1114 | |
| 1115 | assert!(decision.requires_approval); |
| 1116 | assert_eq!( |
| 1117 | decision.matched_rule.as_deref(), |
| 1118 | Some("tool=exec_shell command=npm test") |
| 1119 | ); |
| 1120 | } |
| 1121 | |
| 1122 | #[test] |
| 1123 | fn warns_when_allow_shell_nested_under_general_section() { |
| 1124 | // #2589: the reporter's config nested top-level keys under sections that |
| 1125 | // do not exist, so they were silently dropped and shell tools vanished. |
| 1126 | let raw = "[general]\nallow_shell = true\n\n[sandbox]\nsandbox_mode = \"danger-full-access\"\n"; |
| 1127 | let warning = |
| 1128 | warn_on_misplaced_top_level_keys(raw).expect("misplaced keys should produce a warning"); |
| 1129 | assert!(warning.contains("general.allow_shell")); |
| 1130 | assert!(warning.contains("sandbox.sandbox_mode")); |
| 1131 | assert!(warning.contains("#2589")); |
| 1132 | |
| 1133 | // Correctly placed top-level keys produce no warning. |
| 1134 | let ok = "allow_shell = true\nsandbox_mode = \"danger-full-access\"\n"; |
| 1135 | assert!(warn_on_misplaced_top_level_keys(ok).is_none()); |
| 1136 | |
| 1137 | // A parsed config from the correct placement actually enables shell. |
| 1138 | let parsed: ConfigFile = toml::from_str(ok).expect("parse top-level config"); |
| 1139 | assert!(parsed.base.allow_shell()); |
| 1140 | } |
| 1141 | |
| 1142 | #[test] |
| 1143 | fn sandbox_network_access_parses_and_defaults_to_restricted() { |
| 1144 | // Absent key: restricted. Editing the workspace does not imply egress. |
| 1145 | let parsed: ConfigFile = |
| 1146 | toml::from_str("sandbox_mode = \"workspace-write\"\n").expect("parse without the key"); |
| 1147 | assert_eq!(parsed.base.sandbox_network_access, None); |
| 1148 | |
| 1149 | let parsed: ConfigFile = |
| 1150 | toml::from_str("sandbox_network_access = true\n").expect("parse snake_case"); |
| 1151 | assert_eq!(parsed.base.sandbox_network_access, Some(true)); |
| 1152 | |
| 1153 | let parsed: ConfigFile = |
| 1154 | toml::from_str("sandboxNetworkAccess = true\n").expect("parse camelCase alias"); |
| 1155 | assert_eq!(parsed.base.sandbox_network_access, Some(true)); |
| 1156 | |
| 1157 | let parsed: ConfigFile = |
| 1158 | toml::from_str("sandbox_network_access = false\n").expect("parse explicit false"); |
| 1159 | assert_eq!(parsed.base.sandbox_network_access, Some(false)); |
| 1160 | } |
| 1161 | |
| 1162 | #[test] |
| 1163 | fn load_honors_codewhale_home_for_primary_config_path() -> Result<()> { |
| 1164 | let _lock = lock_test_env(); |
| 1165 | let dir = tempfile::tempdir()?; |
| 1166 | let codewhale_home = dir.path().join("isolated-codewhale"); |
| 1167 | fs::create_dir_all(&codewhale_home)?; |
| 1168 | fs::write(codewhale_home.join("config.toml"), "provider = \"zai\"\n")?; |
| 1169 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 1170 | let _codewhale_config = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"); |
| 1171 | let _deepseek_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"); |
| 1172 | |
| 1173 | let expected = codewhale_home.join("config.toml"); |
| 1174 | assert_eq!(default_config_path()?, expected); |
| 1175 | let config = Config::load(None, None)?; |
| 1176 | |
| 1177 | assert_eq!(config.provider.as_deref(), Some("zai")); |
| 1178 | Ok(()) |
| 1179 | } |
| 1180 | |
| 1181 | #[test] |
| 1182 | fn load_accepts_dispatcher_written_camel_case_config_shape() -> Result<()> { |
| 1183 | let _lock = lock_test_env(); |
| 1184 | let dir = tempfile::tempdir()?; |
| 1185 | let codewhale_home = dir.path().join("isolated-codewhale"); |
| 1186 | fs::create_dir_all(&codewhale_home)?; |
| 1187 | fs::write( |
| 1188 | codewhale_home.join("config.toml"), |
| 1189 | r#" |
| 1190 | provider = "zai" |
| 1191 | fallbackProviders = [] |
| 1192 | apiKey = "deepseek-test-key" |
| 1193 | defaultTextModel = "deepseek-v4-pro" |
| 1194 | authMode = "api_key" |
| 1195 | |
| 1196 | [providers.zai] |
| 1197 | apiKey = "zai-test-key" |
| 1198 | authMode = "api_key" |
| 1199 | |
| 1200 | [providers.zai.httpHeaders] |
| 1201 | |
| 1202 | [providers.xiaomiMimo] |
| 1203 | baseUrl = "https://token-plan-sgp.xiaomimimo.com/v1" |
| 1204 | |
| 1205 | [features.enabled] |
| 1206 | shell_tool = true |
| 1207 | subagents = true |
| 1208 | web_search = true |
| 1209 | "#, |
| 1210 | )?; |
| 1211 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 1212 | let _codewhale_config = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"); |
| 1213 | let _deepseek_config = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"); |
| 1214 | |
| 1215 | let config = Config::load(None, None)?; |
| 1216 | |
| 1217 | assert_eq!(config.provider.as_deref(), Some("zai")); |
| 1218 | assert_eq!(config.deepseek_table_api_key(), Some("deepseek-test-key")); |
| 1219 | assert_eq!( |
| 1220 | config.default_text_model.as_deref(), |
| 1221 | Some("deepseek-v4-pro") |
| 1222 | ); |
| 1223 | assert_eq!(config.auth_mode.as_deref(), Some("api_key")); |
| 1224 | let providers = config.providers.as_ref().expect("provider table"); |
| 1225 | assert_eq!(providers.zai.api_key.as_deref(), Some("zai-test-key")); |
| 1226 | assert_eq!(providers.zai.auth_mode.as_deref(), Some("api_key")); |
| 1227 | assert_eq!( |
| 1228 | providers.xiaomi_mimo.base_url.as_deref(), |
| 1229 | Some("https://token-plan-sgp.xiaomimimo.com/v1") |
| 1230 | ); |
| 1231 | let features = config.features(); |
| 1232 | assert!(features.enabled(crate::features::Feature::ShellTool)); |
| 1233 | assert!(features.enabled(crate::features::Feature::Subagents)); |
| 1234 | assert!(features.enabled(crate::features::Feature::WebSearch)); |
| 1235 | Ok(()) |
| 1236 | } |
| 1237 | |
| 1238 | #[test] |
| 1239 | fn tui_config_parses_lifecycle_outbox_table() { |
| 1240 | let raw = r#" |
| 1241 | [lifecycle_outbox] |
| 1242 | path = "~/.codewhale/notifications/outbox.jsonl" |
| 1243 | webhook_url = "https://example.com/hooks/codewhale" |
| 1244 | webhook_token = "secret-token" |
| 1245 | "#; |
| 1246 | let parsed: ConfigFile = toml::from_str(raw).expect("parse lifecycle_outbox config"); |
| 1247 | |
| 1248 | let outbox = parsed |
| 1249 | .base |
| 1250 | .lifecycle_outbox |
| 1251 | .expect("lifecycle_outbox table should parse"); |
| 1252 | assert_eq!( |
| 1253 | outbox.path, |
| 1254 | Some(PathBuf::from("~/.codewhale/notifications/outbox.jsonl")) |
| 1255 | ); |
| 1256 | assert_eq!( |
| 1257 | outbox.webhook_url.as_deref(), |
| 1258 | Some("https://example.com/hooks/codewhale") |
| 1259 | ); |
| 1260 | assert_eq!(outbox.webhook_token.as_deref(), Some("secret-token")); |
| 1261 | |
| 1262 | // Off by default: a config without the table leaves the feature off. |
| 1263 | let absent: ConfigFile = |
| 1264 | toml::from_str("model = \"demo\"").expect("parse config without outbox table"); |
| 1265 | assert!(absent.base.lifecycle_outbox.is_none()); |
| 1266 | } |
| 1267 | |
| 1268 | /// `tui.posture_bar` / `tui.metrics_line` (#5950): absent means full — an |
| 1269 | /// older `config.toml` keeps loading unchanged — and each key takes one of |
| 1270 | /// the three presets. |
| 1271 | #[test] |
| 1272 | fn tui_config_parses_bottom_chrome_row_presets() { |
| 1273 | let raw = r#" |
| 1274 | [tui] |
| 1275 | posture_bar = "compact" |
| 1276 | metrics_line = "hidden" |
| 1277 | "#; |
| 1278 | let parsed: ConfigFile = toml::from_str(raw).expect("parse row presets"); |
| 1279 | let tui = parsed.base.tui.expect("tui table"); |
| 1280 | assert_eq!(tui.posture_bar, Some(ChromeRowPreset::Compact)); |
| 1281 | assert_eq!(tui.metrics_line, Some(ChromeRowPreset::Hidden)); |
| 1282 | |
| 1283 | let absent: ConfigFile = toml::from_str("[tui]\nmouse_capture = true\n").expect("old file"); |
| 1284 | let tui = absent.base.tui.expect("tui table"); |
| 1285 | assert_eq!(tui.posture_bar, None); |
| 1286 | assert_eq!(tui.metrics_line, None); |
| 1287 | assert_eq!( |
| 1288 | tui.posture_bar.unwrap_or_default(), |
| 1289 | ChromeRowPreset::Full, |
| 1290 | "absent means the full row" |
| 1291 | ); |
| 1292 | |
| 1293 | let bad: Result<ConfigFile, _> = toml::from_str("[tui]\nposture_bar = \"tiny\"\n"); |
| 1294 | assert!( |
| 1295 | bad.is_err(), |
| 1296 | "a preset this build does not know is refused, not guessed" |
| 1297 | ); |
| 1298 | |
| 1299 | for (setting, preset) in [ |
| 1300 | ("full", ChromeRowPreset::Full), |
| 1301 | ("compact", ChromeRowPreset::Compact), |
| 1302 | ("hidden", ChromeRowPreset::Hidden), |
| 1303 | ] { |
| 1304 | assert_eq!(ChromeRowPreset::from_setting(setting), Some(preset)); |
| 1305 | assert_eq!( |
| 1306 | ChromeRowPreset::from_setting(&setting.to_uppercase()), |
| 1307 | Some(preset) |
| 1308 | ); |
| 1309 | assert_eq!(preset.as_setting(), setting); |
| 1310 | } |
| 1311 | assert_eq!(ChromeRowPreset::from_setting("tiny"), None); |
| 1312 | } |
| 1313 | |
| 1314 | #[test] |
| 1315 | fn tui_config_parses_control_socket_table() { |
| 1316 | let raw = r#" |
| 1317 | [control_socket] |
| 1318 | enabled = true |
| 1319 | "#; |
| 1320 | let parsed: ConfigFile = toml::from_str(raw).expect("parse control_socket config"); |
| 1321 | |
| 1322 | let socket = parsed |
| 1323 | .base |
| 1324 | .control_socket |
| 1325 | .expect("control_socket table should parse"); |
| 1326 | assert!(socket.enabled); |
| 1327 | |
| 1328 | // Off by default: a config without the table leaves the feature off. |
| 1329 | let absent: ConfigFile = |
| 1330 | toml::from_str("model = \"demo\"").expect("parse config without control_socket table"); |
| 1331 | assert!(absent.base.control_socket.is_none()); |
| 1332 | |
| 1333 | // An empty table stays off. |
| 1334 | let empty: ConfigFile = |
| 1335 | toml::from_str("[control_socket]").expect("parse empty control_socket table"); |
| 1336 | assert!( |
| 1337 | !empty |
| 1338 | .base |
| 1339 | .control_socket |
| 1340 | .expect("table should parse") |
| 1341 | .enabled, |
| 1342 | "empty table must leave the socket off" |
| 1343 | ); |
| 1344 | } |
| 1345 | |
| 1346 | #[test] |
| 1347 | fn tui_config_parses_hotbar_bindings() { |
| 1348 | let raw = r#" |
| 1349 | [[hotbar]] |
| 1350 | slot = 1 |
| 1351 | label = "Plan" |
| 1352 | action = "mode.plan" |
| 1353 | |
| 1354 | [[hotbar]] |
| 1355 | slot = 2 |
| 1356 | action = "session.compact" |
| 1357 | "#; |
| 1358 | let parsed: ConfigFile = toml::from_str(raw).expect("parse hotbar config"); |
| 1359 | |
| 1360 | let resolved = parsed |
| 1361 | .base |
| 1362 | .resolve_hotbar_bindings(&["mode.plan", "session.compact"]); |
| 1363 | |
| 1364 | assert_eq!(resolved.warnings, Vec::new()); |
| 1365 | assert_eq!( |
| 1366 | resolved |
| 1367 | .bindings |
| 1368 | .iter() |
| 1369 | .map(|binding| ( |
| 1370 | binding.slot, |
| 1371 | binding.action.as_str(), |
| 1372 | binding.label.as_deref() |
| 1373 | )) |
| 1374 | .collect::<Vec<_>>(), |
| 1375 | vec![(1, "mode.plan", Some("Plan")), (2, "session.compact", None),] |
| 1376 | ); |
| 1377 | } |
| 1378 | |
| 1379 | #[test] |
| 1380 | fn tui_config_empty_hotbar_array_disables_defaults() { |
| 1381 | let parsed: ConfigFile = toml::from_str("hotbar = []\n").expect("parse empty hotbar"); |
| 1382 | |
| 1383 | let resolved = parsed |
| 1384 | .base |
| 1385 | .resolve_hotbar_bindings(&["mode.plan", "session.compact"]); |
| 1386 | |
| 1387 | assert_eq!(resolved.warnings, Vec::new()); |
| 1388 | assert_eq!(resolved.bindings, Vec::new()); |
| 1389 | } |
| 1390 | |
| 1391 | #[test] |
| 1392 | fn profile_hotbar_override_replaces_entire_user_list() { |
| 1393 | let mut profiles = HashMap::new(); |
| 1394 | profiles.insert( |
| 1395 | "compact".to_string(), |
| 1396 | Config { |
| 1397 | hotbar: Some(vec![codewhale_config::HotbarBindingToml { |
| 1398 | slot: 2, |
| 1399 | action: "session.compact".to_string(), |
| 1400 | label: Some("Compact".to_string()), |
| 1401 | }]), |
| 1402 | ..Config::default() |
| 1403 | }, |
| 1404 | ); |
| 1405 | let config = ConfigFile { |
| 1406 | base: Box::new(Config { |
| 1407 | hotbar: Some(vec![codewhale_config::HotbarBindingToml { |
| 1408 | slot: 1, |
| 1409 | action: "mode.plan".to_string(), |
| 1410 | label: Some("Plan".to_string()), |
| 1411 | }]), |
| 1412 | ..Config::default() |
| 1413 | }), |
| 1414 | profiles: Some(profiles), |
| 1415 | legacy_root: Default::default(), |
| 1416 | }; |
| 1417 | |
| 1418 | let merged = apply_profile(config, Some("compact")).expect("profile"); |
| 1419 | |
| 1420 | assert_eq!( |
| 1421 | merged.hotbar, |
| 1422 | Some(vec![codewhale_config::HotbarBindingToml { |
| 1423 | slot: 2, |
| 1424 | action: "session.compact".to_string(), |
| 1425 | label: Some("Compact".to_string()), |
| 1426 | }]) |
| 1427 | ); |
| 1428 | } |
| 1429 | |
| 1430 | #[test] |
| 1431 | fn profile_without_scenario() { |
| 1432 | // Scenario consolidation of: profile_without_hotbar_keeps_base_hotbar, profile_without_context_does_not_disable_base_context |
| 1433 | // from profile_without_hotbar_keeps_base_hotbar |
| 1434 | { |
| 1435 | let mut profiles = HashMap::new(); |
| 1436 | profiles.insert("work".to_string(), Config::default()); |
| 1437 | let config = ConfigFile { |
| 1438 | base: Box::new(Config { |
| 1439 | hotbar: Some(vec![codewhale_config::HotbarBindingToml { |
| 1440 | slot: 1, |
| 1441 | action: "mode.plan".to_string(), |
| 1442 | label: None, |
| 1443 | }]), |
| 1444 | ..Config::default() |
| 1445 | }), |
| 1446 | profiles: Some(profiles), |
| 1447 | legacy_root: Default::default(), |
| 1448 | }; |
| 1449 | |
| 1450 | let merged = apply_profile(config, Some("work")).expect("profile"); |
| 1451 | |
| 1452 | assert_eq!( |
| 1453 | merged.hotbar, |
| 1454 | Some(vec![codewhale_config::HotbarBindingToml { |
| 1455 | slot: 1, |
| 1456 | action: "mode.plan".to_string(), |
| 1457 | label: None, |
| 1458 | }]) |
| 1459 | ); |
| 1460 | } |
| 1461 | // from profile_without_context_does_not_disable_base_context |
| 1462 | { |
| 1463 | let mut profiles = HashMap::new(); |
| 1464 | profiles.insert("work".to_string(), Config::default()); |
| 1465 | let config = ConfigFile { |
| 1466 | base: Box::new(Config { |
| 1467 | context: ContextConfig { |
| 1468 | project_pack: Some(true), |
| 1469 | }, |
| 1470 | ..Default::default() |
| 1471 | }), |
| 1472 | profiles: Some(profiles), |
| 1473 | legacy_root: Default::default(), |
| 1474 | }; |
| 1475 | |
| 1476 | let merged = apply_profile(config, Some("work")).expect("profile"); |
| 1477 | assert_eq!(merged.context.project_pack, Some(true)); |
| 1478 | } |
| 1479 | } |
| 1480 | |
| 1481 | #[test] |
| 1482 | fn update_config_scenario() { |
| 1483 | // Scenario consolidation of: update_config_defaults_to_enabled_without_uri, update_config_deserializes_disable_and_custom_uri |
| 1484 | // from update_config_defaults_to_enabled_without_uri |
| 1485 | { |
| 1486 | let config = Config::default(); |
| 1487 | assert_eq!(config.update, None); |
| 1488 | assert_eq!(config.update_config(), UpdateConfig::default()); |
| 1489 | assert!(config.update_config().check_for_updates); |
| 1490 | assert_eq!(config.update_config().update_uri(), None); |
| 1491 | } |
| 1492 | // from update_config_deserializes_disable_and_custom_uri |
| 1493 | { |
| 1494 | let config: Config = toml::from_str( |
| 1495 | r#" |
| 1496 | [update] |
| 1497 | check_for_updates = false |
| 1498 | update_uri = "https://mirror.example/releases/latest" |
| 1499 | "#, |
| 1500 | ) |
| 1501 | .expect("update config"); |
| 1502 | |
| 1503 | let update = config.update_config(); |
| 1504 | assert!(!update.check_for_updates); |
| 1505 | assert_eq!( |
| 1506 | update.update_uri(), |
| 1507 | Some("https://mirror.example/releases/latest") |
| 1508 | ); |
| 1509 | } |
| 1510 | } |
| 1511 | |
| 1512 | #[test] |
| 1513 | fn verifier_config_parses_and_merges_overrides() { |
| 1514 | let config: Config = toml::from_str( |
| 1515 | r#" |
| 1516 | [verifier] |
| 1517 | enabled = true |
| 1518 | "#, |
| 1519 | ) |
| 1520 | .expect("parse verifier config"); |
| 1521 | |
| 1522 | let verifier = config.verifier.expect("verifier table"); |
| 1523 | assert!(verifier.enabled); |
| 1524 | |
| 1525 | let merged = merge_config( |
| 1526 | Config { |
| 1527 | verifier: Some(codewhale_config::VerifierConfigToml { enabled: false }), |
| 1528 | ..Config::default() |
| 1529 | }, |
| 1530 | Config { |
| 1531 | verifier: Some(codewhale_config::VerifierConfigToml { enabled: true }), |
| 1532 | ..Config::default() |
| 1533 | }, |
| 1534 | ); |
| 1535 | |
| 1536 | assert!(merged.verifier.expect("merged verifier").enabled); |
| 1537 | } |
| 1538 | |
| 1539 | #[test] |
| 1540 | fn workflow_config_defaults_when_omitted_and_overrides_round_trip() { |
| 1541 | // #4128: omitted `[workflow]` resolves through the accessor to product |
| 1542 | // defaults; explicit overrides load and survive serialize → parse. |
| 1543 | let omitted: Config = toml::from_str("").expect("empty config"); |
| 1544 | assert!(omitted.workflow.is_none()); |
| 1545 | assert_eq!( |
| 1546 | omitted.workflow_config(), |
| 1547 | codewhale_config::WorkflowConfigToml::default() |
| 1548 | ); |
| 1549 | |
| 1550 | let config: Config = toml::from_str( |
| 1551 | r#" |
| 1552 | [workflow] |
| 1553 | automatic = false |
| 1554 | auto_start_read_only = false |
| 1555 | require_approval_for_writes = true |
| 1556 | max_children = 32 |
| 1557 | max_depth = 1 |
| 1558 | default_token_budget = 90000 |
| 1559 | "#, |
| 1560 | ) |
| 1561 | .expect("parse workflow config"); |
| 1562 | |
| 1563 | let workflow = config.workflow.clone().expect("workflow table"); |
| 1564 | assert!(!workflow.automatic); |
| 1565 | assert!(!workflow.auto_start_read_only); |
| 1566 | assert!(workflow.require_approval_for_writes); |
| 1567 | assert_eq!(workflow.max_children, 32); |
| 1568 | assert_eq!(workflow.max_depth, 1); |
| 1569 | assert_eq!(config.workflow_config(), workflow); |
| 1570 | |
| 1571 | let serialized = toml::to_string_pretty(&workflow).expect("serialize workflow"); |
| 1572 | let round_tripped: codewhale_config::WorkflowConfigToml = |
| 1573 | toml::from_str(&serialized).expect("round-trip parse"); |
| 1574 | assert_eq!(round_tripped, workflow); |
| 1575 | |
| 1576 | // Profile/project overlays replace the whole table when present. |
| 1577 | let merged = merge_config( |
| 1578 | Config { |
| 1579 | workflow: Some(codewhale_config::WorkflowConfigToml::default()), |
| 1580 | ..Config::default() |
| 1581 | }, |
| 1582 | Config { |
| 1583 | workflow: Some(workflow.clone()), |
| 1584 | ..Config::default() |
| 1585 | }, |
| 1586 | ); |
| 1587 | assert_eq!(merged.workflow_config(), workflow); |
| 1588 | } |
| 1589 | |
| 1590 | #[test] |
| 1591 | fn window_title_config_parses_and_overlays() { |
| 1592 | // `title` is a plain optional root key: absent config → `None`. |
| 1593 | let omitted: Config = toml::from_str("").expect("empty config"); |
| 1594 | assert_eq!(omitted.title, None); |
| 1595 | |
| 1596 | let config: Config = toml::from_str(r#"title = "workspace-x""#).expect("parse title config"); |
| 1597 | assert_eq!(config.title.as_deref(), Some("workspace-x")); |
| 1598 | |
| 1599 | // Overlay wins over the base when both define a title. |
| 1600 | let merged = merge_config( |
| 1601 | Config { |
| 1602 | title: Some("base-title".to_string()), |
| 1603 | ..Config::default() |
| 1604 | }, |
| 1605 | Config { |
| 1606 | title: Some("override-title".to_string()), |
| 1607 | ..Config::default() |
| 1608 | }, |
| 1609 | ); |
| 1610 | assert_eq!(merged.title.as_deref(), Some("override-title")); |
| 1611 | |
| 1612 | // Base title survives an overlay that does not mention it. |
| 1613 | let merged = merge_config( |
| 1614 | Config { |
| 1615 | title: Some("base-title".to_string()), |
| 1616 | ..Config::default() |
| 1617 | }, |
| 1618 | Config::default(), |
| 1619 | ); |
| 1620 | assert_eq!(merged.title.as_deref(), Some("base-title")); |
| 1621 | } |
| 1622 | |
| 1623 | /// Run `body` with the three Tavily-resolution signals set exactly as given, |
| 1624 | /// restoring the ambient values afterwards. A `Default` pin (and the |
| 1625 | /// Firecrawl China-switch hint) means all three are absent, not just the |
| 1626 | /// legacy `DEEPSEEK_SEARCH_PROVIDER` alias. |
| 1627 | fn with_search_resolution_env<R>(set: &[(&str, &str)], body: impl FnOnce() -> R) -> R { |
| 1628 | let _guard = lock_test_env(); |
| 1629 | let keys = [ |
| 1630 | "CODEWHALE_SEARCH_PROVIDER", |
| 1631 | "DEEPSEEK_SEARCH_PROVIDER", |
| 1632 | "TAVILY_API_KEY", |
| 1633 | ]; |
| 1634 | let previous: Vec<Option<OsString>> = keys.iter().map(env::var_os).collect(); |
| 1635 | for key in keys { |
| 1636 | unsafe { env::remove_var(key) }; |
| 1637 | } |
| 1638 | for (key, value) in set { |
| 1639 | unsafe { env::set_var(key, value) }; |
| 1640 | } |
| 1641 | let output = body(); |
| 1642 | for (key, value) in keys.iter().zip(previous) { |
| 1643 | unsafe { EnvGuard::restore_var(key, value) }; |
| 1644 | } |
| 1645 | output |
| 1646 | } |
| 1647 | |
| 1648 | #[test] |
| 1649 | fn pinned_search_provider_wins_over_provider_native_search() { |
| 1650 | let parse = |toml_text: &str| -> Config { toml::from_str(toml_text).expect("search config") }; |
| 1651 | with_search_resolution_env(&[], || { |
| 1652 | // Nothing configured: native search keeps leading where offered. |
| 1653 | assert_eq!(Config::default().search_native(), None); |
| 1654 | // A pinned provider wins unless native is explicitly re-enabled. |
| 1655 | assert_eq!( |
| 1656 | parse("[search]\nprovider = \"tavily\"\n").search_native(), |
| 1657 | Some(false) |
| 1658 | ); |
| 1659 | assert_eq!( |
| 1660 | parse("[search]\nprovider = \"tavily\"\nnative = true\n").search_native(), |
| 1661 | Some(true) |
| 1662 | ); |
| 1663 | assert_eq!( |
| 1664 | parse("[search]\nnative = false\n").search_native(), |
| 1665 | Some(false) |
| 1666 | ); |
| 1667 | }); |
| 1668 | with_search_resolution_env(&[("CODEWHALE_SEARCH_PROVIDER", "searxng")], || { |
| 1669 | assert_eq!(Config::default().search_native(), Some(false)); |
| 1670 | }); |
| 1671 | with_search_resolution_env(&[("TAVILY_API_KEY", "tvly-test")], || { |
| 1672 | assert_eq!(Config::default().search_native(), Some(false)); |
| 1673 | }); |
| 1674 | } |
| 1675 | |
| 1676 | const SEARCH_CONSENT_ENV: [&str; 14] = [ |
| 1677 | "CODEWHALE_SEARCH_PROVIDER", |
| 1678 | "DEEPSEEK_SEARCH_PROVIDER", |
| 1679 | "CODEWHALE_SEARCH_API_KEY", |
| 1680 | "FIRECRAWL_API_KEY", |
| 1681 | "TAVILY_API_KEY", |
| 1682 | "METASO_API_KEY", |
| 1683 | "BAIDU_SEARCH_API_KEY", |
| 1684 | "VOLCENGINE_API_KEY", |
| 1685 | "VOLCENGINE_ARK_API_KEY", |
| 1686 | "ARK_API_KEY", |
| 1687 | "SOFYA_API_KEY", |
| 1688 | "SERPLY_API_KEY", |
| 1689 | "SEARCHAPI_API_KEY", |
| 1690 | "DEEPSEEK_API_KEY", |
| 1691 | ]; |
| 1692 | |
| 1693 | fn with_search_consent_env<R>(set: &[(&'static str, &str)], body: impl FnOnce() -> R) -> R { |
| 1694 | let _lock = lock_test_env(); |
| 1695 | let _cleared: Vec<EnvVarGuard> = SEARCH_CONSENT_ENV |
| 1696 | .iter() |
| 1697 | .copied() |
| 1698 | .map(EnvVarGuard::remove) |
| 1699 | .collect(); |
| 1700 | let _set: Vec<EnvVarGuard> = set |
| 1701 | .iter() |
| 1702 | .map(|&(key, value)| EnvVarGuard::set(key, value)) |
| 1703 | .collect(); |
| 1704 | body() |
| 1705 | } |
| 1706 | |
| 1707 | #[test] |
| 1708 | fn search_third_party_values_parse_and_resolve() { |
| 1709 | assert_eq!(SearchThirdParty::parse(" ON "), Some(SearchThirdParty::On)); |
| 1710 | assert_eq!(SearchThirdParty::parse("off"), Some(SearchThirdParty::Off)); |
| 1711 | assert_eq!(SearchThirdParty::parse("ask"), Some(SearchThirdParty::Ask)); |
| 1712 | assert_eq!(SearchThirdParty::parse("maybe"), None); |
| 1713 | assert_eq!(SearchThirdParty::default(), SearchThirdParty::Ask); |
| 1714 | for value in [ |
| 1715 | SearchThirdParty::Ask, |
| 1716 | SearchThirdParty::On, |
| 1717 | SearchThirdParty::Off, |
| 1718 | ] { |
| 1719 | assert_eq!(SearchThirdParty::parse(value.as_str()), Some(value)); |
| 1720 | } |
| 1721 | |
| 1722 | let resolved = SearchThirdPartyResolution::resolve(None, false); |
| 1723 | assert_eq!( |
| 1724 | (resolved.value, resolved.source), |
| 1725 | (SearchThirdParty::Ask, SearchThirdPartySource::Default) |
| 1726 | ); |
| 1727 | let resolved = SearchThirdPartyResolution::resolve(None, true); |
| 1728 | assert_eq!( |
| 1729 | (resolved.value, resolved.source), |
| 1730 | (SearchThirdParty::On, SearchThirdPartySource::Implied) |
| 1731 | ); |
| 1732 | let resolved = SearchThirdPartyResolution::resolve(Some(SearchThirdParty::Off), true); |
| 1733 | assert_eq!( |
| 1734 | (resolved.value, resolved.source), |
| 1735 | (SearchThirdParty::Off, SearchThirdPartySource::Config) |
| 1736 | ); |
| 1737 | |
| 1738 | let disk_ask = PersistedSearchChoice::default(); |
| 1739 | let resolved = SearchThirdPartyResolution::with_persisted( |
| 1740 | Some(disk_ask), |
| 1741 | Some(SearchThirdParty::On), |
| 1742 | false, |
| 1743 | ); |
| 1744 | assert_eq!( |
| 1745 | resolved.value, |
| 1746 | SearchThirdParty::Ask, |
| 1747 | "the file wins over a stale load" |
| 1748 | ); |
| 1749 | let disk_pinned = PersistedSearchChoice { |
| 1750 | third_party: None, |
| 1751 | provider: Some(SearchProvider::Bing), |
| 1752 | }; |
| 1753 | let resolved = SearchThirdPartyResolution::with_persisted(Some(disk_pinned), None, false); |
| 1754 | assert_eq!( |
| 1755 | (resolved.value, resolved.source), |
| 1756 | (SearchThirdParty::On, SearchThirdPartySource::Implied) |
| 1757 | ); |
| 1758 | let resolved = |
| 1759 | SearchThirdPartyResolution::with_persisted(None, Some(SearchThirdParty::Off), true); |
| 1760 | assert_eq!(resolved.value, SearchThirdParty::Off); |
| 1761 | } |
| 1762 | |
| 1763 | #[test] |
| 1764 | fn search_setup_implies_third_party_consent() { |
| 1765 | let parse = |toml_text: &str| -> Config { toml::from_str(toml_text).expect("search config") }; |
| 1766 | with_search_consent_env(&[], || { |
| 1767 | let resolved = Config::default().search_third_party_resolution(); |
| 1768 | assert_eq!( |
| 1769 | (resolved.value, resolved.source), |
| 1770 | (SearchThirdParty::Ask, SearchThirdPartySource::Default) |
| 1771 | ); |
| 1772 | assert!(parse("[search]\nprovider = \"duckduckgo\"\n").search_consent_implied()); |
| 1773 | assert!(parse("[search]\napi_key = \"fc-key\"\n").search_consent_implied()); |
| 1774 | assert!(!parse("[search]\napi_key = \" \"\n").search_consent_implied()); |
| 1775 | let explicit = parse("[search]\nprovider = \"bing\"\nthird_party = \"off\"\n") |
| 1776 | .search_third_party_resolution(); |
| 1777 | assert_eq!( |
| 1778 | (explicit.value, explicit.source), |
| 1779 | (SearchThirdParty::Off, SearchThirdPartySource::Config) |
| 1780 | ); |
| 1781 | }); |
| 1782 | for (key, value) in [ |
| 1783 | ("FIRECRAWL_API_KEY", "fc-test"), |
| 1784 | ("TAVILY_API_KEY", "tvly-test"), |
| 1785 | ("CODEWHALE_SEARCH_PROVIDER", "bing"), |
| 1786 | ] { |
| 1787 | with_search_consent_env(&[(key, value)], || { |
| 1788 | let resolved = Config::default().search_third_party_resolution(); |
| 1789 | assert_eq!( |
| 1790 | (resolved.value, resolved.source), |
| 1791 | (SearchThirdParty::On, SearchThirdPartySource::Implied), |
| 1792 | "{key}" |
| 1793 | ); |
| 1794 | }); |
| 1795 | } |
| 1796 | } |
| 1797 | |
| 1798 | #[test] |
| 1799 | fn search_provider_options_offer_any_keyless_then_present_keys() { |
| 1800 | let ids = |options: Vec<SearchProviderOption>| -> Vec<String> { |
| 1801 | options.into_iter().map(|option| option.id).collect() |
| 1802 | }; |
| 1803 | with_search_consent_env(&[], || { |
| 1804 | let options = search_provider_options(SearchProvider::Firecrawl, None); |
| 1805 | assert_eq!(options[0].label, "Any"); |
| 1806 | assert!(options[0].keyless); |
| 1807 | assert_eq!(ids(options), ["any", "firecrawl", "duckduckgo", "bing"]); |
| 1808 | assert_eq!( |
| 1809 | ids(search_provider_options( |
| 1810 | SearchProvider::Metaso, |
| 1811 | Some("mk-1") |
| 1812 | )), |
| 1813 | ["any", "firecrawl", "duckduckgo", "bing", "metaso"] |
| 1814 | ); |
| 1815 | assert_eq!( |
| 1816 | ids(search_provider_options( |
| 1817 | SearchProvider::Firecrawl, |
| 1818 | Some("tvly-abc") |
| 1819 | )), |
| 1820 | ["any", "firecrawl", "duckduckgo", "bing", "tavily"] |
| 1821 | ); |
| 1822 | assert!(!search_provider_options(SearchProvider::Metaso, Some("mk-1"))[0].keyless); |
| 1823 | }); |
| 1824 | with_search_consent_env(&[("SERPLY_API_KEY", "s"), ("TAVILY_API_KEY", "t")], || { |
| 1825 | let options = search_provider_options(SearchProvider::Firecrawl, None); |
| 1826 | assert_eq!( |
| 1827 | ids(options.clone()), |
| 1828 | ["any", "firecrawl", "duckduckgo", "bing", "tavily", "serply"] |
| 1829 | ); |
| 1830 | assert!(options.iter().skip(4).all(|option| !option.keyless)); |
| 1831 | }); |
| 1832 | } |
| 1833 | |
| 1834 | #[test] |
| 1835 | fn persisted_search_choice_reads_only_the_root_search_table() { |
| 1836 | let dir = tempfile::tempdir().expect("tempdir"); |
| 1837 | let path = dir.path().join("config.toml"); |
| 1838 | assert_eq!( |
| 1839 | read_persisted_search_choice(&path).expect("missing file"), |
| 1840 | PersistedSearchChoice::default() |
| 1841 | ); |
| 1842 | std::fs::write( |
| 1843 | &path, |
| 1844 | "[search]\nthird_party = \"off\"\nprovider = \"tavily\"\n[profiles.work.search]\nthird_party = \"on\"\n", |
| 1845 | ) |
| 1846 | .expect("write"); |
| 1847 | assert_eq!( |
| 1848 | read_persisted_search_choice(&path).expect("read"), |
| 1849 | PersistedSearchChoice { |
| 1850 | third_party: Some(SearchThirdParty::Off), |
| 1851 | provider: Some(SearchProvider::Tavily), |
| 1852 | } |
| 1853 | ); |
| 1854 | std::fs::write(&path, "[search\n").expect("write"); |
| 1855 | assert!(read_persisted_search_choice(&path).is_err()); |
| 1856 | } |
| 1857 | |
| 1858 | #[test] |
| 1859 | fn search_provider_scenario() { |
| 1860 | // Scenario consolidation of: search_provider_defaults_to_firecrawl, search_provider_resolution_reports_default_source, search_provider_resolution_reports_config_source, search_provider_resolution_reports_env_override_source, search_provider_env_override_accepts_baidu, search_provider_resolution_ignores_invalid_env_override |
| 1861 | // from search_provider_defaults_to_firecrawl |
| 1862 | { |
| 1863 | assert_eq!(SearchProvider::default(), SearchProvider::Firecrawl); |
| 1864 | assert_eq!( |
| 1865 | SearchProvider::parse("fire-crawl"), |
| 1866 | Some(SearchProvider::Firecrawl) |
| 1867 | ); |
| 1868 | assert_eq!(SearchProvider::Firecrawl.as_str(), "firecrawl"); |
| 1869 | } |
| 1870 | // from search_provider_resolution_reports_default_source |
| 1871 | // (empty config, no env) |
| 1872 | with_search_resolution_env(&[], || { |
| 1873 | let config = Config::default(); |
| 1874 | let resolution = config.search_provider_resolution(); |
| 1875 | |
| 1876 | assert_eq!(resolution.provider, SearchProvider::Firecrawl); |
| 1877 | assert_eq!(resolution.source, SearchProviderSource::Default); |
| 1878 | // Autodetect never writes a provider into the config view. |
| 1879 | assert_eq!( |
| 1880 | config.search.as_ref().and_then(|search| search.provider), |
| 1881 | None |
| 1882 | ); |
| 1883 | }); |
| 1884 | // `TAVILY_API_KEY=tvly-test`, provider unset |
| 1885 | with_search_resolution_env(&[("TAVILY_API_KEY", "tvly-test")], || { |
| 1886 | let config = Config::default(); |
| 1887 | let resolution = config.search_provider_resolution(); |
| 1888 | |
| 1889 | assert_eq!(resolution.provider, SearchProvider::Tavily); |
| 1890 | assert_eq!(resolution.source, SearchProviderSource::TavilyKey); |
| 1891 | assert_eq!(resolution.source.as_str(), "tavily key"); |
| 1892 | assert_eq!(resolution.provider.as_str(), "tavily"); |
| 1893 | // Autodetect is runtime-only: `config.search.provider` stays unset. |
| 1894 | assert_eq!( |
| 1895 | config.search.as_ref().and_then(|search| search.provider), |
| 1896 | None |
| 1897 | ); |
| 1898 | }); |
| 1899 | // `TAVILY_API_KEY=not-a-tvly-prefix`, provider unset — a dedicated env key |
| 1900 | // is never prefix-checked. |
| 1901 | with_search_resolution_env(&[("TAVILY_API_KEY", "not-a-tvly-prefix")], || { |
| 1902 | let resolution = Config::default().search_provider_resolution(); |
| 1903 | |
| 1904 | assert_eq!(resolution.provider, SearchProvider::Tavily); |
| 1905 | assert_eq!(resolution.source, SearchProviderSource::TavilyKey); |
| 1906 | }); |
| 1907 | // `[search] api_key = "tvly-test"`, provider unset — also the shape left by |
| 1908 | // `CODEWHALE_SEARCH_API_KEY=tvly-test` after `apply_env_overrides`. |
| 1909 | with_search_resolution_env(&[], || { |
| 1910 | let config: Config = toml::from_str( |
| 1911 | r#" |
| 1912 | [search] |
| 1913 | api_key = "tvly-test" |
| 1914 | "#, |
| 1915 | ) |
| 1916 | .expect("search config"); |
| 1917 | let resolution = config.search_provider_resolution(); |
| 1918 | |
| 1919 | assert_eq!(resolution.provider, SearchProvider::Tavily); |
| 1920 | assert_eq!(resolution.source, SearchProviderSource::TavilyKey); |
| 1921 | assert_eq!( |
| 1922 | config.search.as_ref().and_then(|search| search.provider), |
| 1923 | None |
| 1924 | ); |
| 1925 | }); |
| 1926 | // A non-`tvly-` generic key never autodetects. Covers |
| 1927 | // `CODEWHALE_SEARCH_API_KEY=doctor-offline-search-sentinel` and any |
| 1928 | // Firecrawl `fc-` generic value. |
| 1929 | with_search_resolution_env(&[], || { |
| 1930 | let config: Config = toml::from_str( |
| 1931 | r#" |
| 1932 | [search] |
| 1933 | api_key = "doctor-offline-search-sentinel" |
| 1934 | "#, |
| 1935 | ) |
| 1936 | .expect("search config"); |
| 1937 | let resolution = config.search_provider_resolution(); |
| 1938 | |
| 1939 | assert_eq!(resolution.provider, SearchProvider::Firecrawl); |
| 1940 | assert_eq!(resolution.source, SearchProviderSource::Default); |
| 1941 | }); |
| 1942 | // Dedicated provider keys that are not the Tavily signal leave the |
| 1943 | // Firecrawl default in place. |
| 1944 | with_search_resolution_env( |
| 1945 | &[ |
| 1946 | ("FIRECRAWL_API_KEY", "fc-test"), |
| 1947 | ("SOFYA_API_KEY", "ay_live_test"), |
| 1948 | ], |
| 1949 | || { |
| 1950 | let resolution = Config::default().search_provider_resolution(); |
| 1951 | |
| 1952 | assert_eq!(resolution.provider, SearchProvider::Firecrawl); |
| 1953 | assert_eq!(resolution.source, SearchProviderSource::Default); |
| 1954 | }, |
| 1955 | ); |
| 1956 | // Explicit Firecrawl wins over a Tavily key. |
| 1957 | with_search_resolution_env(&[("TAVILY_API_KEY", "tvly-test")], || { |
| 1958 | let config: Config = toml::from_str( |
| 1959 | r#" |
| 1960 | [search] |
| 1961 | provider = "firecrawl" |
| 1962 | "#, |
| 1963 | ) |
| 1964 | .expect("search config"); |
| 1965 | let resolution = config.search_provider_resolution(); |
| 1966 | |
| 1967 | assert_eq!(resolution.provider, SearchProvider::Firecrawl); |
| 1968 | assert_eq!(resolution.source, SearchProviderSource::Config); |
| 1969 | }); |
| 1970 | // An env override outranks both the config pin and the Tavily signal. |
| 1971 | with_search_resolution_env( |
| 1972 | &[ |
| 1973 | ("CODEWHALE_SEARCH_PROVIDER", "firecrawl"), |
| 1974 | ("TAVILY_API_KEY", "tvly-test"), |
| 1975 | ], |
| 1976 | || { |
| 1977 | let resolution = Config::default().search_provider_resolution(); |
| 1978 | |
| 1979 | assert_eq!(resolution.provider, SearchProvider::Firecrawl); |
| 1980 | assert_eq!(resolution.source, SearchProviderSource::EnvOverride); |
| 1981 | }, |
| 1982 | ); |
| 1983 | |
| 1984 | // from search_provider_resolution_reports_config_source |
| 1985 | with_search_resolution_env(&[], || { |
| 1986 | let config: Config = toml::from_str( |
| 1987 | r#" |
| 1988 | [search] |
| 1989 | provider = "tavily" |
| 1990 | "#, |
| 1991 | ) |
| 1992 | .expect("search config"); |
| 1993 | |
| 1994 | let resolution = config.search_provider_resolution(); |
| 1995 | |
| 1996 | assert_eq!(resolution.provider, SearchProvider::Tavily); |
| 1997 | assert_eq!(resolution.source, SearchProviderSource::Config); |
| 1998 | }); |
| 1999 | // from search_provider_resolution_reports_env_override_source |
| 2000 | with_search_resolution_env(&[("CODEWHALE_SEARCH_PROVIDER", "bocha")], || { |
| 2001 | let config: Config = toml::from_str( |
| 2002 | r#" |
| 2003 | [search] |
| 2004 | provider = "duckduckgo" |
| 2005 | "#, |
| 2006 | ) |
| 2007 | .expect("search config"); |
| 2008 | |
| 2009 | let resolution = config.search_provider_resolution(); |
| 2010 | |
| 2011 | assert_eq!(resolution.provider, SearchProvider::Bocha); |
| 2012 | assert_eq!(resolution.source, SearchProviderSource::EnvOverride); |
| 2013 | }); |
| 2014 | // The legacy alias still resolves the same way. |
| 2015 | with_search_resolution_env(&[("DEEPSEEK_SEARCH_PROVIDER", "bocha")], || { |
| 2016 | let config: Config = toml::from_str( |
| 2017 | r#" |
| 2018 | [search] |
| 2019 | provider = "duckduckgo" |
| 2020 | "#, |
| 2021 | ) |
| 2022 | .expect("search config"); |
| 2023 | |
| 2024 | let resolution = config.search_provider_resolution(); |
| 2025 | |
| 2026 | assert_eq!(resolution.provider, SearchProvider::Bocha); |
| 2027 | assert_eq!(resolution.source, SearchProviderSource::EnvOverride); |
| 2028 | }); |
| 2029 | // from search_provider_env_override_accepts_baidu |
| 2030 | with_search_resolution_env(&[("CODEWHALE_SEARCH_PROVIDER", "baidu")], || { |
| 2031 | let config: Config = toml::from_str( |
| 2032 | r#" |
| 2033 | [search] |
| 2034 | provider = "duckduckgo" |
| 2035 | "#, |
| 2036 | ) |
| 2037 | .expect("search config"); |
| 2038 | |
| 2039 | let resolution = config.search_provider_resolution(); |
| 2040 | |
| 2041 | assert_eq!(resolution.provider, SearchProvider::Baidu); |
| 2042 | assert_eq!(resolution.source, SearchProviderSource::EnvOverride); |
| 2043 | }); |
| 2044 | // from search_provider_resolution_ignores_invalid_env_override |
| 2045 | with_search_resolution_env(&[("CODEWHALE_SEARCH_PROVIDER", "not-a-provider")], || { |
| 2046 | let config: Config = toml::from_str( |
| 2047 | r#" |
| 2048 | [search] |
| 2049 | provider = "tavily" |
| 2050 | "#, |
| 2051 | ) |
| 2052 | .expect("search config"); |
| 2053 | |
| 2054 | let resolution = config.search_provider_resolution(); |
| 2055 | |
| 2056 | assert_eq!(resolution.provider, SearchProvider::Tavily); |
| 2057 | assert_eq!(resolution.source, SearchProviderSource::Config); |
| 2058 | }); |
| 2059 | } |
| 2060 | |
| 2061 | #[test] |
| 2062 | fn tools_always_load_parses_and_trims_names() { |
| 2063 | let parsed: ConfigFile = toml::from_str( |
| 2064 | r#" |
| 2065 | [tools] |
| 2066 | always_load = ["git_show", " notify ", ""] |
| 2067 | "#, |
| 2068 | ) |
| 2069 | .expect("tools config"); |
| 2070 | |
| 2071 | let names = parsed.base.tools_always_load(); |
| 2072 | |
| 2073 | assert!(names.contains("git_show")); |
| 2074 | assert!(names.contains("notify")); |
| 2075 | assert!(!names.contains("")); |
| 2076 | } |
| 2077 | |
| 2078 | #[test] |
| 2079 | fn user_input_timeout_defaults_disabled_and_clamps() { |
| 2080 | let parsed: ConfigFile = toml::from_str("").expect("empty config"); |
| 2081 | assert_eq!(parsed.base.user_input_timeout(), None); |
| 2082 | |
| 2083 | let parsed: ConfigFile = toml::from_str( |
| 2084 | r#" |
| 2085 | [tools] |
| 2086 | user_input_timeout_seconds = 900 |
| 2087 | "#, |
| 2088 | ) |
| 2089 | .expect("tools config"); |
| 2090 | assert_eq!( |
| 2091 | parsed.base.user_input_timeout(), |
| 2092 | Some(std::time::Duration::from_secs(900)) |
| 2093 | ); |
| 2094 | |
| 2095 | // An explicit 0 is the documented "wait forever" value, preserved as |
| 2096 | // zero rather than defaulted or clamped away. |
| 2097 | let parsed: ConfigFile = toml::from_str( |
| 2098 | r#" |
| 2099 | [tools] |
| 2100 | user_input_timeout_seconds = 0 |
| 2101 | "#, |
| 2102 | ) |
| 2103 | .expect("tools config"); |
| 2104 | assert_eq!( |
| 2105 | parsed.base.user_input_timeout(), |
| 2106 | Some(std::time::Duration::ZERO) |
| 2107 | ); |
| 2108 | |
| 2109 | let parsed: ConfigFile = toml::from_str( |
| 2110 | r#" |
| 2111 | [tools] |
| 2112 | user_input_timeout_seconds = 999999 |
| 2113 | "#, |
| 2114 | ) |
| 2115 | .expect("tools config"); |
| 2116 | assert_eq!( |
| 2117 | parsed.base.user_input_timeout(), |
| 2118 | Some(std::time::Duration::from_secs(86_400)) |
| 2119 | ); |
| 2120 | } |
| 2121 | |
| 2122 | #[test] |
| 2123 | fn approval_timeout_defaults_unbounded_and_clamps() { |
| 2124 | let parsed: ConfigFile = toml::from_str("").expect("empty config"); |
| 2125 | assert_eq!(parsed.base.approval_timeout(), None); |
| 2126 | |
| 2127 | // The card stays unbounded when only presentation is configured. |
| 2128 | let parsed: ConfigFile = toml::from_str( |
| 2129 | r#" |
| 2130 | [approval] |
| 2131 | default_selection = "allow_once" |
| 2132 | "#, |
| 2133 | ) |
| 2134 | .expect("approval config"); |
| 2135 | assert_eq!(parsed.base.approval_timeout(), None); |
| 2136 | |
| 2137 | let parsed: ConfigFile = toml::from_str( |
| 2138 | r#" |
| 2139 | [approval] |
| 2140 | timeout_seconds = 300 |
| 2141 | "#, |
| 2142 | ) |
| 2143 | .expect("approval config"); |
| 2144 | assert_eq!( |
| 2145 | parsed.base.approval_timeout(), |
| 2146 | Some(std::time::Duration::from_secs(300)) |
| 2147 | ); |
| 2148 | |
| 2149 | // An explicit 0 follows the repo's "wait forever" convention (#6101). |
| 2150 | let parsed: ConfigFile = toml::from_str( |
| 2151 | r#" |
| 2152 | [approval] |
| 2153 | timeout_seconds = 0 |
| 2154 | "#, |
| 2155 | ) |
| 2156 | .expect("approval config"); |
| 2157 | assert_eq!(parsed.base.approval_timeout(), None); |
| 2158 | |
| 2159 | let parsed: ConfigFile = toml::from_str( |
| 2160 | r#" |
| 2161 | [approval] |
| 2162 | timeout_seconds = 999999 |
| 2163 | "#, |
| 2164 | ) |
| 2165 | .expect("approval config"); |
| 2166 | assert_eq!( |
| 2167 | parsed.base.approval_timeout(), |
| 2168 | Some(std::time::Duration::from_secs(86_400)) |
| 2169 | ); |
| 2170 | } |
| 2171 | |
| 2172 | #[test] |
| 2173 | fn explicit_duckduckgo_search_provider_is_preserved() { |
| 2174 | let config: Config = toml::from_str( |
| 2175 | r#" |
| 2176 | [search] |
| 2177 | provider = "duckduckgo" |
| 2178 | "#, |
| 2179 | ) |
| 2180 | .expect("search config"); |
| 2181 | |
| 2182 | assert_eq!( |
| 2183 | config.search.and_then(|search| search.provider), |
| 2184 | Some(SearchProvider::DuckDuckGo) |
| 2185 | ); |
| 2186 | } |
| 2187 | |
| 2188 | #[test] |
| 2189 | fn search_config_preserves_custom_base_url() { |
| 2190 | let config: Config = toml::from_str( |
| 2191 | r#" |
| 2192 | [search] |
| 2193 | provider = "duckduckgo" |
| 2194 | base_url = "https://search.internal.example/html/" |
| 2195 | "#, |
| 2196 | ) |
| 2197 | .expect("search config"); |
| 2198 | |
| 2199 | let search = config.search.expect("search table"); |
| 2200 | assert_eq!(search.provider, Some(SearchProvider::DuckDuckGo)); |
| 2201 | assert_eq!( |
| 2202 | search.base_url.as_deref(), |
| 2203 | Some("https://search.internal.example/html/") |
| 2204 | ); |
| 2205 | } |
| 2206 | |
| 2207 | #[test] |
| 2208 | fn explicit_searxng_search_provider_is_preserved() { |
| 2209 | let config: Config = toml::from_str( |
| 2210 | r#" |
| 2211 | [search] |
| 2212 | provider = "searxng" |
| 2213 | base_url = "https://search.internal.example/" |
| 2214 | "#, |
| 2215 | ) |
| 2216 | .expect("search config"); |
| 2217 | |
| 2218 | let search = config.search.expect("search table"); |
| 2219 | assert_eq!(search.provider, Some(SearchProvider::Searxng)); |
| 2220 | assert_eq!( |
| 2221 | search.base_url.as_deref(), |
| 2222 | Some("https://search.internal.example/") |
| 2223 | ); |
| 2224 | } |
| 2225 | |
| 2226 | #[test] |
| 2227 | fn searxng_search_provider_aliases_parse_and_round_trip() { |
| 2228 | assert_eq!( |
| 2229 | SearchProvider::parse("searxng"), |
| 2230 | Some(SearchProvider::Searxng) |
| 2231 | ); |
| 2232 | assert_eq!( |
| 2233 | SearchProvider::parse("searx-ng"), |
| 2234 | Some(SearchProvider::Searxng) |
| 2235 | ); |
| 2236 | assert_eq!( |
| 2237 | SearchProvider::parse("searx_ng"), |
| 2238 | Some(SearchProvider::Searxng) |
| 2239 | ); |
| 2240 | assert_eq!( |
| 2241 | SearchProvider::parse("searx"), |
| 2242 | Some(SearchProvider::Searxng) |
| 2243 | ); |
| 2244 | assert_eq!(SearchProvider::Searxng.as_str(), "searxng"); |
| 2245 | } |
| 2246 | |
| 2247 | #[test] |
| 2248 | fn explicit_baidu_search_provider_is_preserved() { |
| 2249 | let config: Config = toml::from_str( |
| 2250 | r#" |
| 2251 | [search] |
| 2252 | provider = "baidu" |
| 2253 | "#, |
| 2254 | ) |
| 2255 | .expect("search config"); |
| 2256 | |
| 2257 | assert_eq!( |
| 2258 | config.search.and_then(|search| search.provider), |
| 2259 | Some(SearchProvider::Baidu) |
| 2260 | ); |
| 2261 | } |
| 2262 | |
| 2263 | #[test] |
| 2264 | fn baidu_search_provider_aliases_parse() { |
| 2265 | assert_eq!(SearchProvider::parse("baidu"), Some(SearchProvider::Baidu)); |
| 2266 | assert_eq!( |
| 2267 | SearchProvider::parse("baidu-search"), |
| 2268 | Some(SearchProvider::Baidu) |
| 2269 | ); |
| 2270 | assert_eq!( |
| 2271 | SearchProvider::parse("baidu_ai_search"), |
| 2272 | Some(SearchProvider::Baidu) |
| 2273 | ); |
| 2274 | } |
| 2275 | |
| 2276 | #[test] |
| 2277 | fn volcengine_search_provider_aliases_parse_and_deserialize() { |
| 2278 | assert_eq!( |
| 2279 | SearchProvider::parse("volcengine"), |
| 2280 | Some(SearchProvider::Volcengine) |
| 2281 | ); |
| 2282 | assert_eq!( |
| 2283 | SearchProvider::parse("volcengine-ark"), |
| 2284 | Some(SearchProvider::Volcengine) |
| 2285 | ); |
| 2286 | |
| 2287 | let config: Config = toml::from_str( |
| 2288 | r#" |
| 2289 | [search] |
| 2290 | provider = "volcengine-ark" |
| 2291 | "#, |
| 2292 | ) |
| 2293 | .expect("volcengine search config"); |
| 2294 | |
| 2295 | assert_eq!( |
| 2296 | config.search.and_then(|search| search.provider), |
| 2297 | Some(SearchProvider::Volcengine) |
| 2298 | ); |
| 2299 | } |
| 2300 | |
| 2301 | #[test] |
| 2302 | fn explicit_sofya_search_provider_is_preserved() { |
| 2303 | let config: Config = toml::from_str( |
| 2304 | r#" |
| 2305 | [search] |
| 2306 | provider = "sofya" |
| 2307 | "#, |
| 2308 | ) |
| 2309 | .expect("sofya search config"); |
| 2310 | |
| 2311 | assert_eq!( |
| 2312 | config.search.and_then(|search| search.provider), |
| 2313 | Some(SearchProvider::Sofya) |
| 2314 | ); |
| 2315 | } |
| 2316 | |
| 2317 | #[test] |
| 2318 | fn sofya_search_provider_parses_and_round_trips() { |
| 2319 | assert_eq!(SearchProvider::parse("sofya"), Some(SearchProvider::Sofya)); |
| 2320 | assert_eq!(SearchProvider::parse("Sofya"), Some(SearchProvider::Sofya)); |
| 2321 | assert_eq!(SearchProvider::Sofya.as_str(), "sofya"); |
| 2322 | } |
| 2323 | |
| 2324 | #[test] |
| 2325 | fn explicit_serply_search_provider_is_preserved() { |
| 2326 | let config: Config = toml::from_str( |
| 2327 | r#" |
| 2328 | [search] |
| 2329 | provider = "serply" |
| 2330 | "#, |
| 2331 | ) |
| 2332 | .expect("serply search config"); |
| 2333 | |
| 2334 | assert_eq!( |
| 2335 | config.search.and_then(|search| search.provider), |
| 2336 | Some(SearchProvider::Serply) |
| 2337 | ); |
| 2338 | } |
| 2339 | |
| 2340 | #[test] |
| 2341 | fn serply_search_provider_parses_and_round_trips() { |
| 2342 | assert_eq!( |
| 2343 | SearchProvider::parse("serply"), |
| 2344 | Some(SearchProvider::Serply) |
| 2345 | ); |
| 2346 | assert_eq!( |
| 2347 | SearchProvider::parse("Serply"), |
| 2348 | Some(SearchProvider::Serply) |
| 2349 | ); |
| 2350 | assert_eq!(SearchProvider::Serply.as_str(), "serply"); |
| 2351 | } |
| 2352 | |
| 2353 | #[test] |
| 2354 | fn explicit_searchapi_search_provider_is_preserved() { |
| 2355 | let config: Config = toml::from_str( |
| 2356 | r#" |
| 2357 | [search] |
| 2358 | provider = "searchapi" |
| 2359 | "#, |
| 2360 | ) |
| 2361 | .expect("searchapi search config"); |
| 2362 | |
| 2363 | assert_eq!( |
| 2364 | config.search.and_then(|search| search.provider), |
| 2365 | Some(SearchProvider::SearchApi) |
| 2366 | ); |
| 2367 | } |
| 2368 | |
| 2369 | #[test] |
| 2370 | fn searchapi_search_provider_parses_aliases_and_round_trips() { |
| 2371 | for value in ["searchapi", "SearchApi", "search-api", "search_api"] { |
| 2372 | assert_eq!( |
| 2373 | SearchProvider::parse(value), |
| 2374 | Some(SearchProvider::SearchApi), |
| 2375 | "{value}" |
| 2376 | ); |
| 2377 | } |
| 2378 | assert_eq!(SearchProvider::SearchApi.as_str(), "searchapi"); |
| 2379 | let json = serde_json::to_string(&SearchProvider::SearchApi).expect("serialize"); |
| 2380 | assert_eq!(json, "\"searchapi\""); |
| 2381 | assert_eq!( |
| 2382 | serde_json::from_str::<SearchProvider>(&json).expect("deserialize"), |
| 2383 | SearchProvider::SearchApi |
| 2384 | ); |
| 2385 | } |
| 2386 | |
| 2387 | #[test] |
| 2388 | fn live_search_provider_update_preserves_environment_precedence() { |
| 2389 | let _guard = lock_test_env(); |
| 2390 | let previous_codewhale = env::var_os("CODEWHALE_SEARCH_PROVIDER"); |
| 2391 | let previous_deepseek = env::var_os("DEEPSEEK_SEARCH_PROVIDER"); |
| 2392 | unsafe { |
| 2393 | env::set_var("CODEWHALE_SEARCH_PROVIDER", "bocha"); |
| 2394 | env::remove_var("DEEPSEEK_SEARCH_PROVIDER"); |
| 2395 | } |
| 2396 | let mut config = Config::default(); |
| 2397 | |
| 2398 | let effective = config.set_search_provider(SearchProvider::DuckDuckGo); |
| 2399 | |
| 2400 | unsafe { |
| 2401 | EnvGuard::restore_var("CODEWHALE_SEARCH_PROVIDER", previous_codewhale); |
| 2402 | EnvGuard::restore_var("DEEPSEEK_SEARCH_PROVIDER", previous_deepseek); |
| 2403 | } |
| 2404 | assert_eq!(effective, SearchProvider::Bocha); |
| 2405 | assert_eq!( |
| 2406 | config.search.and_then(|search| search.provider), |
| 2407 | Some(SearchProvider::DuckDuckGo), |
| 2408 | "the requested config value should still be retained beneath the override" |
| 2409 | ); |
| 2410 | } |
| 2411 | |
| 2412 | #[test] |
| 2413 | fn notification_defaults_and_live_updates_share_one_consistent_model() { |
| 2414 | let mut notifications = NotificationsConfig::default(); |
| 2415 | assert_eq!(notifications.threshold_secs, 30); |
| 2416 | assert_eq!(notifications.completion_sound, CompletionSound::Off); |
| 2417 | assert_eq!( |
| 2418 | Config::default().notifications_config().threshold_secs, |
| 2419 | notifications.threshold_secs |
| 2420 | ); |
| 2421 | assert_eq!( |
| 2422 | Config::default().notifications_config().completion_sound, |
| 2423 | CompletionSound::Off, |
| 2424 | "a fresh install must never opt itself into an audible completion cue" |
| 2425 | ); |
| 2426 | |
| 2427 | notifications |
| 2428 | .apply_update(NotificationConfigUpdate::Method(NotificationMethod::Osc9)) |
| 2429 | .unwrap(); |
| 2430 | notifications |
| 2431 | .apply_update(NotificationConfigUpdate::Quiet(true)) |
| 2432 | .unwrap(); |
| 2433 | |
| 2434 | assert_eq!(notifications.method, NotificationMethod::Osc9); |
| 2435 | assert!(notifications.quiet); |
| 2436 | assert_eq!( |
| 2437 | notifications.threshold_secs, 30, |
| 2438 | "field deltas must preserve both defaults and earlier live edits" |
| 2439 | ); |
| 2440 | } |
| 2441 | |
| 2442 | #[test] |
| 2443 | fn notification_condition_accepts_background_only_policy() { |
| 2444 | let config: Config = toml::from_str( |
| 2445 | r#" |
| 2446 | [tui] |
| 2447 | notification_condition = "unfocused" |
| 2448 | "#, |
| 2449 | ) |
| 2450 | .expect("unfocused attention policy should parse"); |
| 2451 | |
| 2452 | assert_eq!( |
| 2453 | config.tui.and_then(|tui| tui.notification_condition), |
| 2454 | Some(NotificationCondition::Unfocused) |
| 2455 | ); |
| 2456 | } |
| 2457 | |
| 2458 | #[test] |
| 2459 | fn apply_env_scenario() { |
| 2460 | // Scenario consolidation of: apply_env_overrides_sets_search_api_key, apply_env_overrides_sets_search_base_url |
| 2461 | // from apply_env_overrides_sets_search_api_key |
| 2462 | { |
| 2463 | let _guard = lock_test_env(); |
| 2464 | let prev = env::var_os("DEEPSEEK_SEARCH_API_KEY"); |
| 2465 | unsafe { env::set_var("DEEPSEEK_SEARCH_API_KEY", "search-env-key") }; |
| 2466 | let mut config = Config::default(); |
| 2467 | |
| 2468 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 2469 | |
| 2470 | unsafe { EnvGuard::restore_var("DEEPSEEK_SEARCH_API_KEY", prev) }; |
| 2471 | assert_eq!( |
| 2472 | config.search.and_then(|search| search.api_key), |
| 2473 | Some("search-env-key".to_string()) |
| 2474 | ); |
| 2475 | } |
| 2476 | // from apply_env_overrides_sets_search_base_url |
| 2477 | { |
| 2478 | let _guard = lock_test_env(); |
| 2479 | let prev_codewhale = env::var_os("CODEWHALE_SEARCH_BASE_URL"); |
| 2480 | let prev_deepseek = env::var_os("DEEPSEEK_SEARCH_BASE_URL"); |
| 2481 | unsafe { |
| 2482 | env::remove_var("CODEWHALE_SEARCH_BASE_URL"); |
| 2483 | env::set_var( |
| 2484 | "DEEPSEEK_SEARCH_BASE_URL", |
| 2485 | "https://search.internal.example/html/", |
| 2486 | ) |
| 2487 | }; |
| 2488 | let mut config = Config::default(); |
| 2489 | |
| 2490 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 2491 | |
| 2492 | unsafe { |
| 2493 | EnvGuard::restore_var("CODEWHALE_SEARCH_BASE_URL", prev_codewhale); |
| 2494 | EnvGuard::restore_var("DEEPSEEK_SEARCH_BASE_URL", prev_deepseek); |
| 2495 | } |
| 2496 | assert_eq!( |
| 2497 | config.search.and_then(|search| search.base_url), |
| 2498 | Some("https://search.internal.example/html/".to_string()) |
| 2499 | ); |
| 2500 | } |
| 2501 | } |
| 2502 | |
| 2503 | #[test] |
| 2504 | fn apply_env_overrides_yolo_prefers_codewhale_and_keeps_deepseek_alias() { |
| 2505 | let _guard = lock_test_env(); |
| 2506 | let codewhale_prev = env::var_os("CODEWHALE_YOLO"); |
| 2507 | let deepseek_prev = env::var_os("DEEPSEEK_YOLO"); |
| 2508 | let mut config = Config::default(); |
| 2509 | |
| 2510 | // Only the canonical name is set. |
| 2511 | unsafe { |
| 2512 | env::set_var("CODEWHALE_YOLO", "true"); |
| 2513 | env::remove_var("DEEPSEEK_YOLO"); |
| 2514 | } |
| 2515 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 2516 | assert_eq!( |
| 2517 | config.yolo, |
| 2518 | Some(true), |
| 2519 | "CODEWHALE_YOLO=true must enable the yolo posture" |
| 2520 | ); |
| 2521 | |
| 2522 | // Only the deprecated alias is set: it must keep working through 0.9.x. |
| 2523 | unsafe { |
| 2524 | env::remove_var("CODEWHALE_YOLO"); |
| 2525 | env::set_var("DEEPSEEK_YOLO", "true"); |
| 2526 | } |
| 2527 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 2528 | assert_eq!( |
| 2529 | config.yolo, |
| 2530 | Some(true), |
| 2531 | "DEEPSEEK_YOLO remains a read-only deprecated alias until 0.10 (#5443)" |
| 2532 | ); |
| 2533 | |
| 2534 | // Both set: the canonical name wins. |
| 2535 | unsafe { env::set_var("CODEWHALE_YOLO", "false") }; |
| 2536 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 2537 | assert_eq!( |
| 2538 | config.yolo, |
| 2539 | Some(false), |
| 2540 | "CODEWHALE_YOLO must win over the deprecated DEEPSEEK_YOLO alias" |
| 2541 | ); |
| 2542 | |
| 2543 | unsafe { |
| 2544 | EnvGuard::restore_var("CODEWHALE_YOLO", codewhale_prev); |
| 2545 | EnvGuard::restore_var("DEEPSEEK_YOLO", deepseek_prev); |
| 2546 | } |
| 2547 | } |
| 2548 | |
| 2549 | #[test] |
| 2550 | fn structural_config_load_keeps_safe_environment_overrides_but_omits_secret_values() { |
| 2551 | let _guard = lock_test_env(); |
| 2552 | let temp = tempfile::tempdir().expect("tempdir"); |
| 2553 | let config_path = temp.path().join("config.toml"); |
| 2554 | fs::write(&config_path, "").expect("empty config"); |
| 2555 | let _home = EnvVarGuard::set("CODEWHALE_HOME", temp.path().join("home")); |
| 2556 | let _profile = EnvVarGuard::remove("CODEWHALE_PROFILE"); |
| 2557 | let _legacy_profile = EnvVarGuard::remove("DEEPSEEK_PROFILE"); |
| 2558 | let _managed = EnvVarGuard::remove("CODEWHALE_MANAGED_CONFIG_PATH"); |
| 2559 | let _legacy_managed = EnvVarGuard::remove("DEEPSEEK_MANAGED_CONFIG_PATH"); |
| 2560 | let _requirements = EnvVarGuard::remove("CODEWHALE_REQUIREMENTS_PATH"); |
| 2561 | let _legacy_requirements = EnvVarGuard::remove("DEEPSEEK_REQUIREMENTS_PATH"); |
| 2562 | let _headers = EnvVarGuard::set( |
| 2563 | "CODEWHALE_HTTP_HEADERS", |
| 2564 | "Authorization=structural-header-secret", |
| 2565 | ); |
| 2566 | let _legacy_headers = EnvVarGuard::set( |
| 2567 | "DEEPSEEK_HTTP_HEADERS", |
| 2568 | "Authorization=legacy-structural-header-secret", |
| 2569 | ); |
| 2570 | let _sandbox_key = EnvVarGuard::set("CODEWHALE_SANDBOX_API_KEY", "structural-sandbox-secret"); |
| 2571 | let _legacy_sandbox_key = EnvVarGuard::set( |
| 2572 | "DEEPSEEK_SANDBOX_API_KEY", |
| 2573 | "legacy-structural-sandbox-secret", |
| 2574 | ); |
| 2575 | let _search_key = EnvVarGuard::set("CODEWHALE_SEARCH_API_KEY", "structural-search-secret"); |
| 2576 | let _legacy_search_key = |
| 2577 | EnvVarGuard::set("DEEPSEEK_SEARCH_API_KEY", "legacy-structural-search-secret"); |
| 2578 | let _base_url = EnvVarGuard::set("CODEWHALE_BASE_URL", "https://safe.example:8443/v1"); |
| 2579 | let _allow_shell = EnvVarGuard::set("CODEWHALE_ALLOW_SHELL", "false"); |
| 2580 | |
| 2581 | let runtime = Config::load(Some(config_path.clone()), None).expect("runtime config"); |
| 2582 | assert!(runtime.http_headers.is_some()); |
| 2583 | assert_eq!( |
| 2584 | runtime.sandbox_api_key.as_deref(), |
| 2585 | Some("structural-sandbox-secret") |
| 2586 | ); |
| 2587 | assert_eq!( |
| 2588 | runtime |
| 2589 | .search |
| 2590 | .as_ref() |
| 2591 | .and_then(|search| search.api_key.as_deref()), |
| 2592 | Some("structural-search-secret") |
| 2593 | ); |
| 2594 | |
| 2595 | let structural = Config::load_structural(Some(config_path), None).expect("structural config"); |
| 2596 | assert!(structural.http_headers.is_none()); |
| 2597 | assert!(structural.sandbox_api_key.is_none()); |
| 2598 | assert!( |
| 2599 | structural |
| 2600 | .search |
| 2601 | .as_ref() |
| 2602 | .and_then(|search| search.api_key.as_deref()) |
| 2603 | .is_none() |
| 2604 | ); |
| 2605 | assert_eq!( |
| 2606 | structural.deepseek_table_base_url(), |
| 2607 | Some("https://safe.example:8443/v1") |
| 2608 | ); |
| 2609 | assert_eq!(structural.allow_shell, Some(false)); |
| 2610 | |
| 2611 | let rendered = format!("{structural:?}"); |
| 2612 | for sentinel in [ |
| 2613 | "structural-header-secret", |
| 2614 | "legacy-structural-header-secret", |
| 2615 | "structural-sandbox-secret", |
| 2616 | "legacy-structural-sandbox-secret", |
| 2617 | "structural-search-secret", |
| 2618 | "legacy-structural-search-secret", |
| 2619 | ] { |
| 2620 | assert!( |
| 2621 | !rendered.contains(sentinel), |
| 2622 | "structural config retained {sentinel}" |
| 2623 | ); |
| 2624 | } |
| 2625 | } |
| 2626 | |
| 2627 | #[test] |
| 2628 | fn codewhale_search_base_url_env_wins_over_legacy_alias() { |
| 2629 | let _guard = lock_test_env(); |
| 2630 | let prev_codewhale = env::var_os("CODEWHALE_SEARCH_BASE_URL"); |
| 2631 | let prev_deepseek = env::var_os("DEEPSEEK_SEARCH_BASE_URL"); |
| 2632 | unsafe { |
| 2633 | env::set_var( |
| 2634 | "CODEWHALE_SEARCH_BASE_URL", |
| 2635 | "https://codewhale-search.example/html/", |
| 2636 | ); |
| 2637 | env::set_var( |
| 2638 | "DEEPSEEK_SEARCH_BASE_URL", |
| 2639 | "https://legacy-search.example/html/", |
| 2640 | ); |
| 2641 | } |
| 2642 | let mut config = Config::default(); |
| 2643 | |
| 2644 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 2645 | |
| 2646 | unsafe { |
| 2647 | EnvGuard::restore_var("CODEWHALE_SEARCH_BASE_URL", prev_codewhale); |
| 2648 | EnvGuard::restore_var("DEEPSEEK_SEARCH_BASE_URL", prev_deepseek); |
| 2649 | } |
| 2650 | assert_eq!( |
| 2651 | config.search.and_then(|search| search.base_url), |
| 2652 | Some("https://codewhale-search.example/html/".to_string()) |
| 2653 | ); |
| 2654 | } |
| 2655 | |
| 2656 | #[test] |
| 2657 | fn codewhale_prefer_bwrap_env_wins_over_legacy_alias() { |
| 2658 | let _guard = lock_test_env(); |
| 2659 | let _primary = EnvVarGuard::set("CODEWHALE_PREFER_BWRAP", "false"); |
| 2660 | let _legacy = EnvVarGuard::set("DEEPSEEK_PREFER_BWRAP", "true"); |
| 2661 | let mut config = Config { |
| 2662 | prefer_bwrap: Some(true), |
| 2663 | ..Config::default() |
| 2664 | }; |
| 2665 | |
| 2666 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 2667 | |
| 2668 | assert_eq!(config.prefer_bwrap, Some(false)); |
| 2669 | } |
| 2670 | |
| 2671 | #[test] |
| 2672 | fn legacy_prefer_bwrap_env_remains_a_compatible_alias() { |
| 2673 | let _guard = lock_test_env(); |
| 2674 | let _primary = EnvVarGuard::remove("CODEWHALE_PREFER_BWRAP"); |
| 2675 | let _legacy = EnvVarGuard::set("DEEPSEEK_PREFER_BWRAP", "true"); |
| 2676 | let mut config = Config::default(); |
| 2677 | |
| 2678 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 2679 | |
| 2680 | assert_eq!(config.prefer_bwrap, Some(true)); |
| 2681 | } |
| 2682 | |
| 2683 | #[test] |
| 2684 | fn prefers_bwrap_defaults_on_and_honors_explicit_opt_out() { |
| 2685 | assert!(Config::default().prefers_bwrap()); |
| 2686 | assert!( |
| 2687 | Config { |
| 2688 | prefer_bwrap: Some(true), |
| 2689 | ..Config::default() |
| 2690 | } |
| 2691 | .prefers_bwrap() |
| 2692 | ); |
| 2693 | assert!( |
| 2694 | !Config { |
| 2695 | prefer_bwrap: Some(false), |
| 2696 | ..Config::default() |
| 2697 | } |
| 2698 | .prefers_bwrap() |
| 2699 | ); |
| 2700 | } |
| 2701 | |
| 2702 | #[test] |
| 2703 | fn max_subagents_scenario() { |
| 2704 | // Scenario consolidation of: max_subagents_defaults_to_default_limit, max_subagents_clamps_subagents_max_concurrent |
| 2705 | // from max_subagents_defaults_to_default_limit |
| 2706 | { |
| 2707 | assert_eq!(Config::default().max_subagents(), DEFAULT_MAX_SUBAGENTS); |
| 2708 | assert_eq!(DEFAULT_MAX_SUBAGENTS, 64); |
| 2709 | } |
| 2710 | // from max_subagents_clamps_subagents_max_concurrent |
| 2711 | { |
| 2712 | let low = Config { |
| 2713 | subagents: Some(SubagentsConfig { |
| 2714 | max_concurrent: Some(0), |
| 2715 | ..SubagentsConfig::default() |
| 2716 | }), |
| 2717 | ..Config::default() |
| 2718 | }; |
| 2719 | assert_eq!(low.max_subagents(), 1); |
| 2720 | |
| 2721 | let high = Config { |
| 2722 | subagents: Some(SubagentsConfig { |
| 2723 | max_concurrent: Some(MAX_SUBAGENTS + 10), |
| 2724 | ..SubagentsConfig::default() |
| 2725 | }), |
| 2726 | ..Config::default() |
| 2727 | }; |
| 2728 | assert_eq!(high.max_subagents(), MAX_SUBAGENTS); |
| 2729 | } |
| 2730 | } |
| 2731 | |
| 2732 | #[test] |
| 2733 | fn launch_concurrency_defaults_and_clamps_to_max_subagents() { |
| 2734 | // Unset launch_concurrency now defaults to the full resolved cap. |
| 2735 | assert_eq!( |
| 2736 | Config::default().launch_concurrency(), |
| 2737 | Config::default().max_subagents() |
| 2738 | ); |
| 2739 | |
| 2740 | let mut config = Config { |
| 2741 | subagents: Some(SubagentsConfig { |
| 2742 | launch_concurrency: Some(50), |
| 2743 | ..SubagentsConfig::default() |
| 2744 | }), |
| 2745 | ..Config::default() |
| 2746 | }; |
| 2747 | assert_eq!(config.launch_concurrency(), 50); |
| 2748 | |
| 2749 | config.subagents = Some(SubagentsConfig { |
| 2750 | launch_concurrency: Some(DEFAULT_MAX_SUBAGENTS + 10), |
| 2751 | ..SubagentsConfig::default() |
| 2752 | }); |
| 2753 | assert_eq!(config.launch_concurrency(), config.max_subagents()); |
| 2754 | |
| 2755 | config.subagents = Some(SubagentsConfig { |
| 2756 | launch_concurrency: Some(0), |
| 2757 | ..SubagentsConfig::default() |
| 2758 | }); |
| 2759 | assert_eq!(config.launch_concurrency(), 1); |
| 2760 | |
| 2761 | config.subagents = Some(SubagentsConfig { |
| 2762 | launch_concurrency: Some(2), |
| 2763 | ..SubagentsConfig::default() |
| 2764 | }); |
| 2765 | assert_eq!(config.launch_concurrency(), 2); |
| 2766 | } |
| 2767 | |
| 2768 | #[test] |
| 2769 | fn subagent_budget_defaults_read_the_subagents_table() { |
| 2770 | // #5324: per-child step/wall-time defaults are operator config |
| 2771 | // (`[subagents]`), not per-call schema fields. `0` means unset (keep the |
| 2772 | // role / 1800s defaults). |
| 2773 | let cfg: SubagentsConfig = |
| 2774 | toml::from_str("default_max_steps = 90\ndefault_wall_time_secs = 600") |
| 2775 | .expect("parse [subagents] budget keys"); |
| 2776 | assert_eq!(cfg.default_max_steps, Some(90)); |
| 2777 | assert_eq!(cfg.default_wall_time_secs, Some(600)); |
| 2778 | |
| 2779 | let mut config = Config { |
| 2780 | subagents: Some(SubagentsConfig { |
| 2781 | default_max_steps: Some(240), |
| 2782 | default_wall_time_secs: Some(2700), |
| 2783 | ..SubagentsConfig::default() |
| 2784 | }), |
| 2785 | ..Config::default() |
| 2786 | }; |
| 2787 | assert_eq!(config.subagent_default_max_steps(), Some(240)); |
| 2788 | assert_eq!(config.subagent_default_wall_time_secs(), Some(2700)); |
| 2789 | |
| 2790 | config.subagents = Some(SubagentsConfig { |
| 2791 | default_max_steps: Some(0), |
| 2792 | default_wall_time_secs: Some(0), |
| 2793 | ..SubagentsConfig::default() |
| 2794 | }); |
| 2795 | assert_eq!(config.subagent_default_max_steps(), None); |
| 2796 | assert_eq!(config.subagent_default_wall_time_secs(), None); |
| 2797 | |
| 2798 | assert_eq!(Config::default().subagent_default_max_steps(), None); |
| 2799 | assert_eq!(Config::default().subagent_default_wall_time_secs(), None); |
| 2800 | } |
| 2801 | |
| 2802 | #[test] |
| 2803 | fn launch_concurrency_scenario() { |
| 2804 | // Scenario consolidation of: launch_concurrency_honors_deprecated_interactive_max_launch_alias, launch_concurrency_new_key_wins_over_deprecated_alias |
| 2805 | // from launch_concurrency_honors_deprecated_interactive_max_launch_alias |
| 2806 | { |
| 2807 | // The old TOML key `interactive_max_launch` still deserializes, via |
| 2808 | // #[serde(rename)], into the hidden legacy field, and the resolver |
| 2809 | // honors it when the new key is unset. |
| 2810 | let cfg: SubagentsConfig = |
| 2811 | toml::from_str("interactive_max_launch = 5").expect("parse legacy key"); |
| 2812 | assert_eq!(cfg.interactive_max_launch_legacy, Some(5)); |
| 2813 | assert_eq!(cfg.launch_concurrency, None); |
| 2814 | |
| 2815 | let config = Config { |
| 2816 | subagents: Some(cfg), |
| 2817 | ..Config::default() |
| 2818 | }; |
| 2819 | assert_eq!(config.launch_concurrency(), 5); |
| 2820 | } |
| 2821 | // from launch_concurrency_new_key_wins_over_deprecated_alias |
| 2822 | { |
| 2823 | // When both keys are present the new `launch_concurrency` wins |
| 2824 | // deterministically, regardless of document order. |
| 2825 | let cfg: SubagentsConfig = |
| 2826 | toml::from_str("launch_concurrency = 3\ninteractive_max_launch = 7") |
| 2827 | .expect("parse both keys"); |
| 2828 | assert_eq!(cfg.launch_concurrency, Some(3)); |
| 2829 | assert_eq!(cfg.interactive_max_launch_legacy, Some(7)); |
| 2830 | |
| 2831 | let config = Config { |
| 2832 | subagents: Some(cfg), |
| 2833 | ..Config::default() |
| 2834 | }; |
| 2835 | assert_eq!(config.launch_concurrency(), 3); |
| 2836 | } |
| 2837 | } |
| 2838 | |
| 2839 | #[test] |
| 2840 | fn fleet_role_model_keys_accept_canonical_and_legacy_names() { |
| 2841 | let canonical: Config = toml::from_str( |
| 2842 | r#" |
| 2843 | [subagents] |
| 2844 | scout_model = "scout-model" |
| 2845 | planner_model = "planner-model" |
| 2846 | reviewer_model = "reviewer-model" |
| 2847 | "#, |
| 2848 | ) |
| 2849 | .expect("parse canonical Fleet role keys"); |
| 2850 | let overrides = canonical.subagent_model_overrides(); |
| 2851 | assert_eq!( |
| 2852 | overrides.get("scout").map(|pin| pin.model.as_str()), |
| 2853 | Some("scout-model") |
| 2854 | ); |
| 2855 | assert_eq!( |
| 2856 | overrides.get("planner").map(|pin| pin.model.as_str()), |
| 2857 | Some("planner-model") |
| 2858 | ); |
| 2859 | assert_eq!( |
| 2860 | overrides.get("reviewer").map(|pin| pin.model.as_str()), |
| 2861 | Some("reviewer-model") |
| 2862 | ); |
| 2863 | |
| 2864 | let legacy: Config = toml::from_str( |
| 2865 | r#" |
| 2866 | [subagents] |
| 2867 | explorer_model = "legacy-scout" |
| 2868 | awaiter_model = "legacy-planner" |
| 2869 | review_model = "legacy-reviewer" |
| 2870 | "#, |
| 2871 | ) |
| 2872 | .expect("parse v0.9.x role aliases"); |
| 2873 | let overrides = legacy.subagent_model_overrides(); |
| 2874 | assert_eq!( |
| 2875 | overrides.get("scout").map(|pin| pin.model.as_str()), |
| 2876 | Some("legacy-scout") |
| 2877 | ); |
| 2878 | assert_eq!( |
| 2879 | overrides.get("planner").map(|pin| pin.model.as_str()), |
| 2880 | Some("legacy-planner") |
| 2881 | ); |
| 2882 | assert_eq!( |
| 2883 | overrides.get("reviewer").map(|pin| pin.model.as_str()), |
| 2884 | Some("legacy-reviewer") |
| 2885 | ); |
| 2886 | } |
| 2887 | |
| 2888 | #[test] |
| 2889 | fn structured_role_pins_merge_into_legacy_override_authority() { |
| 2890 | let config: Config = toml::from_str( |
| 2891 | r#" |
| 2892 | [subagents] |
| 2893 | reviewer_model = "scalar-reviewer" |
| 2894 | worker_model = "scalar-worker" |
| 2895 | scout_model = "scalar-scout" |
| 2896 | [subagents.models] |
| 2897 | reviewer = "map-reviewer" |
| 2898 | [subagents.roles.REVIEW] |
| 2899 | model = "alias-reviewer" |
| 2900 | [subagents.roles.reviewer] |
| 2901 | model = "canonical-reviewer" |
| 2902 | [subagents.roles.scout] |
| 2903 | model = "structured-scout" |
| 2904 | [subagents.roles.default] |
| 2905 | model = "all-role-fallback" |
| 2906 | [subagents.roles.custom] |
| 2907 | model = " " |
| 2908 | "#, |
| 2909 | ) |
| 2910 | .expect("parse structured and legacy inputs together"); |
| 2911 | let overrides = config.subagent_model_overrides(); |
| 2912 | assert_eq!(overrides["reviewer"].model, "canonical-reviewer"); |
| 2913 | assert_eq!(overrides["explore"].model, "structured-scout"); |
| 2914 | assert_eq!(overrides["general"].model, "scalar-worker"); |
| 2915 | assert_eq!(overrides["default"].model, "all-role-fallback"); |
| 2916 | assert_eq!( |
| 2917 | overrides["custom"].model, "", |
| 2918 | "blank explicit pin reaches admission validation" |
| 2919 | ); |
| 2920 | } |
| 2921 | |
| 2922 | #[test] |
| 2923 | fn structured_role_declarations_preserve_provider_identity_and_legacy_wire_ids() { |
| 2924 | let config: Config = toml::from_str( |
| 2925 | r#" |
| 2926 | [subagents] |
| 2927 | worker_model = "deepseek/deepseek-v4-pro" |
| 2928 | [subagents.models] |
| 2929 | reviewer = "deepseek/deepseek-v4-flash" |
| 2930 | [subagents.roles.advisor] |
| 2931 | model = "ReviewerRoute/vendor/model-id" |
| 2932 | [subagents.roles.implement] |
| 2933 | model = "openrouter/deepseek/deepseek-v4-pro" |
| 2934 | "#, |
| 2935 | ) |
| 2936 | .unwrap(); |
| 2937 | let pins = config.subagent_model_overrides(); |
| 2938 | for (role, model) in [ |
| 2939 | ("general", "deepseek/deepseek-v4-pro"), |
| 2940 | ("reviewer", "deepseek/deepseek-v4-flash"), |
| 2941 | ] { |
| 2942 | assert_eq!( |
| 2943 | pins[role].provider, None, |
| 2944 | "legacy ids remain provider-owned" |
| 2945 | ); |
| 2946 | assert_eq!(pins[role].model, model); |
| 2947 | } |
| 2948 | assert_eq!(pins["advisor"].provider.as_deref(), Some("ReviewerRoute")); |
| 2949 | assert_eq!(pins["advisor"].model, "vendor/model-id"); |
| 2950 | assert_eq!(pins["implement"].provider.as_deref(), Some("openrouter")); |
| 2951 | assert_eq!(pins["implement"].model, "deepseek/deepseek-v4-pro"); |
| 2952 | } |
| 2953 | |
| 2954 | #[test] |
| 2955 | fn structured_role_pins_require_a_typed_model_field() { |
| 2956 | for input in [ |
| 2957 | "[subagents.roles.reviewer]\n", |
| 2958 | "[subagents.roles.reviewer]\nmodel = 42\n", |
| 2959 | "[subagents.roles.reviewer]\nmodel = \"model\"\nprovider = \"other\"\n", |
| 2960 | ] { |
| 2961 | assert!( |
| 2962 | toml::from_str::<Config>(input).is_err(), |
| 2963 | "invalid role pin accepted: {input}" |
| 2964 | ); |
| 2965 | } |
| 2966 | } |
| 2967 | |
| 2968 | #[test] |
| 2969 | fn subagent_admission_limit_defaults_and_clamps() { |
| 2970 | assert_eq!( |
| 2971 | Config::default().max_admitted_subagents(), |
| 2972 | MAX_SUBAGENT_ADMISSION |
| 2973 | ); |
| 2974 | |
| 2975 | let configured = Config { |
| 2976 | subagents: Some(SubagentsConfig { |
| 2977 | max_concurrent: Some(4), |
| 2978 | max_admitted: Some(80), |
| 2979 | ..SubagentsConfig::default() |
| 2980 | }), |
| 2981 | ..Config::default() |
| 2982 | }; |
| 2983 | assert_eq!(configured.max_subagents(), 4); |
| 2984 | assert_eq!(configured.max_admitted_subagents(), 80); |
| 2985 | |
| 2986 | let low = Config { |
| 2987 | subagents: Some(SubagentsConfig { |
| 2988 | max_concurrent: Some(4), |
| 2989 | max_admitted: Some(1), |
| 2990 | ..SubagentsConfig::default() |
| 2991 | }), |
| 2992 | ..Config::default() |
| 2993 | }; |
| 2994 | assert_eq!(low.max_admitted_subagents(), 4); |
| 2995 | |
| 2996 | let high = Config { |
| 2997 | subagents: Some(SubagentsConfig { |
| 2998 | max_admitted: Some(MAX_SUBAGENT_ADMISSION + 1), |
| 2999 | ..SubagentsConfig::default() |
| 3000 | }), |
| 3001 | ..Config::default() |
| 3002 | }; |
| 3003 | assert_eq!(high.max_admitted_subagents(), MAX_SUBAGENT_ADMISSION); |
| 3004 | |
| 3005 | let alias_cfg: SubagentsConfig = |
| 3006 | toml::from_str("admission_limit = 80").expect("parse admission alias"); |
| 3007 | assert_eq!(alias_cfg.max_admitted, Some(80)); |
| 3008 | } |
| 3009 | |
| 3010 | #[test] |
| 3011 | fn provider_subagent_profiles_override_global_limits_with_aliases() { |
| 3012 | let config: Config = toml::from_str( |
| 3013 | r#" |
| 3014 | provider = "zai" |
| 3015 | |
| 3016 | [subagents] |
| 3017 | max_concurrent = 20 |
| 3018 | launch_concurrency = 20 |
| 3019 | max_admitted = 200 |
| 3020 | max_depth = 6 |
| 3021 | api_timeout_secs = 900 |
| 3022 | heartbeat_timeout_secs = 1200 |
| 3023 | |
| 3024 | [subagents.providers.glm] |
| 3025 | max_concurrent = 4 |
| 3026 | launch_concurrency = 3 |
| 3027 | max_admitted = 12 |
| 3028 | max_depth = 2 |
| 3029 | api_timeout_secs = 180 |
| 3030 | heartbeat_timeout_secs = 240 |
| 3031 | "#, |
| 3032 | ) |
| 3033 | .expect("parse provider subagent profile"); |
| 3034 | |
| 3035 | assert_eq!( |
| 3036 | config.active_provider_identity().unwrap().provider, |
| 3037 | ProviderKind::Zai |
| 3038 | ); |
| 3039 | assert_eq!(config.max_subagents(), 20); |
| 3040 | assert_eq!( |
| 3041 | config.max_subagents_for_provider(&config.test_identity_for_kind(ProviderKind::Zai)), |
| 3042 | 4 |
| 3043 | ); |
| 3044 | assert_eq!( |
| 3045 | config.launch_concurrency_for_provider(&config.test_identity_for_kind(ProviderKind::Zai)), |
| 3046 | 3 |
| 3047 | ); |
| 3048 | assert_eq!( |
| 3049 | config |
| 3050 | .max_admitted_subagents_for_provider(&config.test_identity_for_kind(ProviderKind::Zai)), |
| 3051 | 12 |
| 3052 | ); |
| 3053 | assert_eq!( |
| 3054 | config.subagent_max_spawn_depth_for_provider( |
| 3055 | &config.test_identity_for_kind(ProviderKind::Zai) |
| 3056 | ), |
| 3057 | 2 |
| 3058 | ); |
| 3059 | assert_eq!( |
| 3060 | config.subagent_api_timeout_secs_for_provider( |
| 3061 | &config.test_identity_for_kind(ProviderKind::Zai) |
| 3062 | ), |
| 3063 | 180 |
| 3064 | ); |
| 3065 | // The explicit 240s provider override sits below the 300s tool timeout, |
| 3066 | // and a heartbeat under the tool timeout kills children mid-legitimate- |
| 3067 | // tool (activity is only recorded at step boundaries). The tool-timeout |
| 3068 | // floor lifts the resolved value above the override |
| 3069 | // (2026-08-04 sub-agent hunt, finding 4). |
| 3070 | assert_eq!( |
| 3071 | config.subagent_heartbeat_timeout_secs_for_provider( |
| 3072 | &config.test_identity_for_kind(ProviderKind::Zai) |
| 3073 | ), |
| 3074 | DEFAULT_SUBAGENT_TOOL_TIMEOUT_SECS + 30 |
| 3075 | ); |
| 3076 | } |
| 3077 | |
| 3078 | #[test] |
| 3079 | fn provider_request_concurrency_defaults_to_zai_and_can_be_overridden() { |
| 3080 | let default_zai: Config = toml::from_str( |
| 3081 | r#" |
| 3082 | provider = "zai" |
| 3083 | "#, |
| 3084 | ) |
| 3085 | .expect("parse zai provider config"); |
| 3086 | assert_eq!( |
| 3087 | default_zai |
| 3088 | .provider_max_concurrency(&default_zai.test_identity_for_kind(ProviderKind::Zai)), |
| 3089 | Some(DEFAULT_ZAI_PROVIDER_MAX_CONCURRENCY) |
| 3090 | ); |
| 3091 | assert_eq!( |
| 3092 | default_zai |
| 3093 | .provider_max_concurrency(&default_zai.test_identity_for_kind(ProviderKind::Deepseek)), |
| 3094 | None |
| 3095 | ); |
| 3096 | |
| 3097 | let configured: Config = toml::from_str( |
| 3098 | r#" |
| 3099 | provider = "zai" |
| 3100 | |
| 3101 | [providers.zhipu] |
| 3102 | max-concurrency = 10 |
| 3103 | "#, |
| 3104 | ) |
| 3105 | .expect("parse zhipu concurrency alias"); |
| 3106 | assert_eq!( |
| 3107 | configured.provider_max_concurrency(&configured.test_identity_for_kind(ProviderKind::Zai)), |
| 3108 | Some(10) |
| 3109 | ); |
| 3110 | |
| 3111 | let disabled: Config = toml::from_str( |
| 3112 | r#" |
| 3113 | provider = "zai" |
| 3114 | |
| 3115 | [providers.zai] |
| 3116 | maxConcurrency = 0 |
| 3117 | "#, |
| 3118 | ) |
| 3119 | .expect("parse disabled concurrency cap"); |
| 3120 | assert_eq!( |
| 3121 | disabled.provider_max_concurrency(&disabled.test_identity_for_kind(ProviderKind::Zai)), |
| 3122 | None |
| 3123 | ); |
| 3124 | |
| 3125 | let clamped: Config = toml::from_str( |
| 3126 | r#" |
| 3127 | [providers.openai] |
| 3128 | concurrency = 999 |
| 3129 | "#, |
| 3130 | ) |
| 3131 | .expect("parse openai concurrency alias"); |
| 3132 | assert_eq!( |
| 3133 | clamped.provider_max_concurrency(&clamped.test_identity_for_kind(ProviderKind::Openai)), |
| 3134 | Some(MAX_PROVIDER_REQUEST_CONCURRENCY) |
| 3135 | ); |
| 3136 | } |
| 3137 | |
| 3138 | #[test] |
| 3139 | fn provider_subagent_profiles_inherit_and_clamp_against_provider_max() { |
| 3140 | let config: Config = toml::from_str( |
| 3141 | r#" |
| 3142 | [subagents] |
| 3143 | max_concurrent = 12 |
| 3144 | launch_concurrency = 8 |
| 3145 | max_depth = 5 |
| 3146 | api_timeout_secs = 300 |
| 3147 | |
| 3148 | [subagents.providers.deepseek_api] |
| 3149 | max_concurrent = 30 |
| 3150 | launch_concurrency = 30 |
| 3151 | max_admitted = 1 |
| 3152 | |
| 3153 | [subagents.providers.anthropic] |
| 3154 | enabled = false |
| 3155 | "#, |
| 3156 | ) |
| 3157 | .expect("parse inherited provider subagent profile"); |
| 3158 | |
| 3159 | assert_eq!( |
| 3160 | config.max_subagents_for_provider(&config.test_identity_for_kind(ProviderKind::Deepseek)), |
| 3161 | 30 |
| 3162 | ); |
| 3163 | assert_eq!( |
| 3164 | config.launch_concurrency_for_provider( |
| 3165 | &config.test_identity_for_kind(ProviderKind::Deepseek) |
| 3166 | ), |
| 3167 | 30 |
| 3168 | ); |
| 3169 | assert_eq!( |
| 3170 | config.max_admitted_subagents_for_provider( |
| 3171 | &config.test_identity_for_kind(ProviderKind::Deepseek) |
| 3172 | ), |
| 3173 | 30 |
| 3174 | ); |
| 3175 | assert_eq!( |
| 3176 | config.subagent_max_spawn_depth_for_provider( |
| 3177 | &config.test_identity_for_kind(ProviderKind::Deepseek) |
| 3178 | ), |
| 3179 | 5 |
| 3180 | ); |
| 3181 | assert_eq!( |
| 3182 | config.subagent_api_timeout_secs_for_provider( |
| 3183 | &config.test_identity_for_kind(ProviderKind::Deepseek) |
| 3184 | ), |
| 3185 | 300 |
| 3186 | ); |
| 3187 | assert!( |
| 3188 | config |
| 3189 | .subagents_enabled_for_provider(&config.test_identity_for_kind(ProviderKind::Deepseek)) |
| 3190 | ); |
| 3191 | assert!( |
| 3192 | !config.subagents_enabled_for_provider( |
| 3193 | &config.test_identity_for_kind(ProviderKind::Anthropic) |
| 3194 | ) |
| 3195 | ); |
| 3196 | } |
| 3197 | |
| 3198 | #[test] |
| 3199 | fn subagents_max_concurrent_overrides_top_level_cap() { |
| 3200 | let config = Config { |
| 3201 | max_subagents: Some(3), |
| 3202 | subagents: Some(SubagentsConfig { |
| 3203 | max_concurrent: Some(12), |
| 3204 | ..SubagentsConfig::default() |
| 3205 | }), |
| 3206 | ..Config::default() |
| 3207 | }; |
| 3208 | |
| 3209 | assert_eq!(config.max_subagents(), 12); |
| 3210 | } |
| 3211 | |
| 3212 | #[test] |
| 3213 | fn subagents_enabled_reports_disable_precedence() { |
| 3214 | assert!(Config::default().subagents_enabled()); |
| 3215 | |
| 3216 | let mut feature_disabled = Config::default(); |
| 3217 | feature_disabled |
| 3218 | .set_feature("subagents", false) |
| 3219 | .expect("known feature"); |
| 3220 | assert!(!feature_disabled.subagents_enabled()); |
| 3221 | assert_eq!( |
| 3222 | feature_disabled.subagents_disabled_reason(), |
| 3223 | Some("features.subagents=false") |
| 3224 | ); |
| 3225 | |
| 3226 | let explicit_disabled = Config { |
| 3227 | subagents: Some(SubagentsConfig { |
| 3228 | enabled: Some(false), |
| 3229 | max_concurrent: Some(0), |
| 3230 | max_depth: Some(0), |
| 3231 | ..SubagentsConfig::default() |
| 3232 | }), |
| 3233 | ..Config::default() |
| 3234 | }; |
| 3235 | assert!(!explicit_disabled.subagents_enabled()); |
| 3236 | assert_eq!( |
| 3237 | explicit_disabled.subagents_disabled_reason(), |
| 3238 | Some("subagents.enabled=false") |
| 3239 | ); |
| 3240 | |
| 3241 | let zero_concurrency = Config { |
| 3242 | subagents: Some(SubagentsConfig { |
| 3243 | enabled: Some(true), |
| 3244 | max_concurrent: Some(0), |
| 3245 | max_depth: Some(1), |
| 3246 | ..SubagentsConfig::default() |
| 3247 | }), |
| 3248 | ..Config::default() |
| 3249 | }; |
| 3250 | assert_eq!( |
| 3251 | zero_concurrency.subagents_disabled_reason(), |
| 3252 | Some("subagents.max_concurrent=0") |
| 3253 | ); |
| 3254 | |
| 3255 | let zero_depth = Config { |
| 3256 | subagents: Some(SubagentsConfig { |
| 3257 | enabled: Some(true), |
| 3258 | max_concurrent: Some(1), |
| 3259 | max_depth: Some(0), |
| 3260 | ..SubagentsConfig::default() |
| 3261 | }), |
| 3262 | ..Config::default() |
| 3263 | }; |
| 3264 | assert_eq!( |
| 3265 | zero_depth.subagents_disabled_reason(), |
| 3266 | Some("subagents.max_depth=0") |
| 3267 | ); |
| 3268 | } |
| 3269 | |
| 3270 | #[test] |
| 3271 | fn subagent_max_spawn_depth_defaults_allows_zero_and_preserves_owner_choice() { |
| 3272 | assert_eq!( |
| 3273 | Config::default().subagent_max_spawn_depth(), |
| 3274 | codewhale_protocol::fleet::DEFAULT_SPAWN_DEPTH |
| 3275 | ); |
| 3276 | |
| 3277 | let disabled = Config { |
| 3278 | subagents: Some(SubagentsConfig { |
| 3279 | max_depth: Some(0), |
| 3280 | ..SubagentsConfig::default() |
| 3281 | }), |
| 3282 | ..Config::default() |
| 3283 | }; |
| 3284 | assert_eq!(disabled.subagent_max_spawn_depth(), 0); |
| 3285 | |
| 3286 | let high = Config { |
| 3287 | subagents: Some(SubagentsConfig { |
| 3288 | max_depth: Some(99), |
| 3289 | ..SubagentsConfig::default() |
| 3290 | }), |
| 3291 | ..Config::default() |
| 3292 | }; |
| 3293 | assert_eq!(high.subagent_max_spawn_depth(), 99); |
| 3294 | } |
| 3295 | |
| 3296 | #[test] |
| 3297 | fn subagent_api_timeout_defaults_and_clamps() { |
| 3298 | assert_eq!( |
| 3299 | Config::default().subagent_api_timeout_secs(), |
| 3300 | DEFAULT_SUBAGENT_API_TIMEOUT_SECS |
| 3301 | ); |
| 3302 | assert_eq!(DEFAULT_SUBAGENT_API_TIMEOUT_SECS, 600); |
| 3303 | |
| 3304 | let zero = Config { |
| 3305 | subagents: Some(SubagentsConfig { |
| 3306 | api_timeout_secs: Some(0), |
| 3307 | ..SubagentsConfig::default() |
| 3308 | }), |
| 3309 | ..Config::default() |
| 3310 | }; |
| 3311 | assert_eq!( |
| 3312 | zero.subagent_api_timeout_secs(), |
| 3313 | DEFAULT_SUBAGENT_API_TIMEOUT_SECS |
| 3314 | ); |
| 3315 | |
| 3316 | let explicit_min = Config { |
| 3317 | subagents: Some(SubagentsConfig { |
| 3318 | api_timeout_secs: Some(MIN_SUBAGENT_API_TIMEOUT_SECS), |
| 3319 | ..SubagentsConfig::default() |
| 3320 | }), |
| 3321 | ..Config::default() |
| 3322 | }; |
| 3323 | assert_eq!(explicit_min.subagent_api_timeout_secs(), 1); |
| 3324 | |
| 3325 | let explicit_max = Config { |
| 3326 | subagents: Some(SubagentsConfig { |
| 3327 | api_timeout_secs: Some(3600), |
| 3328 | ..SubagentsConfig::default() |
| 3329 | }), |
| 3330 | ..Config::default() |
| 3331 | }; |
| 3332 | assert_eq!(explicit_max.subagent_api_timeout_secs(), 3600); |
| 3333 | |
| 3334 | let beyond_max = Config { |
| 3335 | subagents: Some(SubagentsConfig { |
| 3336 | api_timeout_secs: Some(3601), |
| 3337 | ..SubagentsConfig::default() |
| 3338 | }), |
| 3339 | ..Config::default() |
| 3340 | }; |
| 3341 | assert_eq!(beyond_max.subagent_api_timeout_secs(), 3600); |
| 3342 | |
| 3343 | let high = Config { |
| 3344 | subagents: Some(SubagentsConfig { |
| 3345 | api_timeout_secs: Some(MAX_SUBAGENT_API_TIMEOUT_SECS + 60), |
| 3346 | ..SubagentsConfig::default() |
| 3347 | }), |
| 3348 | ..Config::default() |
| 3349 | }; |
| 3350 | assert_eq!( |
| 3351 | high.subagent_api_timeout_secs(), |
| 3352 | MAX_SUBAGENT_API_TIMEOUT_SECS |
| 3353 | ); |
| 3354 | } |
| 3355 | |
| 3356 | #[test] |
| 3357 | fn subagent_heartbeat_timeout_defaults_clamps_and_respects_api_timeout() { |
| 3358 | // With the 600s default API timeout, the heartbeat floor (api + 30s) |
| 3359 | // lifts the resolved default above the raw 300s constant. The tool |
| 3360 | // timeout floor (tool + 30s) also participates but sits below the API |
| 3361 | // floor at default settings. |
| 3362 | let resolved_default = DEFAULT_SUBAGENT_HEARTBEAT_TIMEOUT_SECS |
| 3363 | .max(DEFAULT_SUBAGENT_API_TIMEOUT_SECS + 30) |
| 3364 | .max(DEFAULT_SUBAGENT_TOOL_TIMEOUT_SECS + 30); |
| 3365 | assert_eq!( |
| 3366 | Config::default().subagent_heartbeat_timeout_secs(), |
| 3367 | resolved_default |
| 3368 | ); |
| 3369 | |
| 3370 | let zero = Config { |
| 3371 | subagents: Some(SubagentsConfig { |
| 3372 | heartbeat_timeout_secs: Some(0), |
| 3373 | ..SubagentsConfig::default() |
| 3374 | }), |
| 3375 | ..Config::default() |
| 3376 | }; |
| 3377 | assert_eq!(zero.subagent_heartbeat_timeout_secs(), resolved_default); |
| 3378 | |
| 3379 | // With a tiny API timeout the tool-timeout floor dominates: a single |
| 3380 | // tool execution can run the full tool timeout without touching the |
| 3381 | // heartbeat, so cleanup must not fire before tool_timeout + 30s even |
| 3382 | // though the API floor alone would be 31s (2026-08-04 sub-agent hunt, |
| 3383 | // finding 4 — this case resolved to 31 before the fix, which let |
| 3384 | // cleanup kill a child mid-legitimate-tool). |
| 3385 | let low = Config { |
| 3386 | subagents: Some(SubagentsConfig { |
| 3387 | api_timeout_secs: Some(1), |
| 3388 | heartbeat_timeout_secs: Some(1), |
| 3389 | ..SubagentsConfig::default() |
| 3390 | }), |
| 3391 | ..Config::default() |
| 3392 | }; |
| 3393 | assert_eq!( |
| 3394 | low.subagent_heartbeat_timeout_secs(), |
| 3395 | DEFAULT_SUBAGENT_TOOL_TIMEOUT_SECS + 30 |
| 3396 | ); |
| 3397 | |
| 3398 | let follows_long_api_timeout = Config { |
| 3399 | subagents: Some(SubagentsConfig { |
| 3400 | api_timeout_secs: Some(900), |
| 3401 | heartbeat_timeout_secs: Some(300), |
| 3402 | ..SubagentsConfig::default() |
| 3403 | }), |
| 3404 | ..Config::default() |
| 3405 | }; |
| 3406 | assert_eq!( |
| 3407 | follows_long_api_timeout.subagent_heartbeat_timeout_secs(), |
| 3408 | 930 |
| 3409 | ); |
| 3410 | |
| 3411 | let high = Config { |
| 3412 | subagents: Some(SubagentsConfig { |
| 3413 | heartbeat_timeout_secs: Some(MAX_SUBAGENT_HEARTBEAT_TIMEOUT_SECS + 60), |
| 3414 | ..SubagentsConfig::default() |
| 3415 | }), |
| 3416 | ..Config::default() |
| 3417 | }; |
| 3418 | assert_eq!( |
| 3419 | high.subagent_heartbeat_timeout_secs(), |
| 3420 | MAX_SUBAGENT_HEARTBEAT_TIMEOUT_SECS |
| 3421 | ); |
| 3422 | } |
| 3423 | |
| 3424 | #[test] |
| 3425 | fn subagent_heartbeat_floor_never_drops_below_tool_timeout_plus_margin() { |
| 3426 | // The safety property behind finding 4: for EVERY accepted combination of |
| 3427 | // `[subagents] api_timeout_secs` and `heartbeat_timeout_secs`, the |
| 3428 | // resolved heartbeat timeout stays above the tool timeout, because a tool |
| 3429 | // running up to `tool_timeout` produces no heartbeat activity. Corners |
| 3430 | // cover the smallest legal API timeout and heartbeat against both the |
| 3431 | // global and provider-specific resolvers. |
| 3432 | let corners: [Option<u64>; 4] = [ |
| 3433 | Some(MIN_SUBAGENT_API_TIMEOUT_SECS), |
| 3434 | Some(1), |
| 3435 | None, |
| 3436 | Some(MAX_SUBAGENT_API_TIMEOUT_SECS), |
| 3437 | ]; |
| 3438 | let heartbeats: [Option<u64>; 4] = [ |
| 3439 | Some(MIN_SUBAGENT_HEARTBEAT_TIMEOUT_SECS), |
| 3440 | Some(1), |
| 3441 | None, |
| 3442 | Some(0), |
| 3443 | ]; |
| 3444 | for api in corners { |
| 3445 | for heartbeat in heartbeats { |
| 3446 | let cfg = Config { |
| 3447 | subagents: Some(SubagentsConfig { |
| 3448 | api_timeout_secs: api, |
| 3449 | heartbeat_timeout_secs: heartbeat, |
| 3450 | ..SubagentsConfig::default() |
| 3451 | }), |
| 3452 | ..Config::default() |
| 3453 | }; |
| 3454 | let floor = DEFAULT_SUBAGENT_TOOL_TIMEOUT_SECS + 30; |
| 3455 | assert!( |
| 3456 | cfg.subagent_heartbeat_timeout_secs() >= floor, |
| 3457 | "global resolver: api={api:?} heartbeat={heartbeat:?} resolved {} < {floor}", |
| 3458 | cfg.subagent_heartbeat_timeout_secs() |
| 3459 | ); |
| 3460 | assert!( |
| 3461 | cfg.subagent_heartbeat_timeout_secs_for_provider( |
| 3462 | &cfg.test_identity_for_kind(ProviderKind::Deepseek) |
| 3463 | ) >= floor, |
| 3464 | "provider resolver: api={api:?} heartbeat={heartbeat:?} resolved {} < {floor}", |
| 3465 | cfg.subagent_heartbeat_timeout_secs_for_provider( |
| 3466 | &cfg.test_identity_for_kind(ProviderKind::Deepseek) |
| 3467 | ) |
| 3468 | ); |
| 3469 | } |
| 3470 | } |
| 3471 | } |
| 3472 | |
| 3473 | #[test] |
| 3474 | fn tui_stream_chunk_timeout_defaults_env_and_clamps() { |
| 3475 | let _lock = lock_test_env(); |
| 3476 | let previous = env::var_os(STREAM_CHUNK_TIMEOUT_ENV); |
| 3477 | unsafe { |
| 3478 | env::remove_var(STREAM_CHUNK_TIMEOUT_ENV); |
| 3479 | } |
| 3480 | |
| 3481 | assert_eq!( |
| 3482 | Config::default().stream_chunk_timeout_secs(), |
| 3483 | DEFAULT_STREAM_CHUNK_TIMEOUT_SECS |
| 3484 | ); |
| 3485 | |
| 3486 | let zero = Config { |
| 3487 | tui: Some(TuiConfig { |
| 3488 | stream_chunk_timeout_secs: Some(0), |
| 3489 | max_model_steps: None, |
| 3490 | turn_wall_clock_secs: None, |
| 3491 | stream_max_content_mb: None, |
| 3492 | stream_max_duration_secs: None, |
| 3493 | ..TuiConfig::default() |
| 3494 | }), |
| 3495 | ..Config::default() |
| 3496 | }; |
| 3497 | assert_eq!( |
| 3498 | zero.stream_chunk_timeout_secs(), |
| 3499 | DEFAULT_STREAM_CHUNK_TIMEOUT_SECS |
| 3500 | ); |
| 3501 | |
| 3502 | let explicit_min = Config { |
| 3503 | tui: Some(TuiConfig { |
| 3504 | stream_chunk_timeout_secs: Some(MIN_STREAM_CHUNK_TIMEOUT_SECS), |
| 3505 | max_model_steps: None, |
| 3506 | turn_wall_clock_secs: None, |
| 3507 | stream_max_content_mb: None, |
| 3508 | stream_max_duration_secs: None, |
| 3509 | ..TuiConfig::default() |
| 3510 | }), |
| 3511 | ..Config::default() |
| 3512 | }; |
| 3513 | assert_eq!( |
| 3514 | explicit_min.stream_chunk_timeout_secs(), |
| 3515 | MIN_STREAM_CHUNK_TIMEOUT_SECS |
| 3516 | ); |
| 3517 | |
| 3518 | let high = Config { |
| 3519 | tui: Some(TuiConfig { |
| 3520 | stream_chunk_timeout_secs: Some(MAX_STREAM_CHUNK_TIMEOUT_SECS + 1), |
| 3521 | max_model_steps: None, |
| 3522 | turn_wall_clock_secs: None, |
| 3523 | stream_max_content_mb: None, |
| 3524 | stream_max_duration_secs: None, |
| 3525 | ..TuiConfig::default() |
| 3526 | }), |
| 3527 | ..Config::default() |
| 3528 | }; |
| 3529 | assert_eq!( |
| 3530 | high.stream_chunk_timeout_secs(), |
| 3531 | MAX_STREAM_CHUNK_TIMEOUT_SECS |
| 3532 | ); |
| 3533 | |
| 3534 | unsafe { |
| 3535 | env::set_var(STREAM_CHUNK_TIMEOUT_ENV, "123"); |
| 3536 | } |
| 3537 | assert_eq!(Config::default().stream_chunk_timeout_secs(), 123); |
| 3538 | |
| 3539 | unsafe { |
| 3540 | env::set_var(STREAM_CHUNK_TIMEOUT_ENV, "0"); |
| 3541 | } |
| 3542 | assert_eq!( |
| 3543 | Config::default().stream_chunk_timeout_secs(), |
| 3544 | DEFAULT_STREAM_CHUNK_TIMEOUT_SECS |
| 3545 | ); |
| 3546 | |
| 3547 | unsafe { |
| 3548 | match previous { |
| 3549 | Some(value) => env::set_var(STREAM_CHUNK_TIMEOUT_ENV, value), |
| 3550 | None => env::remove_var(STREAM_CHUNK_TIMEOUT_ENV), |
| 3551 | } |
| 3552 | } |
| 3553 | } |
| 3554 | |
| 3555 | #[test] |
| 3556 | fn save_api_key_writes_config_file_under_cfg_test() -> Result<()> { |
| 3557 | // `save_api_key` writes to the shared user config file. This |
| 3558 | // pins the boring v0.8.8 setup path and avoids platform |
| 3559 | // credential prompts during onboarding. |
| 3560 | let _lock = lock_test_env(); |
| 3561 | let nanos = SystemTime::now() |
| 3562 | .duration_since(UNIX_EPOCH) |
| 3563 | .unwrap() |
| 3564 | .as_nanos(); |
| 3565 | let temp_root = env::temp_dir().join(format!( |
| 3566 | "codewhale-tui-test-{}-{}", |
| 3567 | std::process::id(), |
| 3568 | nanos |
| 3569 | )); |
| 3570 | fs::create_dir_all(&temp_root)?; |
| 3571 | let _guard = EnvGuard::new(&temp_root); |
| 3572 | |
| 3573 | let saved = save_api_key("test-key")?; |
| 3574 | let expected = temp_root.join(".deepseek").join("config.toml"); |
| 3575 | assert_eq!(saved, SavedCredential::ConfigFile(expected.clone())); |
| 3576 | assert_eq!(saved.describe(), expected.display().to_string()); |
| 3577 | |
| 3578 | let contents = fs::read_to_string(&expected)?; |
| 3579 | assert!(contents.contains("api_key = \"")); |
| 3580 | |
| 3581 | #[cfg(unix)] |
| 3582 | { |
| 3583 | assert_eq!(fs::metadata(&expected)?.permissions().mode() & 0o777, 0o600); |
| 3584 | let parent = expected.parent().expect("config has parent dir"); |
| 3585 | assert_eq!(fs::metadata(parent)?.permissions().mode() & 0o077, 0); |
| 3586 | |
| 3587 | fs::set_permissions(&expected, fs::Permissions::from_mode(0o644))?; |
| 3588 | save_api_key("second-test-key")?; |
| 3589 | assert_eq!(fs::metadata(&expected)?.permissions().mode() & 0o777, 0o600); |
| 3590 | } |
| 3591 | Ok(()) |
| 3592 | } |
| 3593 | |
| 3594 | #[test] |
| 3595 | fn policy_control_waits_for_foreign_test_env_overrides_to_restore() { |
| 3596 | // This is a deadlock ceiling, not a latency requirement. In the full |
| 3597 | // library suite, hundreds of environment-sensitive tests can acquire the |
| 3598 | // process-wide lock before this deliberately blocked reader resumes. |
| 3599 | const FULL_SUITE_SCHEDULING_TIMEOUT: Duration = Duration::from_secs(30); |
| 3600 | |
| 3601 | let temp = tempfile::tempdir().expect("tempdir"); |
| 3602 | let config_path = temp.path().join("config.toml"); |
| 3603 | let workspace = temp.path().join("workspace"); |
| 3604 | let managed_config_path = temp.path().join("empty-managed.toml"); |
| 3605 | fs::write(&managed_config_path, "").expect("empty managed config"); |
| 3606 | let requirements_path = temp.path().join("missing-requirements.toml"); |
| 3607 | let (started_tx, started_rx) = mpsc::channel(); |
| 3608 | let (tx, rx) = mpsc::channel(); |
| 3609 | |
| 3610 | let reader = { |
| 3611 | let lock = lock_test_env(); |
| 3612 | let shell_override = EnvVarGuard::set("CODEWHALE_ALLOW_SHELL", "false"); |
| 3613 | let approval_override = EnvVarGuard::set("DEEPSEEK_APPROVAL_POLICY", "never"); |
| 3614 | let reader = std::thread::spawn(move || { |
| 3615 | started_tx.send(()).expect("signal policy read start"); |
| 3616 | let config = Config { |
| 3617 | managed_config_path: Some(managed_config_path.display().to_string()), |
| 3618 | requirements_path: Some(requirements_path.display().to_string()), |
| 3619 | ..Config::default() |
| 3620 | }; |
| 3621 | tx.send(( |
| 3622 | config.allow_shell_control(Some(&config_path), None, &workspace), |
| 3623 | config.approval_policy_control(Some(&config_path), None, &workspace), |
| 3624 | )) |
| 3625 | .expect("send policy controls"); |
| 3626 | }); |
| 3627 | |
| 3628 | started_rx |
| 3629 | .recv_timeout(FULL_SUITE_SCHEDULING_TIMEOUT) |
| 3630 | .expect("reader reached policy read"); |
| 3631 | assert!( |
| 3632 | rx.recv_timeout(Duration::from_millis(50)).is_err(), |
| 3633 | "a foreign reader observed another test's temporary policy overrides" |
| 3634 | ); |
| 3635 | drop(approval_override); |
| 3636 | drop(shell_override); |
| 3637 | drop(lock); |
| 3638 | reader |
| 3639 | }; |
| 3640 | |
| 3641 | let (shell, approval) = rx |
| 3642 | .recv_timeout(FULL_SUITE_SCHEDULING_TIMEOUT) |
| 3643 | .expect("reader resumed after policy overrides were restored"); |
| 3644 | reader.join().expect("reader thread"); |
| 3645 | assert_eq!(shell, ShellAccessControl::Unset); |
| 3646 | assert_eq!(approval, ApprovalPolicyControl::Unset); |
| 3647 | } |
| 3648 | |
| 3649 | /// #6516: the dispatcher exports only `CODEWHALE_*`, so the settings editor |
| 3650 | /// must name whichever variable actually owns the posture instead of a |
| 3651 | /// hard-coded `DEEPSEEK_*` twin the process no longer sets. |
| 3652 | #[test] |
| 3653 | fn environment_policy_labels_name_the_variable_that_is_set() { |
| 3654 | let _lock = lock_test_env(); |
| 3655 | let _legacy_approval = EnvVarGuard::remove("DEEPSEEK_APPROVAL_POLICY"); |
| 3656 | let _approval = EnvVarGuard::set("CODEWHALE_APPROVAL_POLICY", "never"); |
| 3657 | let _shell = EnvVarGuard::remove("CODEWHALE_ALLOW_SHELL"); |
| 3658 | let _legacy_shell = EnvVarGuard::set("DEEPSEEK_ALLOW_SHELL", "false"); |
| 3659 | assert_eq!( |
| 3660 | ApprovalPolicyControl::Environment.label(), |
| 3661 | "CODEWHALE_APPROVAL_POLICY" |
| 3662 | ); |
| 3663 | assert_eq!( |
| 3664 | ShellAccessControl::Environment.label(), |
| 3665 | "DEEPSEEK_ALLOW_SHELL" |
| 3666 | ); |
| 3667 | |
| 3668 | let _both_shell = EnvVarGuard::set("CODEWHALE_ALLOW_SHELL", "true"); |
| 3669 | assert_eq!( |
| 3670 | ShellAccessControl::Environment.label(), |
| 3671 | "CODEWHALE_ALLOW_SHELL", |
| 3672 | "the CODEWHALE_* name wins when both are set, matching the readers" |
| 3673 | ); |
| 3674 | } |
| 3675 | |
| 3676 | #[test] |
| 3677 | fn base_url_reads_wait_for_foreign_test_env_overrides_to_restore() { |
| 3678 | let (started_tx, started_rx) = mpsc::channel(); |
| 3679 | let (tx, rx) = mpsc::channel(); |
| 3680 | |
| 3681 | let reader = { |
| 3682 | let lock = lock_test_env(); |
| 3683 | let expected_after_restore = env_base_url_override(); |
| 3684 | let override_guard = |
| 3685 | EnvVarGuard::set("CODEWHALE_BASE_URL", "https://temporary.test.invalid/v1"); |
| 3686 | let reader = std::thread::spawn(move || { |
| 3687 | started_tx.send(()).expect("signal base URL read start"); |
| 3688 | tx.send(env_base_url_override()) |
| 3689 | .expect("send resolved base URL override"); |
| 3690 | }); |
| 3691 | |
| 3692 | started_rx |
| 3693 | .recv_timeout(Duration::from_secs(2)) |
| 3694 | .expect("reader reached base URL read"); |
| 3695 | assert!( |
| 3696 | rx.recv_timeout(Duration::from_millis(50)).is_err(), |
| 3697 | "a foreign reader observed another test's temporary base URL override" |
| 3698 | ); |
| 3699 | drop(override_guard); |
| 3700 | drop(lock); |
| 3701 | (reader, expected_after_restore) |
| 3702 | }; |
| 3703 | |
| 3704 | let observed = rx |
| 3705 | .recv_timeout(Duration::from_secs(2)) |
| 3706 | .expect("reader resumed after base URL override was restored"); |
| 3707 | reader.0.join().expect("reader thread"); |
| 3708 | assert_eq!(observed, reader.1); |
| 3709 | } |
| 3710 | |
| 3711 | #[test] |
| 3712 | fn save_api_scenario() -> Result<()> { |
| 3713 | // Scenario consolidation of: save_api_key_onboarding_routes_openrouter_key_to_provider_table, save_api_key_rejects_empty_input, save_api_key_for_openai_codex_refuses_config_storage |
| 3714 | // from save_api_key_onboarding_routes_openrouter_key_to_provider_table |
| 3715 | { |
| 3716 | let _lock = lock_test_env(); |
| 3717 | let nanos = SystemTime::now() |
| 3718 | .duration_since(UNIX_EPOCH) |
| 3719 | .unwrap() |
| 3720 | .as_nanos(); |
| 3721 | let temp_root = env::temp_dir().join(format!( |
| 3722 | "codewhale-tui-onboarding-provider-{}-{}", |
| 3723 | std::process::id(), |
| 3724 | nanos |
| 3725 | )); |
| 3726 | fs::create_dir_all(&temp_root)?; |
| 3727 | let _guard = EnvGuard::new(&temp_root); |
| 3728 | |
| 3729 | let path = save_api_key_for(ProviderKind::Openrouter, "onboarding-openrouter-key")?; |
| 3730 | let contents = fs::read_to_string(&path)?; |
| 3731 | assert!( |
| 3732 | contents.contains("openrouter"), |
| 3733 | "expected OpenRouter provider table, got: {contents}" |
| 3734 | ); |
| 3735 | assert!(contents.contains("onboarding-openrouter-key")); |
| 3736 | } |
| 3737 | // from save_api_key_rejects_empty_input |
| 3738 | { |
| 3739 | let _lock = lock_test_env(); |
| 3740 | let err = save_api_key(" ").expect_err("empty should bail"); |
| 3741 | assert!( |
| 3742 | err.to_string().contains("empty"), |
| 3743 | "expected error to mention empty, got: {err}" |
| 3744 | ); |
| 3745 | } |
| 3746 | // from save_api_key_for_openai_codex_refuses_config_storage |
| 3747 | { |
| 3748 | let err = save_api_key_for(ProviderKind::OpenaiCodex, "codex-token") |
| 3749 | .expect_err("Codex OAuth tokens must not be persisted as provider API keys"); |
| 3750 | |
| 3751 | let message = err.to_string(); |
| 3752 | assert!(message.contains("Sign in with ChatGPT"), "{message}"); |
| 3753 | assert!(message.contains("codewhale auth chatgpt"), "{message}"); |
| 3754 | } |
| 3755 | Ok(()) |
| 3756 | } |
| 3757 | |
| 3758 | #[test] |
| 3759 | fn ensure_config_file_exists_creates_first_run_template() -> Result<()> { |
| 3760 | let _lock = lock_test_env(); |
| 3761 | let nanos = SystemTime::now() |
| 3762 | .duration_since(UNIX_EPOCH) |
| 3763 | .unwrap() |
| 3764 | .as_nanos(); |
| 3765 | let temp_root = env::temp_dir().join(format!( |
| 3766 | "codewhale-tui-first-run-config-{}-{}", |
| 3767 | std::process::id(), |
| 3768 | nanos |
| 3769 | )); |
| 3770 | fs::create_dir_all(&temp_root)?; |
| 3771 | let _guard = EnvGuard::new(&temp_root); |
| 3772 | |
| 3773 | let created = ensure_config_file_exists(None)?.expect("should create config"); |
| 3774 | let content = fs::read_to_string(&created)?; |
| 3775 | |
| 3776 | assert_eq!(created, temp_root.join(".deepseek").join("config.toml")); |
| 3777 | assert!(content.contains(&format!("default_text_model = \"{DEFAULT_TEXT_MODEL}\""))); |
| 3778 | assert!(content.contains("reasoning_effort = \"auto\"")); |
| 3779 | // Shift+Tab cycles the permission posture; effort moved to Ctrl+T. |
| 3780 | assert!(content.contains("# Ctrl+T in the TUI")); |
| 3781 | assert!(!content.contains("Shift+Tab")); |
| 3782 | assert!(!content.contains("api_key =")); |
| 3783 | assert!(ensure_config_file_exists(None)?.is_none()); |
| 3784 | Ok(()) |
| 3785 | } |
| 3786 | |
| 3787 | #[test] |
| 3788 | fn workspace_trust_round_trips_through_global_config() -> Result<()> { |
| 3789 | let _lock = lock_test_env(); |
| 3790 | let nanos = SystemTime::now() |
| 3791 | .duration_since(UNIX_EPOCH) |
| 3792 | .unwrap() |
| 3793 | .as_nanos(); |
| 3794 | let temp_root = env::temp_dir().join(format!( |
| 3795 | "codewhale-tui-workspace-trust-{}-{}", |
| 3796 | std::process::id(), |
| 3797 | nanos |
| 3798 | )); |
| 3799 | fs::create_dir_all(&temp_root)?; |
| 3800 | let _guard = EnvGuard::new(&temp_root); |
| 3801 | let workspace = temp_root.join("project"); |
| 3802 | fs::create_dir_all(&workspace)?; |
| 3803 | |
| 3804 | assert!(!is_workspace_trusted(&workspace)); |
| 3805 | let saved = save_workspace_trust(&workspace)?; |
| 3806 | |
| 3807 | assert_eq!(saved, temp_root.join(".deepseek").join("config.toml")); |
| 3808 | assert!(is_workspace_trusted(&workspace)); |
| 3809 | assert!(!crate::config::needs_trust(&workspace)); |
| 3810 | assert!( |
| 3811 | !workspace.join(".deepseek").exists(), |
| 3812 | "trust persistence must not create a project-local .deepseek directory" |
| 3813 | ); |
| 3814 | |
| 3815 | let parsed: toml::Value = toml::from_str(&fs::read_to_string(saved)?)?; |
| 3816 | assert_eq!( |
| 3817 | workspace_trust_level_from_doc(&parsed, &workspace), |
| 3818 | Some("trusted") |
| 3819 | ); |
| 3820 | Ok(()) |
| 3821 | } |
| 3822 | |
| 3823 | #[test] |
| 3824 | fn workspace_trust_reads_existing_projects_table() -> Result<()> { |
| 3825 | let _lock = lock_test_env(); |
| 3826 | let nanos = SystemTime::now() |
| 3827 | .duration_since(UNIX_EPOCH) |
| 3828 | .unwrap() |
| 3829 | .as_nanos(); |
| 3830 | let temp_root = env::temp_dir().join(format!( |
| 3831 | "codewhale-tui-existing-project-trust-{}-{}", |
| 3832 | std::process::id(), |
| 3833 | nanos |
| 3834 | )); |
| 3835 | fs::create_dir_all(&temp_root)?; |
| 3836 | let _guard = EnvGuard::new(&temp_root); |
| 3837 | let workspace = temp_root.join("project"); |
| 3838 | fs::create_dir_all(&workspace)?; |
| 3839 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 3840 | fs::create_dir_all(config_path.parent().unwrap())?; |
| 3841 | fs::write( |
| 3842 | &config_path, |
| 3843 | format!( |
| 3844 | "[projects.\"{}\"]\ntrust_level = \"trusted\"\n", |
| 3845 | workspace_config_key(&workspace) |
| 3846 | .replace('\\', "\\\\") |
| 3847 | .replace('"', "\\\"") |
| 3848 | ), |
| 3849 | )?; |
| 3850 | |
| 3851 | assert!(is_workspace_trusted(&workspace)); |
| 3852 | assert!(!crate::config::needs_trust(&workspace)); |
| 3853 | Ok(()) |
| 3854 | } |
| 3855 | |
| 3856 | #[test] |
| 3857 | fn needs_trust_ignores_repository_self_trust_markers() -> Result<()> { |
| 3858 | let _lock = lock_test_env(); |
| 3859 | let temp_root = tempfile::tempdir()?; |
| 3860 | let _guard = EnvGuard::new(temp_root.path()); |
| 3861 | let workspace = temp_root.path().join("project"); |
| 3862 | let legacy_dir = workspace.join(".deepseek"); |
| 3863 | fs::create_dir_all(&legacy_dir)?; |
| 3864 | fs::write(legacy_dir.join("trusted"), "")?; |
| 3865 | fs::write(legacy_dir.join("trust.json"), "{}")?; |
| 3866 | |
| 3867 | assert!(!is_workspace_trusted(&workspace)); |
| 3868 | assert!(crate::config::needs_trust(&workspace)); |
| 3869 | Ok(()) |
| 3870 | } |
| 3871 | |
| 3872 | #[test] |
| 3873 | fn saved_credential_describe_returns_config_file_path() { |
| 3874 | let cf = SavedCredential::ConfigFile(PathBuf::from("/tmp/x.toml")); |
| 3875 | assert_eq!(cf.describe(), "/tmp/x.toml"); |
| 3876 | } |
| 3877 | |
| 3878 | /// The durable-store outcome makes it explicit that config contains metadata, |
| 3879 | /// not a second plaintext credential copy. |
| 3880 | #[test] |
| 3881 | fn saved_credential_describe_lists_both_targets_for_keyring_and_config() { |
| 3882 | let dual = SavedCredential::KeyringAndConfigFile { |
| 3883 | backend: "system keyring".to_string(), |
| 3884 | path: PathBuf::from("/tmp/x.toml"), |
| 3885 | }; |
| 3886 | assert_eq!( |
| 3887 | dual.describe(), |
| 3888 | "secret store (system keyring); credential-free config metadata in /tmp/x.toml" |
| 3889 | ); |
| 3890 | } |
| 3891 | |
| 3892 | #[test] |
| 3893 | fn save_deepseek_key_uses_isolated_file_store_without_plaintext_config() -> Result<()> { |
| 3894 | let _lock = lock_test_env(); |
| 3895 | let temp_root = tempfile::tempdir()?; |
| 3896 | let _guard = EnvGuard::new(temp_root.path()); |
| 3897 | let codewhale_home = temp_root.path().join("codewhale-home"); |
| 3898 | let config_path = codewhale_home.join("config.toml"); |
| 3899 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 3900 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 3901 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 3902 | |
| 3903 | let saved = save_api_key("deepseek-test-credential")?; |
| 3904 | assert!(matches!( |
| 3905 | saved, |
| 3906 | SavedCredential::KeyringAndConfigFile { .. } |
| 3907 | )); |
| 3908 | |
| 3909 | let config = fs::read_to_string(&config_path)?; |
| 3910 | assert!(!config.contains("deepseek-test-credential"), "{config}"); |
| 3911 | assert!( |
| 3912 | !config |
| 3913 | .lines() |
| 3914 | .any(|line| line.trim_start().starts_with("api_key =")) |
| 3915 | ); |
| 3916 | let parsed: toml::Value = toml::from_str(&config)?; |
| 3917 | assert_eq!( |
| 3918 | parsed["providers"]["deepseek"]["auth_mode"].as_str(), |
| 3919 | Some("api_key") |
| 3920 | ); |
| 3921 | // Saving a key leaves the model to the provider default. |
| 3922 | assert!(!config.contains("default_text_model"), "{config}"); |
| 3923 | assert_eq!( |
| 3924 | codewhale_secrets::Secrets::auto_detect().get("deepseek")?, |
| 3925 | Some("deepseek-test-credential".to_string()) |
| 3926 | ); |
| 3927 | Ok(()) |
| 3928 | } |
| 3929 | |
| 3930 | /// #5196: logout must remove the durable credential, not just the config |
| 3931 | /// file entry. After save + `clear_api_key()`, the whole read chain — |
| 3932 | /// secret-store slot first, config file second — must find nothing. |
| 3933 | #[test] |
| 3934 | fn full_logout_clears_secret_store_slot_and_config_document() -> Result<()> { |
| 3935 | let _lock = lock_test_env(); |
| 3936 | let temp_root = tempfile::tempdir()?; |
| 3937 | // Canonicalize: the xAI credential walker opens each path component with |
| 3938 | // O_NOFOLLOW, so the lexical `/var` symlink in macOS tempdirs fails. |
| 3939 | let temp_root = temp_root.path().canonicalize()?; |
| 3940 | let _guard = EnvGuard::new(&temp_root); |
| 3941 | let codewhale_home = temp_root.join("codewhale-home"); |
| 3942 | let config_path = codewhale_home.join("config.toml"); |
| 3943 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 3944 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 3945 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 3946 | |
| 3947 | let saved = save_api_key("logout-credential")?; |
| 3948 | assert!(matches!( |
| 3949 | saved, |
| 3950 | SavedCredential::KeyringAndConfigFile { .. } |
| 3951 | )); |
| 3952 | assert_eq!( |
| 3953 | codewhale_secrets::Secrets::auto_detect().get("deepseek")?, |
| 3954 | Some("logout-credential".to_string()) |
| 3955 | ); |
| 3956 | |
| 3957 | clear_api_key()?; |
| 3958 | |
| 3959 | assert_eq!( |
| 3960 | codewhale_secrets::Secrets::auto_detect().get("deepseek")?, |
| 3961 | None, |
| 3962 | "logout must delete the durable secret-store slot" |
| 3963 | ); |
| 3964 | assert_eq!( |
| 3965 | provider_secret_store_api_key( |
| 3966 | &Config::default(), |
| 3967 | &(Config::default()).test_identity_for_kind(ProviderKind::Deepseek) |
| 3968 | ), |
| 3969 | None, |
| 3970 | "the read chain must not find a cleared credential" |
| 3971 | ); |
| 3972 | let config = fs::read_to_string(&config_path)?; |
| 3973 | assert!(!config.contains("logout-credential"), "{config}"); |
| 3974 | assert!( |
| 3975 | !config |
| 3976 | .lines() |
| 3977 | .any(|line| line.trim_start().starts_with("api_key =")), |
| 3978 | "{config}" |
| 3979 | ); |
| 3980 | Ok(()) |
| 3981 | } |
| 3982 | |
| 3983 | /// #5196: the single-provider clear used by TUI `/logout` must delete that |
| 3984 | /// provider's secret-store slot as well as its config-file entry. |
| 3985 | #[test] |
| 3986 | fn single_provider_logout_clears_secret_store_slot() -> Result<()> { |
| 3987 | let _lock = lock_test_env(); |
| 3988 | let temp_root = tempfile::tempdir()?; |
| 3989 | let temp_root = temp_root.path().canonicalize()?; |
| 3990 | let _guard = EnvGuard::new(&temp_root); |
| 3991 | let codewhale_home = temp_root.join("codewhale-home"); |
| 3992 | let config_path = codewhale_home.join("config.toml"); |
| 3993 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 3994 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 3995 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 3996 | |
| 3997 | save_api_key_for(ProviderKind::Openrouter, "openrouter-logout-credential")?; |
| 3998 | assert_eq!( |
| 3999 | codewhale_secrets::Secrets::auto_detect().get("openrouter")?, |
| 4000 | Some("openrouter-logout-credential".to_string()) |
| 4001 | ); |
| 4002 | |
| 4003 | clear_active_provider_api_key("openrouter")?; |
| 4004 | |
| 4005 | assert_eq!( |
| 4006 | codewhale_secrets::Secrets::auto_detect().get("openrouter")?, |
| 4007 | None, |
| 4008 | "single-provider logout must delete the durable secret-store slot" |
| 4009 | ); |
| 4010 | assert_eq!( |
| 4011 | provider_secret_store_api_key( |
| 4012 | &Config::default(), |
| 4013 | &(Config::default()).test_identity_for_kind(ProviderKind::Openrouter) |
| 4014 | ), |
| 4015 | None, |
| 4016 | "the read chain must not find a cleared credential" |
| 4017 | ); |
| 4018 | Ok(()) |
| 4019 | } |
| 4020 | |
| 4021 | fn inject_plaintext_openrouter_key(config_path: &std::path::Path) -> Result<()> { |
| 4022 | let contents = fs::read_to_string(config_path)?; |
| 4023 | anyhow::ensure!( |
| 4024 | contents.contains("[providers.openrouter]"), |
| 4025 | "save must have created the provider table: {contents}" |
| 4026 | ); |
| 4027 | fs::write( |
| 4028 | config_path, |
| 4029 | contents.replace( |
| 4030 | "[providers.openrouter]", |
| 4031 | "[providers.openrouter]\napi_key = \"logout-lock-plaintext\"", |
| 4032 | ), |
| 4033 | )?; |
| 4034 | Ok(()) |
| 4035 | } |
| 4036 | |
| 4037 | struct ReleaseOnDrop(Option<mpsc::Sender<()>>); |
| 4038 | |
| 4039 | impl Drop for ReleaseOnDrop { |
| 4040 | fn drop(&mut self) { |
| 4041 | if let Some(tx) = self.0.take() { |
| 4042 | let _ = tx.send(()); |
| 4043 | } |
| 4044 | } |
| 4045 | } |
| 4046 | |
| 4047 | /// Logout used to mutate the config document and (for `/logout`) the durable |
| 4048 | /// slot with no write lock held, so a save racing a logout on one slot could |
| 4049 | /// leave the store and the config file disagreeing. Both logout paths now |
| 4050 | /// hold that provider's lock across the whole sequence. |
| 4051 | #[test] |
| 4052 | fn single_provider_logout_holds_the_slot_write_lock_across_config_and_store() -> Result<()> { |
| 4053 | let _lock = lock_test_env(); |
| 4054 | let temp_root = tempfile::tempdir()?; |
| 4055 | let temp_root = temp_root.path().canonicalize()?; |
| 4056 | let _guard = EnvGuard::new(&temp_root); |
| 4057 | let codewhale_home = temp_root.join("codewhale-home"); |
| 4058 | let config_path = codewhale_home.join("config.toml"); |
| 4059 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 4060 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 4061 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4062 | |
| 4063 | save_api_key_for(ProviderKind::Openrouter, "openrouter-lock-credential")?; |
| 4064 | inject_plaintext_openrouter_key(&config_path)?; |
| 4065 | |
| 4066 | let (held_tx, held_rx) = mpsc::channel(); |
| 4067 | let (release_tx, release_rx) = mpsc::channel(); |
| 4068 | let holder = std::thread::spawn(move || { |
| 4069 | crate::credentials::store::with_provider_write_lock("openrouter", || { |
| 4070 | let _ = held_tx.send(()); |
| 4071 | let _ = release_rx.recv(); |
| 4072 | }); |
| 4073 | }); |
| 4074 | held_rx |
| 4075 | .recv_timeout(Duration::from_secs(5)) |
| 4076 | .expect("holder acquired the slot lock"); |
| 4077 | let release = ReleaseOnDrop(Some(release_tx)); |
| 4078 | |
| 4079 | let ticket = env_scope_ticket(); |
| 4080 | let (done_tx, done_rx) = mpsc::channel(); |
| 4081 | let logout = std::thread::spawn(move || { |
| 4082 | let _membership = join_env_scope(ticket); |
| 4083 | done_tx |
| 4084 | .send(clear_active_provider_api_key("openrouter")) |
| 4085 | .expect("send logout result"); |
| 4086 | }); |
| 4087 | |
| 4088 | let deadline = std::time::Instant::now() + Duration::from_millis(400); |
| 4089 | while std::time::Instant::now() < deadline { |
| 4090 | assert!( |
| 4091 | matches!(done_rx.try_recv(), Err(mpsc::TryRecvError::Empty)), |
| 4092 | "single-provider logout finished while the slot write lock was held" |
| 4093 | ); |
| 4094 | let config = fs::read_to_string(&config_path)?; |
| 4095 | assert!( |
| 4096 | config.contains("logout-lock-plaintext"), |
| 4097 | "logout must not mutate the config document before it holds the slot lock: {config}" |
| 4098 | ); |
| 4099 | assert_eq!( |
| 4100 | codewhale_secrets::Secrets::auto_detect().get("openrouter")?, |
| 4101 | Some("openrouter-lock-credential".to_string()), |
| 4102 | "logout must not delete the slot while the write lock is held" |
| 4103 | ); |
| 4104 | std::thread::sleep(Duration::from_millis(20)); |
| 4105 | } |
| 4106 | |
| 4107 | drop(release); |
| 4108 | holder.join().expect("holder thread"); |
| 4109 | done_rx |
| 4110 | .recv_timeout(Duration::from_secs(5)) |
| 4111 | .expect("logout finished")?; |
| 4112 | logout.join().expect("logout thread"); |
| 4113 | |
| 4114 | assert_eq!( |
| 4115 | codewhale_secrets::Secrets::auto_detect().get("openrouter")?, |
| 4116 | None, |
| 4117 | "logout must delete the durable slot once the lock is released" |
| 4118 | ); |
| 4119 | let config = fs::read_to_string(&config_path)?; |
| 4120 | assert!( |
| 4121 | !config.contains("logout-lock-plaintext"), |
| 4122 | "logout must strip the injected plaintext once the lock is released: {config}" |
| 4123 | ); |
| 4124 | Ok(()) |
| 4125 | } |
| 4126 | |
| 4127 | #[test] |
| 4128 | fn full_logout_holds_every_slot_write_lock_across_config_and_store() -> Result<()> { |
| 4129 | let _lock = lock_test_env(); |
| 4130 | let temp_root = tempfile::tempdir()?; |
| 4131 | let temp_root = temp_root.path().canonicalize()?; |
| 4132 | let _guard = EnvGuard::new(&temp_root); |
| 4133 | let codewhale_home = temp_root.join("codewhale-home"); |
| 4134 | let config_path = codewhale_home.join("config.toml"); |
| 4135 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 4136 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 4137 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4138 | |
| 4139 | save_api_key_for(ProviderKind::Openrouter, "openrouter-lock-credential")?; |
| 4140 | inject_plaintext_openrouter_key(&config_path)?; |
| 4141 | |
| 4142 | let (held_tx, held_rx) = mpsc::channel(); |
| 4143 | let (release_tx, release_rx) = mpsc::channel(); |
| 4144 | let holder = std::thread::spawn(move || { |
| 4145 | crate::credentials::store::with_provider_write_lock("openrouter", || { |
| 4146 | let _ = held_tx.send(()); |
| 4147 | let _ = release_rx.recv(); |
| 4148 | }); |
| 4149 | }); |
| 4150 | held_rx |
| 4151 | .recv_timeout(Duration::from_secs(5)) |
| 4152 | .expect("holder acquired the slot lock"); |
| 4153 | let release = ReleaseOnDrop(Some(release_tx)); |
| 4154 | |
| 4155 | let ticket = env_scope_ticket(); |
| 4156 | let (done_tx, done_rx) = mpsc::channel(); |
| 4157 | let logout = std::thread::spawn(move || { |
| 4158 | let _membership = join_env_scope(ticket); |
| 4159 | done_tx.send(clear_api_key()).expect("send logout result"); |
| 4160 | }); |
| 4161 | |
| 4162 | let deadline = std::time::Instant::now() + Duration::from_millis(400); |
| 4163 | while std::time::Instant::now() < deadline { |
| 4164 | assert!( |
| 4165 | matches!(done_rx.try_recv(), Err(mpsc::TryRecvError::Empty)), |
| 4166 | "full logout finished while a slot write lock was held" |
| 4167 | ); |
| 4168 | let config = fs::read_to_string(&config_path)?; |
| 4169 | assert!( |
| 4170 | config.contains("logout-lock-plaintext"), |
| 4171 | "full logout must not mutate the config document before it holds the slot locks: {config}" |
| 4172 | ); |
| 4173 | assert_eq!( |
| 4174 | codewhale_secrets::Secrets::auto_detect().get("openrouter")?, |
| 4175 | Some("openrouter-lock-credential".to_string()), |
| 4176 | "full logout must not delete a slot while that slot's write lock is held" |
| 4177 | ); |
| 4178 | std::thread::sleep(Duration::from_millis(20)); |
| 4179 | } |
| 4180 | |
| 4181 | drop(release); |
| 4182 | holder.join().expect("holder thread"); |
| 4183 | done_rx |
| 4184 | .recv_timeout(Duration::from_secs(5)) |
| 4185 | .expect("logout finished")?; |
| 4186 | logout.join().expect("logout thread"); |
| 4187 | |
| 4188 | assert_eq!( |
| 4189 | codewhale_secrets::Secrets::auto_detect().get("openrouter")?, |
| 4190 | None, |
| 4191 | "full logout must delete the durable slot once the lock is released" |
| 4192 | ); |
| 4193 | let config = fs::read_to_string(&config_path)?; |
| 4194 | assert!( |
| 4195 | !config.contains("logout-lock-plaintext"), |
| 4196 | "full logout must strip the injected plaintext once the lock is released: {config}" |
| 4197 | ); |
| 4198 | Ok(()) |
| 4199 | } |
| 4200 | |
| 4201 | /// #5194: when both a config-file api_key and the provider's secret-store |
| 4202 | /// slot hold a credential, the shadowing warning names both sources, says |
| 4203 | /// which won, and hands over the resolve command. |
| 4204 | #[test] |
| 4205 | fn config_api_key_shadow_warning_names_sources_winner_and_resolution() -> Result<()> { |
| 4206 | let _lock = lock_test_env(); |
| 4207 | let temp_root = tempfile::tempdir()?; |
| 4208 | let _guard = EnvGuard::new(temp_root.path()); |
| 4209 | let codewhale_home = temp_root.path().join("codewhale-home"); |
| 4210 | let config_path = codewhale_home.join("config.toml"); |
| 4211 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 4212 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 4213 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4214 | codewhale_secrets::Secrets::auto_detect().set("openrouter", "store-key")?; |
| 4215 | |
| 4216 | let mut config = Config::default(); |
| 4217 | config |
| 4218 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Openrouter)) |
| 4219 | .unwrap() |
| 4220 | .api_key = Some("plaintext-config-key".to_string()); |
| 4221 | |
| 4222 | let warning = config_api_key_shadow_warning( |
| 4223 | &config, |
| 4224 | &(config).test_identity_for_kind(ProviderKind::Openrouter), |
| 4225 | "`providers.openrouter` api_key", |
| 4226 | ) |
| 4227 | .expect("a live secret-store slot shadowed by a config key must warn"); |
| 4228 | assert!( |
| 4229 | warning.contains("`providers.openrouter` api_key"), |
| 4230 | "warning must name the config-file source: {warning}" |
| 4231 | ); |
| 4232 | assert!( |
| 4233 | warning.contains("secret-store slot \"openrouter\""), |
| 4234 | "warning must name the secret-store source: {warning}" |
| 4235 | ); |
| 4236 | assert!( |
| 4237 | warning.contains("the config-file key won"), |
| 4238 | "warning must say which source won: {warning}" |
| 4239 | ); |
| 4240 | assert!( |
| 4241 | warning.contains("codewhale auth set --provider openrouter"), |
| 4242 | "warning must name the resolve command: {warning}" |
| 4243 | ); |
| 4244 | Ok(()) |
| 4245 | } |
| 4246 | |
| 4247 | /// #5194: no secret-store credential, no shadow, no warning. |
| 4248 | #[test] |
| 4249 | fn config_api_key_shadow_warning_stays_quiet_without_a_store_slot() -> Result<()> { |
| 4250 | let _lock = lock_test_env(); |
| 4251 | let temp_root = tempfile::tempdir()?; |
| 4252 | let _guard = EnvGuard::new(temp_root.path()); |
| 4253 | let codewhale_home = temp_root.path().join("codewhale-home"); |
| 4254 | let config_path = codewhale_home.join("config.toml"); |
| 4255 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 4256 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 4257 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4258 | |
| 4259 | let mut config = Config::default(); |
| 4260 | config |
| 4261 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Openrouter)) |
| 4262 | .unwrap() |
| 4263 | .api_key = Some("plaintext-config-key".to_string()); |
| 4264 | |
| 4265 | assert_eq!( |
| 4266 | config_api_key_shadow_warning( |
| 4267 | &config, |
| 4268 | &(config).test_identity_for_kind(ProviderKind::Openrouter), |
| 4269 | "`providers.openrouter` api_key" |
| 4270 | ), |
| 4271 | None, |
| 4272 | "a config key with no secret-store slot behind it is not a shadow" |
| 4273 | ); |
| 4274 | Ok(()) |
| 4275 | } |
| 4276 | |
| 4277 | #[test] |
| 4278 | fn whitespace_codewhale_home_never_opens_ambient_file_secret_store() -> Result<()> { |
| 4279 | let _lock = lock_test_env(); |
| 4280 | let temp_root = tempfile::tempdir()?; |
| 4281 | let ambient_home = temp_root.path().join("ambient-home"); |
| 4282 | let config_path = temp_root.path().join("isolated-config.toml"); |
| 4283 | fs::create_dir_all(&ambient_home)?; |
| 4284 | let _home = EnvVarGuard::set("HOME", &ambient_home); |
| 4285 | let _userprofile = EnvVarGuard::set("USERPROFILE", &ambient_home); |
| 4286 | let _codewhale_home_unset = EnvVarGuard::remove("CODEWHALE_HOME"); |
| 4287 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4288 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", &config_path); |
| 4289 | let ambient_store = codewhale_secrets::Secrets::file_backed(); |
| 4290 | ambient_store.set("deepseek", "ambient-secret-sentinel")?; |
| 4291 | let ambient_secret_path = ambient_home |
| 4292 | .join(".codewhale") |
| 4293 | .join("secrets") |
| 4294 | .join("secrets.json"); |
| 4295 | let before = fs::read(&ambient_secret_path)?; |
| 4296 | let _whitespace_home = EnvVarGuard::set("CODEWHALE_HOME", " \t "); |
| 4297 | let resolved_config_path = codewhale_config::resolve_config_path(None)?; |
| 4298 | |
| 4299 | let read = provider_secret_store_api_key( |
| 4300 | &Config::default(), |
| 4301 | &(Config::default()).test_identity_for_kind(ProviderKind::Deepseek), |
| 4302 | ); |
| 4303 | let saved = save_api_key("replacement-secret-sentinel")?; |
| 4304 | let after = fs::read(&ambient_secret_path)?; |
| 4305 | |
| 4306 | assert_eq!( |
| 4307 | read, None, |
| 4308 | "whitespace must not opt tests into ambient reads" |
| 4309 | ); |
| 4310 | assert_eq!(saved, SavedCredential::ConfigFile(resolved_config_path)); |
| 4311 | assert_eq!(after, before, "ambient file secret store was modified"); |
| 4312 | Ok(()) |
| 4313 | } |
| 4314 | |
| 4315 | #[test] |
| 4316 | fn save_non_deepseek_key_uses_isolated_file_store_without_plaintext_config() -> Result<()> { |
| 4317 | let _lock = lock_test_env(); |
| 4318 | let temp_root = tempfile::tempdir()?; |
| 4319 | let _guard = EnvGuard::new(temp_root.path()); |
| 4320 | let codewhale_home = temp_root.path().join("codewhale-home"); |
| 4321 | let config_path = codewhale_home.join("config.toml"); |
| 4322 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 4323 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 4324 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4325 | |
| 4326 | save_api_key_for(ProviderKind::Openrouter, "openrouter-test-credential")?; |
| 4327 | |
| 4328 | let config = fs::read_to_string(&config_path)?; |
| 4329 | assert!(!config.contains("openrouter-test-credential"), "{config}"); |
| 4330 | let parsed: toml::Value = toml::from_str(&config)?; |
| 4331 | let openrouter = parsed |
| 4332 | .get("providers") |
| 4333 | .and_then(|providers| providers.get("openrouter")) |
| 4334 | .expect("openrouter metadata table"); |
| 4335 | assert!(openrouter.get("api_key").is_none()); |
| 4336 | assert_eq!( |
| 4337 | openrouter.get("auth_mode").and_then(toml::Value::as_str), |
| 4338 | Some("api_key") |
| 4339 | ); |
| 4340 | assert_eq!( |
| 4341 | codewhale_secrets::Secrets::auto_detect().get("openrouter")?, |
| 4342 | Some("openrouter-test-credential".to_string()) |
| 4343 | ); |
| 4344 | Ok(()) |
| 4345 | } |
| 4346 | |
| 4347 | #[test] |
| 4348 | fn provider_api_key_config_failure_restores_secret_and_keeps_external_route() -> Result<()> { |
| 4349 | let _lock = lock_test_env(); |
| 4350 | for prior in [None, Some("prior-xai-secret")] { |
| 4351 | let temp_root = tempfile::tempdir()?; |
| 4352 | let _guard = EnvGuard::new(temp_root.path()); |
| 4353 | let codewhale_home = temp_root.path().canonicalize()?.join("codewhale-home"); |
| 4354 | fs::create_dir_all(&codewhale_home)?; |
| 4355 | let config_path = codewhale_home.join("config.toml"); |
| 4356 | fs::create_dir(&config_path)?; |
| 4357 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 4358 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", &config_path); |
| 4359 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4360 | let generation = "xai-auth-0123456789abcdef0123456789abcdef.json"; |
| 4361 | codewhale_config::with_xai_oauth_lifecycle_lock(|store| { |
| 4362 | store.write(generation, b"prior-owned-epoch", false) |
| 4363 | })?; |
| 4364 | let secrets = codewhale_secrets::Secrets::auto_detect(); |
| 4365 | if let Some(prior) = prior { |
| 4366 | secrets.set("xai", prior)?; |
| 4367 | } |
| 4368 | let external_path = temp_root.path().join("external-grok.json"); |
| 4369 | let route_config = Config { |
| 4370 | provider: Some(ProviderKind::Xai.as_str().to_string()), |
| 4371 | providers: Some(ProvidersConfig { |
| 4372 | xai: ProviderConfig { |
| 4373 | auth_mode: Some("oauth".to_string()), |
| 4374 | oauth_credential_generation: Some(generation.to_string()), |
| 4375 | external_credentials: Some( |
| 4376 | codewhale_config::ExternalCredentialConsentToml::read_only( |
| 4377 | codewhale_config::ProviderKind::Xai, |
| 4378 | codewhale_config::ExternalCredentialSource::GrokCli, |
| 4379 | external_path, |
| 4380 | ), |
| 4381 | ), |
| 4382 | ..ProviderConfig::default() |
| 4383 | }, |
| 4384 | ..ProvidersConfig::default() |
| 4385 | }), |
| 4386 | ..Config::default() |
| 4387 | }; |
| 4388 | let identity = ProviderIdentity { |
| 4389 | provider: ProviderKind::Xai, |
| 4390 | key: ProviderKind::Xai.as_str().into(), |
| 4391 | exact_id: Some(ProviderKind::Xai.as_str().into()), |
| 4392 | migrated_legacy_ollama_cloud_route: false, |
| 4393 | legacy_root_custom_generation: None, |
| 4394 | }; |
| 4395 | let error = save_api_key_for_identity(&identity, &route_config, "new-xai-secret") |
| 4396 | .expect_err("config directory must reject metadata mutation"); |
| 4397 | assert!(error.to_string().contains("config"), "{error:#}"); |
| 4398 | assert_eq!(secrets.get("xai")?, prior.map(str::to_string)); |
| 4399 | let xai = route_config |
| 4400 | .provider_config_for(&route_config.test_identity_for_kind(ProviderKind::Xai)) |
| 4401 | .expect("unchanged live route"); |
| 4402 | assert_eq!(xai.auth_mode.as_deref(), Some("oauth")); |
| 4403 | assert!(xai.external_credentials.is_some()); |
| 4404 | assert!(config_path.is_dir()); |
| 4405 | assert_eq!( |
| 4406 | fs::read(codewhale_home.join("credentials").join(generation))?, |
| 4407 | b"prior-owned-epoch", |
| 4408 | "failed API-key mode switch must restore the prior OAuth epoch" |
| 4409 | ); |
| 4410 | } |
| 4411 | Ok(()) |
| 4412 | } |
| 4413 | |
| 4414 | #[test] |
| 4415 | fn root_api_key_config_failure_restores_absent_and_existing_secret_state() -> Result<()> { |
| 4416 | let _lock = lock_test_env(); |
| 4417 | for prior in [None, Some("prior-deepseek-secret")] { |
| 4418 | let temp_root = tempfile::tempdir()?; |
| 4419 | let _guard = EnvGuard::new(temp_root.path()); |
| 4420 | let codewhale_home = temp_root.path().join("codewhale-home"); |
| 4421 | fs::create_dir_all(&codewhale_home)?; |
| 4422 | let config_path = codewhale_home.join("config.toml"); |
| 4423 | fs::create_dir(&config_path)?; |
| 4424 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 4425 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", &config_path); |
| 4426 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4427 | let secrets = codewhale_secrets::Secrets::auto_detect(); |
| 4428 | if let Some(prior) = prior { |
| 4429 | secrets.set("deepseek", prior)?; |
| 4430 | } |
| 4431 | |
| 4432 | let error = save_api_key("new-deepseek-secret") |
| 4433 | .expect_err("config directory must reject root metadata mutation"); |
| 4434 | assert!(error.to_string().contains("config"), "{error:#}"); |
| 4435 | assert_eq!(secrets.get("deepseek")?, prior.map(str::to_string)); |
| 4436 | assert!(config_path.is_dir()); |
| 4437 | } |
| 4438 | Ok(()) |
| 4439 | } |
| 4440 | |
| 4441 | #[test] |
| 4442 | fn save_key_refuses_plaintext_config_when_isolated_file_store_is_unwritable() -> Result<()> { |
| 4443 | let _lock = lock_test_env(); |
| 4444 | let temp_root = tempfile::tempdir()?; |
| 4445 | let _guard = EnvGuard::new(temp_root.path()); |
| 4446 | let codewhale_home = temp_root.path().join("codewhale-home"); |
| 4447 | let config_path = codewhale_home.join("config.toml"); |
| 4448 | fs::create_dir_all(codewhale_home.join("secrets"))?; |
| 4449 | fs::write( |
| 4450 | codewhale_home.join("secrets/secrets.json"), |
| 4451 | "not valid json", |
| 4452 | )?; |
| 4453 | #[cfg(unix)] |
| 4454 | fs::set_permissions( |
| 4455 | codewhale_home.join("secrets/secrets.json"), |
| 4456 | fs::Permissions::from_mode(0o600), |
| 4457 | )?; |
| 4458 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 4459 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 4460 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4461 | let resolved_config_path = codewhale_config::resolve_config_path(None)?; |
| 4462 | |
| 4463 | let error = save_api_key("fallback-test-credential") |
| 4464 | .expect_err("secret-store failure must not downgrade to plaintext"); |
| 4465 | let message = format!("{error:#}"); |
| 4466 | assert!(message.contains("Secret storage"), "{message}"); |
| 4467 | assert!(message.contains("Refusing"), "{message}"); |
| 4468 | assert!( |
| 4469 | message.contains(&codewhale_config::quote_os_path(&resolved_config_path)), |
| 4470 | "{message}" |
| 4471 | ); |
| 4472 | assert!( |
| 4473 | !resolved_config_path.exists(), |
| 4474 | "plaintext config must stay untouched" |
| 4475 | ); |
| 4476 | Ok(()) |
| 4477 | } |
| 4478 | |
| 4479 | #[test] |
| 4480 | fn provider_key_refuses_plaintext_config_when_secret_store_snapshot_fails() -> Result<()> { |
| 4481 | let _lock = lock_test_env(); |
| 4482 | let temp_root = tempfile::tempdir()?; |
| 4483 | let _guard = EnvGuard::new(temp_root.path()); |
| 4484 | let codewhale_home = temp_root.path().join("codewhale-home"); |
| 4485 | let config_path = codewhale_home.join("config.toml"); |
| 4486 | fs::create_dir_all(codewhale_home.join("secrets"))?; |
| 4487 | fs::write( |
| 4488 | codewhale_home.join("secrets/secrets.json"), |
| 4489 | "not valid json", |
| 4490 | )?; |
| 4491 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 4492 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", &config_path); |
| 4493 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4494 | let resolved_config_path = codewhale_config::resolve_config_path(None)?; |
| 4495 | let identity = ProviderIdentity { |
| 4496 | provider: ProviderKind::Openrouter, |
| 4497 | key: ProviderKind::Openrouter.as_str().into(), |
| 4498 | exact_id: Some(ProviderKind::Openrouter.as_str().into()), |
| 4499 | migrated_legacy_ollama_cloud_route: false, |
| 4500 | legacy_root_custom_generation: None, |
| 4501 | }; |
| 4502 | |
| 4503 | let error = save_api_key_for_identity(&identity, &Config::default(), "provider-fallback-key") |
| 4504 | .expect_err("provider key must not downgrade to plaintext"); |
| 4505 | let message = format!("{error:#}"); |
| 4506 | assert!(message.contains("snapshot"), "{message}"); |
| 4507 | assert!( |
| 4508 | message.contains(&codewhale_config::quote_os_path(&resolved_config_path)), |
| 4509 | "{message}" |
| 4510 | ); |
| 4511 | assert!( |
| 4512 | !resolved_config_path.exists(), |
| 4513 | "plaintext config must stay untouched" |
| 4514 | ); |
| 4515 | Ok(()) |
| 4516 | } |
| 4517 | |
| 4518 | #[test] |
| 4519 | fn relative_codewhale_home_key_save_creates_no_workspace_state() -> Result<()> { |
| 4520 | let _lock = lock_test_env(); |
| 4521 | let temp_root = tempfile::tempdir()?; |
| 4522 | let _guard = EnvGuard::new(temp_root.path()); |
| 4523 | let relative_home = PathBuf::from(format!( |
| 4524 | ".codewhale-relative-home-{}-{}", |
| 4525 | std::process::id(), |
| 4526 | SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos() |
| 4527 | )); |
| 4528 | assert!(!relative_home.exists()); |
| 4529 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &relative_home); |
| 4530 | let _config_path = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"); |
| 4531 | let _legacy_config_path = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"); |
| 4532 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4533 | |
| 4534 | let error = save_api_key("never-persisted") |
| 4535 | .expect_err("relative CODEWHALE_HOME must fail before persistence"); |
| 4536 | let message = format!("{error:#}"); |
| 4537 | assert!(message.contains("CODEWHALE_HOME"), "{message}"); |
| 4538 | assert!(message.contains("absolute"), "{message}"); |
| 4539 | assert!( |
| 4540 | !relative_home.exists(), |
| 4541 | "relative home must not create workspace state" |
| 4542 | ); |
| 4543 | Ok(()) |
| 4544 | } |
| 4545 | |
| 4546 | #[test] |
| 4547 | fn deepseek_dispatcher_env_key_overrides_config_key() -> Result<()> { |
| 4548 | let _lock = lock_test_env(); |
| 4549 | let prev_source = std::env::var_os("DEEPSEEK_API_KEY_SOURCE"); |
| 4550 | unsafe { |
| 4551 | std::env::set_var("DEEPSEEK_API_KEY", "ark-dispatcher-key"); |
| 4552 | std::env::set_var("DEEPSEEK_API_KEY_SOURCE", "cli"); |
| 4553 | } |
| 4554 | let config = Config { |
| 4555 | ..Default::default() |
| 4556 | } |
| 4557 | .with_legacy_root(Some("saved-deepseek-key".to_string()), None); |
| 4558 | |
| 4559 | assert_eq!(config.active_route_api_key()?, "ark-dispatcher-key"); |
| 4560 | |
| 4561 | unsafe { |
| 4562 | std::env::remove_var("DEEPSEEK_API_KEY"); |
| 4563 | match prev_source { |
| 4564 | Some(value) => std::env::set_var("DEEPSEEK_API_KEY_SOURCE", value), |
| 4565 | None => std::env::remove_var("DEEPSEEK_API_KEY_SOURCE"), |
| 4566 | } |
| 4567 | } |
| 4568 | Ok(()) |
| 4569 | } |
| 4570 | |
| 4571 | /// Regression for #343: clear_api_key strips both the root `api_key` |
| 4572 | /// and any nested `[providers.<name>].api_key` lines from config.toml |
| 4573 | /// so a stale credential can't shadow a fresh login. |
| 4574 | #[test] |
| 4575 | fn clear_api_key_strips_root_and_provider_scoped_keys() -> Result<()> { |
| 4576 | let _lock = lock_test_env(); |
| 4577 | let nanos = SystemTime::now() |
| 4578 | .duration_since(UNIX_EPOCH) |
| 4579 | .unwrap() |
| 4580 | .as_nanos(); |
| 4581 | let temp_root = env::temp_dir().join(format!( |
| 4582 | "codewhale-tui-clear-{}-{}", |
| 4583 | std::process::id(), |
| 4584 | nanos |
| 4585 | )); |
| 4586 | fs::create_dir_all(&temp_root)?; |
| 4587 | let temp_root = temp_root.canonicalize()?; |
| 4588 | let _guard = EnvGuard::new(&temp_root); |
| 4589 | |
| 4590 | let config_dir = temp_root.join(".deepseek"); |
| 4591 | fs::create_dir_all(&config_dir)?; |
| 4592 | let config_path = config_dir.join("config.toml"); |
| 4593 | fs::write( |
| 4594 | &config_path, |
| 4595 | r#"api_key = "old-root-key" |
| 4596 | default_text_model = "deepseek-v4-flash" |
| 4597 | |
| 4598 | [providers.deepseek] |
| 4599 | api_key = "old-provider-key" |
| 4600 | base_url = "https://api.deepseek.com" |
| 4601 | |
| 4602 | [providers.openrouter] |
| 4603 | api_key = "old-openrouter-key" |
| 4604 | "#, |
| 4605 | )?; |
| 4606 | |
| 4607 | clear_api_key()?; |
| 4608 | |
| 4609 | let after = fs::read_to_string(&config_path)?; |
| 4610 | assert!( |
| 4611 | !after.contains("old-root-key"), |
| 4612 | "root api_key must be stripped: {after}" |
| 4613 | ); |
| 4614 | assert!( |
| 4615 | !after.contains("old-provider-key"), |
| 4616 | "provider-scoped codewhale key must be stripped: {after}" |
| 4617 | ); |
| 4618 | assert!( |
| 4619 | !after.contains("old-openrouter-key"), |
| 4620 | "provider-scoped openrouter key must be stripped: {after}" |
| 4621 | ); |
| 4622 | // Non-credential lines must survive. |
| 4623 | assert!(after.contains("default_text_model")); |
| 4624 | assert!(after.contains("base_url")); |
| 4625 | Ok(()) |
| 4626 | } |
| 4627 | |
| 4628 | /// Finding #20 golden: a comment that merely mentions `api_key` used to |
| 4629 | /// defeat the insert (the old `existing.contains("api_key")` scan treated it |
| 4630 | /// as an existing assignment and never wrote the key). The TOML-aware path |
| 4631 | /// must insert the real key and keep the comment. |
| 4632 | #[test] |
| 4633 | fn save_api_key_inserts_key_when_only_a_comment_mentions_it() -> Result<()> { |
| 4634 | let _lock = lock_test_env(); |
| 4635 | let nanos = SystemTime::now() |
| 4636 | .duration_since(UNIX_EPOCH) |
| 4637 | .unwrap() |
| 4638 | .as_nanos(); |
| 4639 | let temp_root = env::temp_dir().join(format!( |
| 4640 | "codewhale-tui-api-key-comment-{}-{}", |
| 4641 | std::process::id(), |
| 4642 | nanos |
| 4643 | )); |
| 4644 | fs::create_dir_all(&temp_root)?; |
| 4645 | let _guard = EnvGuard::new(&temp_root); |
| 4646 | |
| 4647 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 4648 | fs::create_dir_all(config_path.parent().unwrap())?; |
| 4649 | fs::write( |
| 4650 | &config_path, |
| 4651 | "# api_key = \"sk-placeholder\" (uncomment to set manually)\n\ |
| 4652 | default_text_model = \"deepseek-v4-flash\"\n", |
| 4653 | )?; |
| 4654 | |
| 4655 | save_api_key("fresh-key")?; |
| 4656 | |
| 4657 | let after = fs::read_to_string(&config_path)?; |
| 4658 | assert!( |
| 4659 | after.contains("# api_key = \"sk-placeholder\""), |
| 4660 | "comment must survive: {after}" |
| 4661 | ); |
| 4662 | assert!( |
| 4663 | after.contains("default_text_model = \"deepseek-v4-flash\""), |
| 4664 | "unrelated key must survive: {after}" |
| 4665 | ); |
| 4666 | let parsed: toml::Value = toml::from_str(&after)?; |
| 4667 | assert_eq!( |
| 4668 | parsed["providers"]["deepseek"] |
| 4669 | .get("api_key") |
| 4670 | .and_then(toml::Value::as_str), |
| 4671 | Some("fresh-key"), |
| 4672 | "real key must be inserted despite the comment: {after}" |
| 4673 | ); |
| 4674 | assert!(parsed.get("api_key").is_none(), "{after}"); |
| 4675 | Ok(()) |
| 4676 | } |
| 4677 | |
| 4678 | /// Replacing an existing root api_key must keep surrounding comments, |
| 4679 | /// including the trailing comment on the api_key line itself. |
| 4680 | #[test] |
| 4681 | fn save_api_key_replaces_existing_key_preserving_comments() -> Result<()> { |
| 4682 | let _lock = lock_test_env(); |
| 4683 | let nanos = SystemTime::now() |
| 4684 | .duration_since(UNIX_EPOCH) |
| 4685 | .unwrap() |
| 4686 | .as_nanos(); |
| 4687 | let temp_root = env::temp_dir().join(format!( |
| 4688 | "codewhale-tui-api-key-replace-{}-{}", |
| 4689 | std::process::id(), |
| 4690 | nanos |
| 4691 | )); |
| 4692 | fs::create_dir_all(&temp_root)?; |
| 4693 | let _guard = EnvGuard::new(&temp_root); |
| 4694 | |
| 4695 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 4696 | fs::create_dir_all(config_path.parent().unwrap())?; |
| 4697 | fs::write( |
| 4698 | &config_path, |
| 4699 | r#"# top note |
| 4700 | api_key = "old-key" # keep secret |
| 4701 | model = "deepseek-v4-pro" |
| 4702 | |
| 4703 | # provider note |
| 4704 | [providers.openrouter] |
| 4705 | base_url = "https://openrouter.ai/api/v1" |
| 4706 | "#, |
| 4707 | )?; |
| 4708 | |
| 4709 | save_api_key("new-key")?; |
| 4710 | |
| 4711 | // The key moved into `[providers.deepseek]` with its comment (#6394). |
| 4712 | let after = fs::read_to_string(&config_path)?; |
| 4713 | assert!( |
| 4714 | after.contains("api_key = \"new-key\" # keep secret"), |
| 4715 | "value must be replaced in place with its comment: {after}" |
| 4716 | ); |
| 4717 | let parsed: toml::Table = toml::from_str(&after)?; |
| 4718 | assert_eq!( |
| 4719 | parsed["providers"]["deepseek"]["api_key"].as_str(), |
| 4720 | Some("new-key") |
| 4721 | ); |
| 4722 | assert!(!after.contains("old-key"), "{after}"); |
| 4723 | assert!(after.contains("# top note"), "{after}"); |
| 4724 | assert!(after.contains("# provider note"), "{after}"); |
| 4725 | Ok(()) |
| 4726 | } |
| 4727 | |
| 4728 | /// Provider-scoped key saves used to round-trip through `toml::Value` |
| 4729 | /// pretty-printing, which dropped every comment in the file. |
| 4730 | #[test] |
| 4731 | fn save_api_key_for_preserves_comments_in_provider_tables() -> Result<()> { |
| 4732 | let _lock = lock_test_env(); |
| 4733 | let nanos = SystemTime::now() |
| 4734 | .duration_since(UNIX_EPOCH) |
| 4735 | .unwrap() |
| 4736 | .as_nanos(); |
| 4737 | let temp_root = env::temp_dir().join(format!( |
| 4738 | "codewhale-tui-provider-key-comments-{}-{}", |
| 4739 | std::process::id(), |
| 4740 | nanos |
| 4741 | )); |
| 4742 | fs::create_dir_all(&temp_root)?; |
| 4743 | let _guard = EnvGuard::new(&temp_root); |
| 4744 | |
| 4745 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 4746 | fs::create_dir_all(config_path.parent().unwrap())?; |
| 4747 | fs::write( |
| 4748 | &config_path, |
| 4749 | r#"# root note |
| 4750 | model = "deepseek-v4-pro" |
| 4751 | |
| 4752 | # openrouter note |
| 4753 | [providers.openrouter] |
| 4754 | base_url = "https://openrouter.ai/api/v1" # pinned |
| 4755 | "#, |
| 4756 | )?; |
| 4757 | |
| 4758 | save_api_key_for(ProviderKind::Openrouter, "or-key")?; |
| 4759 | |
| 4760 | let after = fs::read_to_string(&config_path)?; |
| 4761 | assert!(after.contains("# root note"), "{after}"); |
| 4762 | assert!(after.contains("# openrouter note"), "{after}"); |
| 4763 | assert!( |
| 4764 | after.contains("base_url = \"https://openrouter.ai/api/v1\" # pinned"), |
| 4765 | "inline comment must survive: {after}" |
| 4766 | ); |
| 4767 | let parsed: toml::Value = toml::from_str(&after)?; |
| 4768 | assert_eq!( |
| 4769 | parsed |
| 4770 | .get("providers") |
| 4771 | .and_then(|providers| providers.get("openrouter")) |
| 4772 | .and_then(|entry| entry.get("api_key")) |
| 4773 | .and_then(toml::Value::as_str), |
| 4774 | Some("or-key"), |
| 4775 | "{after}" |
| 4776 | ); |
| 4777 | Ok(()) |
| 4778 | } |
| 4779 | |
| 4780 | /// Clearing credentials must not disturb comments, `api_key_env`, or |
| 4781 | /// provider tables with quoted names. |
| 4782 | #[test] |
| 4783 | fn clear_api_key_preserves_comments_and_unrelated_keys() -> Result<()> { |
| 4784 | let _lock = lock_test_env(); |
| 4785 | let nanos = SystemTime::now() |
| 4786 | .duration_since(UNIX_EPOCH) |
| 4787 | .unwrap() |
| 4788 | .as_nanos(); |
| 4789 | let temp_root = env::temp_dir().join(format!( |
| 4790 | "codewhale-tui-clear-comments-{}-{}", |
| 4791 | std::process::id(), |
| 4792 | nanos |
| 4793 | )); |
| 4794 | fs::create_dir_all(&temp_root)?; |
| 4795 | let temp_root = temp_root.canonicalize()?; |
| 4796 | let _guard = EnvGuard::new(&temp_root); |
| 4797 | |
| 4798 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 4799 | fs::create_dir_all(config_path.parent().unwrap())?; |
| 4800 | fs::write( |
| 4801 | &config_path, |
| 4802 | r#"# root note |
| 4803 | api_key = "old-root-key" |
| 4804 | api_key_env = "MY_KEY_ENV" |
| 4805 | model = "deepseek-v4-pro" |
| 4806 | |
| 4807 | # provider note |
| 4808 | [providers."quoted.provider"] |
| 4809 | api_key = "old-quoted-key" |
| 4810 | base_url = "https://quoted.example/v1" |
| 4811 | "#, |
| 4812 | )?; |
| 4813 | |
| 4814 | clear_api_key()?; |
| 4815 | |
| 4816 | let after = fs::read_to_string(&config_path)?; |
| 4817 | assert!(!after.contains("old-root-key"), "{after}"); |
| 4818 | assert!( |
| 4819 | !after.contains("old-quoted-key"), |
| 4820 | "quoted provider table key must be stripped: {after}" |
| 4821 | ); |
| 4822 | assert!( |
| 4823 | after.contains("api_key_env = \"MY_KEY_ENV\""), |
| 4824 | "api_key_env must not be stripped: {after}" |
| 4825 | ); |
| 4826 | assert!(after.contains("# root note"), "{after}"); |
| 4827 | assert!(after.contains("# provider note"), "{after}"); |
| 4828 | assert!(after.contains("model = \"deepseek-v4-pro\""), "{after}"); |
| 4829 | assert!( |
| 4830 | after.contains("base_url = \"https://quoted.example/v1\""), |
| 4831 | "{after}" |
| 4832 | ); |
| 4833 | Ok(()) |
| 4834 | } |
| 4835 | |
| 4836 | /// The old line matcher compared against the literal `[providers.<name>]` |
| 4837 | /// header, so a quoted header (`[providers."openrouter"]`) was never |
| 4838 | /// matched and the key survived a targeted clear. |
| 4839 | #[test] |
| 4840 | fn clear_active_provider_api_key_handles_quoted_table_headers() -> Result<()> { |
| 4841 | let _lock = lock_test_env(); |
| 4842 | let nanos = SystemTime::now() |
| 4843 | .duration_since(UNIX_EPOCH) |
| 4844 | .unwrap() |
| 4845 | .as_nanos(); |
| 4846 | let temp_root = env::temp_dir().join(format!( |
| 4847 | "codewhale-tui-clear-quoted-{}-{}", |
| 4848 | std::process::id(), |
| 4849 | nanos |
| 4850 | )); |
| 4851 | fs::create_dir_all(&temp_root)?; |
| 4852 | let _guard = EnvGuard::new(&temp_root); |
| 4853 | |
| 4854 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 4855 | fs::create_dir_all(config_path.parent().unwrap())?; |
| 4856 | fs::write( |
| 4857 | &config_path, |
| 4858 | r#"api_key = "root-key" |
| 4859 | |
| 4860 | [providers."openrouter"] |
| 4861 | api_key = "old-openrouter-key" |
| 4862 | base_url = "https://openrouter.ai/api/v1" |
| 4863 | "#, |
| 4864 | )?; |
| 4865 | |
| 4866 | clear_active_provider_api_key("openrouter")?; |
| 4867 | |
| 4868 | let after = fs::read_to_string(&config_path)?; |
| 4869 | assert!( |
| 4870 | !after.contains("old-openrouter-key"), |
| 4871 | "quoted provider header must be matched: {after}" |
| 4872 | ); |
| 4873 | assert!( |
| 4874 | after.contains("api_key = \"root-key\""), |
| 4875 | "root key belongs to deepseek and must survive: {after}" |
| 4876 | ); |
| 4877 | assert!( |
| 4878 | after.contains("base_url = \"https://openrouter.ai/api/v1\""), |
| 4879 | "{after}" |
| 4880 | ); |
| 4881 | Ok(()) |
| 4882 | } |
| 4883 | |
| 4884 | #[test] |
| 4885 | fn clear_active_provider_api_key_clears_deepseek_cn_root_scope() -> Result<()> { |
| 4886 | let _lock = lock_test_env(); |
| 4887 | let nanos = SystemTime::now() |
| 4888 | .duration_since(UNIX_EPOCH) |
| 4889 | .unwrap() |
| 4890 | .as_nanos(); |
| 4891 | let temp_root = env::temp_dir().join(format!( |
| 4892 | "codewhale-tui-clear-deepseek-cn-{}-{}", |
| 4893 | std::process::id(), |
| 4894 | nanos |
| 4895 | )); |
| 4896 | fs::create_dir_all(&temp_root)?; |
| 4897 | let _guard = EnvGuard::new(&temp_root); |
| 4898 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 4899 | fs::create_dir_all(config_path.parent().unwrap())?; |
| 4900 | fs::write( |
| 4901 | &config_path, |
| 4902 | r#"provider = "deepseek-cn" |
| 4903 | api_key = "deepseek-cn-root-key" |
| 4904 | |
| 4905 | [providers.deepseek-cn] |
| 4906 | api_key = "deepseek-cn-table-key" |
| 4907 | |
| 4908 | [providers.openrouter] |
| 4909 | api_key = "unrelated-key" |
| 4910 | "#, |
| 4911 | )?; |
| 4912 | |
| 4913 | clear_active_provider_api_key("deepseek-cn")?; |
| 4914 | |
| 4915 | let after = fs::read_to_string(&config_path)?; |
| 4916 | assert!(!after.contains("deepseek-cn-root-key"), "{after}"); |
| 4917 | assert!(!after.contains("deepseek-cn-table-key"), "{after}"); |
| 4918 | assert!(after.contains("unrelated-key"), "{after}"); |
| 4919 | Ok(()) |
| 4920 | } |
| 4921 | |
| 4922 | #[test] |
| 4923 | fn clear_active_provider_api_key_deepseek_cn_keeps_deepseek_own_key() -> Result<()> { |
| 4924 | let _lock = lock_test_env(); |
| 4925 | let nanos = SystemTime::now() |
| 4926 | .duration_since(UNIX_EPOCH) |
| 4927 | .unwrap() |
| 4928 | .as_nanos(); |
| 4929 | let temp_root = env::temp_dir().join(format!( |
| 4930 | "codewhale-tui-clear-deepseek-cn-keeps-intl-{}-{}", |
| 4931 | std::process::id(), |
| 4932 | nanos |
| 4933 | )); |
| 4934 | fs::create_dir_all(&temp_root)?; |
| 4935 | let _guard = EnvGuard::new(&temp_root); |
| 4936 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 4937 | fs::create_dir_all(config_path.parent().unwrap())?; |
| 4938 | |
| 4939 | // Each identity holds its own key: signing CN out leaves DeepSeek's. |
| 4940 | fs::write( |
| 4941 | &config_path, |
| 4942 | r#"provider = "deepseek-cn" |
| 4943 | |
| 4944 | [providers.deepseek] |
| 4945 | api_key = "sk-intl" |
| 4946 | |
| 4947 | [providers.deepseek_cn] |
| 4948 | api_key = "sk-cn" |
| 4949 | "#, |
| 4950 | )?; |
| 4951 | clear_active_provider_api_key("deepseek-cn")?; |
| 4952 | let after = fs::read_to_string(&config_path)?; |
| 4953 | assert!(!after.contains("sk-cn"), "{after}"); |
| 4954 | assert!(after.contains("sk-intl"), "{after}"); |
| 4955 | |
| 4956 | // CN without a key of its own reads DeepSeek's, so that shared key goes. |
| 4957 | fs::write( |
| 4958 | &config_path, |
| 4959 | r#"provider = "deepseek-cn" |
| 4960 | |
| 4961 | [providers.deepseek] |
| 4962 | api_key = "sk-shared" |
| 4963 | "#, |
| 4964 | )?; |
| 4965 | clear_active_provider_api_key("deepseek-cn")?; |
| 4966 | let after = fs::read_to_string(&config_path)?; |
| 4967 | assert!(!after.contains("sk-shared"), "{after}"); |
| 4968 | |
| 4969 | // A top-level key this write moves beside CN's own key was the shared |
| 4970 | // one; a DeepSeek key that only merged with it was DeepSeek's own too. |
| 4971 | fs::write( |
| 4972 | &config_path, |
| 4973 | r#"provider = "deepseek-cn" |
| 4974 | api_key = "sk-root" |
| 4975 | |
| 4976 | [providers.deepseek] |
| 4977 | api_key = "sk-root" |
| 4978 | |
| 4979 | [providers.deepseek_cn] |
| 4980 | api_key = "sk-cn" |
| 4981 | "#, |
| 4982 | )?; |
| 4983 | clear_active_provider_api_key("deepseek-cn")?; |
| 4984 | let after = fs::read_to_string(&config_path)?; |
| 4985 | assert!(!after.contains("sk-cn"), "{after}"); |
| 4986 | assert!(after.contains("[providers.deepseek]"), "{after}"); |
| 4987 | assert!(after.contains("sk-root"), "{after}"); |
| 4988 | Ok(()) |
| 4989 | } |
| 4990 | |
| 4991 | #[test] |
| 4992 | fn clear_active_provider_api_key_distinguishes_literal_and_named_custom_routes() -> Result<()> { |
| 4993 | let _lock = lock_test_env(); |
| 4994 | let nanos = SystemTime::now() |
| 4995 | .duration_since(UNIX_EPOCH) |
| 4996 | .unwrap() |
| 4997 | .as_nanos(); |
| 4998 | let temp_root = env::temp_dir().join(format!( |
| 4999 | "codewhale-tui-clear-custom-{}-{}", |
| 5000 | std::process::id(), |
| 5001 | nanos |
| 5002 | )); |
| 5003 | fs::create_dir_all(&temp_root)?; |
| 5004 | let _guard = EnvGuard::new(&temp_root); |
| 5005 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 5006 | fs::create_dir_all(config_path.parent().unwrap())?; |
| 5007 | let contents = r#"provider = "custom" |
| 5008 | api_key = "legacy-root-key" |
| 5009 | base_url = "http://127.0.0.1:1234/v1" |
| 5010 | default_text_model = "legacy-model" |
| 5011 | |
| 5012 | [providers.lm-studio] |
| 5013 | kind = "openai-compatible" |
| 5014 | api_key = "named-route-key" |
| 5015 | base_url = "http://127.0.0.1:5678/v1" |
| 5016 | model = "named-model" |
| 5017 | "#; |
| 5018 | fs::write(&config_path, contents)?; |
| 5019 | |
| 5020 | clear_active_provider_api_key("custom")?; |
| 5021 | |
| 5022 | let after_literal = fs::read_to_string(&config_path)?; |
| 5023 | assert!( |
| 5024 | !after_literal.contains("legacy-root-key"), |
| 5025 | "{after_literal}" |
| 5026 | ); |
| 5027 | assert!(after_literal.contains("named-route-key"), "{after_literal}"); |
| 5028 | |
| 5029 | fs::write(&config_path, contents)?; |
| 5030 | clear_active_provider_api_key("lm-studio")?; |
| 5031 | |
| 5032 | let after_named = fs::read_to_string(&config_path)?; |
| 5033 | assert!(after_named.contains("legacy-root-key"), "{after_named}"); |
| 5034 | assert!(!after_named.contains("named-route-key"), "{after_named}"); |
| 5035 | Ok(()) |
| 5036 | } |
| 5037 | |
| 5038 | #[test] |
| 5039 | fn clear_active_provider_api_key_prefers_exact_custom_table_over_legacy_root() -> Result<()> { |
| 5040 | let _lock = lock_test_env(); |
| 5041 | let nanos = SystemTime::now() |
| 5042 | .duration_since(UNIX_EPOCH) |
| 5043 | .unwrap() |
| 5044 | .as_nanos(); |
| 5045 | let temp_root = env::temp_dir().join(format!( |
| 5046 | "codewhale-tui-clear-exact-custom-{}-{}", |
| 5047 | std::process::id(), |
| 5048 | nanos |
| 5049 | )); |
| 5050 | fs::create_dir_all(&temp_root)?; |
| 5051 | let _guard = EnvGuard::new(&temp_root); |
| 5052 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 5053 | fs::create_dir_all(config_path.parent().unwrap())?; |
| 5054 | fs::write( |
| 5055 | &config_path, |
| 5056 | r#"provider = "custom" |
| 5057 | api_key = "legacy-root-key" |
| 5058 | base_url = "http://127.0.0.1:1234/v1" |
| 5059 | default_text_model = "legacy-model" |
| 5060 | |
| 5061 | [providers.custom] |
| 5062 | kind = "openai-compatible" |
| 5063 | api_key = "exact-table-key" |
| 5064 | base_url = "http://127.0.0.1:5678/v1" |
| 5065 | model = "exact-model" |
| 5066 | "#, |
| 5067 | )?; |
| 5068 | |
| 5069 | clear_active_provider_api_key("custom")?; |
| 5070 | |
| 5071 | let after = fs::read_to_string(&config_path)?; |
| 5072 | assert!(after.contains("legacy-root-key"), "{after}"); |
| 5073 | assert!(!after.contains("exact-table-key"), "{after}"); |
| 5074 | assert!(after.contains("[providers.custom]"), "{after}"); |
| 5075 | Ok(()) |
| 5076 | } |
| 5077 | |
| 5078 | /// Finding #19: workspace-trust saves used to round-trip through |
| 5079 | /// `toml::to_string_pretty`, destroying comments in the whole file. |
| 5080 | #[test] |
| 5081 | fn save_workspace_trust_preserves_comments() -> Result<()> { |
| 5082 | let _lock = lock_test_env(); |
| 5083 | let nanos = SystemTime::now() |
| 5084 | .duration_since(UNIX_EPOCH) |
| 5085 | .unwrap() |
| 5086 | .as_nanos(); |
| 5087 | let temp_root = env::temp_dir().join(format!( |
| 5088 | "codewhale-tui-trust-comments-{}-{}", |
| 5089 | std::process::id(), |
| 5090 | nanos |
| 5091 | )); |
| 5092 | fs::create_dir_all(&temp_root)?; |
| 5093 | let _guard = EnvGuard::new(&temp_root); |
| 5094 | let workspace = temp_root.join("project"); |
| 5095 | fs::create_dir_all(&workspace)?; |
| 5096 | |
| 5097 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 5098 | fs::create_dir_all(config_path.parent().unwrap())?; |
| 5099 | fs::write( |
| 5100 | &config_path, |
| 5101 | r#"# top note |
| 5102 | model = "deepseek-v4-pro" |
| 5103 | |
| 5104 | # projects note |
| 5105 | [projects."/existing/workspace"] |
| 5106 | trust_level = "trusted" # granted earlier |
| 5107 | "#, |
| 5108 | )?; |
| 5109 | |
| 5110 | save_workspace_trust(&workspace)?; |
| 5111 | |
| 5112 | let after = fs::read_to_string(&config_path)?; |
| 5113 | assert!(after.contains("# top note"), "{after}"); |
| 5114 | assert!(after.contains("# projects note"), "{after}"); |
| 5115 | assert!(after.contains("# granted earlier"), "{after}"); |
| 5116 | assert!( |
| 5117 | after.contains("[projects.\"/existing/workspace\"]"), |
| 5118 | "existing project entry must survive: {after}" |
| 5119 | ); |
| 5120 | assert!(is_workspace_trusted(&workspace)); |
| 5121 | Ok(()) |
| 5122 | } |
| 5123 | |
| 5124 | /// Regression for #343: explicit in-memory `api_key` (non-empty, |
| 5125 | /// non-sentinel) wins over env/config so a freshly-typed onboarding |
| 5126 | /// key takes effect immediately. |
| 5127 | #[test] |
| 5128 | fn deepseek_api_key_prefers_explicit_in_memory_override() -> Result<()> { |
| 5129 | let _lock = lock_test_env(); |
| 5130 | let nanos = SystemTime::now() |
| 5131 | .duration_since(UNIX_EPOCH) |
| 5132 | .unwrap() |
| 5133 | .as_nanos(); |
| 5134 | let temp_root = env::temp_dir().join(format!( |
| 5135 | "codewhale-tui-override-{}-{}", |
| 5136 | std::process::id(), |
| 5137 | nanos |
| 5138 | )); |
| 5139 | fs::create_dir_all(&temp_root)?; |
| 5140 | let _guard = EnvGuard::new(&temp_root); |
| 5141 | |
| 5142 | let config = Config { |
| 5143 | ..Config::default() |
| 5144 | } |
| 5145 | .with_legacy_root(Some("freshly-typed-key".to_string()), None); |
| 5146 | let resolved = config |
| 5147 | .active_route_api_key() |
| 5148 | .expect("explicit override must resolve"); |
| 5149 | assert_eq!(resolved, "freshly-typed-key"); |
| 5150 | Ok(()) |
| 5151 | } |
| 5152 | |
| 5153 | #[test] |
| 5154 | fn deepseek_api_key_prefers_saved_config_over_stale_env() -> Result<()> { |
| 5155 | let _lock = lock_test_env(); |
| 5156 | let nanos = SystemTime::now() |
| 5157 | .duration_since(UNIX_EPOCH) |
| 5158 | .unwrap() |
| 5159 | .as_nanos(); |
| 5160 | let temp_root = env::temp_dir().join(format!( |
| 5161 | "codewhale-tui-config-over-env-{}-{}", |
| 5162 | std::process::id(), |
| 5163 | nanos |
| 5164 | )); |
| 5165 | fs::create_dir_all(&temp_root)?; |
| 5166 | let _guard = EnvGuard::new(&temp_root); |
| 5167 | |
| 5168 | unsafe { |
| 5169 | env::set_var("DEEPSEEK_API_KEY", "stale-env-key"); |
| 5170 | } |
| 5171 | let config = Config { |
| 5172 | ..Config::default() |
| 5173 | } |
| 5174 | .with_legacy_root(Some("fresh-config-key".to_string()), None); |
| 5175 | assert_eq!(config.active_route_api_key()?, "fresh-config-key"); |
| 5176 | unsafe { |
| 5177 | env::remove_var("DEEPSEEK_API_KEY"); |
| 5178 | } |
| 5179 | Ok(()) |
| 5180 | } |
| 5181 | |
| 5182 | #[test] |
| 5183 | fn env_base_url_provenance_tracks_the_route_across_provider_switches() -> Result<()> { |
| 5184 | let _lock = lock_test_env(); |
| 5185 | let temp_root = tempfile::tempdir()?; |
| 5186 | let _guard = EnvGuard::new(temp_root.path()); |
| 5187 | let config_path = temp_root.path().join("config.toml"); |
| 5188 | fs::write( |
| 5189 | &config_path, |
| 5190 | r#"provider = "openrouter" |
| 5191 | |
| 5192 | [providers.openrouter] |
| 5193 | api_key = "stale-openrouter-file-key" |
| 5194 | model = "openrouter-model" |
| 5195 | |
| 5196 | [providers.openai] |
| 5197 | api_key = "file-openai-key" |
| 5198 | base_url = "https://file-openai-gateway.example.test/v1" |
| 5199 | model = "private-openai-model" |
| 5200 | |
| 5201 | [providers.anthropic] |
| 5202 | api_key = "stale-anthropic-file-key" |
| 5203 | model = "claude-sonnet-5" |
| 5204 | "#, |
| 5205 | )?; |
| 5206 | let _base = EnvVarGuard::set("CODEWHALE_BASE_URL", "https://env-gateway.example.test/v1"); |
| 5207 | let mut config = Config::load(Some(config_path), None)?; |
| 5208 | assert!(config.active_route_api_key().is_err()); |
| 5209 | |
| 5210 | config.provider = Some("openai".to_string()); |
| 5211 | assert_eq!( |
| 5212 | config.active_route_base_url(), |
| 5213 | "https://file-openai-gateway.example.test/v1" |
| 5214 | ); |
| 5215 | assert_eq!(config.active_route_api_key()?, "file-openai-key"); |
| 5216 | |
| 5217 | // Anthropic was never the route the environment addressed. Under the |
| 5218 | // endpoint-ownership receipt the generic override does not follow a |
| 5219 | // re-pointed config onto another vendor's route — that is the same |
| 5220 | // mechanism a pinned cross-provider child is resolved through, and it must |
| 5221 | // not be able to dispatch Anthropic traffic at the DeepSeek session's |
| 5222 | // gateway. Anthropic therefore resolves its own canonical endpoint, and |
| 5223 | // because it is no longer on an env-selected host its file-owned key is a |
| 5224 | // legitimate route-bound credential rather than one following a foreign |
| 5225 | // host. |
| 5226 | config.provider = Some("anthropic".to_string()); |
| 5227 | assert_eq!(config.active_route_base_url(), DEFAULT_ANTHROPIC_BASE_URL); |
| 5228 | assert_ne!( |
| 5229 | config.active_route_base_url(), |
| 5230 | "https://env-gateway.example.test/v1" |
| 5231 | ); |
| 5232 | assert_eq!(config.active_route_api_key()?, "stale-anthropic-file-key"); |
| 5233 | |
| 5234 | config.provider = Some("openrouter".to_string()); |
| 5235 | assert!( |
| 5236 | config.active_route_api_key().is_err(), |
| 5237 | "switching away and back must retain the env ownership receipt for that route" |
| 5238 | ); |
| 5239 | Ok(()) |
| 5240 | } |
| 5241 | |
| 5242 | #[test] |
| 5243 | fn active_provider_detects_env_only_api_key() -> Result<()> { |
| 5244 | let _lock = lock_test_env(); |
| 5245 | let temp_root = |
| 5246 | env::temp_dir().join(format!("codewhale-tui-env-only-key-{}", std::process::id())); |
| 5247 | fs::create_dir_all(&temp_root)?; |
| 5248 | let _guard = EnvGuard::new(&temp_root); |
| 5249 | |
| 5250 | unsafe { |
| 5251 | env::set_var("DEEPSEEK_API_KEY", "env-only-key"); |
| 5252 | } |
| 5253 | let mut config = Config::default(); |
| 5254 | assert!(active_provider_has_env_api_key(&config)); |
| 5255 | assert!(!active_provider_has_config_api_key(&config)); |
| 5256 | assert!(active_provider_uses_env_only_api_key(&config)); |
| 5257 | |
| 5258 | config.set_legacy_root(Some("config-key".to_string()), None); |
| 5259 | assert!(active_provider_has_config_api_key(&config)); |
| 5260 | assert!(!active_provider_uses_env_only_api_key(&config)); |
| 5261 | |
| 5262 | unsafe { |
| 5263 | env::remove_var("DEEPSEEK_API_KEY"); |
| 5264 | } |
| 5265 | Ok(()) |
| 5266 | } |
| 5267 | |
| 5268 | #[test] |
| 5269 | fn deepseek_api_key_ignores_sentinel_placeholder() -> Result<()> { |
| 5270 | let _lock = lock_test_env(); |
| 5271 | let nanos = SystemTime::now() |
| 5272 | .duration_since(UNIX_EPOCH) |
| 5273 | .unwrap() |
| 5274 | .as_nanos(); |
| 5275 | let temp_root = env::temp_dir().join(format!( |
| 5276 | "codewhale-tui-sentinel-{}-{}", |
| 5277 | std::process::id(), |
| 5278 | nanos |
| 5279 | )); |
| 5280 | fs::create_dir_all(&temp_root)?; |
| 5281 | let _guard = EnvGuard::new(&temp_root); |
| 5282 | |
| 5283 | let config = Config { |
| 5284 | ..Config::default() |
| 5285 | } |
| 5286 | .with_legacy_root(Some(API_KEYRING_SENTINEL.to_string()), None); |
| 5287 | // Sentinel must not be treated as a real key — the resolver should |
| 5288 | // fall through to env / config-provider and ultimately bail out |
| 5289 | // with a "key not found" error. |
| 5290 | let _err = config |
| 5291 | .active_route_api_key() |
| 5292 | .expect_err("sentinel placeholder must not satisfy the API key check"); |
| 5293 | Ok(()) |
| 5294 | } |
| 5295 | |
| 5296 | #[test] |
| 5297 | fn default_user_paths_use_codewhale_home_for_fresh_installs() -> Result<()> { |
| 5298 | let _lock = lock_test_env(); |
| 5299 | let nanos = SystemTime::now() |
| 5300 | .duration_since(UNIX_EPOCH) |
| 5301 | .unwrap() |
| 5302 | .as_nanos(); |
| 5303 | let temp_root = env::temp_dir().join(format!( |
| 5304 | "codewhale-tui-fresh-home-test-{}-{}", |
| 5305 | std::process::id(), |
| 5306 | nanos |
| 5307 | )); |
| 5308 | fs::create_dir_all(&temp_root)?; |
| 5309 | let _guard = EnvGuard::new(&temp_root); |
| 5310 | |
| 5311 | // EnvGuard pins DEEPSEEK_CONFIG_PATH for older tests; this test wants |
| 5312 | // the no-explicit-path startup behavior. |
| 5313 | unsafe { |
| 5314 | env::remove_var("DEEPSEEK_CONFIG_PATH"); |
| 5315 | } |
| 5316 | |
| 5317 | let config = Config::default(); |
| 5318 | assert_eq!( |
| 5319 | default_config_path().unwrap(), |
| 5320 | temp_root.join(".codewhale").join("config.toml") |
| 5321 | ); |
| 5322 | assert_eq!( |
| 5323 | config.mcp_config_path(), |
| 5324 | temp_root.join(".codewhale").join("mcp.json") |
| 5325 | ); |
| 5326 | assert_eq!( |
| 5327 | config.memory_path(), |
| 5328 | temp_root.join(".codewhale").join("memory.md") |
| 5329 | ); |
| 5330 | assert_eq!( |
| 5331 | config.skills_dir(), |
| 5332 | temp_root.join(".codewhale").join("skills") |
| 5333 | ); |
| 5334 | |
| 5335 | Ok(()) |
| 5336 | } |
| 5337 | |
| 5338 | #[test] |
| 5339 | fn default_user_paths_preserve_existing_legacy_files() -> Result<()> { |
| 5340 | let _lock = lock_test_env(); |
| 5341 | let nanos = SystemTime::now() |
| 5342 | .duration_since(UNIX_EPOCH) |
| 5343 | .unwrap() |
| 5344 | .as_nanos(); |
| 5345 | let temp_root = env::temp_dir().join(format!( |
| 5346 | "codewhale-tui-legacy-home-test-{}-{}", |
| 5347 | std::process::id(), |
| 5348 | nanos |
| 5349 | )); |
| 5350 | let legacy_home = temp_root.join(".deepseek"); |
| 5351 | fs::create_dir_all(&legacy_home)?; |
| 5352 | for name in ["config.toml", "mcp.json", "memory.md"] { |
| 5353 | fs::write(legacy_home.join(name), "")?; |
| 5354 | } |
| 5355 | fs::create_dir_all(legacy_home.join("skills"))?; |
| 5356 | let _guard = EnvGuard::new(&temp_root); |
| 5357 | |
| 5358 | unsafe { |
| 5359 | env::remove_var("DEEPSEEK_CONFIG_PATH"); |
| 5360 | } |
| 5361 | |
| 5362 | let config = Config::default(); |
| 5363 | assert_eq!( |
| 5364 | default_config_path().unwrap(), |
| 5365 | legacy_home.join("config.toml") |
| 5366 | ); |
| 5367 | assert_eq!(config.mcp_config_path(), legacy_home.join("mcp.json")); |
| 5368 | assert_eq!(config.memory_path(), legacy_home.join("memory.md")); |
| 5369 | assert_eq!(config.skills_dir(), legacy_home.join("skills")); |
| 5370 | |
| 5371 | Ok(()) |
| 5372 | } |
| 5373 | |
| 5374 | #[test] |
| 5375 | fn explicit_codewhale_home_isolates_all_config_owned_user_paths() -> Result<()> { |
| 5376 | let _lock = lock_test_env(); |
| 5377 | let temp_root = tempfile::tempdir()?; |
| 5378 | let ambient_home = temp_root.path().join("ambient-home"); |
| 5379 | let explicit_home = temp_root.path().join("explicit-home"); |
| 5380 | let ambient_legacy = ambient_home.join(".deepseek"); |
| 5381 | fs::create_dir_all(ambient_legacy.join("skills"))?; |
| 5382 | for name in ["mcp.json", "memory.md"] { |
| 5383 | fs::write(ambient_legacy.join(name), "legacy")?; |
| 5384 | } |
| 5385 | let _home = EnvVarGuard::set("HOME", &ambient_home); |
| 5386 | let _userprofile = EnvVarGuard::set("USERPROFILE", &ambient_home); |
| 5387 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &explicit_home); |
| 5388 | |
| 5389 | assert_eq!(default_skills_dir(), Some(explicit_home.join("skills"))); |
| 5390 | assert_eq!( |
| 5391 | default_mcp_config_path(), |
| 5392 | Some(explicit_home.join("mcp.json")) |
| 5393 | ); |
| 5394 | assert_eq!(default_memory_path(), Some(explicit_home.join("memory.md"))); |
| 5395 | Ok(()) |
| 5396 | } |
| 5397 | |
| 5398 | #[test] |
| 5399 | fn relative_mcp_config_path_falls_back_to_user_global_config() -> Result<()> { |
| 5400 | let _lock = lock_test_env(); |
| 5401 | let temp_root = tempfile::tempdir()?; |
| 5402 | let explicit_home = temp_root.path().join("codewhale-home"); |
| 5403 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &explicit_home); |
| 5404 | let config = Config { |
| 5405 | mcp_config_path: Some("relative/mcp.json".to_string()), |
| 5406 | ..Config::default() |
| 5407 | }; |
| 5408 | |
| 5409 | assert_eq!(config.mcp_config_path(), explicit_home.join("mcp.json")); |
| 5410 | Ok(()) |
| 5411 | } |
| 5412 | |
| 5413 | #[test] |
| 5414 | fn absolute_mcp_config_path_remains_an_explicit_override() -> Result<()> { |
| 5415 | let temp_root = tempfile::tempdir()?; |
| 5416 | let explicit = temp_root.path().join("custom-mcp.json"); |
| 5417 | let config = Config { |
| 5418 | mcp_config_path: Some(explicit.display().to_string()), |
| 5419 | ..Config::default() |
| 5420 | }; |
| 5421 | |
| 5422 | assert_eq!(config.mcp_config_path(), explicit); |
| 5423 | Ok(()) |
| 5424 | } |
| 5425 | |
| 5426 | #[test] |
| 5427 | fn whitespace_codewhale_home_keeps_ambient_legacy_config_path_fallbacks() -> Result<()> { |
| 5428 | let _lock = lock_test_env(); |
| 5429 | let temp_root = tempfile::tempdir()?; |
| 5430 | let ambient_home = temp_root.path().join("ambient-home"); |
| 5431 | let ambient_legacy = ambient_home.join(".deepseek"); |
| 5432 | fs::create_dir_all(ambient_legacy.join("skills"))?; |
| 5433 | for name in ["mcp.json", "memory.md"] { |
| 5434 | fs::write(ambient_legacy.join(name), "legacy")?; |
| 5435 | } |
| 5436 | let _home = EnvVarGuard::set("HOME", &ambient_home); |
| 5437 | let _userprofile = EnvVarGuard::set("USERPROFILE", &ambient_home); |
| 5438 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", " \t "); |
| 5439 | |
| 5440 | assert_eq!(default_skills_dir(), Some(ambient_legacy.join("skills"))); |
| 5441 | assert_eq!( |
| 5442 | default_mcp_config_path(), |
| 5443 | Some(ambient_legacy.join("mcp.json")) |
| 5444 | ); |
| 5445 | assert_eq!( |
| 5446 | default_memory_path(), |
| 5447 | Some(ambient_legacy.join("memory.md")) |
| 5448 | ); |
| 5449 | Ok(()) |
| 5450 | } |
| 5451 | |
| 5452 | #[cfg(unix)] |
| 5453 | #[test] |
| 5454 | fn non_unicode_codewhale_home_is_preserved_by_config_owned_user_paths() -> Result<()> { |
| 5455 | use std::os::unix::ffi::OsStringExt; |
| 5456 | |
| 5457 | let _lock = lock_test_env(); |
| 5458 | let temp_root = tempfile::tempdir()?; |
| 5459 | let explicit_home = temp_root |
| 5460 | .path() |
| 5461 | .join(OsString::from_vec(b"codewhale-\xff-home".to_vec())); |
| 5462 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &explicit_home); |
| 5463 | |
| 5464 | assert_eq!(default_skills_dir(), Some(explicit_home.join("skills"))); |
| 5465 | assert_eq!( |
| 5466 | default_mcp_config_path(), |
| 5467 | Some(explicit_home.join("mcp.json")) |
| 5468 | ); |
| 5469 | assert_eq!(default_memory_path(), Some(explicit_home.join("memory.md"))); |
| 5470 | Ok(()) |
| 5471 | } |
| 5472 | |
| 5473 | #[test] |
| 5474 | fn codewhale_config_path_env_wins_over_legacy_env() -> Result<()> { |
| 5475 | let _lock = lock_test_env(); |
| 5476 | let nanos = SystemTime::now() |
| 5477 | .duration_since(UNIX_EPOCH) |
| 5478 | .unwrap() |
| 5479 | .as_nanos(); |
| 5480 | let temp_root = env::temp_dir().join(format!( |
| 5481 | "codewhale-tui-config-env-test-{}-{}", |
| 5482 | std::process::id(), |
| 5483 | nanos |
| 5484 | )); |
| 5485 | let preferred = temp_root.join("preferred.toml"); |
| 5486 | let legacy = temp_root.join("legacy.toml"); |
| 5487 | let _codewhale_config = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", &preferred); |
| 5488 | let _legacy_config = EnvVarGuard::set("DEEPSEEK_CONFIG_PATH", &legacy); |
| 5489 | |
| 5490 | assert_eq!(env_config_path().unwrap().unwrap(), preferred); |
| 5491 | |
| 5492 | Ok(()) |
| 5493 | } |
| 5494 | |
| 5495 | #[test] |
| 5496 | fn test_tilde_expansion_in_paths() -> Result<()> { |
| 5497 | let _lock = lock_test_env(); |
| 5498 | let nanos = SystemTime::now() |
| 5499 | .duration_since(UNIX_EPOCH) |
| 5500 | .unwrap() |
| 5501 | .as_nanos(); |
| 5502 | let temp_root = env::temp_dir().join(format!( |
| 5503 | "codewhale-tui-tilde-test-{}-{}", |
| 5504 | std::process::id(), |
| 5505 | nanos |
| 5506 | )); |
| 5507 | fs::create_dir_all(&temp_root)?; |
| 5508 | let _guard = EnvGuard::new(&temp_root); |
| 5509 | |
| 5510 | let config = Config { |
| 5511 | skills_dir: Some("~/.deepseek/skills".to_string()), |
| 5512 | ..Default::default() |
| 5513 | }; |
| 5514 | let expected_skills = temp_root.join(".deepseek").join("skills"); |
| 5515 | let actual_skills = config.skills_dir(); |
| 5516 | assert_eq!( |
| 5517 | actual_skills.components().collect::<Vec<_>>(), |
| 5518 | expected_skills.components().collect::<Vec<_>>() |
| 5519 | ); |
| 5520 | |
| 5521 | Ok(()) |
| 5522 | } |
| 5523 | |
| 5524 | #[test] |
| 5525 | fn skills_scan_codewhale_only_defaults_false_and_parses_true() -> Result<()> { |
| 5526 | assert!(!Config::default().skills_config().scan_codewhale_only()); |
| 5527 | |
| 5528 | let config: Config = toml::from_str( |
| 5529 | r#" |
| 5530 | [skills] |
| 5531 | scan_codewhale_only = true |
| 5532 | listing_max_description_chars = 1024 |
| 5533 | listing_budget_fraction = 0.01 |
| 5534 | "#, |
| 5535 | )?; |
| 5536 | |
| 5537 | assert!(config.skills_config().scan_codewhale_only()); |
| 5538 | assert_eq!( |
| 5539 | config.skills_config().listing_max_description_chars, |
| 5540 | Some(1024) |
| 5541 | ); |
| 5542 | assert_eq!(config.skills_config().listing_budget_fraction, Some(0.01)); |
| 5543 | config.validate()?; |
| 5544 | for value in [ |
| 5545 | "listing_max_description_chars = 0", |
| 5546 | "listing_max_description_chars = 40001", |
| 5547 | "listing_budget_fraction = 0", |
| 5548 | "listing_budget_fraction = -0.1", |
| 5549 | "listing_budget_fraction = 1.1", |
| 5550 | "listing_budget_fraction = nan", |
| 5551 | "listing_budget_fraction = inf", |
| 5552 | ] { |
| 5553 | let invalid: Config = toml::from_str(&format!("[skills]\n{value}"))?; |
| 5554 | assert!(invalid.validate().is_err(), "accepted {value}"); |
| 5555 | } |
| 5556 | |
| 5557 | for (mode, writes) in [("auto", false), ("all", true), ("none", false)] { |
| 5558 | let config: Config = toml::from_str(&format!( |
| 5559 | "skills_dir = '/discovery-only'\n[skills.bundled]\ninstall = '{mode}'\nselected = ['documents']\ndisabled = ['debug']\nexplicit_only = ['pdf']" |
| 5560 | ))?; |
| 5561 | assert_eq!(config.bundled_skills_install_dir().is_some(), writes); |
| 5562 | if writes { |
| 5563 | assert_eq!(config.bundled_skills_install_dir(), owned_skills_dir()); |
| 5564 | } |
| 5565 | assert_eq!( |
| 5566 | config.skills_config().bundled.selected, |
| 5567 | Some(vec!["documents".into()]) |
| 5568 | ); |
| 5569 | } |
| 5570 | assert!(toml::from_str::<Config>("[skills.bundled]\ninstall = 'invalid'").is_err()); |
| 5571 | Ok(()) |
| 5572 | } |
| 5573 | |
| 5574 | #[test] |
| 5575 | fn test_load_uses_tilde_expanded_deepseek_config_path() -> Result<()> { |
| 5576 | let _lock = lock_test_env(); |
| 5577 | let nanos = SystemTime::now() |
| 5578 | .duration_since(UNIX_EPOCH) |
| 5579 | .unwrap() |
| 5580 | .as_nanos(); |
| 5581 | let temp_root = env::temp_dir().join(format!( |
| 5582 | "codewhale-tui-load-tilde-test-{}-{}", |
| 5583 | std::process::id(), |
| 5584 | nanos |
| 5585 | )); |
| 5586 | fs::create_dir_all(&temp_root)?; |
| 5587 | let _guard = EnvGuard::new(&temp_root); |
| 5588 | |
| 5589 | let config_path = temp_root.join(".custom-deepseek").join("config.toml"); |
| 5590 | ensure_parent_dir(&config_path)?; |
| 5591 | fs::write(&config_path, "api_key = \"test-key\"\n")?; |
| 5592 | |
| 5593 | // Safety: test-only environment mutation guarded by a global mutex. |
| 5594 | unsafe { |
| 5595 | env::set_var("DEEPSEEK_CONFIG_PATH", "~/.custom-deepseek/config.toml"); |
| 5596 | } |
| 5597 | |
| 5598 | let config = Config::load(None, None)?; |
| 5599 | assert_eq!(config.deepseek_table_api_key(), Some("test-key")); |
| 5600 | Ok(()) |
| 5601 | } |
| 5602 | |
| 5603 | #[test] |
| 5604 | fn missing_env_config_path_does_not_fall_back_to_a_different_home_file() -> Result<()> { |
| 5605 | let _lock = lock_test_env(); |
| 5606 | let nanos = SystemTime::now() |
| 5607 | .duration_since(UNIX_EPOCH) |
| 5608 | .unwrap() |
| 5609 | .as_nanos(); |
| 5610 | let temp_root = env::temp_dir().join(format!( |
| 5611 | "codewhale-tui-load-fallback-test-{}-{}", |
| 5612 | std::process::id(), |
| 5613 | nanos |
| 5614 | )); |
| 5615 | fs::create_dir_all(&temp_root)?; |
| 5616 | let _guard = EnvGuard::new(&temp_root); |
| 5617 | |
| 5618 | let home_config = temp_root.join(".deepseek").join("config.toml"); |
| 5619 | ensure_parent_dir(&home_config)?; |
| 5620 | fs::write(&home_config, "api_key = \"home-key\"\n")?; |
| 5621 | |
| 5622 | // Safety: test-only environment mutation guarded by a global mutex. |
| 5623 | unsafe { |
| 5624 | env::set_var( |
| 5625 | "DEEPSEEK_CONFIG_PATH", |
| 5626 | temp_root.join("missing-config.toml").as_os_str(), |
| 5627 | ); |
| 5628 | } |
| 5629 | |
| 5630 | let config = Config::load(None, None)?; |
| 5631 | assert_eq!( |
| 5632 | config.deepseek_table_api_key(), |
| 5633 | None, |
| 5634 | "reads must honor the same missing env target that writes will create" |
| 5635 | ); |
| 5636 | Ok(()) |
| 5637 | } |
| 5638 | |
| 5639 | #[test] |
| 5640 | fn save_then_load_uses_the_same_missing_absolute_env_config_path() -> Result<()> { |
| 5641 | let _lock = lock_test_env(); |
| 5642 | let temp_root = tempfile::tempdir()?; |
| 5643 | let _guard = EnvGuard::new(temp_root.path()); |
| 5644 | let config_path = temp_root.path().join("nested/config.toml"); |
| 5645 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", &config_path); |
| 5646 | let _legacy_config_path = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"); |
| 5647 | let identity = ProviderIdentity { |
| 5648 | provider: ProviderKind::Openrouter, |
| 5649 | key: ProviderKind::Openrouter.as_str().into(), |
| 5650 | exact_id: Some(ProviderKind::Openrouter.as_str().into()), |
| 5651 | migrated_legacy_ollama_cloud_route: false, |
| 5652 | legacy_root_custom_generation: None, |
| 5653 | }; |
| 5654 | |
| 5655 | let written = |
| 5656 | save_provider_model_for_identity(&identity, &Config::default(), "round-trip-model")?; |
| 5657 | assert_eq!(written, config_path); |
| 5658 | let loaded = Config::load(None, None)?; |
| 5659 | assert_eq!( |
| 5660 | loaded |
| 5661 | .provider_config_for(&loaded.test_identity_for_kind(ProviderKind::Openrouter)) |
| 5662 | .and_then(|provider| provider.model.as_deref()), |
| 5663 | Some("round-trip-model") |
| 5664 | ); |
| 5665 | Ok(()) |
| 5666 | } |
| 5667 | |
| 5668 | #[test] |
| 5669 | fn relative_config_env_is_a_load_error() -> Result<()> { |
| 5670 | let _lock = lock_test_env(); |
| 5671 | let temp_root = tempfile::tempdir()?; |
| 5672 | let _guard = EnvGuard::new(temp_root.path()); |
| 5673 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", ".codewhale/config.toml"); |
| 5674 | let _legacy_config_path = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"); |
| 5675 | |
| 5676 | let error = Config::load(None, None).expect_err("relative config path must fail closed"); |
| 5677 | let message = format!("{error:#}"); |
| 5678 | assert!(message.contains("CODEWHALE_CONFIG_PATH"), "{message}"); |
| 5679 | assert!(message.contains("absolute"), "{message}"); |
| 5680 | |
| 5681 | for error in [ |
| 5682 | default_config_path().expect_err("default path must preserve the override error"), |
| 5683 | resolve_load_config_path(None) |
| 5684 | .expect_err("load-path helper must preserve the override error"), |
| 5685 | ensure_config_file_exists(None) |
| 5686 | .expect_err("first-run config creation must preserve the override error"), |
| 5687 | ] { |
| 5688 | let message = format!("{error:#}"); |
| 5689 | assert!(message.contains("CODEWHALE_CONFIG_PATH"), "{message}"); |
| 5690 | assert!(message.contains("absolute"), "{message}"); |
| 5691 | assert!(!message.contains("home directory not found"), "{message}"); |
| 5692 | } |
| 5693 | let error = env_config_path().expect_err("env helper must preserve the override error"); |
| 5694 | let message = error.to_string(); |
| 5695 | assert!(message.contains("CODEWHALE_CONFIG_PATH"), "{message}"); |
| 5696 | assert!(workspace_trust_config_candidate_paths().is_empty()); |
| 5697 | Ok(()) |
| 5698 | } |
| 5699 | |
| 5700 | #[test] |
| 5701 | fn test_nonexistent_profile_error() { |
| 5702 | let mut profiles = HashMap::new(); |
| 5703 | profiles.insert("work".to_string(), Config::default()); |
| 5704 | let config = ConfigFile { |
| 5705 | base: Box::default(), |
| 5706 | profiles: Some(profiles), |
| 5707 | legacy_root: Default::default(), |
| 5708 | }; |
| 5709 | |
| 5710 | let err = apply_profile(config, Some("nonexistent")).unwrap_err(); |
| 5711 | let message = err.to_string(); |
| 5712 | assert!(message.contains("Profile 'nonexistent' not found")); |
| 5713 | assert!(message.contains("Available profiles")); |
| 5714 | assert!(message.contains("work")); |
| 5715 | } |
| 5716 | |
| 5717 | /// #6362: `ConfigFile` keeps its base `Config` boxed. Parsing a document |
| 5718 | /// through the profile path used to carry the multi-kilobyte struct by value |
| 5719 | /// through the `toml::de` and `apply_profile` frames, which overflowed the |
| 5720 | /// 2 MiB stack libtest gives every test thread in debug builds and aborted |
| 5721 | /// the whole lib suite. Pin that budget explicitly: CI exports a larger |
| 5722 | /// `RUST_MIN_STACK`, so without this thread the regression would be masked. |
| 5723 | /// A regression here aborts the process with "has overflowed its stack", |
| 5724 | /// which is the reported symptom, not a panic. |
| 5725 | #[test] |
| 5726 | fn profile_document_parses_within_the_default_test_thread_stack() { |
| 5727 | const DEFAULT_TEST_THREAD_STACK: usize = 2 * 1024 * 1024; |
| 5728 | let document = r#" |
| 5729 | provider = "deepseek" |
| 5730 | approval_policy = "on-request" |
| 5731 | |
| 5732 | [tui] |
| 5733 | theme = "underwater" |
| 5734 | |
| 5735 | [profiles.work] |
| 5736 | approval_policy = "never" |
| 5737 | "#; |
| 5738 | let handle = std::thread::Builder::new() |
| 5739 | .name("config-default-test-stack".into()) |
| 5740 | .stack_size(DEFAULT_TEST_THREAD_STACK) |
| 5741 | .spawn(move || { |
| 5742 | let config = |
| 5743 | Config::from_saved_document(document, Some("work")).expect("profile parses"); |
| 5744 | assert_eq!(config.approval_policy.as_deref(), Some("never")); |
| 5745 | let base = Config::from_saved_document(document, None).expect("base parses"); |
| 5746 | assert_eq!(base.approval_policy.as_deref(), Some("on-request")); |
| 5747 | }) |
| 5748 | .expect("spawn a 2 MiB test thread"); |
| 5749 | handle |
| 5750 | .join() |
| 5751 | .expect("config parsing must fit the default test thread stack"); |
| 5752 | } |
| 5753 | |
| 5754 | #[test] |
| 5755 | fn test_profile_with_no_profiles_section() { |
| 5756 | let config = ConfigFile { |
| 5757 | base: Box::default(), |
| 5758 | profiles: None, |
| 5759 | legacy_root: Default::default(), |
| 5760 | }; |
| 5761 | |
| 5762 | let err = apply_profile(config, Some("missing")).unwrap_err(); |
| 5763 | assert!(err.to_string().contains("Available profiles: none")); |
| 5764 | } |
| 5765 | |
| 5766 | #[test] |
| 5767 | fn test_save_api_key_doesnt_match_similar_keys() -> Result<()> { |
| 5768 | let _lock = lock_test_env(); |
| 5769 | let nanos = SystemTime::now() |
| 5770 | .duration_since(UNIX_EPOCH) |
| 5771 | .unwrap() |
| 5772 | .as_nanos(); |
| 5773 | let temp_root = env::temp_dir().join(format!( |
| 5774 | "codewhale-tui-api-key-test-{}-{}", |
| 5775 | std::process::id(), |
| 5776 | nanos |
| 5777 | )); |
| 5778 | fs::create_dir_all(&temp_root)?; |
| 5779 | let _guard = EnvGuard::new(&temp_root); |
| 5780 | |
| 5781 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 5782 | ensure_parent_dir(&config_path)?; |
| 5783 | fs::write( |
| 5784 | &config_path, |
| 5785 | "api_key_backup = \"old\"\napi_key = \"current\"\n", |
| 5786 | )?; |
| 5787 | let resolved_config_path = codewhale_config::resolve_config_path(None)?; |
| 5788 | |
| 5789 | let saved = save_api_key("new-key")?; |
| 5790 | assert_eq!(saved, SavedCredential::ConfigFile(resolved_config_path)); |
| 5791 | |
| 5792 | let contents = fs::read_to_string(&config_path)?; |
| 5793 | assert!(contents.contains("api_key_backup = \"old\"")); |
| 5794 | assert!(contents.contains("api_key = \"")); |
| 5795 | Ok(()) |
| 5796 | } |
| 5797 | |
| 5798 | #[test] |
| 5799 | fn test_empty_top_level_api_key_counts_as_absent() { |
| 5800 | // An empty legacy top-level key is dropped when the file is parsed |
| 5801 | // (#6394); it never reaches a route as an empty credential. |
| 5802 | let config = Config { |
| 5803 | ..Default::default() |
| 5804 | } |
| 5805 | .with_legacy_root(Some(" ".to_string()), None); |
| 5806 | assert!(config.validate().is_ok()); |
| 5807 | assert_eq!(config.deepseek_table_api_key(), None); |
| 5808 | } |
| 5809 | |
| 5810 | #[test] |
| 5811 | fn test_missing_api_key_allowed() -> Result<()> { |
| 5812 | let config = Config::default(); |
| 5813 | config.validate()?; |
| 5814 | Ok(()) |
| 5815 | } |
| 5816 | |
| 5817 | #[test] |
| 5818 | fn apply_env_overrides_ignores_empty_api_key() -> Result<()> { |
| 5819 | let _lock = lock_test_env(); |
| 5820 | let nanos = SystemTime::now() |
| 5821 | .duration_since(UNIX_EPOCH) |
| 5822 | .unwrap() |
| 5823 | .as_nanos(); |
| 5824 | let temp_root = env::temp_dir().join(format!( |
| 5825 | "codewhale-tui-empty-key-{}-{}", |
| 5826 | std::process::id(), |
| 5827 | nanos |
| 5828 | )); |
| 5829 | fs::create_dir_all(&temp_root)?; |
| 5830 | let _guard = EnvGuard::new(&temp_root); |
| 5831 | |
| 5832 | // Simulate a fresh user who copied .env.example to .env without |
| 5833 | // filling in DEEPSEEK_API_KEY: dotenv loads it as the empty string. |
| 5834 | // Safety: test-only environment mutation guarded by a global mutex. |
| 5835 | unsafe { |
| 5836 | env::set_var("DEEPSEEK_API_KEY", ""); |
| 5837 | } |
| 5838 | |
| 5839 | let mut config = Config { |
| 5840 | ..Default::default() |
| 5841 | } |
| 5842 | .with_legacy_root(Some("from-config-file".to_string()), None); |
| 5843 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 5844 | |
| 5845 | assert_eq!(config.deepseek_table_api_key(), Some("from-config-file")); |
| 5846 | config.validate()?; |
| 5847 | Ok(()) |
| 5848 | } |
| 5849 | |
| 5850 | #[test] |
| 5851 | fn apply_env_overrides_does_not_copy_api_key_into_config() -> Result<()> { |
| 5852 | let _lock = lock_test_env(); |
| 5853 | let nanos = SystemTime::now() |
| 5854 | .duration_since(UNIX_EPOCH) |
| 5855 | .unwrap() |
| 5856 | .as_nanos(); |
| 5857 | let temp_root = env::temp_dir().join(format!( |
| 5858 | "codewhale-tui-env-key-not-config-{}-{}", |
| 5859 | std::process::id(), |
| 5860 | nanos |
| 5861 | )); |
| 5862 | fs::create_dir_all(&temp_root)?; |
| 5863 | let _guard = EnvGuard::new(&temp_root); |
| 5864 | |
| 5865 | unsafe { |
| 5866 | env::set_var("DEEPSEEK_API_KEY", "env-key"); |
| 5867 | } |
| 5868 | let mut config = Config::default(); |
| 5869 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 5870 | |
| 5871 | assert_eq!(config.deepseek_table_api_key(), None); |
| 5872 | assert_eq!(config.active_route_api_key()?, "env-key"); |
| 5873 | unsafe { |
| 5874 | env::remove_var("DEEPSEEK_API_KEY"); |
| 5875 | } |
| 5876 | Ok(()) |
| 5877 | } |
| 5878 | |
| 5879 | #[test] |
| 5880 | fn normalize_model_name_preserves_v_series_snapshots() { |
| 5881 | let deepseek_wire = |model: &str| { |
| 5882 | codewhale_config::route::resolve_model(ProviderKind::Deepseek, model, None) |
| 5883 | .ok() |
| 5884 | .map(|resolved| resolved.wire_id) |
| 5885 | }; |
| 5886 | assert_eq!( |
| 5887 | deepseek_wire("deepseek-v4-pro").as_deref(), |
| 5888 | Some("deepseek-v4-pro") |
| 5889 | ); |
| 5890 | assert_eq!( |
| 5891 | deepseek_wire("deepseek-v4pro").as_deref(), |
| 5892 | Some("deepseek-v4-pro") |
| 5893 | ); |
| 5894 | assert_eq!(deepseek_wire("pro").as_deref(), Some("deepseek-v4-pro")); |
| 5895 | assert_eq!(deepseek_wire("flash").as_deref(), Some("deepseek-flash")); |
| 5896 | for alias in ["flash-vision", "deepseek-v4flashvisionexp"] { |
| 5897 | assert_eq!(deepseek_wire(alias).as_deref(), Some("deepseek-flash")); |
| 5898 | assert!(validate_route(ProviderKind::Deepseek, alias).is_ok()); |
| 5899 | } |
| 5900 | assert_eq!( |
| 5901 | deepseek_wire("deepseek-v4-flash-20260423").as_deref(), |
| 5902 | Some("deepseek-v4-flash-20260423") |
| 5903 | ); |
| 5904 | assert_eq!( |
| 5905 | deepseek_wire("deepseek-v5-pro-20270101").as_deref(), |
| 5906 | Some("deepseek-v5-pro-20270101") |
| 5907 | ); |
| 5908 | assert_eq!( |
| 5909 | deepseek_wire("deepseek-chat").as_deref(), |
| 5910 | Some(DEEPSEEK_ALIAS_REPLACEMENT) |
| 5911 | ); |
| 5912 | assert_eq!( |
| 5913 | deepseek_wire("deepseek-ai/deepseek-v4-pro").as_deref(), |
| 5914 | Some("deepseek-v4-pro") |
| 5915 | ); |
| 5916 | assert_eq!( |
| 5917 | deepseek_wire("DeepSeek-V4-Pro").as_deref(), |
| 5918 | Some("deepseek-v4-pro") |
| 5919 | ); |
| 5920 | assert_eq!( |
| 5921 | deepseek_wire("deepseek-ai/DeepSeek-V4-Pro").as_deref(), |
| 5922 | Some("deepseek-v4-pro") |
| 5923 | ); |
| 5924 | } |
| 5925 | |
| 5926 | #[test] |
| 5927 | fn normalize_model_scenario() { |
| 5928 | let resolve_wire = |provider: ProviderKind, model: &str| { |
| 5929 | codewhale_config::route::resolve_model(provider, model, None) |
| 5930 | .ok() |
| 5931 | .map(|resolved| resolved.wire_id) |
| 5932 | }; |
| 5933 | { |
| 5934 | assert_eq!( |
| 5935 | resolve_wire(ProviderKind::Deepseek, "DeepSeek-V4-Pro").as_deref(), |
| 5936 | Some("deepseek-v4-pro") |
| 5937 | ); |
| 5938 | assert_eq!( |
| 5939 | resolve_wire(ProviderKind::NvidiaNim, "DeepSeek-V4-Pro").as_deref(), |
| 5940 | Some(DEFAULT_NVIDIA_NIM_MODEL) |
| 5941 | ); |
| 5942 | } |
| 5943 | { |
| 5944 | for (alias, expected) in [ |
| 5945 | ("kimi", DEFAULT_MOONSHOT_MODEL), |
| 5946 | ("kimi-k2.7", DEFAULT_MOONSHOT_MODEL), |
| 5947 | ("kimi-k2.7-code", DEFAULT_MOONSHOT_MODEL), |
| 5948 | ("kimi-code", DEFAULT_MOONSHOT_MODEL), |
| 5949 | ("kimi-k2.6", MOONSHOT_KIMI_K2_6_MODEL), |
| 5950 | ] { |
| 5951 | assert_eq!( |
| 5952 | resolve_wire(ProviderKind::Moonshot, alias).as_deref(), |
| 5953 | Some(expected) |
| 5954 | ); |
| 5955 | } |
| 5956 | } |
| 5957 | { |
| 5958 | for (alias, expected) in [ |
| 5959 | ("minimax", DEFAULT_MINIMAX_MODEL), |
| 5960 | ("minimax-m3", DEFAULT_MINIMAX_MODEL), |
| 5961 | ("minimax-m2.7", MINIMAX_M2_7_MODEL), |
| 5962 | ("minimax-m2-7-highspeed", MINIMAX_M2_7_HIGHSPEED_MODEL), |
| 5963 | ("minimax-m2.5", MINIMAX_M2_5_MODEL), |
| 5964 | ("minimax-m2-5-highspeed", MINIMAX_M2_5_HIGHSPEED_MODEL), |
| 5965 | ("minimax-m2.1", MINIMAX_M2_1_MODEL), |
| 5966 | ("minimax-m2-1-highspeed", MINIMAX_M2_1_HIGHSPEED_MODEL), |
| 5967 | ("minimax-m2", MINIMAX_M2_MODEL), |
| 5968 | ] { |
| 5969 | assert_eq!( |
| 5970 | resolve_wire(ProviderKind::Minimax, alias).as_deref(), |
| 5971 | Some(expected) |
| 5972 | ); |
| 5973 | } |
| 5974 | } |
| 5975 | { |
| 5976 | for (alias, expected) in [ |
| 5977 | ("trinity", DEFAULT_ARCEE_MODEL), |
| 5978 | ("arcee-trinity", DEFAULT_ARCEE_MODEL), |
| 5979 | ("trinity-large-thinking", DEFAULT_ARCEE_MODEL), |
| 5980 | ("arcee-trinity-large-thinking", DEFAULT_ARCEE_MODEL), |
| 5981 | ("arcee-trinity-mini", ARCEE_TRINITY_MINI_MODEL), |
| 5982 | ("trinity-mini", ARCEE_TRINITY_MINI_MODEL), |
| 5983 | ( |
| 5984 | "arcee-trinity-large-preview", |
| 5985 | ARCEE_TRINITY_LARGE_PREVIEW_MODEL, |
| 5986 | ), |
| 5987 | ("TRINITY_LARGE_PREVIEW", ARCEE_TRINITY_LARGE_PREVIEW_MODEL), |
| 5988 | ] { |
| 5989 | assert_eq!( |
| 5990 | resolve_wire(ProviderKind::Arcee, alias).as_deref(), |
| 5991 | Some(expected) |
| 5992 | ); |
| 5993 | } |
| 5994 | } |
| 5995 | { |
| 5996 | assert!(resolve_wire(ProviderKind::Deepseek, "qwen3-coder").is_none()); |
| 5997 | assert!(resolve_wire(ProviderKind::Deepseek, "codewhale v4").is_none()); |
| 5998 | assert!(resolve_wire(ProviderKind::Deepseek, "").is_none()); |
| 5999 | } |
| 6000 | { |
| 6001 | assert_eq!( |
| 6002 | resolve_wire(ProviderKind::Deepseek, "vendor/deepseek-v4-pro").as_deref(), |
| 6003 | Some("vendor/deepseek-v4-pro") |
| 6004 | ); |
| 6005 | assert!( |
| 6006 | resolve_wire( |
| 6007 | ProviderKind::Deepseek, |
| 6008 | "accounts/fireworks/models/deepseek-v4-flash" |
| 6009 | ) |
| 6010 | .is_none() |
| 6011 | ); |
| 6012 | assert_eq!( |
| 6013 | resolve_wire( |
| 6014 | ProviderKind::Fireworks, |
| 6015 | "accounts/fireworks/models/deepseek-v4-flash" |
| 6016 | ) |
| 6017 | .as_deref(), |
| 6018 | Some("accounts/fireworks/models/deepseek-v4-flash") |
| 6019 | ); |
| 6020 | } |
| 6021 | } |
| 6022 | |
| 6023 | #[test] |
| 6024 | fn normalize_model_name_for_provider_canonicalizes_deepseek_api_variants() { |
| 6025 | let resolve_wire = |provider: ProviderKind, model: &str| { |
| 6026 | codewhale_config::route::resolve_model(provider, model, None) |
| 6027 | .ok() |
| 6028 | .map(|resolved| resolved.wire_id) |
| 6029 | }; |
| 6030 | let resolve_logical = |provider: ProviderKind, model: &str| { |
| 6031 | codewhale_config::route::resolve_model(provider, model, None) |
| 6032 | .ok() |
| 6033 | .map(|resolved| resolved.logical) |
| 6034 | }; |
| 6035 | assert_eq!( |
| 6036 | resolve_wire(ProviderKind::Deepseek, "deepseek-ai/DeepSeek-V4-Pro").as_deref(), |
| 6037 | Some("deepseek-v4-pro") |
| 6038 | ); |
| 6039 | assert_eq!( |
| 6040 | resolve_wire(ProviderKind::Deepseek, "deepseek/deepseek-v4-flash").as_deref(), |
| 6041 | Some("deepseek-v4-flash") |
| 6042 | ); |
| 6043 | |
| 6044 | for provider in [ |
| 6045 | ProviderKind::Deepseek, |
| 6046 | ProviderKind::Deepseek, |
| 6047 | ProviderKind::DeepseekAnthropic, |
| 6048 | ] { |
| 6049 | for alias in ["deepseek-chat", "deepseek-reasoner"] { |
| 6050 | assert_eq!( |
| 6051 | resolve_logical(provider, alias).as_deref(), |
| 6052 | Some(DEEPSEEK_ALIAS_REPLACEMENT), |
| 6053 | "{provider:?} must retire {alias} before the wire boundary" |
| 6054 | ); |
| 6055 | assert_eq!( |
| 6056 | resolve_wire(provider, alias).as_deref(), |
| 6057 | Some(DEEPSEEK_ALIAS_REPLACEMENT), |
| 6058 | "{provider:?} config normalization must retire {alias}" |
| 6059 | ); |
| 6060 | } |
| 6061 | } |
| 6062 | } |
| 6063 | |
| 6064 | #[test] |
| 6065 | fn migrated_deepseek_alias_receipt_is_runtime_only_and_defaults_empty() { |
| 6066 | assert!(Config::default().migrated_deepseek_model_alias.is_none()); |
| 6067 | |
| 6068 | let config: Config = toml::from_str( |
| 6069 | r#" |
| 6070 | default_text_model = "deepseek-v4-flash" |
| 6071 | migrated_deepseek_model_alias = "deepseek-chat" |
| 6072 | "#, |
| 6073 | ) |
| 6074 | .expect("deserialize config"); |
| 6075 | assert!(config.migrated_deepseek_model_alias.is_none()); |
| 6076 | } |
| 6077 | |
| 6078 | #[test] |
| 6079 | fn retired_deepseek_aliases_keep_mode_intent_unless_effort_is_explicit() { |
| 6080 | // Model normalization reads the process-global model override. Without the |
| 6081 | // shared lock, env-focused config tests can replace these fixture aliases. |
| 6082 | let _lock = lock_test_env(); |
| 6083 | for (alias, expected_effort) in [("deepseek-chat", "off"), ("deepseek-reasoner", "high")] { |
| 6084 | for key in ["deepseek", "deepseek-cn", "deepseek-anthropic"] { |
| 6085 | let mut config = Config { |
| 6086 | provider: Some(key.to_string()), |
| 6087 | default_text_model: Some(alias.to_string()), |
| 6088 | ..Default::default() |
| 6089 | }; |
| 6090 | normalize_model_config(&mut config); |
| 6091 | |
| 6092 | assert_eq!( |
| 6093 | config.default_text_model.as_deref(), |
| 6094 | Some(DEEPSEEK_ALIAS_REPLACEMENT) |
| 6095 | ); |
| 6096 | assert_eq!(config.reasoning_effort.as_deref(), Some(expected_effort)); |
| 6097 | } |
| 6098 | } |
| 6099 | |
| 6100 | let mut explicit = Config { |
| 6101 | provider: Some("deepseek".to_string()), |
| 6102 | default_text_model: Some("deepseek-chat".to_string()), |
| 6103 | reasoning_effort: Some("max".to_string()), |
| 6104 | ..Default::default() |
| 6105 | }; |
| 6106 | normalize_model_config(&mut explicit); |
| 6107 | assert_eq!( |
| 6108 | explicit.default_text_model.as_deref(), |
| 6109 | Some(DEEPSEEK_ALIAS_REPLACEMENT) |
| 6110 | ); |
| 6111 | assert_eq!(explicit.reasoning_effort.as_deref(), Some("max")); |
| 6112 | |
| 6113 | let mut provider_scoped = Config { |
| 6114 | provider: Some("deepseek-anthropic".to_string()), |
| 6115 | providers: Some(ProvidersConfig { |
| 6116 | deepseek_anthropic: ProviderConfig { |
| 6117 | model: Some("deepseek-reasoner".to_string()), |
| 6118 | ..Default::default() |
| 6119 | }, |
| 6120 | ..Default::default() |
| 6121 | }), |
| 6122 | ..Default::default() |
| 6123 | }; |
| 6124 | normalize_model_config(&mut provider_scoped); |
| 6125 | assert_eq!( |
| 6126 | provider_scoped |
| 6127 | .provider_config_for( |
| 6128 | &provider_scoped.test_identity_for_kind(ProviderKind::DeepseekAnthropic) |
| 6129 | ) |
| 6130 | .and_then(|entry| entry.model.as_deref()), |
| 6131 | Some(DEEPSEEK_ALIAS_REPLACEMENT) |
| 6132 | ); |
| 6133 | assert_eq!(provider_scoped.reasoning_effort.as_deref(), Some("high")); |
| 6134 | |
| 6135 | let mut custom_endpoint = Config { |
| 6136 | provider: Some("deepseek".to_string()), |
| 6137 | default_text_model: Some("deepseek-chat".to_string()), |
| 6138 | ..Default::default() |
| 6139 | } |
| 6140 | .with_legacy_root(None, Some("https://gateway.example/v1".to_string())); |
| 6141 | normalize_model_config(&mut custom_endpoint); |
| 6142 | assert_eq!( |
| 6143 | custom_endpoint.default_text_model.as_deref(), |
| 6144 | Some("deepseek-chat") |
| 6145 | ); |
| 6146 | assert_eq!(custom_endpoint.reasoning_effort, None); |
| 6147 | } |
| 6148 | |
| 6149 | #[test] |
| 6150 | fn retired_deepseek_aliases_do_not_escape_provider_owned_namespaces() { |
| 6151 | for provider in [ |
| 6152 | ProviderKind::NvidiaNim, |
| 6153 | ProviderKind::Openrouter, |
| 6154 | ProviderKind::WanjieArk, |
| 6155 | ProviderKind::Custom, |
| 6156 | ] { |
| 6157 | for alias in ["deepseek-chat", "deepseek-reasoner"] { |
| 6158 | assert_eq!( |
| 6159 | codewhale_config::route::resolve_model(provider, alias, None) |
| 6160 | .ok() |
| 6161 | .map(|resolved| resolved.logical) |
| 6162 | .as_deref(), |
| 6163 | Some(alias), |
| 6164 | "{provider:?} owns the meaning of {alias}" |
| 6165 | ); |
| 6166 | } |
| 6167 | } |
| 6168 | } |
| 6169 | |
| 6170 | #[test] |
| 6171 | fn openrouter_hunyuan_aliases_resolve_to_hy3_preview() { |
| 6172 | for alias in [ |
| 6173 | "tencent/hy3-preview", |
| 6174 | "hy3-preview", |
| 6175 | "hy3", |
| 6176 | "hunyuan", |
| 6177 | "tencent-hunyuan", |
| 6178 | "hunyuan-hy3", |
| 6179 | ] { |
| 6180 | assert_eq!( |
| 6181 | codewhale_config::route::resolve_model(ProviderKind::Openrouter, alias, None) |
| 6182 | .ok() |
| 6183 | .map(|resolved| resolved.logical) |
| 6184 | .as_deref(), |
| 6185 | Some(OPENROUTER_TENCENT_HY3_PREVIEW_MODEL), |
| 6186 | "{alias} should select the public Hy3 preview id" |
| 6187 | ); |
| 6188 | } |
| 6189 | assert_ne!( |
| 6190 | codewhale_config::route::resolve_model(ProviderKind::Openrouter, "hy4", None) |
| 6191 | .ok() |
| 6192 | .map(|resolved| resolved.logical) |
| 6193 | .as_deref(), |
| 6194 | Some(OPENROUTER_TENCENT_HY3_PREVIEW_MODEL), |
| 6195 | "hy4 is not a released public model id" |
| 6196 | ); |
| 6197 | } |
| 6198 | |
| 6199 | #[test] |
| 6200 | fn deepseek_default_model_canonicalizes_provider_prefixed_ids() { |
| 6201 | let _lock = lock_test_env(); |
| 6202 | let temp_root = tempfile::tempdir().unwrap(); |
| 6203 | let _guard = EnvGuard::new(temp_root.path()); |
| 6204 | |
| 6205 | let config = Config { |
| 6206 | provider: Some("deepseek".to_string()), |
| 6207 | default_text_model: Some(DEFAULT_OPENROUTER_MODEL.to_string()), |
| 6208 | ..Default::default() |
| 6209 | }; |
| 6210 | // The prefixed id canonicalizes to the deepseek-native PRO spelling; it is |
| 6211 | // not the default constant (that is deepseek-flash), it is that model. |
| 6212 | assert_eq!(config.default_model(), "deepseek-v4-pro"); |
| 6213 | |
| 6214 | let config = Config { |
| 6215 | provider: Some("deepseek".to_string()), |
| 6216 | providers: Some(ProvidersConfig { |
| 6217 | deepseek: ProviderConfig { |
| 6218 | model: Some(DEFAULT_OPENROUTER_MODEL.to_string()), |
| 6219 | ..Default::default() |
| 6220 | }, |
| 6221 | ..Default::default() |
| 6222 | }), |
| 6223 | ..Default::default() |
| 6224 | }; |
| 6225 | assert_eq!(config.default_model(), "deepseek-v4-pro"); |
| 6226 | } |
| 6227 | |
| 6228 | #[test] |
| 6229 | fn requested_model_for_provider_is_permissive_off_deepseek() { |
| 6230 | let requested = |provider: ProviderKind, model: &str| { |
| 6231 | codewhale_config::route::resolve_model(provider, model, None) |
| 6232 | .ok() |
| 6233 | .map(|resolved| resolved.logical) |
| 6234 | }; |
| 6235 | assert_eq!( |
| 6236 | requested(ProviderKind::Moonshot, "kimi-k2.5").as_deref(), |
| 6237 | Some("kimi-k2.5") |
| 6238 | ); |
| 6239 | assert_eq!( |
| 6240 | requested(ProviderKind::Ollama, "qwen3:32b").as_deref(), |
| 6241 | Some("qwen3:32b") |
| 6242 | ); |
| 6243 | assert!(requested(ProviderKind::Deepseek, "kimi-k2.5").is_none()); |
| 6244 | assert_eq!( |
| 6245 | requested(ProviderKind::Deepseek, "deepseek-v4-pro").as_deref(), |
| 6246 | Some("deepseek-v4-pro") |
| 6247 | ); |
| 6248 | } |
| 6249 | |
| 6250 | #[test] |
| 6251 | fn validate_route_rejects_mismatched_provider_model_tuple() { |
| 6252 | // #3227: the exact contamination — Z.ai provider paired with a |
| 6253 | // DeepSeek model — is rejected locally with a diagnostic that names |
| 6254 | // the incompatible pair, before any network call. |
| 6255 | let err = validate_route(ProviderKind::Zai, "deepseek-v4-pro") |
| 6256 | .expect_err("zai + deepseek model must be rejected"); |
| 6257 | assert!(err.contains("deepseek-v4-pro"), "names the model: {err}"); |
| 6258 | assert!(err.contains("zai"), "names the provider: {err}"); |
| 6259 | |
| 6260 | // A DeepSeek-native provider rejects a non-DeepSeek model id. |
| 6261 | let err = validate_route(ProviderKind::Deepseek, "GLM-5.2") |
| 6262 | .expect_err("deepseek + GLM must be rejected"); |
| 6263 | assert!(err.contains("GLM-5.2"), "names the model: {err}"); |
| 6264 | |
| 6265 | // Coherent routes pass. |
| 6266 | assert!(validate_route(ProviderKind::Zai, "GLM-5.2").is_ok()); |
| 6267 | assert!(validate_route(ProviderKind::Deepseek, "deepseek-v4-pro").is_ok()); |
| 6268 | // `auto` is always acceptable; the per-turn router resolves it. |
| 6269 | assert!(validate_route(ProviderKind::Zai, "auto").is_ok()); |
| 6270 | // Pass-through / aggregator providers stay permissive — the upstream |
| 6271 | // API remains the authority for them. |
| 6272 | assert!(validate_route(ProviderKind::Openai, "deepseek-v4-pro").is_ok()); |
| 6273 | assert!(validate_route(ProviderKind::Openai, "qwen-plus").is_ok()); |
| 6274 | assert!(validate_route(ProviderKind::Openrouter, "deepseek-v4-pro").is_ok()); |
| 6275 | assert!(validate_route(ProviderKind::NvidiaNim, "deepseek-v4-pro").is_ok()); |
| 6276 | assert!(validate_route(ProviderKind::Together, DEFAULT_TOGETHER_MODEL).is_ok()); |
| 6277 | assert!(validate_route(ProviderKind::Together, DEFAULT_TOGETHER_FLASH_MODEL).is_ok()); |
| 6278 | assert!(validate_route(ProviderKind::Together, "deepseek-v4-pro").is_ok()); |
| 6279 | |
| 6280 | // Sakana AI (Fugu) is a native provider — DeepSeek ids must not cross-wire. |
| 6281 | let err = validate_route(ProviderKind::Sakana, "deepseek-v4-flash") |
| 6282 | .expect_err("sakana + deepseek flash must be rejected"); |
| 6283 | assert!(err.contains("deepseek-v4-flash"), "names the model: {err}"); |
| 6284 | assert!(err.contains("sakana"), "names the provider: {err}"); |
| 6285 | assert!(validate_route(ProviderKind::Sakana, DEFAULT_SAKANA_MODEL).is_ok()); |
| 6286 | } |
| 6287 | |
| 6288 | #[test] |
| 6289 | fn wire_model_for_provider_matches_active_provider_shape() { |
| 6290 | let wire = |provider: ProviderKind, model: &str| { |
| 6291 | codewhale_config::route::resolve_model(provider, model, None) |
| 6292 | .map_or_else(|_| model.trim().to_string(), |resolved| resolved.wire_id) |
| 6293 | }; |
| 6294 | assert_eq!( |
| 6295 | wire(ProviderKind::Deepseek, DEFAULT_OPENROUTER_MODEL), |
| 6296 | "deepseek-v4-pro" |
| 6297 | ); |
| 6298 | assert_eq!( |
| 6299 | wire(ProviderKind::Openrouter, "deepseek-v4-pro"), |
| 6300 | DEFAULT_OPENROUTER_MODEL |
| 6301 | ); |
| 6302 | assert_eq!( |
| 6303 | wire(ProviderKind::NvidiaNim, "deepseek-v4-pro"), |
| 6304 | DEFAULT_NVIDIA_NIM_MODEL |
| 6305 | ); |
| 6306 | assert_eq!( |
| 6307 | wire(ProviderKind::Together, "deepseek-v4-pro"), |
| 6308 | DEFAULT_TOGETHER_MODEL |
| 6309 | ); |
| 6310 | assert_eq!( |
| 6311 | wire(ProviderKind::Together, "deepseek-v4-flash"), |
| 6312 | DEFAULT_TOGETHER_FLASH_MODEL |
| 6313 | ); |
| 6314 | assert_eq!( |
| 6315 | wire(ProviderKind::Together, "thinkingmachines/inkling"), |
| 6316 | TOGETHER_INKLING_MODEL |
| 6317 | ); |
| 6318 | assert_eq!( |
| 6319 | wire(ProviderKind::Together, "inkling"), |
| 6320 | TOGETHER_INKLING_MODEL |
| 6321 | ); |
| 6322 | assert_eq!( |
| 6323 | wire(ProviderKind::Together, "together-inkling"), |
| 6324 | TOGETHER_INKLING_MODEL |
| 6325 | ); |
| 6326 | assert_eq!( |
| 6327 | wire(ProviderKind::Openai, DEFAULT_OPENROUTER_MODEL), |
| 6328 | DEFAULT_OPENROUTER_MODEL |
| 6329 | ); |
| 6330 | assert_eq!( |
| 6331 | wire(ProviderKind::Openrouter, OPENROUTER_MINIMAX_M3_MODEL), |
| 6332 | OPENROUTER_MINIMAX_M3_MODEL |
| 6333 | ); |
| 6334 | assert_eq!( |
| 6335 | wire(ProviderKind::SiliconflowCN, DEFAULT_SILICONFLOW_MODEL), |
| 6336 | DEFAULT_SILICONFLOW_MODEL |
| 6337 | ); |
| 6338 | assert_eq!( |
| 6339 | wire(ProviderKind::SiliconflowCN, "deepseek-v4-pro"), |
| 6340 | DEFAULT_SILICONFLOW_MODEL |
| 6341 | ); |
| 6342 | } |
| 6343 | |
| 6344 | #[test] |
| 6345 | fn wire_model_route_retires_aliases_only_on_official_deepseek_endpoints() { |
| 6346 | let route_wire = |provider: ProviderKind, base_url: &str, model: &str| { |
| 6347 | codewhale_config::route::resolve_model(provider, model, Some(base_url)) |
| 6348 | .map_or_else(|_| model.trim().to_string(), |resolved| resolved.wire_id) |
| 6349 | }; |
| 6350 | for (provider, base_url) in [ |
| 6351 | (ProviderKind::Deepseek, "https://api.deepseek.com"), |
| 6352 | (ProviderKind::Deepseek, "https://api.deepseek.com/v1"), |
| 6353 | (ProviderKind::Deepseek, "https://api.deepseek.com/beta"), |
| 6354 | ( |
| 6355 | ProviderKind::DeepseekAnthropic, |
| 6356 | "https://api.deepseek.com/anthropic", |
| 6357 | ), |
| 6358 | ( |
| 6359 | ProviderKind::DeepseekAnthropic, |
| 6360 | "https://api.deepseek.com/anthropic/v1/", |
| 6361 | ), |
| 6362 | ] { |
| 6363 | for alias in ["deepseek-chat", "deepseek-reasoner"] { |
| 6364 | assert_eq!( |
| 6365 | route_wire(provider, base_url, alias), |
| 6366 | DEEPSEEK_ALIAS_REPLACEMENT, |
| 6367 | "{provider:?} {base_url} must not send {alias}" |
| 6368 | ); |
| 6369 | } |
| 6370 | } |
| 6371 | |
| 6372 | for (provider, base_url, alias) in [ |
| 6373 | ( |
| 6374 | ProviderKind::Deepseek, |
| 6375 | "https://gateway.example/v1", |
| 6376 | "deepseek-chat", |
| 6377 | ), |
| 6378 | ( |
| 6379 | ProviderKind::DeepseekAnthropic, |
| 6380 | "https://messages.example/v1", |
| 6381 | "deepseek-reasoner", |
| 6382 | ), |
| 6383 | ( |
| 6384 | ProviderKind::WanjieArk, |
| 6385 | DEFAULT_WANJIE_ARK_BASE_URL, |
| 6386 | "deepseek-reasoner", |
| 6387 | ), |
| 6388 | ( |
| 6389 | ProviderKind::NvidiaNim, |
| 6390 | DEFAULT_NVIDIA_NIM_BASE_URL, |
| 6391 | "deepseek-reasoner", |
| 6392 | ), |
| 6393 | ] { |
| 6394 | assert_eq!( |
| 6395 | route_wire(provider, base_url, alias), |
| 6396 | alias, |
| 6397 | "{provider:?} owns the meaning of {alias}" |
| 6398 | ); |
| 6399 | } |
| 6400 | } |
| 6401 | |
| 6402 | #[test] |
| 6403 | fn normalize_model_name_for_provider_keeps_provider_specific_ids() { |
| 6404 | let resolve_wire = |provider: ProviderKind, model: &str| { |
| 6405 | codewhale_config::route::resolve_model(provider, model, None) |
| 6406 | .ok() |
| 6407 | .map(|resolved| resolved.wire_id) |
| 6408 | }; |
| 6409 | assert_eq!( |
| 6410 | resolve_wire(ProviderKind::NvidiaNim, "deepseek-v4-pro").as_deref(), |
| 6411 | Some(DEFAULT_NVIDIA_NIM_MODEL) |
| 6412 | ); |
| 6413 | assert_eq!( |
| 6414 | resolve_wire(ProviderKind::Openrouter, "deepseek-v4-flash").as_deref(), |
| 6415 | Some(DEFAULT_OPENROUTER_FLASH_MODEL) |
| 6416 | ); |
| 6417 | assert_eq!( |
| 6418 | resolve_wire(ProviderKind::Siliconflow, "deepseek-v4-pro").as_deref(), |
| 6419 | Some(DEFAULT_SILICONFLOW_MODEL) |
| 6420 | ); |
| 6421 | assert_eq!( |
| 6422 | resolve_wire(ProviderKind::Siliconflow, "deepseek-reasoner").as_deref(), |
| 6423 | Some(DEFAULT_SILICONFLOW_MODEL) |
| 6424 | ); |
| 6425 | assert_eq!( |
| 6426 | resolve_wire(ProviderKind::Siliconflow, "deepseek-r1").as_deref(), |
| 6427 | Some(DEFAULT_SILICONFLOW_MODEL) |
| 6428 | ); |
| 6429 | assert_eq!( |
| 6430 | resolve_wire(ProviderKind::SiliconflowCN, "deepseek-reasoner").as_deref(), |
| 6431 | Some(DEFAULT_SILICONFLOW_MODEL) |
| 6432 | ); |
| 6433 | assert_eq!( |
| 6434 | resolve_wire(ProviderKind::Siliconflow, "deepseek-chat").as_deref(), |
| 6435 | Some(DEFAULT_SILICONFLOW_FLASH_MODEL) |
| 6436 | ); |
| 6437 | assert_eq!( |
| 6438 | resolve_wire(ProviderKind::SiliconflowCN, "deepseek-chat").as_deref(), |
| 6439 | Some(DEFAULT_SILICONFLOW_FLASH_MODEL) |
| 6440 | ); |
| 6441 | assert_eq!( |
| 6442 | resolve_wire(ProviderKind::Siliconflow, "deepseek-v3").as_deref(), |
| 6443 | Some(DEFAULT_SILICONFLOW_FLASH_MODEL) |
| 6444 | ); |
| 6445 | assert_eq!( |
| 6446 | resolve_wire(ProviderKind::Siliconflow, "deepseek-v3.2").as_deref(), |
| 6447 | Some("deepseek-v3.2") |
| 6448 | ); |
| 6449 | assert_eq!( |
| 6450 | resolve_wire(ProviderKind::Together, "deepseek-v4-pro").as_deref(), |
| 6451 | Some(DEFAULT_TOGETHER_MODEL) |
| 6452 | ); |
| 6453 | assert_eq!( |
| 6454 | resolve_wire(ProviderKind::Together, "deepseek-chat").as_deref(), |
| 6455 | Some(DEFAULT_TOGETHER_FLASH_MODEL) |
| 6456 | ); |
| 6457 | } |
| 6458 | |
| 6459 | #[test] |
| 6460 | fn normalize_model_name_for_provider_maps_recent_openrouter_aliases() { |
| 6461 | for (alias, expected) in [ |
| 6462 | ( |
| 6463 | "trinity-large-thinking", |
| 6464 | OPENROUTER_ARCEE_TRINITY_LARGE_THINKING_MODEL, |
| 6465 | ), |
| 6466 | ("qwen3.6-flash", OPENROUTER_QWEN_3_6_FLASH_MODEL), |
| 6467 | ("qwen3.6-35b-a3b", OPENROUTER_QWEN_3_6_35B_A3B_MODEL), |
| 6468 | ("qwen3.6-max-preview", OPENROUTER_QWEN_3_6_MAX_PREVIEW_MODEL), |
| 6469 | ("qwen3.6-plus", OPENROUTER_QWEN_3_6_PLUS_MODEL), |
| 6470 | ("qwen3.7-plus", OPENROUTER_QWEN_3_7_PLUS_MODEL), |
| 6471 | ("qwen-3.7-plus", OPENROUTER_QWEN_3_7_PLUS_MODEL), |
| 6472 | ("mimo-v2.5-pro", OPENROUTER_XIAOMI_MIMO_V2_5_PRO_MODEL), |
| 6473 | ("kimi-k2.7-code", OPENROUTER_KIMI_K2_7_CODE_MODEL), |
| 6474 | ("kimi", OPENROUTER_KIMI_K2_7_CODE_MODEL), |
| 6475 | ("kimi-k2.6", OPENROUTER_KIMI_K2_6_MODEL), |
| 6476 | ("minimax-m3", OPENROUTER_MINIMAX_M3_MODEL), |
| 6477 | ("minimax-2.7", OPENROUTER_MINIMAX_M2_7_MODEL), |
| 6478 | ("gemma-4-31b-it", OPENROUTER_GEMMA_4_31B_MODEL), |
| 6479 | ("glm-5.1", OPENROUTER_GLM_5_1_MODEL), |
| 6480 | ("glm-5.2", OPENROUTER_GLM_5_2_MODEL), |
| 6481 | ] { |
| 6482 | assert_eq!( |
| 6483 | codewhale_config::route::resolve_model(ProviderKind::Openrouter, alias, None) |
| 6484 | .ok() |
| 6485 | .map(|resolved| resolved.wire_id) |
| 6486 | .as_deref(), |
| 6487 | Some(expected) |
| 6488 | ); |
| 6489 | } |
| 6490 | } |
| 6491 | |
| 6492 | #[test] |
| 6493 | fn normalize_xiaomi_mimo_aliases_for_provider() { |
| 6494 | let mimo_wire = |model: &str| { |
| 6495 | codewhale_config::route::resolve_model(ProviderKind::XiaomiMimo, model, None) |
| 6496 | .ok() |
| 6497 | .map(|resolved| resolved.wire_id) |
| 6498 | }; |
| 6499 | assert_eq!(mimo_wire("omni").as_deref(), Some("mimo-v2.6-flash")); |
| 6500 | assert_eq!(mimo_wire("tts").as_deref(), Some("mimo-v2.5-tts")); |
| 6501 | assert_eq!( |
| 6502 | mimo_wire("voice-design").as_deref(), |
| 6503 | Some("mimo-v2.5-tts-voicedesign") |
| 6504 | ); |
| 6505 | assert_eq!( |
| 6506 | mimo_wire("voiceclone").as_deref(), |
| 6507 | Some("mimo-v2.5-tts-voiceclone") |
| 6508 | ); |
| 6509 | } |
| 6510 | |
| 6511 | #[test] |
| 6512 | fn model_completion_scenario() { |
| 6513 | // Scenario consolidation of: model_completion_names_for_xiaomi_mimo_include_chat_models, model_completion_names_for_deepseek_api_are_deduplicated_bare_ids, model_completion_names_for_openai_are_native_to_its_default_endpoint, model_completion_names_for_atlascloud_keep_its_provider_owned_default, model_completion_names_for_together_include_provider_owned_models, model_completion_names_for_wanjie_keep_legacy_default_and_v4_ids, model_completion_names_for_ollama_do_not_promote_static_remote_models, model_completion_names_for_openrouter_include_recent_large_models |
| 6514 | // from model_completion_names_for_xiaomi_mimo_include_chat_models |
| 6515 | { |
| 6516 | let models = model_completion_names_for_provider(ProviderKind::XiaomiMimo); |
| 6517 | for expected in ["mimo-v2.6-pro", "mimo-v2.6-flash"] { |
| 6518 | assert!(models.contains(&expected), "missing {expected}"); |
| 6519 | } |
| 6520 | for deprecated in ["mimo-v2-pro", "mimo-v2-omni", "mimo-v2-flash"] { |
| 6521 | assert!( |
| 6522 | !models.contains(&deprecated), |
| 6523 | "{deprecated} is deprecated and should not be promoted" |
| 6524 | ); |
| 6525 | } |
| 6526 | for speech_model in [ |
| 6527 | "mimo-v2.5-tts", |
| 6528 | "mimo-v2.5-tts-voicedesign", |
| 6529 | "mimo-v2.5-tts-voiceclone", |
| 6530 | "mimo-v2-tts", |
| 6531 | ] { |
| 6532 | assert!( |
| 6533 | !models.contains(&speech_model), |
| 6534 | "{speech_model} belongs in speech/TTS selection, not /model" |
| 6535 | ); |
| 6536 | } |
| 6537 | } |
| 6538 | // from model_completion_names_for_deepseek_api_are_deduplicated_bare_ids |
| 6539 | { |
| 6540 | assert_eq!( |
| 6541 | model_completion_names_for_provider(ProviderKind::Deepseek), |
| 6542 | vec![ |
| 6543 | "deepseek-v4-pro", |
| 6544 | "deepseek-flash", |
| 6545 | "deepseek-v4-flash", |
| 6546 | "deepseek-v4-flash-vision-exp" |
| 6547 | ] |
| 6548 | ); |
| 6549 | } |
| 6550 | // from model_completion_names_for_openai_are_native_to_its_default_endpoint |
| 6551 | { |
| 6552 | let models = model_completion_names_for_provider(ProviderKind::Openai); |
| 6553 | |
| 6554 | assert_eq!(models.first().copied(), Some("gpt-5.6")); |
| 6555 | assert!(models.iter().all(|model| !model.contains("deepseek"))); |
| 6556 | } |
| 6557 | // from model_completion_names_for_atlascloud_keep_its_provider_owned_default |
| 6558 | { |
| 6559 | assert_eq!( |
| 6560 | model_completion_names_for_provider(ProviderKind::Atlascloud), |
| 6561 | vec![DEFAULT_ATLASCLOUD_MODEL] |
| 6562 | ); |
| 6563 | } |
| 6564 | // from model_completion_names_for_together_include_provider_owned_models |
| 6565 | { |
| 6566 | assert_eq!( |
| 6567 | model_completion_names_for_provider(ProviderKind::Together), |
| 6568 | vec![DEFAULT_TOGETHER_MODEL, DEFAULT_TOGETHER_FLASH_MODEL] |
| 6569 | ); |
| 6570 | } |
| 6571 | // from model_completion_names_for_wanjie_keep_legacy_default_and_v4_ids |
| 6572 | { |
| 6573 | let models = model_completion_names_for_provider(ProviderKind::WanjieArk); |
| 6574 | |
| 6575 | assert_eq!(models.first().copied(), Some(DEFAULT_WANJIE_ARK_MODEL)); |
| 6576 | assert!(models.contains(&"deepseek-v4-pro")); |
| 6577 | assert!(models.contains(&"deepseek-v4-flash")); |
| 6578 | } |
| 6579 | // from model_completion_names_for_ollama_do_not_promote_static_remote_models |
| 6580 | { |
| 6581 | let models = model_completion_names_for_provider(ProviderKind::Ollama); |
| 6582 | |
| 6583 | assert!(models.is_empty()); |
| 6584 | } |
| 6585 | // from model_completion_names_for_openrouter_include_recent_large_models |
| 6586 | { |
| 6587 | let models = model_completion_names_for_provider(ProviderKind::Openrouter); |
| 6588 | |
| 6589 | for expected in [ |
| 6590 | DEFAULT_OPENROUTER_MODEL, |
| 6591 | DEFAULT_OPENROUTER_FLASH_MODEL, |
| 6592 | OPENROUTER_ARCEE_TRINITY_LARGE_THINKING_MODEL, |
| 6593 | OPENROUTER_XIAOMI_MIMO_V2_5_PRO_MODEL, |
| 6594 | OPENROUTER_MINIMAX_M3_MODEL, |
| 6595 | OPENROUTER_MINIMAX_M2_7_MODEL, |
| 6596 | OPENROUTER_QWEN_3_6_FLASH_MODEL, |
| 6597 | OPENROUTER_QWEN_3_6_35B_A3B_MODEL, |
| 6598 | OPENROUTER_QWEN_3_6_MAX_PREVIEW_MODEL, |
| 6599 | OPENROUTER_QWEN_3_6_27B_MODEL, |
| 6600 | OPENROUTER_QWEN_3_6_PLUS_MODEL, |
| 6601 | OPENROUTER_GLM_5_1_MODEL, |
| 6602 | OPENROUTER_GLM_5_2_MODEL, |
| 6603 | OPENROUTER_GEMMA_4_31B_MODEL, |
| 6604 | ] { |
| 6605 | assert!(models.contains(&expected), "missing {expected}"); |
| 6606 | } |
| 6607 | } |
| 6608 | } |
| 6609 | |
| 6610 | #[test] |
| 6611 | fn model_completion_scenario_2() { |
| 6612 | // Scenario consolidation of: model_completion_names_for_moonshot_uses_latest_platform_model, model_completion_names_for_zai_lists_default_5_1_and_turbo, model_completion_names_for_minimax_include_direct_chat_models, model_completion_names_for_minimax_anthropic_include_target_models, model_completion_names_for_sakana_include_fugu_models |
| 6613 | // from model_completion_names_for_moonshot_uses_latest_platform_model |
| 6614 | { |
| 6615 | let models = model_completion_names_for_provider(ProviderKind::Moonshot); |
| 6616 | |
| 6617 | assert_eq!(models.first().copied(), Some(DEFAULT_MOONSHOT_MODEL)); |
| 6618 | // `kimi-k3` is served by this provider's default (direct platform) route |
| 6619 | // and must be offerable — a dogfood user on v0.9.1 could not find it. |
| 6620 | assert!(models.contains(&MOONSHOT_KIMI_K3_MODEL), "{models:?}"); |
| 6621 | // The Kimi Code coding-plan ids belong to api.kimi.com/coding/v1, which |
| 6622 | // this base-URL-less list cannot express. Offering them here would |
| 6623 | // advertise a pairing `validate_kimi_code_api_model_id` rejects. |
| 6624 | assert!(!models.contains(&KIMI_CODE_K3_MODEL), "{models:?}"); |
| 6625 | assert!(!models.contains(&DEFAULT_KIMI_CODE_MODEL), "{models:?}"); |
| 6626 | for model in &models { |
| 6627 | let config = Config { |
| 6628 | provider: Some(ProviderKind::Moonshot.as_str().to_string()), |
| 6629 | default_text_model: Some((*model).to_string()), |
| 6630 | ..Default::default() |
| 6631 | }; |
| 6632 | config |
| 6633 | .validate() |
| 6634 | .expect("every advertised Moonshot model must be valid on its default route"); |
| 6635 | } |
| 6636 | } |
| 6637 | // from model_completion_names_for_zai_lists_default_5_1_and_turbo |
| 6638 | { |
| 6639 | let models = model_completion_names_for_provider(ProviderKind::Zai); |
| 6640 | |
| 6641 | // GLM-5.3 is the default and must be first; GLM-5.4, GLM-5.2 and |
| 6642 | // GLM-5.1 stay available, and GLM-5-Turbo is the faster sub-agent sibling. |
| 6643 | assert_eq!(models.first().copied(), Some(DEFAULT_ZAI_MODEL)); |
| 6644 | assert_eq!(DEFAULT_ZAI_MODEL, ZAI_GLM_5_3_MODEL); |
| 6645 | assert!(models.contains(&ZAI_GLM_5_4_MODEL)); |
| 6646 | assert!(models.contains(&ZAI_GLM_5_1_MODEL)); |
| 6647 | assert!(models.contains(&ZAI_GLM_5_3_FLASH_MODEL)); |
| 6648 | assert!(models.contains(&ZAI_GLM_5_TURBO_MODEL)); |
| 6649 | // GLM-5.2 is still offered alongside the others but no longer takes the |
| 6650 | // default slot; explicit 5.2 routes are untouched. |
| 6651 | assert!(models.contains(&ZAI_GLM_5_2_MODEL)); |
| 6652 | assert_ne!(models.first().copied(), Some(ZAI_GLM_5_2_MODEL)); |
| 6653 | // No accidental duplicate entries. |
| 6654 | let mut sorted = models.to_vec(); |
| 6655 | sorted.sort_unstable(); |
| 6656 | let mut deduped = sorted.clone(); |
| 6657 | deduped.dedup(); |
| 6658 | assert_eq!(sorted, deduped); |
| 6659 | } |
| 6660 | // from model_completion_names_for_minimax_include_direct_chat_models |
| 6661 | { |
| 6662 | let models = model_completion_names_for_provider(ProviderKind::Minimax); |
| 6663 | |
| 6664 | for expected in [ |
| 6665 | DEFAULT_MINIMAX_MODEL, |
| 6666 | MINIMAX_M2_1_MODEL, |
| 6667 | MINIMAX_M2_1_HIGHSPEED_MODEL, |
| 6668 | MINIMAX_M2_MODEL, |
| 6669 | ] { |
| 6670 | assert!(models.contains(&expected), "missing {expected}"); |
| 6671 | } |
| 6672 | assert!( |
| 6673 | !models.contains(&OPENROUTER_MINIMAX_M3_MODEL), |
| 6674 | "direct MiniMax picker must not expose OpenRouter namespaced IDs" |
| 6675 | ); |
| 6676 | } |
| 6677 | // from model_completion_names_for_minimax_anthropic_include_target_models |
| 6678 | { |
| 6679 | let models = model_completion_names_for_provider(ProviderKind::MinimaxAnthropic); |
| 6680 | |
| 6681 | assert!(models.contains(&DEFAULT_MINIMAX_MODEL)); |
| 6682 | assert!(models.contains(&MINIMAX_M2_1_MODEL)); |
| 6683 | } |
| 6684 | // from model_completion_names_for_sakana_include_fugu_models |
| 6685 | { |
| 6686 | assert_eq!( |
| 6687 | model_completion_names_for_provider(ProviderKind::Sakana), |
| 6688 | vec![DEFAULT_SAKANA_MODEL, SAKANA_FUGU_ULTRA_MODEL] |
| 6689 | ); |
| 6690 | } |
| 6691 | } |
| 6692 | |
| 6693 | #[test] |
| 6694 | fn normalize_model_name_for_zai_canonicalizes_current_glm_models() { |
| 6695 | let zai_wire = |model: &str| { |
| 6696 | codewhale_config::route::resolve_model(ProviderKind::Zai, model, None) |
| 6697 | .ok() |
| 6698 | .map(|resolved| resolved.wire_id) |
| 6699 | }; |
| 6700 | for (alias, expected) in [ |
| 6701 | ("glm-5.1", ZAI_GLM_5_1_MODEL), |
| 6702 | ("glm-5-1", ZAI_GLM_5_1_MODEL), |
| 6703 | ("glm-5.2", ZAI_GLM_5_2_MODEL), |
| 6704 | ("zai-glm-5-2", ZAI_GLM_5_2_MODEL), |
| 6705 | ("glm-5.4", ZAI_GLM_5_4_MODEL), |
| 6706 | ("glm-5-4", ZAI_GLM_5_4_MODEL), |
| 6707 | ("zai-glm-5-4", ZAI_GLM_5_4_MODEL), |
| 6708 | ("glm-5.3", DEFAULT_ZAI_MODEL), |
| 6709 | ("glm-5-3", ZAI_GLM_5_3_MODEL), |
| 6710 | ("zai-glm-5-3", ZAI_GLM_5_3_MODEL), |
| 6711 | ("glm-5.3-flash", ZAI_GLM_5_3_FLASH_MODEL), |
| 6712 | ("glm-5-3-flash", ZAI_GLM_5_3_FLASH_MODEL), |
| 6713 | ("zai-glm-5.3-flash", ZAI_GLM_5_3_FLASH_MODEL), |
| 6714 | ("glm-5-turbo", ZAI_GLM_5_TURBO_MODEL), |
| 6715 | ("zai-glm-5-turbo", ZAI_GLM_5_TURBO_MODEL), |
| 6716 | ] { |
| 6717 | assert_eq!(zai_wire(alias).as_deref(), Some(expected)); |
| 6718 | } |
| 6719 | assert_ne!(ZAI_GLM_5_2_MODEL, DEFAULT_ZAI_MODEL); |
| 6720 | assert_eq!(zai_wire("glm-5.2").as_deref(), Some(ZAI_GLM_5_2_MODEL)); |
| 6721 | assert_eq!( |
| 6722 | zai_wire("glm-next-preview").as_deref(), |
| 6723 | Some("glm-next-preview") |
| 6724 | ); |
| 6725 | } |
| 6726 | |
| 6727 | #[test] |
| 6728 | fn config_preserves_live_go_wire_ids_without_granting_a_transport() -> Result<()> { |
| 6729 | let _home = crate::test_support::SealedHome::new(); |
| 6730 | let _provider = EnvVarGuard::set("CODEWHALE_PROVIDER", "opencode-go"); |
| 6731 | let _model = EnvVarGuard::set("CODEWHALE_MODEL", "step-5"); |
| 6732 | let config = Config::load(None, None)?; |
| 6733 | assert_eq!(config.default_model(), "step-5"); |
| 6734 | assert!(config.configured_model_error().is_none()); |
| 6735 | assert!(validate_route(ProviderKind::OpencodeGo, "step-5").is_err()); |
| 6736 | |
| 6737 | let _malformed = EnvVarGuard::set("CODEWHALE_MODEL", "step 5"); |
| 6738 | assert!(Config::load(None, None).is_err()); |
| 6739 | Ok(()) |
| 6740 | } |
| 6741 | |
| 6742 | #[test] |
| 6743 | fn opencode_go_config_uses_documented_model_protocols() -> Result<()> { |
| 6744 | let _lock = lock_test_env(); |
| 6745 | let _api_key = EnvVarGuard::remove("OPENCODE_GO_API_KEY"); |
| 6746 | let _base_url = EnvVarGuard::remove("OPENCODE_GO_BASE_URL"); |
| 6747 | let _model = EnvVarGuard::remove("OPENCODE_GO_MODEL"); |
| 6748 | |
| 6749 | let config: Config = toml::from_str( |
| 6750 | r#" |
| 6751 | provider = "opencode_go" |
| 6752 | |
| 6753 | [providers.opencode_go] |
| 6754 | api_key = "go-config-key" |
| 6755 | model = "opencode-go/glm-5.2" |
| 6756 | "#, |
| 6757 | )?; |
| 6758 | |
| 6759 | assert_eq!( |
| 6760 | config.active_provider_identity().unwrap().provider, |
| 6761 | ProviderKind::OpencodeGo |
| 6762 | ); |
| 6763 | assert_eq!(config.active_route_base_url(), DEFAULT_OPENCODE_GO_BASE_URL); |
| 6764 | assert_eq!(config.default_model(), "glm-5.2"); |
| 6765 | assert_eq!(config.active_route_api_key()?, "go-config-key"); |
| 6766 | assert_eq!( |
| 6767 | codewhale_config::route::resolve_model( |
| 6768 | ProviderKind::OpencodeGo, |
| 6769 | "opencode-go/mimo-v2.5-pro", |
| 6770 | None, |
| 6771 | ) |
| 6772 | .unwrap() |
| 6773 | .wire_id, |
| 6774 | "mimo-v2.5-pro" |
| 6775 | ); |
| 6776 | assert_eq!( |
| 6777 | model_completion_names_for_provider(ProviderKind::OpencodeGo), |
| 6778 | opencode_go_models() |
| 6779 | ); |
| 6780 | for chat_model in opencode_go_models() { |
| 6781 | assert_eq!( |
| 6782 | codewhale_config::route::resolve_model(ProviderKind::OpencodeGo, chat_model, None) |
| 6783 | .ok() |
| 6784 | .map(|resolved| resolved.logical) |
| 6785 | .as_deref(), |
| 6786 | Some(chat_model) |
| 6787 | ); |
| 6788 | assert!(validate_route(ProviderKind::OpencodeGo, chat_model).is_ok()); |
| 6789 | } |
| 6790 | for messages_only in ["claude-unproven", "gpt-unlisted"] { |
| 6791 | assert!( |
| 6792 | !model_completion_names_for_provider(ProviderKind::OpencodeGo).contains(&messages_only), |
| 6793 | "{messages_only} has no documented Go protocol and must not be advertised" |
| 6794 | ); |
| 6795 | assert!( |
| 6796 | codewhale_config::route::resolve_model(ProviderKind::OpencodeGo, messages_only, None) |
| 6797 | .is_err(), |
| 6798 | "{messages_only} must not pass the explicit selector gate" |
| 6799 | ); |
| 6800 | assert!(validate_route(ProviderKind::OpencodeGo, messages_only).is_err()); |
| 6801 | assert!( |
| 6802 | codewhale_config::route::resolve_model( |
| 6803 | ProviderKind::OpencodeGo, |
| 6804 | messages_only, |
| 6805 | Some("https://go-gateway.example/v1"), |
| 6806 | ) |
| 6807 | .is_err(), |
| 6808 | "a base URL override must not rewrite or re-admit {messages_only}" |
| 6809 | ); |
| 6810 | } |
| 6811 | |
| 6812 | Ok(()) |
| 6813 | } |
| 6814 | |
| 6815 | /// #6516: the removed seam-manager keys and `tui.terminal_probe_timeout_ms` |
| 6816 | /// are no longer fields. A config that still carries them must keep loading, |
| 6817 | /// with the live `[context] project_pack` key intact. |
| 6818 | #[test] |
| 6819 | fn removed_context_seam_and_terminal_probe_keys_still_load() -> Result<()> { |
| 6820 | let parsed: ConfigFile = toml::from_str( |
| 6821 | r#" |
| 6822 | [tui] |
| 6823 | terminal_probe_timeout_ms = 500 |
| 6824 | |
| 6825 | [context] |
| 6826 | enabled = true |
| 6827 | project_pack = true |
| 6828 | verbatim_window_turns = 4 |
| 6829 | l1_threshold = 1 |
| 6830 | l2_threshold = 2 |
| 6831 | l3_threshold = 3 |
| 6832 | seam_model = "deepseek-v4-flash" |
| 6833 | "#, |
| 6834 | )?; |
| 6835 | |
| 6836 | assert_eq!(parsed.base.context.project_pack, Some(true)); |
| 6837 | // #6516: the retired keys still load but are no longer typed fields, so |
| 6838 | // nothing can read or merge them again. The derived Debug lists every |
| 6839 | // field, which makes a reintroduced field visible here. |
| 6840 | let context = format!("{:?}", parsed.base.context); |
| 6841 | for retired in [ |
| 6842 | "enabled", |
| 6843 | "verbatim_window_turns", |
| 6844 | "l1_threshold", |
| 6845 | "l2_threshold", |
| 6846 | "l3_threshold", |
| 6847 | "seam_model", |
| 6848 | ] { |
| 6849 | assert!(!context.contains(retired), "{retired} in {context}"); |
| 6850 | } |
| 6851 | let tui = format!("{:?}", parsed.base.tui.expect("[tui] table loads")); |
| 6852 | assert!(!tui.contains("terminal_probe_timeout_ms"), "{tui}"); |
| 6853 | Ok(()) |
| 6854 | } |
| 6855 | |
| 6856 | #[test] |
| 6857 | fn profile_skills_config_merges_individual_fields() { |
| 6858 | let mut profiles = HashMap::new(); |
| 6859 | profiles.insert( |
| 6860 | "strict".to_string(), |
| 6861 | Config { |
| 6862 | skills: Some(SkillsConfig { |
| 6863 | scan_codewhale_only: Some(true), |
| 6864 | listing_max_description_chars: Some(80), |
| 6865 | flat_workspace_root: Some(false), |
| 6866 | ..Default::default() |
| 6867 | }), |
| 6868 | ..Default::default() |
| 6869 | }, |
| 6870 | ); |
| 6871 | let config = ConfigFile { |
| 6872 | base: Box::new(Config { |
| 6873 | skills: Some(SkillsConfig { |
| 6874 | registry_url: Some("https://registry.example/skills.json".to_string()), |
| 6875 | max_install_size_bytes: Some(1234), |
| 6876 | listing_max_description_chars: Some(1024), |
| 6877 | listing_budget_fraction: Some(0.01), |
| 6878 | flat_workspace_root: Some(true), |
| 6879 | ..Default::default() |
| 6880 | }), |
| 6881 | ..Default::default() |
| 6882 | }), |
| 6883 | profiles: Some(profiles), |
| 6884 | legacy_root: Default::default(), |
| 6885 | }; |
| 6886 | |
| 6887 | let merged = apply_profile(config, Some("strict")).expect("profile"); |
| 6888 | let skills = merged.skills.expect("merged skills config"); |
| 6889 | assert_eq!( |
| 6890 | skills.registry_url.as_deref(), |
| 6891 | Some("https://registry.example/skills.json") |
| 6892 | ); |
| 6893 | assert_eq!(skills.max_install_size_bytes, Some(1234)); |
| 6894 | assert_eq!(skills.scan_codewhale_only, Some(true)); |
| 6895 | assert_eq!(skills.flat_workspace_root, Some(false)); |
| 6896 | assert_eq!(skills.listing_max_description_chars, Some(80)); |
| 6897 | assert_eq!(skills.listing_budget_fraction, Some(0.01)); |
| 6898 | let base: Config = toml::from_str("[skills.bundled]\ninstall='all'\nselected=['debug']\ndisabled=['pdf']\nexplicit_only=['debug']").unwrap(); |
| 6899 | let override_cfg: Config = |
| 6900 | toml::from_str("[skills.bundled]\nselected=[]\nexplicit_only=[]").unwrap(); |
| 6901 | let merged = merge_skills_config(base.skills, override_cfg.skills) |
| 6902 | .unwrap() |
| 6903 | .bundled; |
| 6904 | assert_eq!(merged.install, Some(BundledSkillsInstall::All)); |
| 6905 | assert_eq!(merged.selected, Some(vec![])); |
| 6906 | assert_eq!(merged.explicit_only, Some(vec![])); |
| 6907 | assert_eq!(merged.disabled, Some(vec!["pdf".into()])); |
| 6908 | } |
| 6909 | |
| 6910 | #[test] |
| 6911 | fn removed_context_per_model_table_is_ignored_for_compatibility() -> Result<()> { |
| 6912 | let parsed: ConfigFile = toml::from_str( |
| 6913 | r#" |
| 6914 | [context] |
| 6915 | project_pack = true |
| 6916 | |
| 6917 | [context.per_model.deepseek-v4-pro] |
| 6918 | l1_threshold = 111 |
| 6919 | l2_threshold = 222 |
| 6920 | l3_threshold = 333 |
| 6921 | "#, |
| 6922 | )?; |
| 6923 | |
| 6924 | assert_eq!(parsed.base.context.project_pack, Some(true)); |
| 6925 | Ok(()) |
| 6926 | } |
| 6927 | |
| 6928 | #[test] |
| 6929 | fn project_context_pack_defaults_off_and_can_be_enabled() { |
| 6930 | // #4781: project context pack is opt-in (large pretty-printed tree). |
| 6931 | let mut config = Config::default(); |
| 6932 | assert!(!config.project_context_pack_enabled()); |
| 6933 | |
| 6934 | config.context.project_pack = Some(true); |
| 6935 | assert!(config.project_context_pack_enabled()); |
| 6936 | |
| 6937 | config.context.project_pack = Some(false); |
| 6938 | assert!(!config.project_context_pack_enabled()); |
| 6939 | } |
| 6940 | |
| 6941 | #[test] |
| 6942 | fn validate_accepts_scenario() -> Result<()> { |
| 6943 | // Scenario consolidation of: validate_accepts_future_deepseek_model_id, validate_accepts_auto_default_text_model |
| 6944 | // from validate_accepts_future_deepseek_model_id |
| 6945 | { |
| 6946 | let config = Config { |
| 6947 | default_text_model: Some("deepseek-v4".to_string()), |
| 6948 | ..Default::default() |
| 6949 | }; |
| 6950 | config.validate()?; |
| 6951 | } |
| 6952 | // from validate_accepts_auto_default_text_model |
| 6953 | { |
| 6954 | let config = Config { |
| 6955 | default_text_model: Some("auto".to_string()), |
| 6956 | ..Default::default() |
| 6957 | }; |
| 6958 | config.validate()?; |
| 6959 | assert_eq!(config.default_model(), "auto"); |
| 6960 | } |
| 6961 | Ok(()) |
| 6962 | } |
| 6963 | |
| 6964 | #[test] |
| 6965 | fn deepseek_provider_defaults_to_beta_endpoint() { |
| 6966 | let config = Config::default(); |
| 6967 | |
| 6968 | assert_eq!( |
| 6969 | config.active_provider_identity().unwrap().provider, |
| 6970 | ProviderKind::Deepseek |
| 6971 | ); |
| 6972 | assert_eq!(config.active_route_base_url(), DEFAULT_DEEPSEEK_BASE_URL); |
| 6973 | } |
| 6974 | |
| 6975 | #[test] |
| 6976 | fn explicit_deepseek_base_url_overrides_beta_default() { |
| 6977 | let config = Config { |
| 6978 | ..Default::default() |
| 6979 | } |
| 6980 | .with_legacy_root(None, Some("https://api.deepseek.com".to_string())); |
| 6981 | |
| 6982 | assert_eq!( |
| 6983 | config.active_provider_identity().unwrap().provider, |
| 6984 | ProviderKind::Deepseek |
| 6985 | ); |
| 6986 | assert_eq!(config.active_route_base_url(), "https://api.deepseek.com"); |
| 6987 | } |
| 6988 | |
| 6989 | #[test] |
| 6990 | fn deepseek_model_env_overrides_default_text_model() -> Result<()> { |
| 6991 | let _lock = lock_test_env(); |
| 6992 | let nanos = SystemTime::now() |
| 6993 | .duration_since(UNIX_EPOCH) |
| 6994 | .unwrap() |
| 6995 | .as_nanos(); |
| 6996 | let temp_root = env::temp_dir().join(format!( |
| 6997 | "codewhale-tui-model-env-test-{}-{}", |
| 6998 | std::process::id(), |
| 6999 | nanos |
| 7000 | )); |
| 7001 | fs::create_dir_all(&temp_root)?; |
| 7002 | let _guard = EnvGuard::new(&temp_root); |
| 7003 | |
| 7004 | // Safety: test-only environment mutation guarded by a global mutex. |
| 7005 | unsafe { |
| 7006 | env::set_var("DEEPSEEK_MODEL", "deepseek-v4-flash-20260423"); |
| 7007 | } |
| 7008 | |
| 7009 | let config = Config::load(None, None)?; |
| 7010 | // v-series snapshots pass through unchanged — no alias folding |
| 7011 | assert_eq!( |
| 7012 | config.default_text_model.as_deref(), |
| 7013 | Some("deepseek-v4-flash-20260423") |
| 7014 | ); |
| 7015 | Ok(()) |
| 7016 | } |
| 7017 | |
| 7018 | #[test] |
| 7019 | fn retired_deepseek_aliases_from_env_are_migrated_before_runtime() -> Result<()> { |
| 7020 | let _lock = lock_test_env(); |
| 7021 | let temp_root = tempfile::tempdir()?; |
| 7022 | let _managed_config = no_managed_config(temp_root.path()); |
| 7023 | |
| 7024 | for (provider, alias, expected_effort) in [ |
| 7025 | ("deepseek", "deepseek-chat", "off"), |
| 7026 | ("deepseek-cn", "deepseek-reasoner", "high"), |
| 7027 | ("deepseek-anthropic", "deepseek-chat", "off"), |
| 7028 | ] { |
| 7029 | let _guard = EnvGuard::new(temp_root.path()); |
| 7030 | // Safety: test-only environment mutation guarded by a global mutex. |
| 7031 | unsafe { |
| 7032 | env::set_var("CODEWHALE_PROVIDER", provider); |
| 7033 | env::set_var("CODEWHALE_MODEL", alias); |
| 7034 | } |
| 7035 | |
| 7036 | // Pass the isolated path explicitly: the process-wide default config |
| 7037 | // path is cached by earlier tests and can otherwise point back at the |
| 7038 | // developer's real provider-scoped model. |
| 7039 | let config = Config::load( |
| 7040 | Some(temp_root.path().join("isolated-alias-config.toml")), |
| 7041 | None, |
| 7042 | )?; |
| 7043 | assert_eq!( |
| 7044 | config.default_model(), |
| 7045 | DEEPSEEK_ALIAS_REPLACEMENT, |
| 7046 | "provider={provider} resolved={:?} root_model={:?} scoped_model={:?}", |
| 7047 | config.active_provider_identity().unwrap().provider, |
| 7048 | config.default_text_model, |
| 7049 | config |
| 7050 | .provider_config_for(&config.active_provider_identity().unwrap()) |
| 7051 | .and_then(|entry| entry.model.as_deref()) |
| 7052 | ); |
| 7053 | assert_eq!(config.reasoning_effort(), Some(expected_effort)); |
| 7054 | let deprecation = config |
| 7055 | .active_deepseek_alias_deprecation() |
| 7056 | .expect("loaded config should retain the alias migration receipt"); |
| 7057 | assert_eq!(deprecation.alias, alias); |
| 7058 | assert_eq!(deprecation.replacement, DEEPSEEK_ALIAS_REPLACEMENT); |
| 7059 | } |
| 7060 | |
| 7061 | Ok(()) |
| 7062 | } |
| 7063 | |
| 7064 | #[test] |
| 7065 | fn http_headers_load_from_root_config() -> Result<()> { |
| 7066 | let _lock = lock_test_env(); |
| 7067 | let nanos = SystemTime::now() |
| 7068 | .duration_since(UNIX_EPOCH) |
| 7069 | .unwrap() |
| 7070 | .as_nanos(); |
| 7071 | let temp_root = env::temp_dir().join(format!( |
| 7072 | "codewhale-tui-http-headers-root-{}-{}", |
| 7073 | std::process::id(), |
| 7074 | nanos |
| 7075 | )); |
| 7076 | fs::create_dir_all(&temp_root)?; |
| 7077 | let _guard = EnvGuard::new(&temp_root); |
| 7078 | |
| 7079 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 7080 | ensure_parent_dir(&config_path)?; |
| 7081 | fs::write( |
| 7082 | &config_path, |
| 7083 | r#" |
| 7084 | api_key = "test-key" |
| 7085 | http_headers = { "X-Model-Provider-Id" = "tongyi" } |
| 7086 | "#, |
| 7087 | )?; |
| 7088 | |
| 7089 | let config = Config::load(None, None)?; |
| 7090 | assert_eq!( |
| 7091 | config |
| 7092 | .http_headers() |
| 7093 | .get("X-Model-Provider-Id") |
| 7094 | .map(String::as_str), |
| 7095 | Some("tongyi") |
| 7096 | ); |
| 7097 | Ok(()) |
| 7098 | } |
| 7099 | |
| 7100 | #[test] |
| 7101 | fn provider_http_headers_extend_and_override_root_config() { |
| 7102 | let mut providers = ProvidersConfig::default(); |
| 7103 | providers.deepseek.http_headers = Some(HashMap::from([ |
| 7104 | ("X-Model-Provider-Id".to_string(), "tongyi".to_string()), |
| 7105 | ("X-Shared".to_string(), "provider".to_string()), |
| 7106 | ])); |
| 7107 | let config = Config { |
| 7108 | http_headers: Some(HashMap::from([ |
| 7109 | ("X-Root".to_string(), "root".to_string()), |
| 7110 | ("X-Shared".to_string(), "root".to_string()), |
| 7111 | ])), |
| 7112 | providers: Some(providers), |
| 7113 | ..Default::default() |
| 7114 | }; |
| 7115 | |
| 7116 | let headers = config.http_headers(); |
| 7117 | assert_eq!( |
| 7118 | headers.get("X-Model-Provider-Id").map(String::as_str), |
| 7119 | Some("tongyi") |
| 7120 | ); |
| 7121 | assert_eq!(headers.get("X-Root").map(String::as_str), Some("root")); |
| 7122 | assert_eq!( |
| 7123 | headers.get("X-Shared").map(String::as_str), |
| 7124 | Some("provider") |
| 7125 | ); |
| 7126 | } |
| 7127 | |
| 7128 | #[test] |
| 7129 | fn http_headers_env_overrides_config() -> Result<()> { |
| 7130 | let _lock = lock_test_env(); |
| 7131 | let nanos = SystemTime::now() |
| 7132 | .duration_since(UNIX_EPOCH) |
| 7133 | .unwrap() |
| 7134 | .as_nanos(); |
| 7135 | let temp_root = env::temp_dir().join(format!( |
| 7136 | "codewhale-tui-http-headers-env-{}-{}", |
| 7137 | std::process::id(), |
| 7138 | nanos |
| 7139 | )); |
| 7140 | fs::create_dir_all(&temp_root)?; |
| 7141 | let _guard = EnvGuard::new(&temp_root); |
| 7142 | |
| 7143 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 7144 | ensure_parent_dir(&config_path)?; |
| 7145 | fs::write( |
| 7146 | &config_path, |
| 7147 | r#" |
| 7148 | api_key = "test-key" |
| 7149 | http_headers = { "X-Model-Provider-Id" = "from-file" } |
| 7150 | "#, |
| 7151 | )?; |
| 7152 | // Safety: test-only environment mutation guarded by a global mutex. |
| 7153 | unsafe { |
| 7154 | env::set_var("DEEPSEEK_HTTP_HEADERS", "X-Model-Provider-Id=from-env"); |
| 7155 | } |
| 7156 | |
| 7157 | let config = Config::load(None, None)?; |
| 7158 | assert_eq!( |
| 7159 | config |
| 7160 | .http_headers() |
| 7161 | .get("X-Model-Provider-Id") |
| 7162 | .map(String::as_str), |
| 7163 | Some("from-env") |
| 7164 | ); |
| 7165 | Ok(()) |
| 7166 | } |
| 7167 | |
| 7168 | #[test] |
| 7169 | fn nvidia_nim_scenario() -> Result<()> { |
| 7170 | // Scenario consolidation of: nvidia_nim_provider_uses_nim_defaults, nvidia_nim_provider_normalizes_deepseek_v4_flash_alias, nvidia_nim_env_accepts_short_nim_base_url_alias |
| 7171 | // from nvidia_nim_provider_uses_nim_defaults |
| 7172 | { |
| 7173 | let config = Config { |
| 7174 | provider: Some("nvidia-nim".to_string()), |
| 7175 | ..Default::default() |
| 7176 | }; |
| 7177 | |
| 7178 | config.validate()?; |
| 7179 | assert_eq!( |
| 7180 | config.active_provider_identity().unwrap().provider, |
| 7181 | ProviderKind::NvidiaNim |
| 7182 | ); |
| 7183 | assert_eq!(config.default_model(), DEFAULT_NVIDIA_NIM_MODEL); |
| 7184 | assert_eq!(config.active_route_base_url(), DEFAULT_NVIDIA_NIM_BASE_URL); |
| 7185 | } |
| 7186 | // from nvidia_nim_provider_normalizes_deepseek_v4_flash_alias |
| 7187 | { |
| 7188 | let _lock = lock_test_env(); |
| 7189 | let nanos = SystemTime::now() |
| 7190 | .duration_since(UNIX_EPOCH) |
| 7191 | .unwrap() |
| 7192 | .as_nanos(); |
| 7193 | let temp_root = env::temp_dir().join(format!( |
| 7194 | "codewhale-tui-nim-flash-model-alias-test-{}-{}", |
| 7195 | std::process::id(), |
| 7196 | nanos |
| 7197 | )); |
| 7198 | fs::create_dir_all(&temp_root)?; |
| 7199 | let _guard = EnvGuard::new(&temp_root); |
| 7200 | |
| 7201 | let config = Config { |
| 7202 | provider: Some("nvidia-nim".to_string()), |
| 7203 | default_text_model: Some("deepseek-v4-flash".to_string()), |
| 7204 | ..Default::default() |
| 7205 | }; |
| 7206 | |
| 7207 | config.validate()?; |
| 7208 | assert_eq!(config.default_model(), DEFAULT_NVIDIA_NIM_FLASH_MODEL); |
| 7209 | } |
| 7210 | // from nvidia_nim_env_accepts_short_nim_base_url_alias |
| 7211 | { |
| 7212 | let _lock = lock_test_env(); |
| 7213 | let nanos = SystemTime::now() |
| 7214 | .duration_since(UNIX_EPOCH) |
| 7215 | .unwrap() |
| 7216 | .as_nanos(); |
| 7217 | let temp_root = env::temp_dir().join(format!( |
| 7218 | "codewhale-tui-nim-base-url-alias-test-{}-{}", |
| 7219 | std::process::id(), |
| 7220 | nanos |
| 7221 | )); |
| 7222 | fs::create_dir_all(&temp_root)?; |
| 7223 | let _guard = EnvGuard::new(&temp_root); |
| 7224 | |
| 7225 | // Safety: test-only environment mutation guarded by a global mutex. |
| 7226 | unsafe { |
| 7227 | env::set_var("DEEPSEEK_PROVIDER", "nvidia-nim"); |
| 7228 | env::set_var("NIM_BASE_URL", "https://short-nim.example/v1"); |
| 7229 | } |
| 7230 | |
| 7231 | let config = Config::load(None, None)?; |
| 7232 | assert_eq!( |
| 7233 | config.active_provider_identity().unwrap().provider, |
| 7234 | ProviderKind::NvidiaNim |
| 7235 | ); |
| 7236 | assert_eq!( |
| 7237 | config.active_route_base_url(), |
| 7238 | "https://short-nim.example/v1" |
| 7239 | ); |
| 7240 | } |
| 7241 | Ok(()) |
| 7242 | } |
| 7243 | |
| 7244 | #[test] |
| 7245 | fn nvidia_nim_provider_normalizes_deepseek_v4_pro_alias() -> Result<()> { |
| 7246 | let _lock = lock_test_env(); |
| 7247 | let nanos = SystemTime::now() |
| 7248 | .duration_since(UNIX_EPOCH) |
| 7249 | .unwrap() |
| 7250 | .as_nanos(); |
| 7251 | let temp_root = env::temp_dir().join(format!( |
| 7252 | "codewhale-tui-nim-model-alias-test-{}-{}", |
| 7253 | std::process::id(), |
| 7254 | nanos |
| 7255 | )); |
| 7256 | fs::create_dir_all(&temp_root)?; |
| 7257 | let _guard = EnvGuard::new(&temp_root); |
| 7258 | |
| 7259 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 7260 | ensure_parent_dir(&config_path)?; |
| 7261 | fs::write( |
| 7262 | &config_path, |
| 7263 | "provider = \"nvidia-nim\"\ndefault_text_model = \"deepseek-v4-pro\"\napi_key = \"nim-key\"\n", |
| 7264 | )?; |
| 7265 | |
| 7266 | let config = Config::load(None, None)?; |
| 7267 | assert_eq!( |
| 7268 | config.active_provider_identity().unwrap().provider, |
| 7269 | ProviderKind::NvidiaNim |
| 7270 | ); |
| 7271 | assert_eq!( |
| 7272 | config.default_text_model.as_deref(), |
| 7273 | Some(DEFAULT_NVIDIA_NIM_MODEL) |
| 7274 | ); |
| 7275 | Ok(()) |
| 7276 | } |
| 7277 | |
| 7278 | #[test] |
| 7279 | fn vendor_locked_providers_reject_foreign_root_default_model() { |
| 7280 | let _lock = lock_test_env(); |
| 7281 | for (provider, expected) in [ |
| 7282 | ("xai", DEFAULT_XAI_MODEL), |
| 7283 | ("openai", DEFAULT_OPENAI_MODEL), |
| 7284 | ("moonshot", DEFAULT_MOONSHOT_MODEL), |
| 7285 | ("mistral", DEFAULT_MISTRAL_MODEL), |
| 7286 | ] { |
| 7287 | let config = Config { |
| 7288 | provider: Some(provider.to_string()), |
| 7289 | default_text_model: Some("deepseek-v4-pro".to_string()), |
| 7290 | ..Default::default() |
| 7291 | }; |
| 7292 | assert_eq!( |
| 7293 | config.default_model(), |
| 7294 | expected, |
| 7295 | "a root DeepSeek default must not leak onto the official {provider} endpoint" |
| 7296 | ); |
| 7297 | } |
| 7298 | } |
| 7299 | |
| 7300 | #[test] |
| 7301 | fn mistral_model_env_overrides_vendor_default() { |
| 7302 | let _lock = lock_test_env(); |
| 7303 | let _model = EnvVarGuard::set("MISTRAL_MODEL", "mistral-medium-latest"); |
| 7304 | let _generic_model = EnvVarGuard::remove("CODEWHALE_MODEL"); |
| 7305 | let _legacy_model = EnvVarGuard::remove("DEEPSEEK_MODEL"); |
| 7306 | let mut config = Config { |
| 7307 | provider: Some("mistral".to_string()), |
| 7308 | ..Config::default() |
| 7309 | }; |
| 7310 | |
| 7311 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 7312 | |
| 7313 | assert_eq!( |
| 7314 | config.active_provider_identity().unwrap().provider, |
| 7315 | ProviderKind::Mistral |
| 7316 | ); |
| 7317 | assert_eq!(config.default_model(), "mistral-medium-latest"); |
| 7318 | } |
| 7319 | |
| 7320 | #[test] |
| 7321 | fn codewhale_model_precedes_mistral_model() { |
| 7322 | let _lock = lock_test_env(); |
| 7323 | let _provider_model = EnvVarGuard::set("MISTRAL_MODEL", "mistral-small-latest"); |
| 7324 | let _generic_model = EnvVarGuard::set("CODEWHALE_MODEL", "mistral-medium-latest"); |
| 7325 | let _legacy_model = EnvVarGuard::remove("DEEPSEEK_MODEL"); |
| 7326 | let mut config = Config { |
| 7327 | provider: Some("mistral".to_string()), |
| 7328 | ..Config::default() |
| 7329 | }; |
| 7330 | |
| 7331 | apply_env_overrides(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 7332 | |
| 7333 | assert_eq!(config.default_model(), "mistral-medium-latest"); |
| 7334 | } |
| 7335 | |
| 7336 | #[test] |
| 7337 | fn xai_custom_endpoint_keeps_root_default_model_pass_through() { |
| 7338 | let _lock = lock_test_env(); |
| 7339 | let mut providers = ProvidersConfig::default(); |
| 7340 | providers.xai.base_url = Some("https://proxy.example.test/v1".to_string()); |
| 7341 | let config = Config { |
| 7342 | provider: Some("xai".to_string()), |
| 7343 | default_text_model: Some("deepseek-v4-pro".to_string()), |
| 7344 | providers: Some(providers), |
| 7345 | ..Default::default() |
| 7346 | }; |
| 7347 | assert_eq!( |
| 7348 | config.default_model(), |
| 7349 | "deepseek-v4-pro", |
| 7350 | "custom compatible endpoints may serve any model id" |
| 7351 | ); |
| 7352 | } |
| 7353 | |
| 7354 | #[test] |
| 7355 | fn xai_explicit_provider_model_is_honored_over_vendor_default() { |
| 7356 | let _lock = lock_test_env(); |
| 7357 | let mut providers = ProvidersConfig::default(); |
| 7358 | providers.xai.model = Some("grok-4.5-mini".to_string()); |
| 7359 | let config = Config { |
| 7360 | provider: Some("xai".to_string()), |
| 7361 | default_text_model: Some("deepseek-v4-pro".to_string()), |
| 7362 | providers: Some(providers), |
| 7363 | ..Default::default() |
| 7364 | }; |
| 7365 | assert_eq!(config.default_model(), "grok-4.5-mini"); |
| 7366 | } |
| 7367 | |
| 7368 | #[test] |
| 7369 | fn nvidia_nim_env_overrides_provider_and_credentials() -> Result<()> { |
| 7370 | let _lock = lock_test_env(); |
| 7371 | let nanos = SystemTime::now() |
| 7372 | .duration_since(UNIX_EPOCH) |
| 7373 | .unwrap() |
| 7374 | .as_nanos(); |
| 7375 | let temp_root = env::temp_dir().join(format!( |
| 7376 | "codewhale-tui-nim-env-test-{}-{}", |
| 7377 | std::process::id(), |
| 7378 | nanos |
| 7379 | )); |
| 7380 | fs::create_dir_all(&temp_root)?; |
| 7381 | let _guard = EnvGuard::new(&temp_root); |
| 7382 | |
| 7383 | // Safety: test-only environment mutation guarded by a global mutex. |
| 7384 | unsafe { |
| 7385 | env::set_var("DEEPSEEK_PROVIDER", "nvidia-nim"); |
| 7386 | env::set_var("NVIDIA_API_KEY", "nim-env-key"); |
| 7387 | env::set_var("NVIDIA_NIM_MODEL", "deepseek-ai/deepseek-v4-pro"); |
| 7388 | } |
| 7389 | |
| 7390 | let config = Config::load(None, None)?; |
| 7391 | assert_eq!( |
| 7392 | config.active_provider_identity().unwrap().provider, |
| 7393 | ProviderKind::NvidiaNim |
| 7394 | ); |
| 7395 | assert_eq!(config.active_route_api_key()?, "nim-env-key"); |
| 7396 | assert_eq!(config.default_model(), DEFAULT_NVIDIA_NIM_MODEL); |
| 7397 | Ok(()) |
| 7398 | } |
| 7399 | |
| 7400 | #[test] |
| 7401 | fn nvidia_nim_env_accepts_facade_base_url_forwarding() -> Result<()> { |
| 7402 | let _lock = lock_test_env(); |
| 7403 | let nanos = SystemTime::now() |
| 7404 | .duration_since(UNIX_EPOCH) |
| 7405 | .unwrap() |
| 7406 | .as_nanos(); |
| 7407 | let temp_root = env::temp_dir().join(format!( |
| 7408 | "codewhale-tui-nim-forwarded-base-url-test-{}-{}", |
| 7409 | std::process::id(), |
| 7410 | nanos |
| 7411 | )); |
| 7412 | fs::create_dir_all(&temp_root)?; |
| 7413 | let _guard = EnvGuard::new(&temp_root); |
| 7414 | |
| 7415 | // Safety: test-only environment mutation guarded by a global mutex. |
| 7416 | unsafe { |
| 7417 | env::set_var("DEEPSEEK_PROVIDER", "nvidia-nim"); |
| 7418 | env::set_var("DEEPSEEK_BASE_URL", "https://forwarded-nim.example/v1"); |
| 7419 | } |
| 7420 | |
| 7421 | let config = Config::load(None, None)?; |
| 7422 | assert_eq!( |
| 7423 | config.active_provider_identity().unwrap().provider, |
| 7424 | ProviderKind::NvidiaNim |
| 7425 | ); |
| 7426 | assert_eq!( |
| 7427 | config.active_route_base_url(), |
| 7428 | "https://forwarded-nim.example/v1" |
| 7429 | ); |
| 7430 | Ok(()) |
| 7431 | } |
| 7432 | |
| 7433 | #[test] |
| 7434 | fn openai_provider_uses_openai_compatible_defaults() -> Result<()> { |
| 7435 | let config = Config { |
| 7436 | provider: Some("openai".to_string()), |
| 7437 | ..Default::default() |
| 7438 | }; |
| 7439 | |
| 7440 | config.validate()?; |
| 7441 | assert_eq!( |
| 7442 | config.active_provider_identity().unwrap().provider, |
| 7443 | ProviderKind::Openai |
| 7444 | ); |
| 7445 | assert_eq!(config.default_model(), "gpt-5.6"); |
| 7446 | assert_eq!(config.active_route_base_url(), "https://api.openai.com/v1"); |
| 7447 | assert_eq!( |
| 7448 | codewhale_config::provider::provider_for_kind(codewhale_config::ProviderKind::Openai) |
| 7449 | .default_model(), |
| 7450 | DEFAULT_OPENAI_MODEL |
| 7451 | ); |
| 7452 | Ok(()) |
| 7453 | } |
| 7454 | |
| 7455 | #[test] |
| 7456 | fn openai_codex_default_model_falls_back_to_codex_model() { |
| 7457 | // The Codex Responses backend only accepts its own model family, and a |
| 7458 | // global `default_text_model` is validated to DeepSeek IDs (or "auto"), |
| 7459 | // so with the Codex provider it must resolve to the Codex default |
| 7460 | // instead of leaking a DeepSeek id the backend rejects. |
| 7461 | // Isolate from any ambient developer Codex roster: the seed fallback is |
| 7462 | // asserted here; the fresh-roster preference (#5034) is covered by |
| 7463 | // codex_switch_without_saved_model_prefers_fresh_roster_head. |
| 7464 | let _lock = lock_test_env(); |
| 7465 | let empty_codex_home = tempfile::tempdir().expect("empty codex home"); |
| 7466 | let _codex_home = EnvVarGuard::set("CODEX_HOME", empty_codex_home.path()); |
| 7467 | let with_deepseek_default = Config { |
| 7468 | provider: Some("openai-codex".to_string()), |
| 7469 | default_text_model: Some(DEFAULT_TEXT_MODEL.to_string()), |
| 7470 | ..Default::default() |
| 7471 | }; |
| 7472 | assert_eq!( |
| 7473 | with_deepseek_default |
| 7474 | .active_provider_identity() |
| 7475 | .unwrap() |
| 7476 | .provider, |
| 7477 | ProviderKind::OpenaiCodex |
| 7478 | ); |
| 7479 | assert_eq!( |
| 7480 | with_deepseek_default.default_model(), |
| 7481 | DEFAULT_OPENAI_CODEX_MODEL |
| 7482 | ); |
| 7483 | |
| 7484 | // No global default resolves the same way. |
| 7485 | let bare = Config { |
| 7486 | provider: Some("openai-codex".to_string()), |
| 7487 | ..Default::default() |
| 7488 | }; |
| 7489 | assert_eq!(bare.default_model(), DEFAULT_OPENAI_CODEX_MODEL); |
| 7490 | |
| 7491 | // An explicit provider-scoped model still wins over the fallback. |
| 7492 | let mut providers = ProvidersConfig::default(); |
| 7493 | providers.openai_codex.model = Some("gpt-5.5-codex-preview".to_string()); |
| 7494 | let pinned = Config { |
| 7495 | provider: Some("openai-codex".to_string()), |
| 7496 | default_text_model: Some(DEFAULT_TEXT_MODEL.to_string()), |
| 7497 | providers: Some(providers), |
| 7498 | ..Default::default() |
| 7499 | }; |
| 7500 | assert_eq!(pinned.default_model(), "gpt-5.5-codex-preview"); |
| 7501 | } |
| 7502 | |
| 7503 | #[test] |
| 7504 | fn direct_provider_ignores_foreign_deepseek_root_default_model() { |
| 7505 | let _lock = lock_test_env(); |
| 7506 | |
| 7507 | let config = Config { |
| 7508 | provider: Some("zai".to_string()), |
| 7509 | default_text_model: Some(DEFAULT_TEXT_MODEL.to_string()), |
| 7510 | ..Default::default() |
| 7511 | }; |
| 7512 | |
| 7513 | assert_eq!( |
| 7514 | config.active_provider_identity().unwrap().provider, |
| 7515 | ProviderKind::Zai |
| 7516 | ); |
| 7517 | assert_eq!(config.default_model(), DEFAULT_ZAI_MODEL); |
| 7518 | } |
| 7519 | |
| 7520 | #[test] |
| 7521 | fn insecure_skip_scenario() { |
| 7522 | // Scenario consolidation of: insecure_skip_tls_verify_is_scoped_to_active_provider, insecure_skip_tls_verify_reads_active_provider_table |
| 7523 | // from insecure_skip_tls_verify_is_scoped_to_active_provider |
| 7524 | { |
| 7525 | let mut providers = ProvidersConfig::default(); |
| 7526 | providers.deepseek.insecure_skip_tls_verify = Some(true); |
| 7527 | providers.openai.insecure_skip_tls_verify = Some(false); |
| 7528 | let config = Config { |
| 7529 | provider: Some("openai".to_string()), |
| 7530 | providers: Some(providers), |
| 7531 | ..Default::default() |
| 7532 | }; |
| 7533 | |
| 7534 | assert_eq!( |
| 7535 | config.active_provider_identity().unwrap().provider, |
| 7536 | ProviderKind::Openai |
| 7537 | ); |
| 7538 | assert!(!config.insecure_skip_tls_verify()); |
| 7539 | } |
| 7540 | // from insecure_skip_tls_verify_reads_active_provider_table |
| 7541 | { |
| 7542 | let mut providers = ProvidersConfig::default(); |
| 7543 | providers.openai.insecure_skip_tls_verify = Some(true); |
| 7544 | let config = Config { |
| 7545 | provider: Some("openai".to_string()), |
| 7546 | providers: Some(providers), |
| 7547 | ..Default::default() |
| 7548 | }; |
| 7549 | |
| 7550 | assert!(config.insecure_skip_tls_verify()); |
| 7551 | } |
| 7552 | } |
| 7553 | |
| 7554 | #[test] |
| 7555 | fn xiaomi_mimo_scenario() -> Result<()> { |
| 7556 | // Scenario consolidation of: xiaomi_mimo_provider_uses_documented_defaults, xiaomi_mimo_provider_honours_root_default_model_and_base_url, xiaomi_mimo_provider_drops_stale_deepseek_root_default_model, xiaomi_mimo_token_plan_mode_accepts_region_aliases, xiaomi_mimo_unknown_mode_stays_on_token_plan_endpoint |
| 7557 | // from xiaomi_mimo_provider_uses_documented_defaults |
| 7558 | { |
| 7559 | let _lock = lock_test_env(); |
| 7560 | let nanos = SystemTime::now() |
| 7561 | .duration_since(UNIX_EPOCH) |
| 7562 | .unwrap() |
| 7563 | .as_nanos(); |
| 7564 | let temp_root = env::temp_dir().join(format!( |
| 7565 | "codewhale-tui-xiaomi-mimo-defaults-{}-{}", |
| 7566 | std::process::id(), |
| 7567 | nanos |
| 7568 | )); |
| 7569 | fs::create_dir_all(&temp_root)?; |
| 7570 | let _guard = EnvGuard::new(&temp_root); |
| 7571 | |
| 7572 | let config = Config { |
| 7573 | provider: Some("xiaomi-mimo".to_string()), |
| 7574 | ..Default::default() |
| 7575 | }; |
| 7576 | |
| 7577 | config.validate()?; |
| 7578 | assert_eq!( |
| 7579 | config.active_provider_identity().unwrap().provider, |
| 7580 | ProviderKind::XiaomiMimo |
| 7581 | ); |
| 7582 | assert_eq!(config.default_model(), DEFAULT_XIAOMI_MIMO_MODEL); |
| 7583 | assert_eq!(config.active_route_base_url(), DEFAULT_XIAOMI_MIMO_BASE_URL); |
| 7584 | } |
| 7585 | // from xiaomi_mimo_provider_honours_root_default_model_and_base_url |
| 7586 | { |
| 7587 | let config = Config { |
| 7588 | provider: Some("xiaomi-mimo".to_string()), |
| 7589 | default_text_model: Some("mimo-v2.5".to_string()), |
| 7590 | ..Default::default() |
| 7591 | } |
| 7592 | .with_legacy_root( |
| 7593 | None, |
| 7594 | Some("https://token-plan-cn.xiaomimimo.com/v1".to_string()), |
| 7595 | ); |
| 7596 | |
| 7597 | config.validate()?; |
| 7598 | assert_eq!( |
| 7599 | config.active_provider_identity().unwrap().provider, |
| 7600 | ProviderKind::XiaomiMimo |
| 7601 | ); |
| 7602 | assert_eq!(config.default_model(), "mimo-v2.6-flash"); |
| 7603 | assert_eq!( |
| 7604 | config.active_route_base_url(), |
| 7605 | "https://token-plan-cn.xiaomimimo.com/v1" |
| 7606 | ); |
| 7607 | } |
| 7608 | // from xiaomi_mimo_provider_drops_stale_deepseek_root_default_model |
| 7609 | { |
| 7610 | // A leftover DeepSeek id after a provider switch must not be forwarded to |
| 7611 | // Xiaomi. Fall back to the MiMo seed default instead of substituting a |
| 7612 | // different *configured* model. |
| 7613 | let config = Config { |
| 7614 | provider: Some("xiaomi-mimo".to_string()), |
| 7615 | default_text_model: Some(DEFAULT_OPENROUTER_MODEL.to_string()), |
| 7616 | ..Default::default() |
| 7617 | }; |
| 7618 | |
| 7619 | config.validate()?; |
| 7620 | assert_eq!( |
| 7621 | config.active_provider_identity().unwrap().provider, |
| 7622 | ProviderKind::XiaomiMimo |
| 7623 | ); |
| 7624 | assert_eq!(config.default_model(), DEFAULT_XIAOMI_MIMO_MODEL); |
| 7625 | } |
| 7626 | // from xiaomi_mimo_token_plan_mode_accepts_region_aliases |
| 7627 | { |
| 7628 | let config: Config = toml::from_str( |
| 7629 | r#" |
| 7630 | provider = "mimo" |
| 7631 | |
| 7632 | [providers.mimo] |
| 7633 | mode = "token-plan-ams" |
| 7634 | "#, |
| 7635 | )?; |
| 7636 | |
| 7637 | config.validate()?; |
| 7638 | assert_eq!( |
| 7639 | config.active_provider_identity().unwrap().provider, |
| 7640 | ProviderKind::XiaomiMimo |
| 7641 | ); |
| 7642 | assert_eq!( |
| 7643 | config.active_route_base_url(), |
| 7644 | XIAOMI_MIMO_TOKEN_PLAN_AMS_BASE_URL |
| 7645 | ); |
| 7646 | } |
| 7647 | // from xiaomi_mimo_unknown_mode_stays_on_token_plan_endpoint |
| 7648 | { |
| 7649 | let config: Config = toml::from_str( |
| 7650 | r#" |
| 7651 | provider = "mimo" |
| 7652 | |
| 7653 | [providers.mimo] |
| 7654 | mode = "token-plan-usa" |
| 7655 | "#, |
| 7656 | )?; |
| 7657 | |
| 7658 | config.validate()?; |
| 7659 | assert_eq!( |
| 7660 | config.active_provider_identity().unwrap().provider, |
| 7661 | ProviderKind::XiaomiMimo |
| 7662 | ); |
| 7663 | assert_eq!(config.active_route_base_url(), DEFAULT_XIAOMI_MIMO_BASE_URL); |
| 7664 | } |
| 7665 | Ok(()) |
| 7666 | } |
| 7667 | |
| 7668 | #[test] |
| 7669 | fn only_the_identity_that_owns_the_legacy_root_may_inherit_it() -> Result<()> { |
| 7670 | // The legacy root `base_url` is the DeepSeek field. A foreign value must |
| 7671 | // never become another route's endpoint: the custom-endpoint guard withholds |
| 7672 | // that route's credential from the foreign host, so the route answers with |
| 7673 | // the *other* vendor's unauthenticated 401 and the user reads it as a bad |
| 7674 | // key. The literal `provider = "custom"` shape is deliberately excluded — |
| 7675 | // it owns the root by design — and named custom providers read their own |
| 7676 | // `[providers.<name>]` table. |
| 7677 | let foreign = "https://api.deepseek.com"; |
| 7678 | for name in [ |
| 7679 | "deepseek", |
| 7680 | "deepseek-cn", |
| 7681 | "xiaomi-mimo", |
| 7682 | "openai-codex", |
| 7683 | "nvidia-nim", |
| 7684 | ] { |
| 7685 | let Some(provider) = ProviderKind::parse(name) else { |
| 7686 | continue; |
| 7687 | }; |
| 7688 | // Parsed, not constructed: the legacy top-level key only exists in a |
| 7689 | // file, and parsing moves it into its owner's table (#6394). |
| 7690 | let config = legacy_config(&format!( |
| 7691 | "provider = \"{name}\"\nbase_url = \"{foreign}\"\n" |
| 7692 | )); |
| 7693 | config.validate()?; |
| 7694 | let resolved = config.active_route_base_url(); |
| 7695 | if matches!(provider, ProviderKind::Deepseek) { |
| 7696 | assert_eq!(resolved, foreign, "{name} owns the legacy root"); |
| 7697 | } else { |
| 7698 | assert!( |
| 7699 | !resolved.contains("api.deepseek.com"), |
| 7700 | "{name} inherited a foreign legacy root: {resolved}" |
| 7701 | ); |
| 7702 | } |
| 7703 | } |
| 7704 | Ok(()) |
| 7705 | } |
| 7706 | |
| 7707 | #[test] |
| 7708 | fn xiaomi_mimo_ignores_an_unrelated_legacy_root_base_url() -> Result<()> { |
| 7709 | // The legacy root `base_url` is a DeepSeek field. Inheriting it aimed MiMo |
| 7710 | // traffic — and the MiMo key probe — at api.deepseek.com, whose |
| 7711 | // unauthenticated 401 ("Authentication Fails (governor)") then read as a |
| 7712 | // rejected MiMo key. Only MiMo's own hosts may be inherited. |
| 7713 | let config = |
| 7714 | legacy_config("provider = \"xiaomi-mimo\"\nbase_url = \"https://api.deepseek.com\"\n"); |
| 7715 | |
| 7716 | config.validate()?; |
| 7717 | assert_eq!( |
| 7718 | config.active_provider_identity().unwrap().provider, |
| 7719 | ProviderKind::XiaomiMimo |
| 7720 | ); |
| 7721 | assert_eq!(config.active_route_base_url(), DEFAULT_XIAOMI_MIMO_BASE_URL); |
| 7722 | assert_eq!( |
| 7723 | config.base_url_for_route(&config.test_identity_for_kind(ProviderKind::Deepseek)), |
| 7724 | "https://api.deepseek.com" |
| 7725 | ); |
| 7726 | |
| 7727 | // A MiMo host on the same legacy field moves to `[providers.xiaomi_mimo]`. |
| 7728 | let config = legacy_config( |
| 7729 | "provider = \"xiaomi-mimo\"\nbase_url = \"https://token-plan-ams.xiaomimimo.com/v1\"\n", |
| 7730 | ); |
| 7731 | |
| 7732 | config.validate()?; |
| 7733 | assert_eq!( |
| 7734 | config.active_route_base_url(), |
| 7735 | XIAOMI_MIMO_TOKEN_PLAN_AMS_BASE_URL |
| 7736 | ); |
| 7737 | Ok(()) |
| 7738 | } |
| 7739 | |
| 7740 | #[test] |
| 7741 | fn openai_codex_provider_ignores_legacy_root_base_url() -> Result<()> { |
| 7742 | // `base_url` is the legacy DeepSeek setting in a normal multi-provider |
| 7743 | // config. Switching to Codex must not inherit it and make the official |
| 7744 | // CLI OAuth login ineligible. |
| 7745 | let config = legacy_config( |
| 7746 | "provider = \"openai-codex\"\nbase_url = \"https://api.deepseek.com\"\ndefault_text_model = \"gpt-5.5\"\n", |
| 7747 | ); |
| 7748 | |
| 7749 | config.validate()?; |
| 7750 | assert_eq!( |
| 7751 | config.active_provider_identity().unwrap().provider, |
| 7752 | ProviderKind::OpenaiCodex |
| 7753 | ); |
| 7754 | assert_eq!(config.default_model(), "gpt-5.5"); |
| 7755 | assert_eq!( |
| 7756 | config.active_route_base_url(), |
| 7757 | DEFAULT_OPENAI_CODEX_BASE_URL |
| 7758 | ); |
| 7759 | assert!( |
| 7760 | !config.provider_uses_custom_endpoint( |
| 7761 | &config.test_identity_for_kind(ProviderKind::OpenaiCodex) |
| 7762 | ) |
| 7763 | ); |
| 7764 | Ok(()) |
| 7765 | } |
| 7766 | |
| 7767 | #[test] |
| 7768 | fn xiaomi_provider_alias_table_maps_to_mimo_config() -> Result<()> { |
| 7769 | let config: Config = toml::from_str( |
| 7770 | r#" |
| 7771 | provider = "xiaomi-mimo" |
| 7772 | default_text_model = "deepseek/deepseek-v4-pro" |
| 7773 | |
| 7774 | [providers.xiaomi] |
| 7775 | api_key = "mimo-table-key" |
| 7776 | base_url = "https://token-plan-sgp.xiaomimimo.com/v1" |
| 7777 | model = "mimo-v2.6-pro" |
| 7778 | "#, |
| 7779 | )?; |
| 7780 | |
| 7781 | config.validate()?; |
| 7782 | assert_eq!( |
| 7783 | config.active_provider_identity().unwrap().provider, |
| 7784 | ProviderKind::XiaomiMimo |
| 7785 | ); |
| 7786 | assert_eq!(config.active_route_api_key()?, "mimo-table-key"); |
| 7787 | assert_eq!( |
| 7788 | config.active_route_base_url(), |
| 7789 | "https://token-plan-sgp.xiaomimimo.com/v1" |
| 7790 | ); |
| 7791 | assert_eq!(config.default_model(), DEFAULT_XIAOMI_MIMO_MODEL); |
| 7792 | Ok(()) |
| 7793 | } |
| 7794 | |
| 7795 | #[test] |
| 7796 | fn xiaomi_token_plan_key_rewrites_saved_pay_as_you_go_base_url() -> Result<()> { |
| 7797 | let config: Config = toml::from_str( |
| 7798 | r#" |
| 7799 | provider = "xiaomi-mimo" |
| 7800 | |
| 7801 | [providers.xiaomi_mimo] |
| 7802 | api_key = "tp-test-token-plan-key" |
| 7803 | base_url = "https://api.xiaomimimo.com/v1" |
| 7804 | model = "mimo-v2.6-pro" |
| 7805 | "#, |
| 7806 | )?; |
| 7807 | |
| 7808 | config.validate()?; |
| 7809 | assert_eq!( |
| 7810 | config.active_provider_identity().unwrap().provider, |
| 7811 | ProviderKind::XiaomiMimo |
| 7812 | ); |
| 7813 | assert_eq!(config.active_route_base_url(), DEFAULT_XIAOMI_MIMO_BASE_URL); |
| 7814 | assert_eq!(config.default_model(), DEFAULT_XIAOMI_MIMO_MODEL); |
| 7815 | Ok(()) |
| 7816 | } |
| 7817 | |
| 7818 | #[test] |
| 7819 | fn xiaomi_mimo_env_token_plan_mode_uses_token_plan_key_and_endpoint() -> Result<()> { |
| 7820 | let _lock = lock_test_env(); |
| 7821 | let nanos = SystemTime::now() |
| 7822 | .duration_since(UNIX_EPOCH) |
| 7823 | .unwrap() |
| 7824 | .as_nanos(); |
| 7825 | let temp_root = env::temp_dir().join(format!( |
| 7826 | "codewhale-tui-xiaomi-mimo-token-plan-env-test-{}-{}", |
| 7827 | std::process::id(), |
| 7828 | nanos |
| 7829 | )); |
| 7830 | fs::create_dir_all(&temp_root)?; |
| 7831 | let _guard = EnvGuard::new(&temp_root); |
| 7832 | |
| 7833 | // Safety: test-only environment mutation guarded by a global mutex. |
| 7834 | unsafe { |
| 7835 | env::set_var("DEEPSEEK_PROVIDER", "xiaomi-mimo"); |
| 7836 | env::set_var("XIAOMI_MIMO_MODE", "token-plan-cn"); |
| 7837 | env::set_var("XIAOMI_MIMO_TOKEN_PLAN_API_KEY", "tp-env-key"); |
| 7838 | env::set_var("XIAOMI_MIMO_API_KEY", "sk-env-key"); |
| 7839 | env::set_var("XIAOMI_MIMO_MODEL", "voiceclone"); |
| 7840 | } |
| 7841 | |
| 7842 | let config = Config::load(None, None)?; |
| 7843 | assert_eq!( |
| 7844 | config.active_provider_identity().unwrap().provider, |
| 7845 | ProviderKind::XiaomiMimo |
| 7846 | ); |
| 7847 | assert_eq!(config.active_route_api_key()?, "tp-env-key"); |
| 7848 | assert_eq!( |
| 7849 | config.active_route_base_url(), |
| 7850 | XIAOMI_MIMO_TOKEN_PLAN_CN_BASE_URL |
| 7851 | ); |
| 7852 | assert_eq!(config.default_model(), "mimo-v2.5-tts-voiceclone"); |
| 7853 | Ok(()) |
| 7854 | } |
| 7855 | |
| 7856 | #[test] |
| 7857 | fn xiaomi_mimo_env_pay_as_you_go_mode_prefers_standard_key() -> Result<()> { |
| 7858 | let _lock = lock_test_env(); |
| 7859 | let nanos = SystemTime::now() |
| 7860 | .duration_since(UNIX_EPOCH) |
| 7861 | .unwrap() |
| 7862 | .as_nanos(); |
| 7863 | let temp_root = env::temp_dir().join(format!( |
| 7864 | "codewhale-tui-xiaomi-mimo-payg-env-test-{}-{}", |
| 7865 | std::process::id(), |
| 7866 | nanos |
| 7867 | )); |
| 7868 | fs::create_dir_all(&temp_root)?; |
| 7869 | let _guard = EnvGuard::new(&temp_root); |
| 7870 | |
| 7871 | // Safety: test-only environment mutation guarded by a global mutex. |
| 7872 | unsafe { |
| 7873 | env::set_var("DEEPSEEK_PROVIDER", "xiaomi-mimo"); |
| 7874 | env::set_var("XIAOMI_MIMO_MODE", "pay-as-you-go"); |
| 7875 | env::set_var("XIAOMI_MIMO_TOKEN_PLAN_API_KEY", "tp-env-key"); |
| 7876 | env::set_var("XIAOMI_MIMO_API_KEY", "sk-env-key"); |
| 7877 | } |
| 7878 | |
| 7879 | let config = Config::load(None, None)?; |
| 7880 | assert_eq!( |
| 7881 | config.active_provider_identity().unwrap().provider, |
| 7882 | ProviderKind::XiaomiMimo |
| 7883 | ); |
| 7884 | assert_eq!(config.active_route_api_key()?, "sk-env-key"); |
| 7885 | assert_eq!( |
| 7886 | config.active_route_base_url(), |
| 7887 | XIAOMI_MIMO_PAY_AS_YOU_GO_BASE_URL |
| 7888 | ); |
| 7889 | Ok(()) |
| 7890 | } |
| 7891 | |
| 7892 | #[test] |
| 7893 | fn xiaomi_mimo_bound_api_key_env_resolves_endpoint_without_recursing_on_custom_url() -> Result<()> { |
| 7894 | let _lock = lock_test_env(); |
| 7895 | let nanos = SystemTime::now() |
| 7896 | .duration_since(UNIX_EPOCH) |
| 7897 | .unwrap() |
| 7898 | .as_nanos(); |
| 7899 | let temp_root = env::temp_dir().join(format!( |
| 7900 | "codewhale-tui-xiaomi-mimo-bound-env-test-{}-{}", |
| 7901 | std::process::id(), |
| 7902 | nanos |
| 7903 | )); |
| 7904 | fs::create_dir_all(&temp_root)?; |
| 7905 | let _guard = EnvGuard::new(&temp_root); |
| 7906 | let var_name = "CODEWHALE_TEST_RUNTIME_XIAOMI_BOUND_KEY"; |
| 7907 | let saved = env::var_os(var_name); |
| 7908 | |
| 7909 | let config: Config = toml::from_str( |
| 7910 | r#" |
| 7911 | provider = "xiaomi-mimo" |
| 7912 | |
| 7913 | [providers.xiaomi_mimo] |
| 7914 | api_key_env = "CODEWHALE_TEST_RUNTIME_XIAOMI_BOUND_KEY" |
| 7915 | "#, |
| 7916 | )?; |
| 7917 | config.validate()?; |
| 7918 | |
| 7919 | unsafe { |
| 7920 | env::set_var(var_name, "tp-bound-token-plan-key"); |
| 7921 | env::set_var("MIMO_API_KEY", "sk-ambient-payg-key"); |
| 7922 | } |
| 7923 | assert_eq!(config.active_route_base_url(), DEFAULT_XIAOMI_MIMO_BASE_URL); |
| 7924 | assert_eq!(config.active_route_api_key()?, "tp-bound-token-plan-key"); |
| 7925 | |
| 7926 | unsafe { |
| 7927 | env::set_var(var_name, "sk-bound-payg-key"); |
| 7928 | env::remove_var("MIMO_API_KEY"); |
| 7929 | } |
| 7930 | assert_eq!( |
| 7931 | config.active_route_base_url(), |
| 7932 | XIAOMI_MIMO_PAY_AS_YOU_GO_BASE_URL |
| 7933 | ); |
| 7934 | assert_eq!(config.active_route_api_key()?, "sk-bound-payg-key"); |
| 7935 | |
| 7936 | let explicit_sgp: Config = toml::from_str( |
| 7937 | r#" |
| 7938 | provider = "xiaomi-mimo" |
| 7939 | |
| 7940 | [providers.xiaomi_mimo] |
| 7941 | api_key_env = "CODEWHALE_TEST_RUNTIME_XIAOMI_BOUND_KEY" |
| 7942 | base_url = "https://token-plan-sgp.xiaomimimo.com/v1" |
| 7943 | "#, |
| 7944 | )?; |
| 7945 | explicit_sgp.validate()?; |
| 7946 | unsafe { |
| 7947 | env::set_var(var_name, "tp-bound-token-plan-key"); |
| 7948 | } |
| 7949 | assert_eq!( |
| 7950 | explicit_sgp.active_route_base_url(), |
| 7951 | "https://token-plan-sgp.xiaomimimo.com/v1" |
| 7952 | ); |
| 7953 | assert_eq!( |
| 7954 | explicit_sgp.active_route_api_key()?, |
| 7955 | "tp-bound-token-plan-key" |
| 7956 | ); |
| 7957 | |
| 7958 | unsafe { |
| 7959 | env::set_var("MIMO_BASE_URL", "https://mimo-gateway.example/v1"); |
| 7960 | } |
| 7961 | let custom_base = config.active_route_base_url(); |
| 7962 | let custom_key = config.active_route_api_key(); |
| 7963 | unsafe { |
| 7964 | env::remove_var("MIMO_BASE_URL"); |
| 7965 | env::remove_var(var_name); |
| 7966 | } |
| 7967 | if let Some(value) = saved { |
| 7968 | unsafe { env::set_var(var_name, value) }; |
| 7969 | } |
| 7970 | assert_eq!(custom_base, "https://mimo-gateway.example/v1"); |
| 7971 | assert!(custom_key.is_err()); |
| 7972 | Ok(()) |
| 7973 | } |
| 7974 | |
| 7975 | #[test] |
| 7976 | fn atlascloud_provider_uses_documented_defaults() -> Result<()> { |
| 7977 | let config = Config { |
| 7978 | provider: Some("atlascloud".to_string()), |
| 7979 | ..Default::default() |
| 7980 | }; |
| 7981 | |
| 7982 | config.validate()?; |
| 7983 | assert_eq!( |
| 7984 | config.active_provider_identity().unwrap().provider, |
| 7985 | ProviderKind::Atlascloud |
| 7986 | ); |
| 7987 | assert_eq!(config.default_model(), DEFAULT_ATLASCLOUD_MODEL); |
| 7988 | assert_eq!(config.active_route_base_url(), DEFAULT_ATLASCLOUD_BASE_URL); |
| 7989 | Ok(()) |
| 7990 | } |
| 7991 | |
| 7992 | #[test] |
| 7993 | fn atlascloud_env_overrides_provider_base_url_and_model() -> Result<()> { |
| 7994 | let _lock = lock_test_env(); |
| 7995 | let nanos = SystemTime::now() |
| 7996 | .duration_since(UNIX_EPOCH) |
| 7997 | .unwrap() |
| 7998 | .as_nanos(); |
| 7999 | let temp_root = env::temp_dir().join(format!( |
| 8000 | "codewhale-tui-atlascloud-env-test-{}-{}", |
| 8001 | std::process::id(), |
| 8002 | nanos |
| 8003 | )); |
| 8004 | fs::create_dir_all(&temp_root)?; |
| 8005 | let _guard = EnvGuard::new(&temp_root); |
| 8006 | |
| 8007 | unsafe { |
| 8008 | env::set_var("DEEPSEEK_PROVIDER", "atlascloud"); |
| 8009 | env::set_var("ATLASCLOUD_API_KEY", "atlascloud-env-key"); |
| 8010 | env::set_var("ATLASCLOUD_BASE_URL", "https://api.atlascloud.ai/v1"); |
| 8011 | env::set_var("ATLASCLOUD_MODEL", "deepseek-ai/deepseek-v4-flash"); |
| 8012 | } |
| 8013 | |
| 8014 | let config = Config::load(None, None)?; |
| 8015 | assert_eq!( |
| 8016 | config.active_provider_identity().unwrap().provider, |
| 8017 | ProviderKind::Atlascloud |
| 8018 | ); |
| 8019 | assert_eq!(config.active_route_api_key()?, "atlascloud-env-key"); |
| 8020 | assert_eq!( |
| 8021 | config.active_route_base_url(), |
| 8022 | "https://api.atlascloud.ai/v1" |
| 8023 | ); |
| 8024 | assert_eq!(config.default_model(), "deepseek-ai/deepseek-v4-flash"); |
| 8025 | Ok(()) |
| 8026 | } |
| 8027 | |
| 8028 | #[test] |
| 8029 | fn wanjie_ark_provider_uses_documented_defaults() -> Result<()> { |
| 8030 | let config = Config { |
| 8031 | provider: Some("wanjie-ark".to_string()), |
| 8032 | ..Default::default() |
| 8033 | }; |
| 8034 | |
| 8035 | config.validate()?; |
| 8036 | assert_eq!( |
| 8037 | config.active_provider_identity().unwrap().provider, |
| 8038 | ProviderKind::WanjieArk |
| 8039 | ); |
| 8040 | assert_eq!(config.default_model(), DEFAULT_WANJIE_ARK_MODEL); |
| 8041 | assert_eq!(config.active_route_base_url(), DEFAULT_WANJIE_ARK_BASE_URL); |
| 8042 | Ok(()) |
| 8043 | } |
| 8044 | |
| 8045 | #[test] |
| 8046 | fn wanjie_ark_provider_accepts_custom_model_and_table_key() -> Result<()> { |
| 8047 | let _lock = lock_test_env(); |
| 8048 | let nanos = SystemTime::now() |
| 8049 | .duration_since(UNIX_EPOCH) |
| 8050 | .unwrap() |
| 8051 | .as_nanos(); |
| 8052 | let temp_root = env::temp_dir().join(format!( |
| 8053 | "codewhale-tui-wanjie-table-{}-{}", |
| 8054 | std::process::id(), |
| 8055 | nanos |
| 8056 | )); |
| 8057 | fs::create_dir_all(&temp_root)?; |
| 8058 | let _guard = EnvGuard::new(&temp_root); |
| 8059 | |
| 8060 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 8061 | ensure_parent_dir(&config_path)?; |
| 8062 | fs::write( |
| 8063 | &config_path, |
| 8064 | r#"provider = "wanjie-ark" |
| 8065 | |
| 8066 | [providers.wanjie_ark] |
| 8067 | api_key = "wanjie-table-key" |
| 8068 | base_url = "https://maas-openapi.wanjiedata.com/api/v1" |
| 8069 | model = "account-model-id" |
| 8070 | "#, |
| 8071 | )?; |
| 8072 | |
| 8073 | let config = Config::load(None, None)?; |
| 8074 | assert_eq!( |
| 8075 | config.active_provider_identity().unwrap().provider, |
| 8076 | ProviderKind::WanjieArk |
| 8077 | ); |
| 8078 | assert_eq!(config.active_route_api_key()?, "wanjie-table-key"); |
| 8079 | assert_eq!( |
| 8080 | config.active_route_base_url(), |
| 8081 | "https://maas-openapi.wanjiedata.com/api/v1" |
| 8082 | ); |
| 8083 | assert_eq!(config.default_model(), "account-model-id"); |
| 8084 | Ok(()) |
| 8085 | } |
| 8086 | |
| 8087 | #[test] |
| 8088 | fn openai_provider_accepts_custom_model_and_base_url() -> Result<()> { |
| 8089 | let _lock = lock_test_env(); |
| 8090 | let nanos = SystemTime::now() |
| 8091 | .duration_since(UNIX_EPOCH) |
| 8092 | .unwrap() |
| 8093 | .as_nanos(); |
| 8094 | let temp_root = env::temp_dir().join(format!( |
| 8095 | "codewhale-tui-openai-table-{}-{}", |
| 8096 | std::process::id(), |
| 8097 | nanos |
| 8098 | )); |
| 8099 | fs::create_dir_all(&temp_root)?; |
| 8100 | let _guard = EnvGuard::new(&temp_root); |
| 8101 | |
| 8102 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 8103 | ensure_parent_dir(&config_path)?; |
| 8104 | fs::write( |
| 8105 | &config_path, |
| 8106 | r#"provider = "openai" |
| 8107 | |
| 8108 | [providers.openai] |
| 8109 | api_key = "openai-table-key" |
| 8110 | base_url = "https://openai-compatible.example/api/coding/paas/v4" |
| 8111 | model = "glm-5" |
| 8112 | "#, |
| 8113 | )?; |
| 8114 | |
| 8115 | let config = Config::load(None, None)?; |
| 8116 | assert_eq!( |
| 8117 | config.active_provider_identity().unwrap().provider, |
| 8118 | ProviderKind::Openai |
| 8119 | ); |
| 8120 | assert_eq!(config.active_route_api_key()?, "openai-table-key"); |
| 8121 | assert_eq!( |
| 8122 | config.active_route_base_url(), |
| 8123 | "https://openai-compatible.example/api/coding/paas/v4" |
| 8124 | ); |
| 8125 | assert_eq!(config.default_model(), "glm-5"); |
| 8126 | Ok(()) |
| 8127 | } |
| 8128 | |
| 8129 | #[test] |
| 8130 | fn openai_provider_accepts_dashscope_bailian_fixture() -> Result<()> { |
| 8131 | let _lock = lock_test_env(); |
| 8132 | let nanos = SystemTime::now() |
| 8133 | .duration_since(UNIX_EPOCH) |
| 8134 | .unwrap() |
| 8135 | .as_nanos(); |
| 8136 | let temp_root = env::temp_dir().join(format!( |
| 8137 | "codewhale-tui-dashscope-openai-{}-{}", |
| 8138 | std::process::id(), |
| 8139 | nanos |
| 8140 | )); |
| 8141 | fs::create_dir_all(&temp_root)?; |
| 8142 | let _guard = EnvGuard::new(&temp_root); |
| 8143 | |
| 8144 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 8145 | ensure_parent_dir(&config_path)?; |
| 8146 | fs::write( |
| 8147 | &config_path, |
| 8148 | r#"provider = "openai" |
| 8149 | |
| 8150 | [providers.openai] |
| 8151 | api_key = "dashscope-table-key" |
| 8152 | base_url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1" |
| 8153 | model = "qwen-plus" |
| 8154 | "#, |
| 8155 | )?; |
| 8156 | |
| 8157 | let config = Config::load(None, None)?; |
| 8158 | assert_eq!( |
| 8159 | config.active_provider_identity().unwrap().provider, |
| 8160 | ProviderKind::Openai |
| 8161 | ); |
| 8162 | assert_eq!(config.active_route_api_key()?, "dashscope-table-key"); |
| 8163 | assert_eq!( |
| 8164 | config.active_route_base_url(), |
| 8165 | "https://dashscope-intl.aliyuncs.com/compatible-mode/v1" |
| 8166 | ); |
| 8167 | assert_eq!(config.default_model(), "qwen-plus"); |
| 8168 | Ok(()) |
| 8169 | } |
| 8170 | |
| 8171 | #[test] |
| 8172 | fn qianfan_provider_accepts_custom_model_and_base_url() -> Result<()> { |
| 8173 | let _lock = lock_test_env(); |
| 8174 | let nanos = SystemTime::now() |
| 8175 | .duration_since(UNIX_EPOCH) |
| 8176 | .unwrap() |
| 8177 | .as_nanos(); |
| 8178 | let temp_root = env::temp_dir().join(format!( |
| 8179 | "codewhale-tui-qianfan-provider-{}-{}", |
| 8180 | std::process::id(), |
| 8181 | nanos |
| 8182 | )); |
| 8183 | fs::create_dir_all(&temp_root)?; |
| 8184 | let _guard = EnvGuard::new(&temp_root); |
| 8185 | |
| 8186 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 8187 | ensure_parent_dir(&config_path)?; |
| 8188 | fs::write( |
| 8189 | &config_path, |
| 8190 | r#"provider = "qianfan" |
| 8191 | |
| 8192 | [providers.qianfan] |
| 8193 | api_key = "qianfan-table-key" |
| 8194 | base_url = "https://qianfan.baidubce.com/v2" |
| 8195 | model = "custom-qianfan-service-id" |
| 8196 | "#, |
| 8197 | )?; |
| 8198 | |
| 8199 | let config = Config::load(None, None)?; |
| 8200 | assert_eq!( |
| 8201 | config.active_provider_identity().unwrap().provider, |
| 8202 | ProviderKind::Qianfan |
| 8203 | ); |
| 8204 | assert_eq!(config.active_route_api_key()?, "qianfan-table-key"); |
| 8205 | assert_eq!( |
| 8206 | config.active_route_base_url(), |
| 8207 | "https://qianfan.baidubce.com/v2" |
| 8208 | ); |
| 8209 | assert_eq!(config.default_model(), "custom-qianfan-service-id"); |
| 8210 | Ok(()) |
| 8211 | } |
| 8212 | |
| 8213 | #[test] |
| 8214 | fn provider_config_loads_reasoning_stream_style() -> Result<()> { |
| 8215 | let _lock = lock_test_env(); |
| 8216 | let nanos = SystemTime::now() |
| 8217 | .duration_since(UNIX_EPOCH) |
| 8218 | .unwrap() |
| 8219 | .as_nanos(); |
| 8220 | let temp_root = env::temp_dir().join(format!( |
| 8221 | "codewhale-tui-reasoning-style-{}-{}", |
| 8222 | std::process::id(), |
| 8223 | nanos |
| 8224 | )); |
| 8225 | fs::create_dir_all(&temp_root)?; |
| 8226 | let _guard = EnvGuard::new(&temp_root); |
| 8227 | |
| 8228 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 8229 | ensure_parent_dir(&config_path)?; |
| 8230 | fs::write( |
| 8231 | &config_path, |
| 8232 | r#"provider = "openai" |
| 8233 | |
| 8234 | [providers.openai] |
| 8235 | api_key = "openai-table-key" |
| 8236 | base_url = "https://openai-compatible.example/v1" |
| 8237 | model = "custom-reasoner" |
| 8238 | reasoning_stream_style = "inline_tags" |
| 8239 | "#, |
| 8240 | )?; |
| 8241 | |
| 8242 | let config = Config::load(None, None)?; |
| 8243 | let openai = config |
| 8244 | .provider_config_for(&config.test_identity_for_kind(ProviderKind::Openai)) |
| 8245 | .expect("openai provider config"); |
| 8246 | assert_eq!( |
| 8247 | openai.reasoning_stream_style.as_deref(), |
| 8248 | Some("inline_tags") |
| 8249 | ); |
| 8250 | Ok(()) |
| 8251 | } |
| 8252 | |
| 8253 | // Regression for issue #1714: `codewhale --provider openai --model |
| 8254 | // MiniMax-M2.7` forwards the choice via DEEPSEEK_MODEL (never |
| 8255 | // OPENAI_MODEL) and uses the DEFAULT base_url. The explicit custom model |
| 8256 | // must pass through verbatim instead of silently becoming a |
| 8257 | // DeepSeek/provider default. |
| 8258 | #[test] |
| 8259 | fn deepseek_model_env_passes_custom_model_through_for_non_deepseek_providers() -> Result<()> { |
| 8260 | let _lock = lock_test_env(); |
| 8261 | let nanos = SystemTime::now() |
| 8262 | .duration_since(UNIX_EPOCH) |
| 8263 | .unwrap() |
| 8264 | .as_nanos(); |
| 8265 | let temp_root = env::temp_dir().join(format!( |
| 8266 | "codewhale-tui-1714-passthrough-{}-{}", |
| 8267 | std::process::id(), |
| 8268 | nanos |
| 8269 | )); |
| 8270 | fs::create_dir_all(&temp_root)?; |
| 8271 | |
| 8272 | // (a) provider=openai + model="MiniMax-M2.7" via env, NO OPENAI_MODEL, |
| 8273 | // DEFAULT base_url. |
| 8274 | { |
| 8275 | let _guard = EnvGuard::new(&temp_root); |
| 8276 | // Safety: test-only environment mutation guarded by a global mutex. |
| 8277 | unsafe { |
| 8278 | env::set_var("DEEPSEEK_PROVIDER", "openai"); |
| 8279 | env::set_var("OPENAI_API_KEY", "openai-env-key"); |
| 8280 | env::set_var("DEEPSEEK_MODEL", "MiniMax-M2.7"); |
| 8281 | } |
| 8282 | |
| 8283 | let config = Config::load(None, None)?; |
| 8284 | assert_eq!( |
| 8285 | config.active_provider_identity().unwrap().provider, |
| 8286 | ProviderKind::Openai |
| 8287 | ); |
| 8288 | assert_eq!(config.active_route_base_url(), DEFAULT_OPENAI_BASE_URL); |
| 8289 | assert_eq!(config.default_model(), "MiniMax-M2.7"); |
| 8290 | } |
| 8291 | |
| 8292 | // (b) a non-passthrough provider (novita) with an unknown custom model |
| 8293 | // and the DEFAULT base_url must also be preserved verbatim — never |
| 8294 | // rewritten to DEFAULT_NOVITA_MODEL. |
| 8295 | { |
| 8296 | let _guard = EnvGuard::new(&temp_root); |
| 8297 | // Safety: test-only environment mutation guarded by a global mutex. |
| 8298 | unsafe { |
| 8299 | env::set_var("DEEPSEEK_PROVIDER", "novita"); |
| 8300 | env::set_var("NOVITA_API_KEY", "novita-env-key"); |
| 8301 | env::set_var("DEEPSEEK_MODEL", "MiniMax-M2.7"); |
| 8302 | } |
| 8303 | |
| 8304 | let config = Config::load(None, None)?; |
| 8305 | assert_eq!( |
| 8306 | config.active_provider_identity().unwrap().provider, |
| 8307 | ProviderKind::Novita |
| 8308 | ); |
| 8309 | assert_eq!(config.active_route_base_url(), DEFAULT_NOVITA_BASE_URL); |
| 8310 | assert_ne!(config.default_model(), DEFAULT_NOVITA_MODEL); |
| 8311 | assert_eq!(config.default_model(), "MiniMax-M2.7"); |
| 8312 | } |
| 8313 | |
| 8314 | Ok(()) |
| 8315 | } |
| 8316 | |
| 8317 | #[test] |
| 8318 | fn openrouter_provider_uses_canonical_defaults() -> Result<()> { |
| 8319 | let _lock = lock_test_env(); |
| 8320 | let nanos = SystemTime::now() |
| 8321 | .duration_since(UNIX_EPOCH) |
| 8322 | .unwrap() |
| 8323 | .as_nanos(); |
| 8324 | let temp_root = env::temp_dir().join(format!( |
| 8325 | "codewhale-tui-or-defaults-{}-{}", |
| 8326 | std::process::id(), |
| 8327 | nanos |
| 8328 | )); |
| 8329 | fs::create_dir_all(&temp_root)?; |
| 8330 | let _guard = EnvGuard::new(&temp_root); |
| 8331 | |
| 8332 | let config = Config { |
| 8333 | provider: Some("openrouter".to_string()), |
| 8334 | ..Default::default() |
| 8335 | }; |
| 8336 | config.validate()?; |
| 8337 | assert_eq!( |
| 8338 | config.active_provider_identity().unwrap().provider, |
| 8339 | ProviderKind::Openrouter |
| 8340 | ); |
| 8341 | assert_eq!(config.default_model(), DEFAULT_OPENROUTER_MODEL); |
| 8342 | assert_eq!(config.active_route_base_url(), DEFAULT_OPENROUTER_BASE_URL); |
| 8343 | Ok(()) |
| 8344 | } |
| 8345 | |
| 8346 | #[test] |
| 8347 | fn novita_provider_uses_canonical_defaults() -> Result<()> { |
| 8348 | let _lock = lock_test_env(); |
| 8349 | let nanos = SystemTime::now() |
| 8350 | .duration_since(UNIX_EPOCH) |
| 8351 | .unwrap() |
| 8352 | .as_nanos(); |
| 8353 | let temp_root = env::temp_dir().join(format!( |
| 8354 | "codewhale-tui-novita-defaults-{}-{}", |
| 8355 | std::process::id(), |
| 8356 | nanos |
| 8357 | )); |
| 8358 | fs::create_dir_all(&temp_root)?; |
| 8359 | let _guard = EnvGuard::new(&temp_root); |
| 8360 | |
| 8361 | let config = Config { |
| 8362 | provider: Some("novita".to_string()), |
| 8363 | ..Default::default() |
| 8364 | }; |
| 8365 | config.validate()?; |
| 8366 | assert_eq!( |
| 8367 | config.active_provider_identity().unwrap().provider, |
| 8368 | ProviderKind::Novita |
| 8369 | ); |
| 8370 | assert_eq!(config.default_model(), DEFAULT_NOVITA_MODEL); |
| 8371 | assert_eq!(config.active_route_base_url(), DEFAULT_NOVITA_BASE_URL); |
| 8372 | Ok(()) |
| 8373 | } |
| 8374 | |
| 8375 | #[test] |
| 8376 | fn fireworks_provider_uses_canonical_defaults() -> Result<()> { |
| 8377 | let _lock = lock_test_env(); |
| 8378 | let nanos = SystemTime::now() |
| 8379 | .duration_since(UNIX_EPOCH) |
| 8380 | .unwrap() |
| 8381 | .as_nanos(); |
| 8382 | let temp_root = env::temp_dir().join(format!( |
| 8383 | "codewhale-tui-fireworks-defaults-{}-{}", |
| 8384 | std::process::id(), |
| 8385 | nanos |
| 8386 | )); |
| 8387 | fs::create_dir_all(&temp_root)?; |
| 8388 | let _guard = EnvGuard::new(&temp_root); |
| 8389 | |
| 8390 | let config = Config { |
| 8391 | provider: Some("fireworks".to_string()), |
| 8392 | ..Default::default() |
| 8393 | }; |
| 8394 | config.validate()?; |
| 8395 | assert_eq!( |
| 8396 | config.active_provider_identity().unwrap().provider, |
| 8397 | ProviderKind::Fireworks |
| 8398 | ); |
| 8399 | assert_eq!(config.default_model(), DEFAULT_FIREWORKS_MODEL); |
| 8400 | assert_eq!(config.active_route_base_url(), DEFAULT_FIREWORKS_BASE_URL); |
| 8401 | Ok(()) |
| 8402 | } |
| 8403 | |
| 8404 | #[test] |
| 8405 | fn fireworks_flash_alias_is_not_mapped_to_undocumented_model() -> Result<()> { |
| 8406 | let config = Config { |
| 8407 | provider: Some("fireworks".to_string()), |
| 8408 | default_text_model: Some("deepseek-v4-flash".to_string()), |
| 8409 | ..Default::default() |
| 8410 | }; |
| 8411 | |
| 8412 | config.validate()?; |
| 8413 | assert_eq!( |
| 8414 | config.active_provider_identity().unwrap().provider, |
| 8415 | ProviderKind::Fireworks |
| 8416 | ); |
| 8417 | assert_eq!(config.default_model(), "deepseek-v4-flash"); |
| 8418 | Ok(()) |
| 8419 | } |
| 8420 | |
| 8421 | #[test] |
| 8422 | fn volcengine_provider_requires_api_key() -> Result<()> { |
| 8423 | let _lock = lock_test_env(); |
| 8424 | let nanos = SystemTime::now() |
| 8425 | .duration_since(UNIX_EPOCH) |
| 8426 | .unwrap() |
| 8427 | .as_nanos(); |
| 8428 | let temp_root = env::temp_dir().join(format!( |
| 8429 | "codewhale-tui-volcengine-auth-test-{}-{}", |
| 8430 | std::process::id(), |
| 8431 | nanos |
| 8432 | )); |
| 8433 | fs::create_dir_all(&temp_root)?; |
| 8434 | let _guard = EnvGuard::new(&temp_root); |
| 8435 | |
| 8436 | let config = Config { |
| 8437 | provider: Some("volcengine".to_string()), |
| 8438 | ..Default::default() |
| 8439 | }; |
| 8440 | |
| 8441 | config.validate()?; |
| 8442 | let err = config.active_route_api_key().expect_err("missing key"); |
| 8443 | assert!(err.to_string().contains("Volcengine Ark API key not found")); |
| 8444 | Ok(()) |
| 8445 | } |
| 8446 | |
| 8447 | #[test] |
| 8448 | fn siliconflow_provider_uses_canonical_defaults() -> Result<()> { |
| 8449 | let _lock = lock_test_env(); |
| 8450 | let nanos = SystemTime::now() |
| 8451 | .duration_since(UNIX_EPOCH) |
| 8452 | .unwrap() |
| 8453 | .as_nanos(); |
| 8454 | let temp_root = env::temp_dir().join(format!( |
| 8455 | "codewhale-tui-siliconflow-defaults-{}-{}", |
| 8456 | std::process::id(), |
| 8457 | nanos |
| 8458 | )); |
| 8459 | fs::create_dir_all(&temp_root)?; |
| 8460 | let _guard = EnvGuard::new(&temp_root); |
| 8461 | |
| 8462 | let config = Config { |
| 8463 | provider: Some("siliconflow".to_string()), |
| 8464 | ..Default::default() |
| 8465 | }; |
| 8466 | config.validate()?; |
| 8467 | assert_eq!( |
| 8468 | config.active_provider_identity().unwrap().provider, |
| 8469 | ProviderKind::Siliconflow |
| 8470 | ); |
| 8471 | assert_eq!(config.default_model(), DEFAULT_SILICONFLOW_MODEL); |
| 8472 | assert_eq!(config.active_route_base_url(), DEFAULT_SILICONFLOW_BASE_URL); |
| 8473 | assert_eq!( |
| 8474 | model_completion_names_for_provider(ProviderKind::Siliconflow), |
| 8475 | vec![DEFAULT_SILICONFLOW_MODEL, DEFAULT_SILICONFLOW_FLASH_MODEL] |
| 8476 | ); |
| 8477 | Ok(()) |
| 8478 | } |
| 8479 | |
| 8480 | #[test] |
| 8481 | fn ollama_cloud_env_precedence_is_cloud_name_then_official_name() -> Result<()> { |
| 8482 | let _lock = lock_test_env(); |
| 8483 | let temp_root = tempfile::tempdir()?; |
| 8484 | let _guard = EnvGuard::new(temp_root.path()); |
| 8485 | // Safety: test-only environment mutation guarded by a global mutex and |
| 8486 | // restored by EnvGuard. |
| 8487 | unsafe { |
| 8488 | env::set_var("OLLAMA_CLOUD_API_KEY", "cloud-specific-key"); |
| 8489 | env::set_var("OLLAMA_API_KEY", "official-fallback-key"); |
| 8490 | } |
| 8491 | let config = Config { |
| 8492 | provider: Some("ollama-cloud".to_string()), |
| 8493 | ..Config::default() |
| 8494 | }; |
| 8495 | |
| 8496 | assert_eq!(config.active_route_api_key()?, "cloud-specific-key"); |
| 8497 | // Safety: same serialized test and EnvGuard restore the prior value. |
| 8498 | unsafe { env::remove_var("OLLAMA_CLOUD_API_KEY") }; |
| 8499 | assert_eq!(config.active_route_api_key()?, "official-fallback-key"); |
| 8500 | Ok(()) |
| 8501 | } |
| 8502 | |
| 8503 | #[test] |
| 8504 | fn migrated_ollama_cloud_scope_preserves_legacy_table_and_slot_read_only() -> Result<()> { |
| 8505 | let _lock = lock_test_env(); |
| 8506 | let temp_root = tempfile::tempdir()?; |
| 8507 | let _guard = EnvGuard::new(temp_root.path()); |
| 8508 | let codewhale_home = temp_root.path().join("isolated-codewhale"); |
| 8509 | fs::create_dir_all(&codewhale_home)?; |
| 8510 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 8511 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 8512 | codewhale_secrets::Secrets::auto_detect().set("ollama", "legacy-cloud-key")?; |
| 8513 | |
| 8514 | let config = Config { |
| 8515 | provider: Some("deepseek".to_string()), |
| 8516 | providers: Some(ProvidersConfig { |
| 8517 | ollama: ProviderConfig { |
| 8518 | base_url: Some(codewhale_config::provider::OLLAMA_CLOUD_BASE_URL.to_string()), |
| 8519 | model: Some("legacy-cloud-model".to_string()), |
| 8520 | ..ProviderConfig::default() |
| 8521 | }, |
| 8522 | ..ProvidersConfig::default() |
| 8523 | }), |
| 8524 | ..Config::default() |
| 8525 | }; |
| 8526 | let identity = config |
| 8527 | .resolve_provider_identity("ollama") |
| 8528 | .expect("legacy identity migrates"); |
| 8529 | assert_eq!(identity.provider, ProviderKind::OllamaCloud); |
| 8530 | assert_eq!(identity.key.as_str(), "ollama-cloud"); |
| 8531 | assert!(identity.migrated_legacy_ollama_cloud_route); |
| 8532 | |
| 8533 | let mut scoped = config.clone(); |
| 8534 | scoped.scope_to_provider_identity(&identity).unwrap(); |
| 8535 | assert_eq!( |
| 8536 | scoped.active_provider_identity().unwrap().provider, |
| 8537 | ProviderKind::OllamaCloud |
| 8538 | ); |
| 8539 | assert_eq!( |
| 8540 | scoped.active_route_base_url(), |
| 8541 | codewhale_config::provider::OLLAMA_CLOUD_BASE_URL |
| 8542 | ); |
| 8543 | assert_eq!(scoped.default_model(), "legacy-cloud-model"); |
| 8544 | assert_eq!(scoped.active_route_api_key()?, "legacy-cloud-key"); |
| 8545 | assert!( |
| 8546 | scoped |
| 8547 | .providers |
| 8548 | .as_ref() |
| 8549 | .expect("providers") |
| 8550 | .ollama_cloud |
| 8551 | .api_key |
| 8552 | .is_none(), |
| 8553 | "migration must not copy secret material into the new config table" |
| 8554 | ); |
| 8555 | assert_eq!( |
| 8556 | codewhale_secrets::Secrets::auto_detect().get("ollama-cloud")?, |
| 8557 | None, |
| 8558 | "migration must not copy the legacy secret into the new slot" |
| 8559 | ); |
| 8560 | Ok(()) |
| 8561 | } |
| 8562 | |
| 8563 | #[test] |
| 8564 | fn ollama_model_is_passed_through_verbatim() -> Result<()> { |
| 8565 | let _lock = lock_test_env(); |
| 8566 | let nanos = SystemTime::now() |
| 8567 | .duration_since(UNIX_EPOCH) |
| 8568 | .unwrap() |
| 8569 | .as_nanos(); |
| 8570 | let temp_root = env::temp_dir().join(format!( |
| 8571 | "codewhale-tui-ollama-model-test-{}-{}", |
| 8572 | std::process::id(), |
| 8573 | nanos |
| 8574 | )); |
| 8575 | fs::create_dir_all(&temp_root)?; |
| 8576 | let _guard = EnvGuard::new(&temp_root); |
| 8577 | |
| 8578 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 8579 | ensure_parent_dir(&config_path)?; |
| 8580 | fs::write( |
| 8581 | &config_path, |
| 8582 | r#"provider = "ollama" |
| 8583 | |
| 8584 | [providers.ollama] |
| 8585 | base_url = "http://127.0.0.1:11434/v1" |
| 8586 | model = "qwen2.5-coder:7b" |
| 8587 | "#, |
| 8588 | )?; |
| 8589 | |
| 8590 | let config = Config::load(None, None)?; |
| 8591 | assert_eq!( |
| 8592 | config.active_provider_identity().unwrap().provider, |
| 8593 | ProviderKind::Ollama |
| 8594 | ); |
| 8595 | assert_eq!(config.default_model(), "qwen2.5-coder:7b"); |
| 8596 | assert_eq!(config.active_route_base_url(), "http://127.0.0.1:11434/v1"); |
| 8597 | Ok(()) |
| 8598 | } |
| 8599 | |
| 8600 | #[test] |
| 8601 | fn deepseek_base_url_env_scopes_to_self_hosted_providers() -> Result<()> { |
| 8602 | let _lock = lock_test_env(); |
| 8603 | let nanos = SystemTime::now() |
| 8604 | .duration_since(UNIX_EPOCH) |
| 8605 | .unwrap() |
| 8606 | .as_nanos(); |
| 8607 | let temp_root = env::temp_dir().join(format!( |
| 8608 | "codewhale-tui-self-hosted-base-url-test-{}-{}", |
| 8609 | std::process::id(), |
| 8610 | nanos |
| 8611 | )); |
| 8612 | fs::create_dir_all(&temp_root)?; |
| 8613 | let _guard = EnvGuard::new(&temp_root); |
| 8614 | |
| 8615 | // Safety: test-only environment mutation guarded by a global mutex. |
| 8616 | unsafe { |
| 8617 | env::set_var("DEEPSEEK_PROVIDER", "ollama"); |
| 8618 | env::set_var("DEEPSEEK_BASE_URL", "http://ollama.remote:11434/v1"); |
| 8619 | } |
| 8620 | let config = Config::load(None, None)?; |
| 8621 | assert_eq!( |
| 8622 | config.active_provider_identity().unwrap().provider, |
| 8623 | ProviderKind::Ollama |
| 8624 | ); |
| 8625 | assert_eq!( |
| 8626 | config.active_route_base_url(), |
| 8627 | "http://ollama.remote:11434/v1" |
| 8628 | ); |
| 8629 | |
| 8630 | // Safety: test-only environment mutation guarded by a global mutex. |
| 8631 | unsafe { |
| 8632 | env::set_var("DEEPSEEK_PROVIDER", "vllm"); |
| 8633 | env::set_var("DEEPSEEK_BASE_URL", "http://vllm.remote:8000/v1"); |
| 8634 | } |
| 8635 | let config = Config::load(None, None)?; |
| 8636 | assert_eq!( |
| 8637 | config.active_provider_identity().unwrap().provider, |
| 8638 | ProviderKind::Vllm |
| 8639 | ); |
| 8640 | assert_eq!(config.active_route_base_url(), "http://vllm.remote:8000/v1"); |
| 8641 | Ok(()) |
| 8642 | } |
| 8643 | |
| 8644 | #[test] |
| 8645 | fn vllm_env_resolves_reported_lan_http_endpoint_and_model() -> Result<()> { |
| 8646 | let _lock = lock_test_env(); |
| 8647 | let nanos = SystemTime::now() |
| 8648 | .duration_since(UNIX_EPOCH) |
| 8649 | .unwrap() |
| 8650 | .as_nanos(); |
| 8651 | let temp_root = env::temp_dir().join(format!( |
| 8652 | "codewhale-tui-vllm-lan-http-test-{}-{}", |
| 8653 | std::process::id(), |
| 8654 | nanos |
| 8655 | )); |
| 8656 | fs::create_dir_all(&temp_root)?; |
| 8657 | let _guard = EnvGuard::new(&temp_root); |
| 8658 | |
| 8659 | // Safety: test-only environment mutation guarded by a global mutex. |
| 8660 | unsafe { |
| 8661 | env::set_var("DEEPSEEK_PROVIDER", "vllm"); |
| 8662 | env::set_var("VLLM_BASE_URL", "http://192.168.0.110:8000/v1"); |
| 8663 | env::set_var("DEEPSEEK_MODEL", "deepseek-v4-flash"); |
| 8664 | } |
| 8665 | |
| 8666 | let config = Config::load(None, None)?; |
| 8667 | assert_eq!( |
| 8668 | config.active_provider_identity().unwrap().provider, |
| 8669 | ProviderKind::Vllm |
| 8670 | ); |
| 8671 | assert_eq!( |
| 8672 | config.active_route_base_url(), |
| 8673 | "http://192.168.0.110:8000/v1" |
| 8674 | ); |
| 8675 | assert_eq!(config.default_model(), "deepseek-v4-flash"); |
| 8676 | Ok(()) |
| 8677 | } |
| 8678 | |
| 8679 | #[test] |
| 8680 | fn ollama_env_overrides_base_url_and_model() -> Result<()> { |
| 8681 | let _lock = lock_test_env(); |
| 8682 | let nanos = SystemTime::now() |
| 8683 | .duration_since(UNIX_EPOCH) |
| 8684 | .unwrap() |
| 8685 | .as_nanos(); |
| 8686 | let temp_root = env::temp_dir().join(format!( |
| 8687 | "codewhale-tui-ollama-env-test-{}-{}", |
| 8688 | std::process::id(), |
| 8689 | nanos |
| 8690 | )); |
| 8691 | fs::create_dir_all(&temp_root)?; |
| 8692 | let _guard = EnvGuard::new(&temp_root); |
| 8693 | |
| 8694 | // Safety: test-only environment mutation guarded by a global mutex. |
| 8695 | unsafe { |
| 8696 | env::set_var("DEEPSEEK_PROVIDER", "ollama-local"); |
| 8697 | env::set_var("OLLAMA_BASE_URL", "http://ollama.example/v1"); |
| 8698 | env::set_var("OLLAMA_MODEL", "deepseek-coder-v2:16b"); |
| 8699 | } |
| 8700 | |
| 8701 | let config = Config::load(None, None)?; |
| 8702 | assert_eq!( |
| 8703 | config.active_provider_identity().unwrap().provider, |
| 8704 | ProviderKind::Ollama |
| 8705 | ); |
| 8706 | assert_eq!(config.active_route_base_url(), "http://ollama.example/v1"); |
| 8707 | assert_eq!(config.default_model(), "deepseek-coder-v2:16b"); |
| 8708 | Ok(()) |
| 8709 | } |
| 8710 | |
| 8711 | #[test] |
| 8712 | fn openrouter_env_api_key_resolves_via_deepseek_api_key() -> Result<()> { |
| 8713 | let _lock = lock_test_env(); |
| 8714 | let nanos = SystemTime::now() |
| 8715 | .duration_since(UNIX_EPOCH) |
| 8716 | .unwrap() |
| 8717 | .as_nanos(); |
| 8718 | let temp_root = env::temp_dir().join(format!( |
| 8719 | "codewhale-tui-or-env-key-{}-{}", |
| 8720 | std::process::id(), |
| 8721 | nanos |
| 8722 | )); |
| 8723 | fs::create_dir_all(&temp_root)?; |
| 8724 | let _guard = EnvGuard::new(&temp_root); |
| 8725 | |
| 8726 | // Safety: test-only environment mutation guarded by a global mutex. |
| 8727 | unsafe { |
| 8728 | env::set_var("DEEPSEEK_PROVIDER", "openrouter"); |
| 8729 | env::set_var("OPENROUTER_API_KEY", "or-env-key"); |
| 8730 | env::set_var("OPENROUTER_MODEL", "deepseek-v4-flash"); |
| 8731 | } |
| 8732 | |
| 8733 | let config = Config::load(None, None)?; |
| 8734 | assert_eq!( |
| 8735 | config.active_provider_identity().unwrap().provider, |
| 8736 | ProviderKind::Openrouter |
| 8737 | ); |
| 8738 | assert_eq!(config.active_route_api_key()?, "or-env-key"); |
| 8739 | assert_eq!(config.default_model(), DEFAULT_OPENROUTER_FLASH_MODEL); |
| 8740 | Ok(()) |
| 8741 | } |
| 8742 | |
| 8743 | #[test] |
| 8744 | fn novita_env_api_key_resolves_via_deepseek_api_key() -> Result<()> { |
| 8745 | let _lock = lock_test_env(); |
| 8746 | let nanos = SystemTime::now() |
| 8747 | .duration_since(UNIX_EPOCH) |
| 8748 | .unwrap() |
| 8749 | .as_nanos(); |
| 8750 | let temp_root = env::temp_dir().join(format!( |
| 8751 | "codewhale-tui-novita-env-key-{}-{}", |
| 8752 | std::process::id(), |
| 8753 | nanos |
| 8754 | )); |
| 8755 | fs::create_dir_all(&temp_root)?; |
| 8756 | let _guard = EnvGuard::new(&temp_root); |
| 8757 | |
| 8758 | // Safety: test-only environment mutation guarded by a global mutex. |
| 8759 | unsafe { |
| 8760 | env::set_var("DEEPSEEK_PROVIDER", "novita"); |
| 8761 | env::set_var("NOVITA_API_KEY", "novita-env-key"); |
| 8762 | env::set_var("NOVITA_MODEL", "deepseek-v4-flash"); |
| 8763 | } |
| 8764 | |
| 8765 | let config = Config::load(None, None)?; |
| 8766 | assert_eq!( |
| 8767 | config.active_provider_identity().unwrap().provider, |
| 8768 | ProviderKind::Novita |
| 8769 | ); |
| 8770 | assert_eq!(config.active_route_api_key()?, "novita-env-key"); |
| 8771 | assert_eq!(config.default_model(), DEFAULT_NOVITA_FLASH_MODEL); |
| 8772 | Ok(()) |
| 8773 | } |
| 8774 | |
| 8775 | #[test] |
| 8776 | fn fireworks_env_overrides_key_and_model() -> Result<()> { |
| 8777 | let _lock = lock_test_env(); |
| 8778 | let nanos = SystemTime::now() |
| 8779 | .duration_since(UNIX_EPOCH) |
| 8780 | .unwrap() |
| 8781 | .as_nanos(); |
| 8782 | let temp_root = env::temp_dir().join(format!( |
| 8783 | "codewhale-tui-fireworks-env-key-{}-{}", |
| 8784 | std::process::id(), |
| 8785 | nanos |
| 8786 | )); |
| 8787 | fs::create_dir_all(&temp_root)?; |
| 8788 | let _guard = EnvGuard::new(&temp_root); |
| 8789 | |
| 8790 | // Safety: test-only environment mutation guarded by a global mutex. |
| 8791 | unsafe { |
| 8792 | env::set_var("DEEPSEEK_PROVIDER", "fireworks"); |
| 8793 | env::set_var("FIREWORKS_API_KEY", "fw-env-key"); |
| 8794 | env::set_var( |
| 8795 | "FIREWORKS_MODEL", |
| 8796 | "accounts/fireworks/models/account-specific-model", |
| 8797 | ); |
| 8798 | } |
| 8799 | |
| 8800 | let config = Config::load(None, None)?; |
| 8801 | assert_eq!( |
| 8802 | config.active_provider_identity().unwrap().provider, |
| 8803 | ProviderKind::Fireworks |
| 8804 | ); |
| 8805 | assert_eq!(config.active_route_api_key()?, "fw-env-key"); |
| 8806 | assert_eq!( |
| 8807 | config.default_model(), |
| 8808 | "accounts/fireworks/models/account-specific-model" |
| 8809 | ); |
| 8810 | Ok(()) |
| 8811 | } |
| 8812 | |
| 8813 | #[test] |
| 8814 | fn arcee_provider_uses_direct_defaults() -> Result<()> { |
| 8815 | let _lock = lock_test_env(); |
| 8816 | let nanos = SystemTime::now() |
| 8817 | .duration_since(UNIX_EPOCH) |
| 8818 | .unwrap() |
| 8819 | .as_nanos(); |
| 8820 | let temp_root = env::temp_dir().join(format!( |
| 8821 | "codewhale-tui-arcee-defaults-test-{}-{}", |
| 8822 | std::process::id(), |
| 8823 | nanos |
| 8824 | )); |
| 8825 | fs::create_dir_all(&temp_root)?; |
| 8826 | let _guard = EnvGuard::new(&temp_root); |
| 8827 | |
| 8828 | unsafe { |
| 8829 | env::set_var("CODEWHALE_PROVIDER", "arcee"); |
| 8830 | env::set_var("ARCEE_API_KEY", "arcee-env-key"); |
| 8831 | } |
| 8832 | |
| 8833 | let config = Config::load(None, None)?; |
| 8834 | assert_eq!( |
| 8835 | config.active_provider_identity().unwrap().provider, |
| 8836 | ProviderKind::Arcee |
| 8837 | ); |
| 8838 | assert_eq!(config.active_route_api_key()?, "arcee-env-key"); |
| 8839 | assert_eq!(config.active_route_base_url(), DEFAULT_ARCEE_BASE_URL); |
| 8840 | assert_eq!(config.default_model(), DEFAULT_ARCEE_MODEL); |
| 8841 | Ok(()) |
| 8842 | } |
| 8843 | |
| 8844 | #[test] |
| 8845 | fn arcee_provider_table_configures_direct_route() -> Result<()> { |
| 8846 | let _lock = lock_test_env(); |
| 8847 | let nanos = SystemTime::now() |
| 8848 | .duration_since(UNIX_EPOCH) |
| 8849 | .unwrap() |
| 8850 | .as_nanos(); |
| 8851 | let temp_root = env::temp_dir().join(format!( |
| 8852 | "codewhale-tui-arcee-table-test-{}-{}", |
| 8853 | std::process::id(), |
| 8854 | nanos |
| 8855 | )); |
| 8856 | let config_dir = temp_root.join(".deepseek"); |
| 8857 | fs::create_dir_all(&config_dir)?; |
| 8858 | let _guard = EnvGuard::new(&temp_root); |
| 8859 | fs::write( |
| 8860 | config_dir.join("config.toml"), |
| 8861 | r#" |
| 8862 | provider = "arcee" |
| 8863 | |
| 8864 | [providers.arcee] |
| 8865 | api_key = "arcee-file-key" |
| 8866 | base_url = "https://api.arcee.ai/api/v1" |
| 8867 | model = "arcee-trinity-large-preview" |
| 8868 | "#, |
| 8869 | )?; |
| 8870 | |
| 8871 | let config = Config::load(None, None)?; |
| 8872 | assert_eq!( |
| 8873 | config.active_provider_identity().unwrap().provider, |
| 8874 | ProviderKind::Arcee |
| 8875 | ); |
| 8876 | assert_eq!(config.active_route_api_key()?, "arcee-file-key"); |
| 8877 | assert_eq!(config.active_route_base_url(), DEFAULT_ARCEE_BASE_URL); |
| 8878 | assert_eq!(config.default_model(), ARCEE_TRINITY_LARGE_PREVIEW_MODEL); |
| 8879 | Ok(()) |
| 8880 | } |
| 8881 | |
| 8882 | #[test] |
| 8883 | fn siliconflow_cn_base_url_env_normalizes_model_aliases() -> Result<()> { |
| 8884 | let _lock = lock_test_env(); |
| 8885 | let nanos = SystemTime::now() |
| 8886 | .duration_since(UNIX_EPOCH) |
| 8887 | .unwrap() |
| 8888 | .as_nanos(); |
| 8889 | let temp_root = env::temp_dir().join(format!( |
| 8890 | "codewhale-tui-siliconflow-cn-env-test-{}-{}", |
| 8891 | std::process::id(), |
| 8892 | nanos |
| 8893 | )); |
| 8894 | fs::create_dir_all(&temp_root)?; |
| 8895 | let _guard = EnvGuard::new(&temp_root); |
| 8896 | |
| 8897 | // Safety: test-only environment mutation guarded by a global mutex. |
| 8898 | unsafe { |
| 8899 | env::set_var("CODEWHALE_PROVIDER", "siliconflow-CN"); |
| 8900 | env::set_var("SILICONFLOW_API_KEY", "sf-env-key"); |
| 8901 | env::set_var("SILICONFLOW_BASE_URL", "https://api.siliconflow.cn/v1"); |
| 8902 | env::set_var("SILICONFLOW_MODEL", "deepseek-reasoner"); |
| 8903 | } |
| 8904 | |
| 8905 | let config = Config::load(None, None)?; |
| 8906 | assert_eq!( |
| 8907 | config.active_provider_identity().unwrap().provider, |
| 8908 | ProviderKind::SiliconflowCN |
| 8909 | ); |
| 8910 | assert_eq!(config.active_route_api_key()?, "sf-env-key"); |
| 8911 | assert_eq!( |
| 8912 | config.active_route_base_url(), |
| 8913 | "https://api.siliconflow.cn/v1" |
| 8914 | ); |
| 8915 | assert_eq!(config.default_model(), DEFAULT_SILICONFLOW_MODEL); |
| 8916 | Ok(()) |
| 8917 | } |
| 8918 | |
| 8919 | #[test] |
| 8920 | fn openrouter_base_url_env_overrides_default() -> Result<()> { |
| 8921 | let _lock = lock_test_env(); |
| 8922 | let nanos = SystemTime::now() |
| 8923 | .duration_since(UNIX_EPOCH) |
| 8924 | .unwrap() |
| 8925 | .as_nanos(); |
| 8926 | let temp_root = env::temp_dir().join(format!( |
| 8927 | "codewhale-tui-or-base-url-{}-{}", |
| 8928 | std::process::id(), |
| 8929 | nanos |
| 8930 | )); |
| 8931 | fs::create_dir_all(&temp_root)?; |
| 8932 | let _guard = EnvGuard::new(&temp_root); |
| 8933 | |
| 8934 | // Safety: test-only environment mutation guarded by a global mutex. |
| 8935 | unsafe { |
| 8936 | env::set_var("DEEPSEEK_PROVIDER", "openrouter"); |
| 8937 | env::set_var("OPENROUTER_BASE_URL", "https://or-mirror.example/v1"); |
| 8938 | } |
| 8939 | |
| 8940 | let config = Config::load(None, None)?; |
| 8941 | assert_eq!( |
| 8942 | config.active_provider_identity().unwrap().provider, |
| 8943 | ProviderKind::Openrouter |
| 8944 | ); |
| 8945 | assert_eq!( |
| 8946 | config.active_route_base_url(), |
| 8947 | "https://or-mirror.example/v1" |
| 8948 | ); |
| 8949 | Ok(()) |
| 8950 | } |
| 8951 | |
| 8952 | #[test] |
| 8953 | fn openrouter_reads_provider_table_from_config_file() -> Result<()> { |
| 8954 | let _lock = lock_test_env(); |
| 8955 | let nanos = SystemTime::now() |
| 8956 | .duration_since(UNIX_EPOCH) |
| 8957 | .unwrap() |
| 8958 | .as_nanos(); |
| 8959 | let temp_root = env::temp_dir().join(format!( |
| 8960 | "codewhale-tui-or-table-{}-{}", |
| 8961 | std::process::id(), |
| 8962 | nanos |
| 8963 | )); |
| 8964 | fs::create_dir_all(&temp_root)?; |
| 8965 | let _guard = EnvGuard::new(&temp_root); |
| 8966 | |
| 8967 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 8968 | ensure_parent_dir(&config_path)?; |
| 8969 | fs::write( |
| 8970 | &config_path, |
| 8971 | r#"provider = "openrouter" |
| 8972 | |
| 8973 | [providers.openrouter] |
| 8974 | api_key = "or-table-key" |
| 8975 | base_url = "https://or-table.example/v1" |
| 8976 | "#, |
| 8977 | )?; |
| 8978 | |
| 8979 | let config = Config::load(None, None)?; |
| 8980 | assert_eq!( |
| 8981 | config.active_provider_identity().unwrap().provider, |
| 8982 | ProviderKind::Openrouter |
| 8983 | ); |
| 8984 | assert_eq!(config.active_route_api_key()?, "or-table-key"); |
| 8985 | assert_eq!( |
| 8986 | config.active_route_base_url(), |
| 8987 | "https://or-table.example/v1" |
| 8988 | ); |
| 8989 | Ok(()) |
| 8990 | } |
| 8991 | |
| 8992 | #[test] |
| 8993 | fn siliconflow_reads_provider_table_from_config_file() -> Result<()> { |
| 8994 | let _lock = lock_test_env(); |
| 8995 | let nanos = SystemTime::now() |
| 8996 | .duration_since(UNIX_EPOCH) |
| 8997 | .unwrap() |
| 8998 | .as_nanos(); |
| 8999 | let temp_root = env::temp_dir().join(format!( |
| 9000 | "codewhale-tui-siliconflow-table-{}-{}", |
| 9001 | std::process::id(), |
| 9002 | nanos |
| 9003 | )); |
| 9004 | fs::create_dir_all(&temp_root)?; |
| 9005 | let _guard = EnvGuard::new(&temp_root); |
| 9006 | |
| 9007 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9008 | ensure_parent_dir(&config_path)?; |
| 9009 | fs::write( |
| 9010 | &config_path, |
| 9011 | r#"provider = "siliconflow" |
| 9012 | |
| 9013 | [providers.siliconflow] |
| 9014 | api_key = "sf-table-key" |
| 9015 | model = "deepseek-v4-flash" |
| 9016 | "#, |
| 9017 | )?; |
| 9018 | |
| 9019 | let config = Config::load(None, None)?; |
| 9020 | assert_eq!( |
| 9021 | config.active_provider_identity().unwrap().provider, |
| 9022 | ProviderKind::Siliconflow |
| 9023 | ); |
| 9024 | assert_eq!(config.active_route_api_key()?, "sf-table-key"); |
| 9025 | assert_eq!(config.active_route_base_url(), DEFAULT_SILICONFLOW_BASE_URL); |
| 9026 | assert_eq!(config.default_model(), DEFAULT_SILICONFLOW_FLASH_MODEL); |
| 9027 | Ok(()) |
| 9028 | } |
| 9029 | |
| 9030 | #[test] |
| 9031 | fn siliconflow_cn_preserves_reported_deepseek_prefixed_v4_route() -> Result<()> { |
| 9032 | let _lock = lock_test_env(); |
| 9033 | let nanos = SystemTime::now() |
| 9034 | .duration_since(UNIX_EPOCH) |
| 9035 | .unwrap() |
| 9036 | .as_nanos(); |
| 9037 | let temp_root = env::temp_dir().join(format!( |
| 9038 | "codewhale-tui-siliconflow-cn-v4-report-{}-{}", |
| 9039 | std::process::id(), |
| 9040 | nanos |
| 9041 | )); |
| 9042 | fs::create_dir_all(&temp_root)?; |
| 9043 | let _guard = EnvGuard::new(&temp_root); |
| 9044 | |
| 9045 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9046 | ensure_parent_dir(&config_path)?; |
| 9047 | fs::write( |
| 9048 | &config_path, |
| 9049 | r#"provider = "siliconflow-CN" |
| 9050 | |
| 9051 | [providers.siliconflow-CN] |
| 9052 | api_key = "sf-cn-table-key" |
| 9053 | base_url = "https://api.siliconflow.cn/v1" |
| 9054 | model = "deepseek-ai/DeepSeek-V4-Pro" |
| 9055 | "#, |
| 9056 | )?; |
| 9057 | |
| 9058 | let config = Config::load(None, None)?; |
| 9059 | assert_eq!( |
| 9060 | config.active_provider_identity().unwrap().provider, |
| 9061 | ProviderKind::SiliconflowCN |
| 9062 | ); |
| 9063 | assert_ne!( |
| 9064 | config.active_provider_identity().unwrap().provider, |
| 9065 | ProviderKind::Deepseek |
| 9066 | ); |
| 9067 | assert_eq!(config.active_route_api_key()?, "sf-cn-table-key"); |
| 9068 | assert_eq!( |
| 9069 | config.active_route_base_url(), |
| 9070 | DEFAULT_SILICONFLOW_CN_BASE_URL |
| 9071 | ); |
| 9072 | assert_eq!(config.default_model(), DEFAULT_SILICONFLOW_MODEL); |
| 9073 | assert_eq!( |
| 9074 | codewhale_config::route::resolve_model( |
| 9075 | config.active_provider_identity().unwrap().provider, |
| 9076 | &config.default_model(), |
| 9077 | None, |
| 9078 | ) |
| 9079 | .unwrap() |
| 9080 | .wire_id, |
| 9081 | DEFAULT_SILICONFLOW_MODEL |
| 9082 | ); |
| 9083 | Ok(()) |
| 9084 | } |
| 9085 | |
| 9086 | #[test] |
| 9087 | fn siliconflow_cn_falls_back_to_shared_siliconflow_table_when_unset() -> Result<()> { |
| 9088 | let _lock = lock_test_env(); |
| 9089 | let nanos = SystemTime::now() |
| 9090 | .duration_since(UNIX_EPOCH) |
| 9091 | .unwrap() |
| 9092 | .as_nanos(); |
| 9093 | let temp_root = env::temp_dir().join(format!( |
| 9094 | "codewhale-tui-siliconflow-cn-fallback-{}-{}", |
| 9095 | std::process::id(), |
| 9096 | nanos |
| 9097 | )); |
| 9098 | fs::create_dir_all(&temp_root)?; |
| 9099 | let _guard = EnvGuard::new(&temp_root); |
| 9100 | |
| 9101 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9102 | ensure_parent_dir(&config_path)?; |
| 9103 | fs::write( |
| 9104 | &config_path, |
| 9105 | r#"provider = "siliconflow-CN" |
| 9106 | |
| 9107 | [providers.siliconflow] |
| 9108 | api_key = "sf-shared-key" |
| 9109 | base_url = "https://api.siliconflow.com/v1" |
| 9110 | model = "deepseek-chat" |
| 9111 | |
| 9112 | [providers.siliconflow_cn] |
| 9113 | base_url = "https://api.siliconflow.cn/v1" |
| 9114 | "#, |
| 9115 | )?; |
| 9116 | |
| 9117 | let config = Config::load(None, None)?; |
| 9118 | assert_eq!( |
| 9119 | config.active_provider_identity().unwrap().provider, |
| 9120 | ProviderKind::SiliconflowCN |
| 9121 | ); |
| 9122 | assert_eq!(config.active_route_api_key()?, "sf-shared-key"); |
| 9123 | assert_eq!( |
| 9124 | config.active_route_base_url(), |
| 9125 | DEFAULT_SILICONFLOW_CN_BASE_URL |
| 9126 | ); |
| 9127 | assert_eq!(config.default_model(), DEFAULT_SILICONFLOW_FLASH_MODEL); |
| 9128 | assert!(active_provider_has_config_api_key(&config)); |
| 9129 | Ok(()) |
| 9130 | } |
| 9131 | |
| 9132 | #[test] |
| 9133 | fn siliconflow_cn_env_overrides_write_cn_table_only() -> Result<()> { |
| 9134 | let _lock = lock_test_env(); |
| 9135 | let nanos = SystemTime::now() |
| 9136 | .duration_since(UNIX_EPOCH) |
| 9137 | .unwrap() |
| 9138 | .as_nanos(); |
| 9139 | let temp_root = env::temp_dir().join(format!( |
| 9140 | "codewhale-tui-siliconflow-cn-env-table-{}-{}", |
| 9141 | std::process::id(), |
| 9142 | nanos |
| 9143 | )); |
| 9144 | fs::create_dir_all(&temp_root)?; |
| 9145 | let _guard = EnvGuard::new(&temp_root); |
| 9146 | |
| 9147 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9148 | ensure_parent_dir(&config_path)?; |
| 9149 | fs::write( |
| 9150 | &config_path, |
| 9151 | r#"provider = "siliconflow-CN" |
| 9152 | |
| 9153 | [providers.siliconflow] |
| 9154 | api_key = "sf-shared-key" |
| 9155 | base_url = "https://api.siliconflow.com/v1" |
| 9156 | model = "deepseek-reasoner" |
| 9157 | "#, |
| 9158 | )?; |
| 9159 | unsafe { |
| 9160 | env::set_var("SILICONFLOW_BASE_URL", "https://api.siliconflow.cn/v1"); |
| 9161 | env::set_var("SILICONFLOW_MODEL", "deepseek-chat"); |
| 9162 | } |
| 9163 | |
| 9164 | let config = Config::load(None, None)?; |
| 9165 | let providers = config.providers.as_ref().expect("providers"); |
| 9166 | assert_eq!( |
| 9167 | providers.siliconflow.base_url.as_deref(), |
| 9168 | Some(DEFAULT_SILICONFLOW_BASE_URL) |
| 9169 | ); |
| 9170 | assert_eq!( |
| 9171 | providers.siliconflow.model.as_deref(), |
| 9172 | Some(DEFAULT_SILICONFLOW_MODEL) |
| 9173 | ); |
| 9174 | assert_eq!( |
| 9175 | providers.siliconflow_cn.base_url.as_deref(), |
| 9176 | Some(DEFAULT_SILICONFLOW_CN_BASE_URL) |
| 9177 | ); |
| 9178 | assert_eq!( |
| 9179 | providers.siliconflow_cn.model.as_deref(), |
| 9180 | Some(DEFAULT_SILICONFLOW_FLASH_MODEL) |
| 9181 | ); |
| 9182 | assert_eq!(config.active_route_api_key()?, "sf-shared-key"); |
| 9183 | assert_eq!(config.default_model(), DEFAULT_SILICONFLOW_FLASH_MODEL); |
| 9184 | Ok(()) |
| 9185 | } |
| 9186 | |
| 9187 | #[test] |
| 9188 | fn openrouter_custom_base_url_preserves_provider_model() -> Result<()> { |
| 9189 | let _lock = lock_test_env(); |
| 9190 | let nanos = SystemTime::now() |
| 9191 | .duration_since(UNIX_EPOCH) |
| 9192 | .unwrap() |
| 9193 | .as_nanos(); |
| 9194 | let temp_root = env::temp_dir().join(format!( |
| 9195 | "codewhale-tui-or-custom-model-{}-{}", |
| 9196 | std::process::id(), |
| 9197 | nanos |
| 9198 | )); |
| 9199 | fs::create_dir_all(&temp_root)?; |
| 9200 | let _guard = EnvGuard::new(&temp_root); |
| 9201 | |
| 9202 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9203 | ensure_parent_dir(&config_path)?; |
| 9204 | fs::write( |
| 9205 | &config_path, |
| 9206 | r#"provider = "openrouter" |
| 9207 | |
| 9208 | [providers.openrouter] |
| 9209 | api_key = "or-table-key" |
| 9210 | base_url = "https://gateway.example.com/v1" |
| 9211 | model = "DeepSeek-V4-Pro" |
| 9212 | "#, |
| 9213 | )?; |
| 9214 | |
| 9215 | let config = Config::load(None, None)?; |
| 9216 | assert_eq!( |
| 9217 | config.active_provider_identity().unwrap().provider, |
| 9218 | ProviderKind::Openrouter |
| 9219 | ); |
| 9220 | assert_eq!(config.active_route_api_key()?, "or-table-key"); |
| 9221 | assert_eq!( |
| 9222 | config.active_route_base_url(), |
| 9223 | "https://gateway.example.com/v1" |
| 9224 | ); |
| 9225 | assert_eq!(config.default_model(), "DeepSeek-V4-Pro"); |
| 9226 | Ok(()) |
| 9227 | } |
| 9228 | |
| 9229 | #[test] |
| 9230 | fn novita_reads_provider_table_from_config_file() -> Result<()> { |
| 9231 | let _lock = lock_test_env(); |
| 9232 | let nanos = SystemTime::now() |
| 9233 | .duration_since(UNIX_EPOCH) |
| 9234 | .unwrap() |
| 9235 | .as_nanos(); |
| 9236 | let temp_root = env::temp_dir().join(format!( |
| 9237 | "codewhale-tui-novita-table-{}-{}", |
| 9238 | std::process::id(), |
| 9239 | nanos |
| 9240 | )); |
| 9241 | fs::create_dir_all(&temp_root)?; |
| 9242 | let _guard = EnvGuard::new(&temp_root); |
| 9243 | |
| 9244 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9245 | ensure_parent_dir(&config_path)?; |
| 9246 | fs::write( |
| 9247 | &config_path, |
| 9248 | r#"provider = "novita" |
| 9249 | |
| 9250 | [providers.novita] |
| 9251 | api_key = "novita-table-key" |
| 9252 | "#, |
| 9253 | )?; |
| 9254 | |
| 9255 | let config = Config::load(None, None)?; |
| 9256 | assert_eq!( |
| 9257 | config.active_provider_identity().unwrap().provider, |
| 9258 | ProviderKind::Novita |
| 9259 | ); |
| 9260 | assert_eq!(config.active_route_api_key()?, "novita-table-key"); |
| 9261 | assert_eq!(config.active_route_base_url(), DEFAULT_NOVITA_BASE_URL); |
| 9262 | Ok(()) |
| 9263 | } |
| 9264 | |
| 9265 | #[test] |
| 9266 | fn moonshot_credential_help_keeps_direct_and_kimi_code_routes_distinct() { |
| 9267 | let direct = |
| 9268 | credential_help_for_provider_route(ProviderKind::Moonshot, DEFAULT_MOONSHOT_BASE_URL); |
| 9269 | assert_eq!( |
| 9270 | direct.credential_url, |
| 9271 | Some("https://platform.kimi.ai/console/api-keys") |
| 9272 | ); |
| 9273 | assert_eq!( |
| 9274 | direct.docs_url, |
| 9275 | Some("https://platform.kimi.ai/docs/overview") |
| 9276 | ); |
| 9277 | |
| 9278 | let kimi_code = |
| 9279 | credential_help_for_provider_route(ProviderKind::Moonshot, DEFAULT_KIMI_CODE_BASE_URL); |
| 9280 | assert_eq!( |
| 9281 | kimi_code.credential_url, |
| 9282 | Some(KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL) |
| 9283 | ); |
| 9284 | assert_eq!(kimi_code.docs_url, None); |
| 9285 | assert!(kimi_code.guidance.contains("membership-plan API key")); |
| 9286 | assert!( |
| 9287 | kimi_code |
| 9288 | .guidance |
| 9289 | .contains("does not import Kimi CLI credentials") |
| 9290 | ); |
| 9291 | } |
| 9292 | |
| 9293 | #[test] |
| 9294 | fn codex_read_only_consent_reads_exact_file_without_mutation() -> Result<()> { |
| 9295 | let _lock = lock_test_env(); |
| 9296 | let temp = tempfile::tempdir()?; |
| 9297 | let temp_root = temp.path().canonicalize()?; |
| 9298 | let auth_path = temp_root.join("codex-auth.json"); |
| 9299 | let token = crate::test_support::future_test_jwt("codex"); |
| 9300 | let raw = serde_json::to_string_pretty(&json!({ |
| 9301 | "tokens": { |
| 9302 | "access_token": token.clone(), |
| 9303 | "account_id": "acct-read-only", |
| 9304 | "refresh_token": "must-never-be-used", |
| 9305 | "future_field": ["preserve"] |
| 9306 | }, |
| 9307 | "future_top_level": true |
| 9308 | }))?; |
| 9309 | fs::write(&auth_path, &raw)?; |
| 9310 | let ambient_decoy = temp_root.join("ambient-decoy.json"); |
| 9311 | let ambient_decoy_raw = r#"{"tokens":{"access_token":"must-not-be-read"}}"#; |
| 9312 | fs::write(&ambient_decoy, ambient_decoy_raw)?; |
| 9313 | let _auth_path = EnvVarGuard::set("OPENAI_CODEX_AUTH_FILE", &ambient_decoy); |
| 9314 | let _access = EnvVarGuard::remove("OPENAI_CODEX_ACCESS_TOKEN"); |
| 9315 | let _legacy_access = EnvVarGuard::remove("CODEX_ACCESS_TOKEN"); |
| 9316 | let config = Config { |
| 9317 | provider: Some(ProviderKind::OpenaiCodex.as_str().to_string()), |
| 9318 | providers: Some(ProvidersConfig { |
| 9319 | openai_codex: ProviderConfig { |
| 9320 | auth_mode: Some("oauth".to_string()), |
| 9321 | external_credentials: Some( |
| 9322 | codewhale_config::ExternalCredentialConsentToml::read_only( |
| 9323 | codewhale_config::ProviderKind::OpenaiCodex, |
| 9324 | codewhale_config::ExternalCredentialSource::CodexCli, |
| 9325 | auth_path.clone(), |
| 9326 | ), |
| 9327 | ), |
| 9328 | ..Default::default() |
| 9329 | }, |
| 9330 | ..Default::default() |
| 9331 | }), |
| 9332 | ..Default::default() |
| 9333 | }; |
| 9334 | |
| 9335 | let mut inactive = config.clone(); |
| 9336 | inactive.provider = Some(ProviderKind::Deepseek.as_str().to_string()); |
| 9337 | crate::external_credentials::reset_side_effect_trap(); |
| 9338 | assert!(inactive.external_credential_read_consent_configured( |
| 9339 | &inactive.test_identity_for_kind(ProviderKind::OpenaiCodex), |
| 9340 | codewhale_config::ExternalCredentialSource::CodexCli, |
| 9341 | )); |
| 9342 | let dormant_error = inactive |
| 9343 | .external_credential_read_grant( |
| 9344 | &inactive.test_identity_for_kind(ProviderKind::OpenaiCodex), |
| 9345 | codewhale_config::ExternalCredentialSource::CodexCli, |
| 9346 | &ambient_decoy, |
| 9347 | ) |
| 9348 | .expect_err("inactive providers cannot mint external read capabilities"); |
| 9349 | assert!(dormant_error.to_string().contains("explicitly selected")); |
| 9350 | assert_eq!( |
| 9351 | crate::external_credentials::side_effect_trap_counts(), |
| 9352 | (0, 0) |
| 9353 | ); |
| 9354 | |
| 9355 | let active_grant = config.external_credential_read_grant( |
| 9356 | &config.test_identity_for_kind(ProviderKind::OpenaiCodex), |
| 9357 | codewhale_config::ExternalCredentialSource::CodexCli, |
| 9358 | &ambient_decoy, |
| 9359 | )?; |
| 9360 | assert_eq!( |
| 9361 | active_grant.path(), |
| 9362 | auth_path, |
| 9363 | "the selected route remains pinned to the persisted consent path" |
| 9364 | ); |
| 9365 | |
| 9366 | crate::external_credentials::reset_side_effect_trap(); |
| 9367 | assert!(config.active_route_api_key().is_err()); |
| 9368 | assert_eq!( |
| 9369 | crate::external_credentials::side_effect_trap_counts(), |
| 9370 | (0, 0) |
| 9371 | ); |
| 9372 | assert_eq!(fs::read_to_string(&auth_path)?, raw); |
| 9373 | assert_eq!(fs::read_to_string(&ambient_decoy)?, ambient_decoy_raw); |
| 9374 | |
| 9375 | drop(_access); |
| 9376 | let _process_access = EnvVarGuard::set("OPENAI_CODEX_ACCESS_TOKEN", "process-token"); |
| 9377 | crate::external_credentials::reset_side_effect_trap(); |
| 9378 | assert!(config.active_route_api_key().is_err()); |
| 9379 | assert_eq!(config.codex_account_id(), None); |
| 9380 | assert_eq!( |
| 9381 | crate::external_credentials::side_effect_trap_counts(), |
| 9382 | (0, 0), |
| 9383 | "external tokens must never substitute for Codewhale-issued plan access" |
| 9384 | ); |
| 9385 | Ok(()) |
| 9386 | } |
| 9387 | |
| 9388 | #[test] |
| 9389 | fn moonshot_kimi_code_missing_key_reports_membership_plan_console() -> Result<()> { |
| 9390 | let _lock = lock_test_env(); |
| 9391 | let temp = tempfile::tempdir()?; |
| 9392 | let _guard = EnvGuard::new(temp.path()); |
| 9393 | let config = Config { |
| 9394 | provider: Some(ProviderKind::Moonshot.as_str().to_string()), |
| 9395 | providers: Some(ProvidersConfig { |
| 9396 | moonshot: ProviderConfig { |
| 9397 | base_url: Some(DEFAULT_KIMI_CODE_BASE_URL.to_string()), |
| 9398 | model: Some(KIMI_CODE_K3_MODEL.to_string()), |
| 9399 | ..Default::default() |
| 9400 | }, |
| 9401 | ..Default::default() |
| 9402 | }), |
| 9403 | ..Default::default() |
| 9404 | }; |
| 9405 | |
| 9406 | let error = config |
| 9407 | .active_route_api_key() |
| 9408 | .expect_err("Kimi Code route needs a membership-plan API key"); |
| 9409 | let message = error.to_string(); |
| 9410 | assert!( |
| 9411 | message.contains(KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL), |
| 9412 | "{message}" |
| 9413 | ); |
| 9414 | assert!(message.contains("api.kimi.com/coding/v1"), "{message}"); |
| 9415 | assert!( |
| 9416 | message.contains("does not import Kimi CLI credentials"), |
| 9417 | "{message}" |
| 9418 | ); |
| 9419 | assert!(!message.contains("https://platform.kimi.ai/console/api-keys")); |
| 9420 | Ok(()) |
| 9421 | } |
| 9422 | |
| 9423 | #[test] |
| 9424 | fn moonshot_kimi_code_saved_claude_k3_1m_alias_fails_with_api_model_guidance() -> Result<()> { |
| 9425 | let _lock = lock_test_env(); |
| 9426 | let temp = tempfile::tempdir()?; |
| 9427 | let _guard = EnvGuard::new(temp.path()); |
| 9428 | let config_path = temp.path().join(".deepseek").join("config.toml"); |
| 9429 | ensure_parent_dir(&config_path)?; |
| 9430 | fs::write( |
| 9431 | &config_path, |
| 9432 | r#"provider = "moonshot" |
| 9433 | |
| 9434 | [providers.moonshot] |
| 9435 | api_key = "kimi-code-key" |
| 9436 | base_url = "https://api.kimi.com/coding/v1" |
| 9437 | model = "k3[1m]" |
| 9438 | "#, |
| 9439 | )?; |
| 9440 | |
| 9441 | let error = Config::load(None, None) |
| 9442 | .expect_err("saved Claude Code context hints must not become API model ids"); |
| 9443 | let message = error.to_string(); |
| 9444 | assert!(message.contains("model = \"k3\""), "{message}"); |
| 9445 | assert!(message.contains("context_window = 1048576"), "{message}"); |
| 9446 | assert!(message.contains("plan includes 1M context"), "{message}"); |
| 9447 | assert!(message.contains("262144 safe default"), "{message}"); |
| 9448 | Ok(()) |
| 9449 | } |
| 9450 | |
| 9451 | /// Regression for issue #2160: a stale root `default_text_model` carried |
| 9452 | /// over from a DeepSeek setup must not steer the Kimi Code endpoint to |
| 9453 | /// `deepseek-v4-pro`. The user-facing trigger here is the legacy |
| 9454 | /// `DEEPSEEK_PROVIDER` env var (still produced by the `codewhale |
| 9455 | /// --provider moonshot` dispatcher for compat); the test also has a |
| 9456 | /// `CODEWHALE_PROVIDER` twin below for the public env path. |
| 9457 | #[test] |
| 9458 | fn moonshot_kimi_code_model_overrides_root_deepseek_default() -> Result<()> { |
| 9459 | let _lock = lock_test_env(); |
| 9460 | let nanos = SystemTime::now() |
| 9461 | .duration_since(UNIX_EPOCH) |
| 9462 | .unwrap() |
| 9463 | .as_nanos(); |
| 9464 | let temp_root = env::temp_dir().join(format!( |
| 9465 | "codewhale-tui-kimi-code-root-model-{}-{}", |
| 9466 | std::process::id(), |
| 9467 | nanos |
| 9468 | )); |
| 9469 | fs::create_dir_all(&temp_root)?; |
| 9470 | let _guard = EnvGuard::new(&temp_root); |
| 9471 | |
| 9472 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9473 | ensure_parent_dir(&config_path)?; |
| 9474 | fs::write( |
| 9475 | &config_path, |
| 9476 | r#"provider = "deepseek" |
| 9477 | default_text_model = "deepseek-v4-pro" |
| 9478 | |
| 9479 | [providers.moonshot] |
| 9480 | api_key = "kimi-code-key" |
| 9481 | base_url = "https://api.kimi.com/coding/v1" |
| 9482 | "#, |
| 9483 | )?; |
| 9484 | // Safety: test-only env mutation guarded by lock_test_env(). |
| 9485 | unsafe { env::set_var("DEEPSEEK_PROVIDER", "moonshot") }; |
| 9486 | |
| 9487 | let config = Config::load(None, None)?; |
| 9488 | assert_eq!( |
| 9489 | config.active_provider_identity().unwrap().provider, |
| 9490 | ProviderKind::Moonshot |
| 9491 | ); |
| 9492 | assert_eq!(config.active_route_base_url(), DEFAULT_KIMI_CODE_BASE_URL); |
| 9493 | assert_eq!(config.default_model(), DEFAULT_KIMI_CODE_MODEL); |
| 9494 | Ok(()) |
| 9495 | } |
| 9496 | |
| 9497 | /// Same regression as above, but driven by the public `CODEWHALE_PROVIDER` |
| 9498 | /// env var. Documents the recommended user-facing setup path: never |
| 9499 | /// `DEEPSEEK_PROVIDER=moonshot`, always `CODEWHALE_PROVIDER=moonshot` |
| 9500 | /// (or `codewhale --provider moonshot`, which also resolves through |
| 9501 | /// this code path internally). |
| 9502 | #[test] |
| 9503 | fn moonshot_kimi_code_model_resolves_via_codewhale_provider_env() -> Result<()> { |
| 9504 | let _lock = lock_test_env(); |
| 9505 | let nanos = SystemTime::now() |
| 9506 | .duration_since(UNIX_EPOCH) |
| 9507 | .unwrap() |
| 9508 | .as_nanos(); |
| 9509 | let temp_root = env::temp_dir().join(format!( |
| 9510 | "codewhale-tui-kimi-code-cw-env-{}-{}", |
| 9511 | std::process::id(), |
| 9512 | nanos |
| 9513 | )); |
| 9514 | fs::create_dir_all(&temp_root)?; |
| 9515 | let _guard = EnvGuard::new(&temp_root); |
| 9516 | |
| 9517 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9518 | ensure_parent_dir(&config_path)?; |
| 9519 | fs::write( |
| 9520 | &config_path, |
| 9521 | r#"provider = "deepseek" |
| 9522 | default_text_model = "deepseek-v4-pro" |
| 9523 | |
| 9524 | [providers.moonshot] |
| 9525 | api_key = "kimi-code-key" |
| 9526 | base_url = "https://api.kimi.com/coding/v1" |
| 9527 | "#, |
| 9528 | )?; |
| 9529 | // Safety: test-only env mutation guarded by lock_test_env(). |
| 9530 | unsafe { env::set_var("CODEWHALE_PROVIDER", "moonshot") }; |
| 9531 | |
| 9532 | let config = Config::load(None, None)?; |
| 9533 | assert_eq!( |
| 9534 | config.active_provider_identity().unwrap().provider, |
| 9535 | ProviderKind::Moonshot |
| 9536 | ); |
| 9537 | assert_eq!(config.active_route_base_url(), DEFAULT_KIMI_CODE_BASE_URL); |
| 9538 | assert_eq!(config.default_model(), DEFAULT_KIMI_CODE_MODEL); |
| 9539 | Ok(()) |
| 9540 | } |
| 9541 | |
| 9542 | /// `CODEWHALE_PROVIDER` wins when both it and the legacy |
| 9543 | /// `DEEPSEEK_PROVIDER` are set, so a user adding the new alias to their |
| 9544 | /// shell isn't surprised by a stale legacy export. |
| 9545 | #[test] |
| 9546 | fn codewhale_provider_env_takes_precedence_over_deepseek_provider() -> Result<()> { |
| 9547 | let _lock = lock_test_env(); |
| 9548 | let nanos = SystemTime::now() |
| 9549 | .duration_since(UNIX_EPOCH) |
| 9550 | .unwrap() |
| 9551 | .as_nanos(); |
| 9552 | let temp_root = env::temp_dir().join(format!( |
| 9553 | "codewhale-tui-cw-vs-ds-provider-{}-{}", |
| 9554 | std::process::id(), |
| 9555 | nanos |
| 9556 | )); |
| 9557 | fs::create_dir_all(&temp_root)?; |
| 9558 | let _guard = EnvGuard::new(&temp_root); |
| 9559 | |
| 9560 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9561 | ensure_parent_dir(&config_path)?; |
| 9562 | fs::write(&config_path, "provider = \"deepseek\"\n")?; |
| 9563 | // Safety: test-only env mutation guarded by lock_test_env(). |
| 9564 | unsafe { |
| 9565 | env::set_var("CODEWHALE_PROVIDER", "moonshot"); |
| 9566 | env::set_var("DEEPSEEK_PROVIDER", "openrouter"); |
| 9567 | } |
| 9568 | |
| 9569 | let config = Config::load(None, None)?; |
| 9570 | assert_eq!( |
| 9571 | config.active_provider_identity().unwrap().provider, |
| 9572 | ProviderKind::Moonshot |
| 9573 | ); |
| 9574 | Ok(()) |
| 9575 | } |
| 9576 | |
| 9577 | /// Moonshot Platform path: when [providers.moonshot] is empty (or |
| 9578 | /// missing) and no Kimi Code endpoint is configured, the resolver |
| 9579 | /// defaults to the Moonshot Platform base URL and the latest Kimi platform |
| 9580 | /// model. This is the "I have a Moonshot Platform API key, not a |
| 9581 | /// Kimi Code plan key" path. |
| 9582 | #[test] |
| 9583 | fn moonshot_platform_defaults_to_kimi_k27_code() -> Result<()> { |
| 9584 | let _lock = lock_test_env(); |
| 9585 | let nanos = SystemTime::now() |
| 9586 | .duration_since(UNIX_EPOCH) |
| 9587 | .unwrap() |
| 9588 | .as_nanos(); |
| 9589 | let temp_root = env::temp_dir().join(format!( |
| 9590 | "codewhale-tui-moonshot-platform-{}-{}", |
| 9591 | std::process::id(), |
| 9592 | nanos |
| 9593 | )); |
| 9594 | fs::create_dir_all(&temp_root)?; |
| 9595 | let _guard = EnvGuard::new(&temp_root); |
| 9596 | |
| 9597 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9598 | ensure_parent_dir(&config_path)?; |
| 9599 | fs::write( |
| 9600 | &config_path, |
| 9601 | r#"provider = "moonshot" |
| 9602 | |
| 9603 | [providers.moonshot] |
| 9604 | api_key = "moonshot-platform-key" |
| 9605 | "#, |
| 9606 | )?; |
| 9607 | |
| 9608 | let config = Config::load(None, None)?; |
| 9609 | assert_eq!( |
| 9610 | config.active_provider_identity().unwrap().provider, |
| 9611 | ProviderKind::Moonshot |
| 9612 | ); |
| 9613 | assert_eq!(config.active_route_base_url(), DEFAULT_MOONSHOT_BASE_URL); |
| 9614 | assert_eq!(config.default_model(), DEFAULT_MOONSHOT_MODEL); |
| 9615 | assert_eq!(config.active_route_api_key()?, "moonshot-platform-key"); |
| 9616 | Ok(()) |
| 9617 | } |
| 9618 | |
| 9619 | #[test] |
| 9620 | fn xai_invalid_owned_generation_blocks_external_and_uses_api_key_fallback() -> Result<()> { |
| 9621 | let _lock = lock_test_env(); |
| 9622 | let root = tempfile::tempdir()?; |
| 9623 | let root = root.path().canonicalize()?; |
| 9624 | let external_path = root.join("grok-auth.json"); |
| 9625 | let external_raw = r#"{"token":"external-owner-bytes-must-not-be-read"}"#; |
| 9626 | fs::write(&external_path, external_raw)?; |
| 9627 | let _home = EnvVarGuard::set("CODEWHALE_HOME", &root); |
| 9628 | let _auth_path = EnvVarGuard::set("GROK_AUTH_PATH", &external_path); |
| 9629 | let _xai_key = EnvVarGuard::remove("XAI_API_KEY"); |
| 9630 | let _xai_base_url = EnvVarGuard::remove("XAI_BASE_URL"); |
| 9631 | |
| 9632 | let mut providers = ProvidersConfig::default(); |
| 9633 | providers.xai.api_key = Some("fake-xai-cfg-key".to_string()); |
| 9634 | providers.xai.auth_mode = Some("oauth".to_string()); |
| 9635 | providers.xai.oauth_credential_generation = Some("../unsafe.json".to_string()); |
| 9636 | providers.xai.external_credentials = |
| 9637 | Some(codewhale_config::ExternalCredentialConsentToml::read_only( |
| 9638 | codewhale_config::ProviderKind::Xai, |
| 9639 | codewhale_config::ExternalCredentialSource::GrokCli, |
| 9640 | external_path.clone(), |
| 9641 | )); |
| 9642 | let config = Config { |
| 9643 | provider: Some(ProviderKind::Xai.as_str().to_string()), |
| 9644 | providers: Some(providers), |
| 9645 | ..Config::default() |
| 9646 | }; |
| 9647 | |
| 9648 | crate::external_credentials::reset_side_effect_trap(); |
| 9649 | assert!( |
| 9650 | !crate::oauth::credentials_present(crate::oauth::OAuthProvider::Xai, &config), |
| 9651 | "an invalid owned generation pointer must not resolve external OAuth" |
| 9652 | ); |
| 9653 | assert_eq!(config.active_route_api_key()?, "fake-xai-cfg-key"); |
| 9654 | assert_eq!( |
| 9655 | crate::external_credentials::side_effect_trap_counts(), |
| 9656 | (0, 0), |
| 9657 | "an unusable owned generation must not access the external Grok CLI" |
| 9658 | ); |
| 9659 | assert_eq!(fs::read_to_string(external_path)?, external_raw); |
| 9660 | Ok(()) |
| 9661 | } |
| 9662 | |
| 9663 | /// #6528 — a key pasted with a BOM, zero-width characters, NBSP or internal |
| 9664 | /// whitespace is saved clean, and an ambient env key is normalized and named |
| 9665 | /// as the source the runtime resolver used. |
| 9666 | #[test] |
| 9667 | fn pasted_key_is_saved_clean_and_env_source_is_named() -> Result<()> { |
| 9668 | let _lock = lock_test_env(); |
| 9669 | let nanos = SystemTime::now() |
| 9670 | .duration_since(UNIX_EPOCH) |
| 9671 | .unwrap() |
| 9672 | .as_nanos(); |
| 9673 | let temp_root = env::temp_dir().join(format!( |
| 9674 | "codewhale-tui-pasted-key-{}-{}", |
| 9675 | std::process::id(), |
| 9676 | nanos |
| 9677 | )); |
| 9678 | fs::create_dir_all(&temp_root)?; |
| 9679 | let _guard = EnvGuard::new(&temp_root); |
| 9680 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9681 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 9682 | let _secret_backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "local"); |
| 9683 | |
| 9684 | let path = save_api_key_for( |
| 9685 | ProviderKind::Openrouter, |
| 9686 | "\u{feff}or-\u{200b}pasted\u{a0}key \u{2060}\n", |
| 9687 | )?; |
| 9688 | let parsed: toml::Value = toml::from_str(&fs::read_to_string(&path)?)?; |
| 9689 | assert_eq!( |
| 9690 | parsed |
| 9691 | .get("providers") |
| 9692 | .and_then(|p| p.get("openrouter")) |
| 9693 | .and_then(|t| t.get("api_key")) |
| 9694 | .and_then(toml::Value::as_str), |
| 9695 | Some("or-pastedkey") |
| 9696 | ); |
| 9697 | |
| 9698 | let _env_key = EnvVarGuard::set("OPENROUTER_API_KEY", "\u{feff}or-env\u{200d}key\u{a0}"); |
| 9699 | let config = Config { |
| 9700 | provider: Some("openrouter".to_string()), |
| 9701 | ..Config::default() |
| 9702 | }; |
| 9703 | let (key, source) = config.active_route_api_key_with_source()?; |
| 9704 | assert_eq!(key, "or-envkey"); |
| 9705 | assert_eq!(source, "env var OPENROUTER_API_KEY"); |
| 9706 | let _ = fs::remove_dir_all(&temp_root); |
| 9707 | Ok(()) |
| 9708 | } |
| 9709 | |
| 9710 | #[test] |
| 9711 | fn save_api_key_for_openrouter_writes_provider_table() -> Result<()> { |
| 9712 | let _lock = lock_test_env(); |
| 9713 | let nanos = SystemTime::now() |
| 9714 | .duration_since(UNIX_EPOCH) |
| 9715 | .unwrap() |
| 9716 | .as_nanos(); |
| 9717 | let temp_root = env::temp_dir().join(format!( |
| 9718 | "codewhale-tui-save-key-or-{}-{}", |
| 9719 | std::process::id(), |
| 9720 | nanos |
| 9721 | )); |
| 9722 | fs::create_dir_all(&temp_root)?; |
| 9723 | let _guard = EnvGuard::new(&temp_root); |
| 9724 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9725 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 9726 | let _secret_backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "local"); |
| 9727 | let resolved_config_path = codewhale_config::resolve_config_path(None)?; |
| 9728 | |
| 9729 | let path = save_api_key_for(ProviderKind::Openrouter, "or-saved-key")?; |
| 9730 | assert_eq!(path, resolved_config_path); |
| 9731 | let contents = fs::read_to_string(&path)?; |
| 9732 | let parsed: toml::Value = toml::from_str(&contents)?; |
| 9733 | assert_eq!( |
| 9734 | parsed |
| 9735 | .get("providers") |
| 9736 | .and_then(|p| p.get("openrouter")) |
| 9737 | .and_then(|t| t.get("api_key")) |
| 9738 | .and_then(toml::Value::as_str), |
| 9739 | Some("or-saved-key") |
| 9740 | ); |
| 9741 | // Re-saving must not duplicate or wipe sibling tables. |
| 9742 | let novita_path = save_api_key_for(ProviderKind::Novita, "novita-saved-key")?; |
| 9743 | assert_eq!(novita_path.canonicalize()?, path.canonicalize()?); |
| 9744 | let contents = fs::read_to_string(&path)?; |
| 9745 | let parsed: toml::Value = toml::from_str(&contents)?; |
| 9746 | assert_eq!( |
| 9747 | parsed |
| 9748 | .get("providers") |
| 9749 | .and_then(|p| p.get("openrouter")) |
| 9750 | .and_then(|t| t.get("api_key")) |
| 9751 | .and_then(toml::Value::as_str), |
| 9752 | Some("or-saved-key") |
| 9753 | ); |
| 9754 | assert_eq!( |
| 9755 | parsed |
| 9756 | .get("providers") |
| 9757 | .and_then(|p| p.get("novita")) |
| 9758 | .and_then(|t| t.get("api_key")) |
| 9759 | .and_then(toml::Value::as_str), |
| 9760 | Some("novita-saved-key") |
| 9761 | ); |
| 9762 | for (provider, key) in [ |
| 9763 | (ProviderKind::Openai, "openai-saved-key"), |
| 9764 | (ProviderKind::WanjieArk, "wanjie-saved-key"), |
| 9765 | (ProviderKind::Fireworks, "fireworks-saved-key"), |
| 9766 | (ProviderKind::XiaomiMimo, "mimo-saved-key"), |
| 9767 | (ProviderKind::Siliconflow, "sf-saved-key"), |
| 9768 | (ProviderKind::Sglang, "sglang-saved-key"), |
| 9769 | ] { |
| 9770 | assert_eq!( |
| 9771 | save_api_key_for(provider, key)?.canonicalize()?, |
| 9772 | path.canonicalize()? |
| 9773 | ); |
| 9774 | } |
| 9775 | let contents = fs::read_to_string(&path)?; |
| 9776 | let parsed: toml::Value = toml::from_str(&contents)?; |
| 9777 | assert_eq!( |
| 9778 | parsed |
| 9779 | .get("providers") |
| 9780 | .and_then(|p| p.get("openai")) |
| 9781 | .and_then(|t| t.get("api_key")) |
| 9782 | .and_then(toml::Value::as_str), |
| 9783 | Some("openai-saved-key") |
| 9784 | ); |
| 9785 | assert_eq!( |
| 9786 | parsed |
| 9787 | .get("providers") |
| 9788 | .and_then(|p| p.get("wanjie_ark")) |
| 9789 | .and_then(|t| t.get("api_key")) |
| 9790 | .and_then(toml::Value::as_str), |
| 9791 | Some("wanjie-saved-key") |
| 9792 | ); |
| 9793 | assert_eq!( |
| 9794 | parsed |
| 9795 | .get("providers") |
| 9796 | .and_then(|p| p.get("fireworks")) |
| 9797 | .and_then(|t| t.get("api_key")) |
| 9798 | .and_then(toml::Value::as_str), |
| 9799 | Some("fireworks-saved-key") |
| 9800 | ); |
| 9801 | assert_eq!( |
| 9802 | parsed |
| 9803 | .get("providers") |
| 9804 | .and_then(|p| p.get("xiaomi_mimo")) |
| 9805 | .and_then(|t| t.get("api_key")) |
| 9806 | .and_then(toml::Value::as_str), |
| 9807 | Some("mimo-saved-key") |
| 9808 | ); |
| 9809 | assert_eq!( |
| 9810 | parsed |
| 9811 | .get("providers") |
| 9812 | .and_then(|p| p.get("siliconflow")) |
| 9813 | .and_then(|t| t.get("api_key")) |
| 9814 | .and_then(toml::Value::as_str), |
| 9815 | Some("sf-saved-key") |
| 9816 | ); |
| 9817 | assert_eq!( |
| 9818 | parsed |
| 9819 | .get("providers") |
| 9820 | .and_then(|p| p.get("sglang")) |
| 9821 | .and_then(|t| t.get("api_key")) |
| 9822 | .and_then(toml::Value::as_str), |
| 9823 | Some("sglang-saved-key") |
| 9824 | ); |
| 9825 | save_api_key_for(ProviderKind::SiliconflowCN, "sf-cn-saved-key")?; |
| 9826 | let contents = fs::read_to_string(&path)?; |
| 9827 | let parsed: toml::Value = toml::from_str(&contents)?; |
| 9828 | assert_eq!( |
| 9829 | parsed |
| 9830 | .get("providers") |
| 9831 | .and_then(|p| p.get("siliconflow_cn")) |
| 9832 | .and_then(|t| t.get("api_key")) |
| 9833 | .and_then(toml::Value::as_str), |
| 9834 | Some("sf-cn-saved-key") |
| 9835 | ); |
| 9836 | assert_eq!( |
| 9837 | parsed |
| 9838 | .get("providers") |
| 9839 | .and_then(|p| p.get("siliconflow")) |
| 9840 | .and_then(|t| t.get("api_key")) |
| 9841 | .and_then(toml::Value::as_str), |
| 9842 | Some("sf-saved-key") |
| 9843 | ); |
| 9844 | Ok(()) |
| 9845 | } |
| 9846 | |
| 9847 | #[test] |
| 9848 | fn save_api_key_for_deepseek_cn_uses_root_deepseek_storage() -> Result<()> { |
| 9849 | let _lock = lock_test_env(); |
| 9850 | let nanos = SystemTime::now() |
| 9851 | .duration_since(UNIX_EPOCH) |
| 9852 | .unwrap() |
| 9853 | .as_nanos(); |
| 9854 | let temp_root = env::temp_dir().join(format!( |
| 9855 | "codewhale-tui-save-key-cn-{}-{}", |
| 9856 | std::process::id(), |
| 9857 | nanos |
| 9858 | )); |
| 9859 | fs::create_dir_all(&temp_root)?; |
| 9860 | let _guard = EnvGuard::new(&temp_root); |
| 9861 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9862 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 9863 | let _secret_backend = EnvVarGuard::set("DEEPSEEK_SECRET_BACKEND", "local"); |
| 9864 | |
| 9865 | let path = save_api_key_for(ProviderKind::Deepseek, "cn-saved-key")?; |
| 9866 | assert_eq!(path, config_path); |
| 9867 | let contents = fs::read_to_string(&path)?; |
| 9868 | let parsed: toml::Value = toml::from_str(&contents)?; |
| 9869 | |
| 9870 | // DeepSeek-CN reads `[providers.deepseek]`, which replaced the shared |
| 9871 | // top-level key (#6394). |
| 9872 | assert_eq!( |
| 9873 | parsed["providers"]["deepseek"] |
| 9874 | .get("api_key") |
| 9875 | .and_then(toml::Value::as_str), |
| 9876 | Some("cn-saved-key") |
| 9877 | ); |
| 9878 | assert!(parsed.get("api_key").is_none(), "{contents}"); |
| 9879 | Ok(()) |
| 9880 | } |
| 9881 | |
| 9882 | #[test] |
| 9883 | fn nvidia_nim_reads_facade_provider_table() -> Result<()> { |
| 9884 | let _lock = lock_test_env(); |
| 9885 | let nanos = SystemTime::now() |
| 9886 | .duration_since(UNIX_EPOCH) |
| 9887 | .unwrap() |
| 9888 | .as_nanos(); |
| 9889 | let temp_root = env::temp_dir().join(format!( |
| 9890 | "codewhale-tui-nim-provider-table-test-{}-{}", |
| 9891 | std::process::id(), |
| 9892 | nanos |
| 9893 | )); |
| 9894 | fs::create_dir_all(&temp_root)?; |
| 9895 | let _guard = EnvGuard::new(&temp_root); |
| 9896 | |
| 9897 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9898 | ensure_parent_dir(&config_path)?; |
| 9899 | fs::write( |
| 9900 | &config_path, |
| 9901 | r#"provider = "nvidia-nim" |
| 9902 | default_text_model = "deepseek-v4-flash" |
| 9903 | |
| 9904 | [providers.nvidia_nim] |
| 9905 | api_key = "nim-table-key" |
| 9906 | base_url = "https://nim-table.example/v1" |
| 9907 | model = "deepseek-v4-pro" |
| 9908 | "#, |
| 9909 | )?; |
| 9910 | |
| 9911 | let config = Config::load(None, None)?; |
| 9912 | assert_eq!( |
| 9913 | config.active_provider_identity().unwrap().provider, |
| 9914 | ProviderKind::NvidiaNim |
| 9915 | ); |
| 9916 | assert_eq!(config.active_route_api_key()?, "nim-table-key"); |
| 9917 | assert_eq!( |
| 9918 | config.active_route_base_url(), |
| 9919 | "https://nim-table.example/v1" |
| 9920 | ); |
| 9921 | // Custom base URL preserves the user-specified model name; normalisation |
| 9922 | // is skipped because the gateway expects the model name as-provided. |
| 9923 | assert_eq!(config.default_model(), "deepseek-v4-pro"); |
| 9924 | Ok(()) |
| 9925 | } |
| 9926 | |
| 9927 | #[test] |
| 9928 | fn nvidia_nim_provider_table_key_overrides_root_deepseek_key() -> Result<()> { |
| 9929 | let _lock = lock_test_env(); |
| 9930 | let nanos = SystemTime::now() |
| 9931 | .duration_since(UNIX_EPOCH) |
| 9932 | .unwrap() |
| 9933 | .as_nanos(); |
| 9934 | let temp_root = env::temp_dir().join(format!( |
| 9935 | "codewhale-tui-nim-root-key-precedence-test-{}-{}", |
| 9936 | std::process::id(), |
| 9937 | nanos |
| 9938 | )); |
| 9939 | fs::create_dir_all(&temp_root)?; |
| 9940 | let _guard = EnvGuard::new(&temp_root); |
| 9941 | |
| 9942 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 9943 | ensure_parent_dir(&config_path)?; |
| 9944 | fs::write( |
| 9945 | &config_path, |
| 9946 | r#"api_key = "codewhale-root-key" |
| 9947 | provider = "nvidia-nim" |
| 9948 | |
| 9949 | [providers.nvidia_nim] |
| 9950 | api_key = "nim-table-key" |
| 9951 | base_url = "https://integrate.api.nvidia.com/v1" |
| 9952 | model = "deepseek-ai/deepseek-v4-pro" |
| 9953 | "#, |
| 9954 | )?; |
| 9955 | |
| 9956 | let config = Config::load(None, None)?; |
| 9957 | assert_eq!( |
| 9958 | config.active_provider_identity().unwrap().provider, |
| 9959 | ProviderKind::NvidiaNim |
| 9960 | ); |
| 9961 | assert_eq!(config.active_route_api_key()?, "nim-table-key"); |
| 9962 | Ok(()) |
| 9963 | } |
| 9964 | |
| 9965 | #[test] |
| 9966 | fn invalid_provider_scenario() { |
| 9967 | // Scenario consolidation of: invalid_provider_auth_source_is_not_explicit_configuration, invalid_provider_error_lists_huggingface |
| 9968 | // from invalid_provider_auth_source_is_not_explicit_configuration |
| 9969 | { |
| 9970 | let entry = ProviderConfig { |
| 9971 | auth: Some(codewhale_config::ProviderAuthSourceToml { |
| 9972 | source: codewhale_config::AuthSourceKind::Command, |
| 9973 | command: Vec::new(), |
| 9974 | timeout_ms: None, |
| 9975 | secret_id: None, |
| 9976 | }), |
| 9977 | ..ProviderConfig::default() |
| 9978 | }; |
| 9979 | |
| 9980 | assert!(!provider_config_is_explicit(&entry)); |
| 9981 | } |
| 9982 | // from invalid_provider_error_lists_huggingface |
| 9983 | { |
| 9984 | let config = Config { |
| 9985 | provider: Some("not-a-provider".to_string()), |
| 9986 | ..Default::default() |
| 9987 | }; |
| 9988 | let err = config.validate().expect_err("unknown provider should fail"); |
| 9989 | let message = err.to_string(); |
| 9990 | assert!(message.contains("Invalid provider 'not-a-provider'")); |
| 9991 | assert!(message.contains("huggingface")); |
| 9992 | } |
| 9993 | } |
| 9994 | |
| 9995 | #[test] |
| 9996 | fn openrouter_nemotron_ultra_aliases_resolve_to_live_id() { |
| 9997 | assert_eq!( |
| 9998 | OPENROUTER_NEMOTRON_3_ULTRA_MODEL, |
| 9999 | "nvidia/nemotron-3-ultra-550b-a55b" |
| 10000 | ); |
| 10001 | assert_ne!(OPENROUTER_NEMOTRON_3_ULTRA_MODEL, "nvidia/nemotron-3-ultra"); |
| 10002 | |
| 10003 | for alias in [ |
| 10004 | "nemotron-3-ultra", |
| 10005 | "nvidia/nemotron-3-ultra", |
| 10006 | "nvidia-nemotron-3-ultra", |
| 10007 | ] { |
| 10008 | assert_eq!( |
| 10009 | codewhale_config::route::resolve_model(ProviderKind::Openrouter, alias, None) |
| 10010 | .ok() |
| 10011 | .map(|resolved| resolved.wire_id) |
| 10012 | .as_deref(), |
| 10013 | Some(OPENROUTER_NEMOTRON_3_ULTRA_MODEL) |
| 10014 | ); |
| 10015 | } |
| 10016 | } |
| 10017 | |
| 10018 | #[test] |
| 10019 | fn status_item_balance_available_for_prepaid_providers() { |
| 10020 | assert!(StatusItem::Balance.is_available_for(ProviderKind::Deepseek)); |
| 10021 | assert!(StatusItem::Balance.is_available_for(ProviderKind::Deepseek)); |
| 10022 | assert!(StatusItem::Balance.is_available_for(ProviderKind::Openrouter)); |
| 10023 | assert!(StatusItem::Balance.is_available_for(ProviderKind::Siliconflow)); |
| 10024 | assert!(StatusItem::Balance.is_available_for(ProviderKind::SiliconflowCN)); |
| 10025 | // Invoice-only, local, and unimplemented prepaid vendors stay hidden. |
| 10026 | assert!(!StatusItem::Balance.is_available_for(ProviderKind::Novita)); |
| 10027 | assert!(!StatusItem::Balance.is_available_for(ProviderKind::NvidiaNim)); |
| 10028 | assert!(!StatusItem::Balance.is_available_for(ProviderKind::Fireworks)); |
| 10029 | assert!(!StatusItem::Balance.is_available_for(ProviderKind::Sglang)); |
| 10030 | assert!(!StatusItem::Balance.is_available_for(ProviderKind::Vllm)); |
| 10031 | assert!(!StatusItem::Balance.is_available_for(ProviderKind::Ollama)); |
| 10032 | assert!(!StatusItem::Balance.is_available_for(ProviderKind::Openai)); |
| 10033 | assert!(!StatusItem::Balance.is_available_for(ProviderKind::Atlascloud)); |
| 10034 | // Other StatusItem variants should be available everywhere. |
| 10035 | assert!(StatusItem::Mode.is_available_for(ProviderKind::Ollama)); |
| 10036 | } |
| 10037 | |
| 10038 | #[test] |
| 10039 | fn status_items_scenario() { |
| 10040 | // Scenario consolidation of: status_items_deser_ignores_unknown_variants, status_items_deser_allows_missing_field |
| 10041 | // from status_items_deser_ignores_unknown_variants |
| 10042 | { |
| 10043 | // Simulate a stable build reading config written by a dev build that |
| 10044 | // knows about items the stable build doesn't (e.g. "balance" or a |
| 10045 | // future "cost_saving" chip). |
| 10046 | let toml_str = r#" |
| 10047 | alternate_screen = "auto" |
| 10048 | status_items = ["mode", "model", "unknown_future_item", "cost", "another_unknown", "cache"] |
| 10049 | "#; |
| 10050 | let tui: TuiConfig = toml::from_str(toml_str).expect("should parse without error"); |
| 10051 | let items = tui.status_items.expect("status_items should be Some"); |
| 10052 | assert_eq!(items.len(), 4, "unknown items should be silently dropped"); |
| 10053 | assert_eq!(items[0], StatusItem::Mode); |
| 10054 | assert_eq!(items[1], StatusItem::Model); |
| 10055 | assert_eq!(items[2], StatusItem::Cost); |
| 10056 | assert_eq!(items[3], StatusItem::Cache); |
| 10057 | } |
| 10058 | // A config written before #5950 retired the inert items keeps loading: |
| 10059 | // the retired keys are skipped, the live ones survive in order. |
| 10060 | { |
| 10061 | let toml_str = r#" |
| 10062 | status_items = ["mode", "status", "model", "agents", "rate_limit", "tokens"] |
| 10063 | "#; |
| 10064 | let tui: TuiConfig = toml::from_str(toml_str).expect("legacy items should parse"); |
| 10065 | let items = tui.status_items.expect("status_items should be Some"); |
| 10066 | assert_eq!( |
| 10067 | items, |
| 10068 | vec![StatusItem::Mode, StatusItem::Model, StatusItem::Tokens], |
| 10069 | "retired keys should drop out without failing the whole file" |
| 10070 | ); |
| 10071 | } |
| 10072 | // #6112 revived `git_branch` and added `workspace`: both parse again and |
| 10073 | // round-trip through their canonical keys. |
| 10074 | { |
| 10075 | let toml_str = r#" |
| 10076 | status_items = ["workspace", "git_branch"] |
| 10077 | "#; |
| 10078 | let tui: TuiConfig = toml::from_str(toml_str).expect("revived items should parse"); |
| 10079 | let items = tui.status_items.expect("status_items should be Some"); |
| 10080 | assert_eq!(items, vec![StatusItem::Workspace, StatusItem::GitBranch]); |
| 10081 | assert_eq!(StatusItem::Workspace.key(), "workspace"); |
| 10082 | assert_eq!(StatusItem::GitBranch.key(), "git_branch"); |
| 10083 | } |
| 10084 | { |
| 10085 | let tui: TuiConfig = |
| 10086 | toml::from_str(r#"status_items = ["ttft", "output_rate", "session_metrics"]"#) |
| 10087 | .expect("new and legacy metrics keys should parse"); |
| 10088 | assert_eq!( |
| 10089 | tui.status_items, |
| 10090 | Some(vec![ |
| 10091 | StatusItem::Ttft, |
| 10092 | StatusItem::OutputRate, |
| 10093 | StatusItem::SessionMetrics |
| 10094 | ]) |
| 10095 | ); |
| 10096 | assert_eq!(StatusItem::Ttft.key(), "ttft"); |
| 10097 | assert_eq!(StatusItem::OutputRate.key(), "output_rate"); |
| 10098 | } |
| 10099 | // from status_items_deser_allows_missing_field |
| 10100 | { |
| 10101 | let toml_str = r#" |
| 10102 | locale = "zh-Hans" |
| 10103 | mouse_capture = false |
| 10104 | "#; |
| 10105 | let tui: TuiConfig = toml::from_str(toml_str).expect("missing status_items should parse"); |
| 10106 | assert_eq!(tui.status_items, None); |
| 10107 | } |
| 10108 | } |
| 10109 | |
| 10110 | #[test] |
| 10111 | fn transcript_prose_scenario() -> Result<()> { |
| 10112 | // Scenario consolidation of: transcript_prose_measure_loads_and_resolves, transcript_prose_measure_rejects_negative_with_clear_error, transcript_prose_measure_rejects_non_integers_with_clear_error |
| 10113 | // from transcript_prose_measure_loads_and_resolves |
| 10114 | { |
| 10115 | // #5436: absent = full width; 0 also means full width; a positive |
| 10116 | // integer caps prose wrap at that many columns. |
| 10117 | let absent: Config = toml::from_str("provider = \"openai\"\n")?; |
| 10118 | absent.validate()?; |
| 10119 | assert_eq!(absent.prose_measure(), None); |
| 10120 | |
| 10121 | let zero: Config = toml::from_str( |
| 10122 | " |
| 10123 | [transcript] |
| 10124 | prose_measure = 0 |
| 10125 | ", |
| 10126 | )?; |
| 10127 | zero.validate()?; |
| 10128 | assert_eq!(zero.prose_measure(), None, "0 must mean full width"); |
| 10129 | |
| 10130 | let capped: Config = toml::from_str( |
| 10131 | " |
| 10132 | [transcript] |
| 10133 | prose_measure = 120 |
| 10134 | ", |
| 10135 | )?; |
| 10136 | capped.validate()?; |
| 10137 | assert_eq!(capped.prose_measure(), Some(120)); |
| 10138 | } |
| 10139 | // from transcript_prose_measure_rejects_negative_with_clear_error |
| 10140 | { |
| 10141 | let config: Config = toml::from_str( |
| 10142 | " |
| 10143 | [transcript] |
| 10144 | prose_measure = -5 |
| 10145 | ", |
| 10146 | ) |
| 10147 | .expect("negative integers must parse so validate can name the key"); |
| 10148 | |
| 10149 | let error = config |
| 10150 | .validate() |
| 10151 | .expect_err("negative prose_measure should be rejected"); |
| 10152 | let message = error.to_string(); |
| 10153 | assert!( |
| 10154 | message.contains("transcript.prose_measure"), |
| 10155 | "error should name the key: {message}" |
| 10156 | ); |
| 10157 | assert!( |
| 10158 | message.contains("-5"), |
| 10159 | "error should echo the value: {message}" |
| 10160 | ); |
| 10161 | assert!( |
| 10162 | message.contains("positive whole number"), |
| 10163 | "error should say what is expected: {message}" |
| 10164 | ); |
| 10165 | } |
| 10166 | // from transcript_prose_measure_rejects_non_integers_with_clear_error |
| 10167 | { |
| 10168 | for raw in ["\"fill\"", "12.5", "true"] { |
| 10169 | let config: Config = toml::from_str(&format!( |
| 10170 | " |
| 10171 | [transcript] |
| 10172 | prose_measure = {raw} |
| 10173 | " |
| 10174 | )) |
| 10175 | .unwrap_or_else(|_| panic!("{raw} must parse so validate can name the key")); |
| 10176 | |
| 10177 | let error = config |
| 10178 | .validate() |
| 10179 | .expect_err(&format!("{raw} should be rejected")); |
| 10180 | let message = error.to_string(); |
| 10181 | assert!( |
| 10182 | message.contains("transcript.prose_measure"), |
| 10183 | "error should name the key for {raw}: {message}" |
| 10184 | ); |
| 10185 | assert!( |
| 10186 | message.contains("positive whole number"), |
| 10187 | "error should say what is expected for {raw}: {message}" |
| 10188 | ); |
| 10189 | } |
| 10190 | } |
| 10191 | Ok(()) |
| 10192 | } |
| 10193 | |
| 10194 | #[test] |
| 10195 | fn huggingface_provider_scenario() -> Result<()> { |
| 10196 | // Scenario consolidation of: huggingface_provider_aliases_parse, huggingface_provider_uses_direct_defaults |
| 10197 | // from huggingface_provider_aliases_parse |
| 10198 | { |
| 10199 | for alias in ["huggingface", "hugging-face", "hugging_face", "hf"] { |
| 10200 | assert_eq!(ProviderKind::parse(alias), Some(ProviderKind::Huggingface)); |
| 10201 | } |
| 10202 | } |
| 10203 | // from huggingface_provider_uses_direct_defaults |
| 10204 | { |
| 10205 | let _lock = lock_test_env(); |
| 10206 | let nanos = SystemTime::now() |
| 10207 | .duration_since(UNIX_EPOCH) |
| 10208 | .unwrap() |
| 10209 | .as_nanos(); |
| 10210 | let temp_root = env::temp_dir().join(format!( |
| 10211 | "codewhale-tui-huggingface-defaults-test-{}-{}", |
| 10212 | std::process::id(), |
| 10213 | nanos |
| 10214 | )); |
| 10215 | fs::create_dir_all(&temp_root)?; |
| 10216 | let _guard = EnvGuard::new(&temp_root); |
| 10217 | |
| 10218 | unsafe { |
| 10219 | env::set_var("CODEWHALE_PROVIDER", "huggingface"); |
| 10220 | env::set_var("HUGGINGFACE_API_KEY", "hf-env-key"); |
| 10221 | } |
| 10222 | |
| 10223 | let config = Config::load(None, None)?; |
| 10224 | assert_eq!( |
| 10225 | config.active_provider_identity().unwrap().provider, |
| 10226 | ProviderKind::Huggingface |
| 10227 | ); |
| 10228 | assert_eq!(config.active_route_api_key()?, "hf-env-key"); |
| 10229 | assert_eq!(config.active_route_base_url(), DEFAULT_HUGGINGFACE_BASE_URL); |
| 10230 | assert_eq!(config.default_model(), DEFAULT_HUGGINGFACE_MODEL); |
| 10231 | } |
| 10232 | Ok(()) |
| 10233 | } |
| 10234 | |
| 10235 | #[test] |
| 10236 | fn modelscope_provider_scenario() -> Result<()> { |
| 10237 | // from modelscope_provider_aliases_parse |
| 10238 | { |
| 10239 | for alias in ["modelscope", "modelscope-cn"] { |
| 10240 | assert_eq!(ProviderKind::parse(alias), Some(ProviderKind::Modelscope)); |
| 10241 | } |
| 10242 | } |
| 10243 | // from modelscope_provider_uses_direct_defaults |
| 10244 | { |
| 10245 | let _lock = lock_test_env(); |
| 10246 | let nanos = SystemTime::now() |
| 10247 | .duration_since(UNIX_EPOCH) |
| 10248 | .unwrap() |
| 10249 | .as_nanos(); |
| 10250 | let temp_root = env::temp_dir().join(format!( |
| 10251 | "codewhale-tui-modelscope-defaults-test-{}-{}", |
| 10252 | std::process::id(), |
| 10253 | nanos |
| 10254 | )); |
| 10255 | fs::create_dir_all(&temp_root)?; |
| 10256 | let _guard = EnvGuard::new(&temp_root); |
| 10257 | |
| 10258 | unsafe { |
| 10259 | env::set_var("CODEWHALE_PROVIDER", "modelscope"); |
| 10260 | env::set_var("MODELSCOPE_API_KEY", "ms-env-key"); |
| 10261 | } |
| 10262 | |
| 10263 | let config = Config::load(None, None)?; |
| 10264 | assert_eq!( |
| 10265 | config.active_provider_identity().unwrap().provider, |
| 10266 | ProviderKind::Modelscope |
| 10267 | ); |
| 10268 | assert_eq!(config.active_route_api_key()?, "ms-env-key"); |
| 10269 | assert_eq!(config.active_route_base_url(), DEFAULT_MODELSCOPE_BASE_URL); |
| 10270 | assert_eq!(config.default_model(), DEFAULT_MODELSCOPE_MODEL); |
| 10271 | } |
| 10272 | Ok(()) |
| 10273 | } |
| 10274 | |
| 10275 | #[test] |
| 10276 | fn huggingface_hf_token_env_api_key_resolves() -> Result<()> { |
| 10277 | let _lock = lock_test_env(); |
| 10278 | let nanos = SystemTime::now() |
| 10279 | .duration_since(UNIX_EPOCH) |
| 10280 | .unwrap() |
| 10281 | .as_nanos(); |
| 10282 | let temp_root = env::temp_dir().join(format!( |
| 10283 | "codewhale-tui-huggingface-hf-token-test-{}-{}", |
| 10284 | std::process::id(), |
| 10285 | nanos |
| 10286 | )); |
| 10287 | fs::create_dir_all(&temp_root)?; |
| 10288 | let _guard = EnvGuard::new(&temp_root); |
| 10289 | |
| 10290 | unsafe { |
| 10291 | env::set_var("CODEWHALE_PROVIDER", "huggingface"); |
| 10292 | env::set_var("HF_TOKEN", "hf-token-value"); |
| 10293 | } |
| 10294 | |
| 10295 | let config = Config::load(None, None)?; |
| 10296 | assert_eq!( |
| 10297 | config.active_provider_identity().unwrap().provider, |
| 10298 | ProviderKind::Huggingface |
| 10299 | ); |
| 10300 | assert_eq!(config.active_route_api_key()?, "hf-token-value"); |
| 10301 | Ok(()) |
| 10302 | } |
| 10303 | |
| 10304 | #[test] |
| 10305 | fn huggingface_missing_key_error_mentions_env_fallbacks() -> Result<()> { |
| 10306 | let _lock = lock_test_env(); |
| 10307 | let nanos = SystemTime::now() |
| 10308 | .duration_since(UNIX_EPOCH) |
| 10309 | .unwrap() |
| 10310 | .as_nanos(); |
| 10311 | let temp_root = env::temp_dir().join(format!( |
| 10312 | "codewhale-tui-huggingface-missing-key-test-{}-{}", |
| 10313 | std::process::id(), |
| 10314 | nanos |
| 10315 | )); |
| 10316 | fs::create_dir_all(&temp_root)?; |
| 10317 | let _guard = EnvGuard::new(&temp_root); |
| 10318 | |
| 10319 | let config = Config { |
| 10320 | provider: Some("huggingface".to_string()), |
| 10321 | ..Default::default() |
| 10322 | }; |
| 10323 | |
| 10324 | config.validate()?; |
| 10325 | let err = config.active_route_api_key().expect_err("missing key"); |
| 10326 | let message = err.to_string(); |
| 10327 | assert!(message.contains("Hugging Face API key not found")); |
| 10328 | assert!(message.contains("https://huggingface.co/settings/tokens")); |
| 10329 | assert!(message.contains("HUGGINGFACE_API_KEY")); |
| 10330 | assert!(message.contains("HF_TOKEN")); |
| 10331 | Ok(()) |
| 10332 | } |
| 10333 | |
| 10334 | #[test] |
| 10335 | fn notifications_parse_scenario() { |
| 10336 | // Scenario consolidation of: notifications_parse_custom_completion_sound_file, notifications_parse_quiet_and_event_categories |
| 10337 | // from notifications_parse_custom_completion_sound_file |
| 10338 | { |
| 10339 | let config: Config = toml::from_str( |
| 10340 | r#" |
| 10341 | [notifications] |
| 10342 | completion_sound = "file" |
| 10343 | sound_file = "E:\\google\\downloads\\xm4114.wav" |
| 10344 | "#, |
| 10345 | ) |
| 10346 | .expect("custom completion sound config should parse"); |
| 10347 | |
| 10348 | let notifications = config.notifications_config(); |
| 10349 | assert_eq!(notifications.completion_sound, CompletionSound::File); |
| 10350 | assert_eq!( |
| 10351 | notifications.sound_file.as_deref(), |
| 10352 | Some(std::path::Path::new("E:\\google\\downloads\\xm4114.wav")) |
| 10353 | ); |
| 10354 | } |
| 10355 | // from notifications_parse_quiet_and_event_categories |
| 10356 | { |
| 10357 | let config: Config = toml::from_str( |
| 10358 | r#" |
| 10359 | [notifications] |
| 10360 | quiet = true |
| 10361 | |
| 10362 | [notifications.events] |
| 10363 | approval-needed = false |
| 10364 | model-notify = false |
| 10365 | "#, |
| 10366 | ) |
| 10367 | .expect("quiet + events config should parse"); |
| 10368 | |
| 10369 | let notifications = config.notifications_config(); |
| 10370 | assert!(notifications.quiet); |
| 10371 | let events = notifications.events; |
| 10372 | assert!(!events.approval_needed); |
| 10373 | assert!(!events.model_notify); |
| 10374 | // Unlisted categories keep their enabled default. |
| 10375 | assert!(events.turn_complete); |
| 10376 | assert!(events.subagent_terminal); |
| 10377 | assert!(events.input_needed); |
| 10378 | assert!(events.elevation_needed); |
| 10379 | } |
| 10380 | } |
| 10381 | |
| 10382 | #[test] |
| 10383 | fn notifications_parse_event_sound_table() { |
| 10384 | let config: Config = toml::from_str( |
| 10385 | r#" |
| 10386 | [notifications.event_sound] |
| 10387 | enabled = true |
| 10388 | events = ["turn-complete", "bogus-event", "approval-needed"] |
| 10389 | min_interval_ms = 500 |
| 10390 | quiet = true |
| 10391 | "#, |
| 10392 | ) |
| 10393 | .expect("event sound config should parse"); |
| 10394 | |
| 10395 | let notifications = config.notifications_config(); |
| 10396 | assert_eq!( |
| 10397 | notifications.event_sound, |
| 10398 | EventSoundConfig { |
| 10399 | enabled: true, |
| 10400 | events: vec![ |
| 10401 | "turn-complete".to_string(), |
| 10402 | "bogus-event".to_string(), |
| 10403 | "approval-needed".to_string(), |
| 10404 | ], |
| 10405 | min_interval_ms: 500, |
| 10406 | quiet: true, |
| 10407 | } |
| 10408 | ); |
| 10409 | } |
| 10410 | |
| 10411 | #[test] |
| 10412 | fn notifications_event_sound_defaults_when_table_absent() { |
| 10413 | let config: Config = toml::from_str("[notifications]\nmethod = \"off\"\n") |
| 10414 | .expect("bare notifications table should parse"); |
| 10415 | |
| 10416 | let event_sound = config.notifications_config().event_sound; |
| 10417 | assert_eq!(event_sound, EventSoundConfig::default()); |
| 10418 | assert!(!event_sound.enabled); |
| 10419 | assert_eq!( |
| 10420 | event_sound.events, |
| 10421 | vec!["turn-complete".to_string(), "approval-needed".to_string()] |
| 10422 | ); |
| 10423 | assert_eq!(event_sound.min_interval_ms, 2000); |
| 10424 | assert!(!event_sound.quiet); |
| 10425 | } |
| 10426 | |
| 10427 | #[test] |
| 10428 | fn notifications_quiet_and_events_default_off_and_all_enabled() { |
| 10429 | let config: Config = toml::from_str("[notifications]\nmethod = \"auto\"\n") |
| 10430 | .expect("bare notifications table should parse"); |
| 10431 | |
| 10432 | let notifications = config.notifications_config(); |
| 10433 | assert!(!notifications.quiet); |
| 10434 | assert_eq!(notifications.events, NotificationEventsConfig::default()); |
| 10435 | assert!(notifications.events.turn_complete); |
| 10436 | assert!(notifications.events.model_notify); |
| 10437 | } |
| 10438 | |
| 10439 | // === #1519 custom OpenAI-compatible provider slice === |
| 10440 | |
| 10441 | #[test] |
| 10442 | fn custom_provider_flatten_map_parses_alongside_named_provider() { |
| 10443 | // A custom `[providers.my_thing]` table lands in the flatten map while a |
| 10444 | // built-in `[providers.openai]` table still binds its named field. |
| 10445 | let config: Config = toml::from_str( |
| 10446 | r#" |
| 10447 | provider = "my_thing" |
| 10448 | |
| 10449 | [providers.openai] |
| 10450 | api_key = "openai-key" |
| 10451 | |
| 10452 | [providers.my_thing] |
| 10453 | kind = "openai-compatible" |
| 10454 | base_url = "https://api.example.com/v1" |
| 10455 | model = "custom-model-v1" |
| 10456 | api_key_env = "EXAMPLE_API_KEY" |
| 10457 | "#, |
| 10458 | ) |
| 10459 | .expect("config with a custom provider table should parse"); |
| 10460 | |
| 10461 | let providers = config.providers.as_ref().expect("providers table present"); |
| 10462 | // Built-in named field still works. |
| 10463 | assert_eq!(providers.openai.api_key.as_deref(), Some("openai-key")); |
| 10464 | // The custom entry is captured by name in the flatten map. |
| 10465 | let custom = providers |
| 10466 | .custom_provider_config("my_thing") |
| 10467 | .expect("custom entry parsed into flatten map"); |
| 10468 | assert_eq!(custom.kind.as_deref(), Some("openai-compatible")); |
| 10469 | assert_eq!( |
| 10470 | custom.base_url.as_deref(), |
| 10471 | Some("https://api.example.com/v1") |
| 10472 | ); |
| 10473 | assert_eq!(custom.model.as_deref(), Some("custom-model-v1")); |
| 10474 | assert_eq!(custom.api_key_env.as_deref(), Some("EXAMPLE_API_KEY")); |
| 10475 | assert!(custom.is_openai_compatible_custom()); |
| 10476 | // A built-in provider name never leaks into the custom map. |
| 10477 | assert!(providers.custom_provider_config("openai").is_none()); |
| 10478 | } |
| 10479 | |
| 10480 | #[test] |
| 10481 | fn api_provider_returns_custom_for_custom_name_and_deepseek_for_junk() { |
| 10482 | // Names a real custom table → Custom (the #1519 silent-misroute fix). |
| 10483 | let mut custom = HashMap::new(); |
| 10484 | custom.insert( |
| 10485 | "my_thing".to_string(), |
| 10486 | ProviderConfig { |
| 10487 | kind: Some("openai-compatible".to_string()), |
| 10488 | base_url: Some("https://api.example.com/v1".to_string()), |
| 10489 | ..Default::default() |
| 10490 | }, |
| 10491 | ); |
| 10492 | let config = Config { |
| 10493 | provider: Some("my_thing".to_string()), |
| 10494 | providers: Some(ProvidersConfig { |
| 10495 | custom, |
| 10496 | ..Default::default() |
| 10497 | }), |
| 10498 | ..Config::default() |
| 10499 | }; |
| 10500 | assert_eq!( |
| 10501 | config.active_provider_identity().unwrap().provider, |
| 10502 | ProviderKind::Custom |
| 10503 | ); |
| 10504 | config |
| 10505 | .validate() |
| 10506 | .expect("named custom providers should pass config validation"); |
| 10507 | |
| 10508 | // An unknown selection has no admitted route; it cannot borrow DeepSeek. |
| 10509 | let junk = Config { |
| 10510 | provider: Some("totally-not-a-provider".to_string()), |
| 10511 | ..Config::default() |
| 10512 | }; |
| 10513 | assert!( |
| 10514 | junk.active_provider_identity().is_err(), |
| 10515 | "unknown selections cannot fall back to DeepSeek" |
| 10516 | ); |
| 10517 | assert!( |
| 10518 | junk.validate().is_err(), |
| 10519 | "invalid provider names should still fail validation" |
| 10520 | ); |
| 10521 | } |
| 10522 | |
| 10523 | #[test] |
| 10524 | fn custom_provider_scenario() { |
| 10525 | // Scenario consolidation of: custom_provider_kind_only_accepts_openai_compatible, custom_provider_base_url_and_model_resolve_from_named_table |
| 10526 | // from custom_provider_kind_only_accepts_openai_compatible |
| 10527 | { |
| 10528 | let ok = ProviderConfig { |
| 10529 | kind: Some("openai-compatible".to_string()), |
| 10530 | ..Default::default() |
| 10531 | }; |
| 10532 | assert!(ok.is_openai_compatible_custom()); |
| 10533 | |
| 10534 | // Underscore spelling and case are tolerated. |
| 10535 | let underscore = ProviderConfig { |
| 10536 | kind: Some("OpenAI_Compatible".to_string()), |
| 10537 | ..Default::default() |
| 10538 | }; |
| 10539 | assert!(underscore.is_openai_compatible_custom()); |
| 10540 | |
| 10541 | // Any other declared wire format is rejected (callers error on these). |
| 10542 | let other = ProviderConfig { |
| 10543 | kind: Some("anthropic-messages".to_string()), |
| 10544 | ..Default::default() |
| 10545 | }; |
| 10546 | assert!(!other.is_openai_compatible_custom()); |
| 10547 | |
| 10548 | // Built-in providers leave `kind` unset. |
| 10549 | assert!(!ProviderConfig::default().is_openai_compatible_custom()); |
| 10550 | } |
| 10551 | // from custom_provider_base_url_and_model_resolve_from_named_table |
| 10552 | { |
| 10553 | let mut custom = HashMap::new(); |
| 10554 | custom.insert( |
| 10555 | "my_thing".to_string(), |
| 10556 | ProviderConfig { |
| 10557 | kind: Some("openai-compatible".to_string()), |
| 10558 | base_url: Some("https://api.example.com/v1".to_string()), |
| 10559 | model: Some("custom-model-v1".to_string()), |
| 10560 | ..Default::default() |
| 10561 | }, |
| 10562 | ); |
| 10563 | let config = Config { |
| 10564 | provider: Some("my_thing".to_string()), |
| 10565 | providers: Some(ProvidersConfig { |
| 10566 | custom, |
| 10567 | ..Default::default() |
| 10568 | }), |
| 10569 | ..Config::default() |
| 10570 | }; |
| 10571 | |
| 10572 | // Resolution reads the named table, not a DeepSeek default. |
| 10573 | assert_eq!( |
| 10574 | config.active_provider_identity().unwrap().provider, |
| 10575 | ProviderKind::Custom |
| 10576 | ); |
| 10577 | assert_eq!(config.active_route_base_url(), "https://api.example.com/v1"); |
| 10578 | assert_eq!(config.default_model(), "custom-model-v1"); |
| 10579 | } |
| 10580 | } |
| 10581 | |
| 10582 | #[test] |
| 10583 | fn session_provider_identity_preserves_exact_named_custom_key() { |
| 10584 | let config = session_custom_provider_config( |
| 10585 | "lm-studio", |
| 10586 | "openai-compatible", |
| 10587 | "http://127.0.0.1:1234/v1", |
| 10588 | ); |
| 10589 | |
| 10590 | assert_eq!( |
| 10591 | config.active_provider_identity().unwrap().key.as_str(), |
| 10592 | "lm-studio" |
| 10593 | ); |
| 10594 | assert_eq!( |
| 10595 | config |
| 10596 | .resolve_provider_identity("lm-studio") |
| 10597 | .expect("exact custom identity"), |
| 10598 | ProviderIdentity { |
| 10599 | provider: ProviderKind::Custom, |
| 10600 | key: "lm-studio".into(), |
| 10601 | exact_id: Some("lm-studio".into()), |
| 10602 | migrated_legacy_ollama_cloud_route: false, |
| 10603 | legacy_root_custom_generation: None, |
| 10604 | } |
| 10605 | ); |
| 10606 | assert_eq!( |
| 10607 | config |
| 10608 | .resolve_provider_identity("openrouter") |
| 10609 | .expect("built-in identity"), |
| 10610 | ProviderIdentity { |
| 10611 | provider: ProviderKind::Openrouter, |
| 10612 | key: "openrouter".into(), |
| 10613 | exact_id: Some("openrouter".into()), |
| 10614 | migrated_legacy_ollama_cloud_route: false, |
| 10615 | legacy_root_custom_generation: None, |
| 10616 | } |
| 10617 | ); |
| 10618 | let migrated = config |
| 10619 | .resolve_provider_identity("custom") |
| 10620 | .expect("released generic custom record migrates to sole live named route"); |
| 10621 | assert_eq!( |
| 10622 | migrated, |
| 10623 | ProviderIdentity { |
| 10624 | provider: ProviderKind::Custom, |
| 10625 | key: "lm-studio".into(), |
| 10626 | exact_id: Some("lm-studio".into()), |
| 10627 | migrated_legacy_ollama_cloud_route: false, |
| 10628 | legacy_root_custom_generation: None, |
| 10629 | } |
| 10630 | ); |
| 10631 | } |
| 10632 | |
| 10633 | #[test] |
| 10634 | fn persisted_legacy_ollama_cloud_receipts_upgrade_only_on_exact_live_route() { |
| 10635 | let exact = Config { |
| 10636 | provider: Some("ollama".to_string()), |
| 10637 | providers: Some(ProvidersConfig { |
| 10638 | ollama: ProviderConfig { |
| 10639 | base_url: Some(codewhale_config::provider::OLLAMA_CLOUD_BASE_URL.to_string()), |
| 10640 | ..ProviderConfig::default() |
| 10641 | }, |
| 10642 | ..ProvidersConfig::default() |
| 10643 | }), |
| 10644 | ..Config::default() |
| 10645 | }; |
| 10646 | for provider_id in [None, Some("ollama")] { |
| 10647 | let identity = exact |
| 10648 | .resolve_persisted_provider_identity(Some("ollama"), provider_id) |
| 10649 | .expect("exact released tuple migrates"); |
| 10650 | assert_eq!(identity.provider, ProviderKind::OllamaCloud); |
| 10651 | assert_eq!(identity.key.as_str(), "ollama-cloud"); |
| 10652 | assert_eq!(identity.persisted_id(), Some("ollama")); |
| 10653 | assert!(identity.migrated_legacy_ollama_cloud_route); |
| 10654 | } |
| 10655 | |
| 10656 | let neighbor = Config { |
| 10657 | provider: Some("ollama".to_string()), |
| 10658 | providers: Some(ProvidersConfig { |
| 10659 | ollama: ProviderConfig { |
| 10660 | base_url: Some("https://ollama.com/v1/preview".to_string()), |
| 10661 | ..ProviderConfig::default() |
| 10662 | }, |
| 10663 | ..ProvidersConfig::default() |
| 10664 | }), |
| 10665 | ..Config::default() |
| 10666 | }; |
| 10667 | let identity = neighbor |
| 10668 | .resolve_persisted_provider_identity(Some("ollama"), Some("ollama")) |
| 10669 | .expect("neighbor remains local/custom ollama identity"); |
| 10670 | assert_eq!(identity.provider, ProviderKind::Ollama); |
| 10671 | assert_eq!(identity.key.as_str(), "ollama"); |
| 10672 | |
| 10673 | let explicit = Config { |
| 10674 | provider: Some("ollama-cloud".to_string()), |
| 10675 | ..Config::default() |
| 10676 | }; |
| 10677 | let identity = explicit |
| 10678 | .resolve_persisted_provider_identity(Some("ollama-cloud"), Some("ollama-cloud")) |
| 10679 | .expect("new receipt remains first-class cloud identity"); |
| 10680 | assert_eq!(identity.provider, ProviderKind::OllamaCloud); |
| 10681 | assert_eq!(identity.key.as_str(), "ollama-cloud"); |
| 10682 | assert_eq!(identity.persisted_id(), Some("ollama-cloud")); |
| 10683 | assert!(!identity.migrated_legacy_ollama_cloud_route); |
| 10684 | |
| 10685 | let coexisting = Config { |
| 10686 | provider: Some("ollama".to_string()), |
| 10687 | providers: Some(ProvidersConfig { |
| 10688 | ollama: ProviderConfig { |
| 10689 | base_url: Some(codewhale_config::provider::OLLAMA_CLOUD_BASE_URL.to_string()), |
| 10690 | ..ProviderConfig::default() |
| 10691 | }, |
| 10692 | ollama_cloud: ProviderConfig { |
| 10693 | base_url: Some(codewhale_config::provider::OLLAMA_CLOUD_BASE_URL.to_string()), |
| 10694 | ..ProviderConfig::default() |
| 10695 | }, |
| 10696 | ..ProvidersConfig::default() |
| 10697 | }), |
| 10698 | ..Config::default() |
| 10699 | }; |
| 10700 | let explicit = coexisting |
| 10701 | .resolve_persisted_provider_identity(Some("ollama-cloud"), Some("ollama-cloud")) |
| 10702 | .expect("explicit receipt stays on the first-class route"); |
| 10703 | assert!(!explicit.migrated_legacy_ollama_cloud_route); |
| 10704 | assert_eq!(explicit.persisted_id(), Some("ollama-cloud")); |
| 10705 | |
| 10706 | let mut explicit_live = coexisting.clone(); |
| 10707 | explicit_live.provider = Some("ollama-cloud".to_string()); |
| 10708 | let migrated = explicit_live |
| 10709 | .resolve_persisted_provider_identity(Some("ollama-cloud"), Some("ollama")) |
| 10710 | .expect("legacy receipt retains its source route after a live provider switch"); |
| 10711 | assert!(migrated.migrated_legacy_ollama_cloud_route); |
| 10712 | assert_eq!(migrated.persisted_id(), Some("ollama")); |
| 10713 | } |
| 10714 | |
| 10715 | #[test] |
| 10716 | fn persisted_custom_fields_require_root_provenance_when_exact_id_is_absent() { |
| 10717 | let table_only = Config::from_saved_document( |
| 10718 | r#"provider = "custom" |
| 10719 | [providers.custom] |
| 10720 | kind = "openai-compatible" |
| 10721 | base_url = "http://127.0.0.1:1234/v1" |
| 10722 | model = "local-model" |
| 10723 | "#, |
| 10724 | None, |
| 10725 | ) |
| 10726 | .unwrap(); |
| 10727 | assert!( |
| 10728 | table_only |
| 10729 | .resolve_persisted_provider_identity(Some("custom"), None) |
| 10730 | .is_err() |
| 10731 | ); |
| 10732 | let exact = table_only |
| 10733 | .resolve_persisted_provider_identity(Some("custom"), Some("custom")) |
| 10734 | .unwrap(); |
| 10735 | assert_eq!(exact.persisted_id(), Some("custom")); |
| 10736 | |
| 10737 | let root_only = Config::from_saved_document( |
| 10738 | r#"provider = "custom" |
| 10739 | base_url = "http://127.0.0.1:18180/v1" |
| 10740 | default_text_model = "legacy-root-model" |
| 10741 | "#, |
| 10742 | None, |
| 10743 | ) |
| 10744 | .unwrap(); |
| 10745 | let root = root_only |
| 10746 | .resolve_persisted_provider_identity(Some("custom"), None) |
| 10747 | .unwrap(); |
| 10748 | assert_eq!(root.provider, ProviderKind::Custom); |
| 10749 | assert_eq!(root.key.as_str(), "custom"); |
| 10750 | assert_eq!(root.persisted_id(), None); |
| 10751 | assert_eq!(root_only.active_provider_identity().unwrap(), root); |
| 10752 | assert_eq!( |
| 10753 | root_only.base_url_for_route(&root), |
| 10754 | "http://127.0.0.1:18180/v1" |
| 10755 | ); |
| 10756 | assert_eq!( |
| 10757 | root_only |
| 10758 | .resolve_persisted_provider_identity(Some("custom"), Some("custom")) |
| 10759 | .unwrap() |
| 10760 | .persisted_id(), |
| 10761 | Some("custom") |
| 10762 | ); |
| 10763 | let mut scoped = root_only.clone(); |
| 10764 | scoped.scope_to_provider_identity(&root).unwrap(); |
| 10765 | assert_eq!( |
| 10766 | scoped.base_url_for_route(&root), |
| 10767 | "http://127.0.0.1:18180/v1" |
| 10768 | ); |
| 10769 | assert!(format!("{root:?}").contains("<redacted>")); |
| 10770 | assert!(!format!("{root:?}").contains("18180")); |
| 10771 | |
| 10772 | // A pre-existing exact table owns its own endpoint. The conflicting root |
| 10773 | // endpoint is routed to DeepSeek by #6394 and cannot authorize id-less custom. |
| 10774 | let coexist = Config::from_saved_document( |
| 10775 | r#"provider = "custom" |
| 10776 | base_url = "http://127.0.0.1:18180/v1" |
| 10777 | [providers.custom] |
| 10778 | kind = "openai-compatible" |
| 10779 | base_url = "http://127.0.0.1:1234/v1" |
| 10780 | model = "local-model" |
| 10781 | "#, |
| 10782 | None, |
| 10783 | ) |
| 10784 | .unwrap(); |
| 10785 | assert!( |
| 10786 | coexist |
| 10787 | .resolve_persisted_provider_identity(Some("custom"), None) |
| 10788 | .is_err() |
| 10789 | ); |
| 10790 | let exact = coexist |
| 10791 | .resolve_persisted_provider_identity(Some("custom"), Some("custom")) |
| 10792 | .unwrap(); |
| 10793 | assert_eq!( |
| 10794 | coexist.base_url_for_route(&exact), |
| 10795 | "http://127.0.0.1:1234/v1" |
| 10796 | ); |
| 10797 | assert_eq!( |
| 10798 | coexist.deepseek_table_base_url(), |
| 10799 | Some("http://127.0.0.1:18180/v1") |
| 10800 | ); |
| 10801 | } |
| 10802 | |
| 10803 | #[test] |
| 10804 | fn persisted_empty_custom_id_never_authorizes_a_route() { |
| 10805 | let config = Config::from_saved_document( |
| 10806 | r#"provider = "custom" |
| 10807 | base_url = "http://127.0.0.1:18180/v1" |
| 10808 | default_text_model = "legacy-root-model" |
| 10809 | "#, |
| 10810 | None, |
| 10811 | ) |
| 10812 | .unwrap(); |
| 10813 | for malformed_id in ["", " "] { |
| 10814 | let error = config |
| 10815 | .resolve_persisted_provider_identity(Some("custom"), Some(malformed_id)) |
| 10816 | .unwrap_err(); |
| 10817 | assert!(error.contains("empty exact provider id"), "{error}"); |
| 10818 | assert!(error.contains("will not guess or fall back"), "{error}"); |
| 10819 | } |
| 10820 | assert_eq!( |
| 10821 | config |
| 10822 | .resolve_persisted_provider_identity(Some("custom"), None) |
| 10823 | .unwrap() |
| 10824 | .persisted_id(), |
| 10825 | None |
| 10826 | ); |
| 10827 | assert_eq!( |
| 10828 | config |
| 10829 | .resolve_persisted_provider_identity(Some("custom"), Some("custom")) |
| 10830 | .unwrap() |
| 10831 | .persisted_id(), |
| 10832 | Some("custom") |
| 10833 | ); |
| 10834 | } |
| 10835 | |
| 10836 | #[test] |
| 10837 | fn persisted_provider_pair_never_collapses_builtin_into_same_key_custom_route() { |
| 10838 | let config = |
| 10839 | session_custom_provider_config("openai", "openai-compatible", "http://127.0.0.1:1234/v1"); |
| 10840 | assert_eq!( |
| 10841 | config |
| 10842 | .resolve_provider_identity("openai") |
| 10843 | .expect("raw exact identity intentionally prefers custom"), |
| 10844 | ProviderIdentity { |
| 10845 | provider: ProviderKind::Custom, |
| 10846 | key: "openai".into(), |
| 10847 | exact_id: Some("openai".into()), |
| 10848 | migrated_legacy_ollama_cloud_route: false, |
| 10849 | legacy_root_custom_generation: None, |
| 10850 | } |
| 10851 | ); |
| 10852 | |
| 10853 | for provider_id in [None, Some("openai")] { |
| 10854 | let error = config |
| 10855 | .resolve_persisted_provider_identity(Some("openai"), provider_id) |
| 10856 | .expect_err("built-in record must not be captured by the custom table"); |
| 10857 | assert!(error.contains("requires built-in 'openai'"), "{error}"); |
| 10858 | assert!(error.contains("shadows"), "{error}"); |
| 10859 | assert!(error.contains("will not guess or fall back"), "{error}"); |
| 10860 | } |
| 10861 | |
| 10862 | let exact_custom = config |
| 10863 | .resolve_persisted_provider_identity(Some("custom"), Some("openai")) |
| 10864 | .expect("custom kind plus exact id intentionally selects the table"); |
| 10865 | assert_eq!(exact_custom.provider, ProviderKind::Custom); |
| 10866 | assert_eq!(exact_custom.key.as_str(), "openai"); |
| 10867 | |
| 10868 | let mismatch = config |
| 10869 | .resolve_persisted_provider_identity(Some("openrouter"), Some("openai")) |
| 10870 | .expect_err("mismatched built-in kind/id pair must fail closed"); |
| 10871 | assert!(mismatch.contains("mismatched fields"), "{mismatch}"); |
| 10872 | } |
| 10873 | |
| 10874 | #[test] |
| 10875 | fn legacy_literal_custom_identity_resolves_to_its_migrated_table() { |
| 10876 | let _lock = lock_test_env(); |
| 10877 | let _source = EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 10878 | let _cli_key = EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 10879 | let legacy = Config { |
| 10880 | provider: Some("custom".to_string()), |
| 10881 | default_text_model: Some("local-legacy-model".to_string()), |
| 10882 | ..Config::default() |
| 10883 | } |
| 10884 | .with_legacy_root( |
| 10885 | Some("legacy-root-key".to_string()), |
| 10886 | Some("http://127.0.0.1:1234/v1".to_string()), |
| 10887 | ); |
| 10888 | |
| 10889 | assert_eq!( |
| 10890 | legacy |
| 10891 | .resolve_provider_identity("custom") |
| 10892 | .expect("unchanged legacy root route"), |
| 10893 | // The top-level route became the exact `[providers.custom]` table |
| 10894 | // when parsed (#6394). |
| 10895 | ProviderIdentity { |
| 10896 | provider: ProviderKind::Custom, |
| 10897 | key: "custom".into(), |
| 10898 | exact_id: Some("custom".into()), |
| 10899 | migrated_legacy_ollama_cloud_route: false, |
| 10900 | legacy_root_custom_generation: None, |
| 10901 | } |
| 10902 | ); |
| 10903 | assert_eq!(legacy.active_route_base_url(), "http://127.0.0.1:1234/v1"); |
| 10904 | assert_eq!(legacy.default_model(), "local-legacy-model"); |
| 10905 | assert_eq!(legacy.active_route_api_key().unwrap(), "legacy-root-key"); |
| 10906 | |
| 10907 | let mut named = session_custom_provider_config( |
| 10908 | "lm-studio", |
| 10909 | "openai-compatible", |
| 10910 | "https://api.example.com/v1", |
| 10911 | ); |
| 10912 | named.set_legacy_root(Some("must-not-leak-to-named-route".to_string()), None); |
| 10913 | let named_key_error = named |
| 10914 | .active_route_api_key() |
| 10915 | .expect_err("root legacy key must never authorize a named custom route") |
| 10916 | .to_string(); |
| 10917 | assert!(named_key_error.contains("lm-studio"), "{named_key_error}"); |
| 10918 | assert!(!named_key_error.contains("must-not-leak")); |
| 10919 | |
| 10920 | let mut ambiguous_named = named.clone(); |
| 10921 | ambiguous_named |
| 10922 | .providers |
| 10923 | .as_mut() |
| 10924 | .expect("providers") |
| 10925 | .custom |
| 10926 | .insert( |
| 10927 | "vllm-local".to_string(), |
| 10928 | ProviderConfig { |
| 10929 | kind: Some("openai-compatible".to_string()), |
| 10930 | base_url: Some("http://127.0.0.1:8000/v1".to_string()), |
| 10931 | model: Some("other-local-model".to_string()), |
| 10932 | ..ProviderConfig::default() |
| 10933 | }, |
| 10934 | ); |
| 10935 | let ambiguous_named_error = ambiguous_named |
| 10936 | .resolve_provider_identity("custom") |
| 10937 | .expect_err("generic released record cannot choose between named routes"); |
| 10938 | assert!( |
| 10939 | ambiguous_named_error.contains("valid named routes: 2"), |
| 10940 | "{ambiguous_named_error}" |
| 10941 | ); |
| 10942 | assert!(ambiguous_named_error.contains("will not guess or fall back")); |
| 10943 | |
| 10944 | let removed_named = legacy |
| 10945 | .resolve_provider_identity("lm-studio") |
| 10946 | .expect_err("a removed named route must not fall back to legacy custom"); |
| 10947 | assert!(removed_named.contains("[providers.lm-studio]")); |
| 10948 | assert!(removed_named.contains("will not fall back")); |
| 10949 | } |
| 10950 | |
| 10951 | #[test] |
| 10952 | fn legacy_literal_custom_env_overrides_keep_the_literal_route() -> Result<()> { |
| 10953 | let _lock = lock_test_env(); |
| 10954 | let nanos = SystemTime::now() |
| 10955 | .duration_since(UNIX_EPOCH) |
| 10956 | .unwrap() |
| 10957 | .as_nanos(); |
| 10958 | let temp_root = env::temp_dir().join(format!( |
| 10959 | "codewhale-tui-legacy-custom-env-{}-{}", |
| 10960 | std::process::id(), |
| 10961 | nanos |
| 10962 | )); |
| 10963 | fs::create_dir_all(&temp_root)?; |
| 10964 | let _guard = EnvGuard::new(&temp_root); |
| 10965 | let _source = EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 10966 | let _cli_key = EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 10967 | |
| 10968 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 10969 | ensure_parent_dir(&config_path)?; |
| 10970 | fs::write( |
| 10971 | &config_path, |
| 10972 | r#"provider = "custom" |
| 10973 | api_key = "legacy-root-key" |
| 10974 | base_url = "http://127.0.0.1:18184/v1" |
| 10975 | default_text_model = "legacy-model" |
| 10976 | "#, |
| 10977 | )?; |
| 10978 | // Safety: test-only env mutation guarded by lock_test_env(). |
| 10979 | unsafe { |
| 10980 | env::set_var("CODEWHALE_BASE_URL", "http://127.0.0.1:18185/v1"); |
| 10981 | env::set_var("CODEWHALE_MODEL", "env-legacy-model"); |
| 10982 | env::set_var("DEEPSEEK_HTTP_HEADERS", "X-Legacy-Route=kept"); |
| 10983 | } |
| 10984 | |
| 10985 | let config = Config::load(None, None)?; |
| 10986 | |
| 10987 | // The top-level route moved into `[providers.custom]` when parsed (#6394). |
| 10988 | assert!(config.selects_literal_custom_provider()); |
| 10989 | assert!( |
| 10990 | config |
| 10991 | .providers |
| 10992 | .as_ref() |
| 10993 | .is_some_and(|providers| providers.custom.contains_key("custom")) |
| 10994 | ); |
| 10995 | assert_eq!(config.active_route_base_url(), "http://127.0.0.1:18185/v1"); |
| 10996 | assert_eq!(config.default_model(), "env-legacy-model"); |
| 10997 | assert_eq!( |
| 10998 | config.active_route_api_key()?, |
| 10999 | "", |
| 11000 | "an env-selected keyless loopback route must not inherit the file-owned root key" |
| 11001 | ); |
| 11002 | assert!(!active_provider_has_config_api_key(&config)); |
| 11003 | assert_eq!( |
| 11004 | config |
| 11005 | .http_headers() |
| 11006 | .get("X-Legacy-Route") |
| 11007 | .map(String::as_str), |
| 11008 | Some("kept") |
| 11009 | ); |
| 11010 | for _ in 0..2 { |
| 11011 | assert_eq!( |
| 11012 | config |
| 11013 | .resolve_provider_identity("custom") |
| 11014 | .expect("legacy route remains repeatedly resolvable") |
| 11015 | .key |
| 11016 | .as_str(), |
| 11017 | "custom" |
| 11018 | ); |
| 11019 | } |
| 11020 | Ok(()) |
| 11021 | } |
| 11022 | |
| 11023 | #[test] |
| 11024 | fn session_provider_identity_fails_closed_for_removed_or_invalid_custom_table() { |
| 11025 | let removed = Config::default(); |
| 11026 | let missing = removed |
| 11027 | .resolve_provider_identity("lm-studio") |
| 11028 | .expect_err("removed provider must fail closed"); |
| 11029 | assert!(missing.contains("[providers.lm-studio]")); |
| 11030 | assert!(missing.contains("will not fall back")); |
| 11031 | |
| 11032 | let invalid_kind = session_custom_provider_config( |
| 11033 | "lm-studio", |
| 11034 | "anthropic-messages", |
| 11035 | "http://127.0.0.1:1234/v1", |
| 11036 | ); |
| 11037 | let kind_error = invalid_kind |
| 11038 | .resolve_provider_identity("lm-studio") |
| 11039 | .expect_err("unsupported custom wire kind must fail closed"); |
| 11040 | assert!(kind_error.contains("kind = \"openai-compatible\"")); |
| 11041 | |
| 11042 | let invalid_url = |
| 11043 | session_custom_provider_config("lm-studio", "openai-compatible", "not a provider URL"); |
| 11044 | let url_error = invalid_url |
| 11045 | .resolve_provider_identity("lm-studio") |
| 11046 | .expect_err("invalid custom URL must fail closed"); |
| 11047 | assert!(url_error.contains("base_url")); |
| 11048 | assert!(url_error.contains("will not fall back")); |
| 11049 | } |
| 11050 | |
| 11051 | #[test] |
| 11052 | fn picker_consent_persists_only_confirmed_exact_scope_and_revoke_is_one_step() { |
| 11053 | let dir = tempfile::TempDir::new().expect("tempdir"); |
| 11054 | let config_path = dir.path().join("config.toml"); |
| 11055 | let external_path = dir.path().join("codex-auth.json"); |
| 11056 | std::fs::write( |
| 11057 | &config_path, |
| 11058 | "# preserve operator comment\n[providers.openai_codex]\nmodel = \"gpt-5-codex\" # preserve model\n", |
| 11059 | ) |
| 11060 | .expect("seed config"); |
| 11061 | // #5772: persistence now reads and validates the exact confirmed file |
| 11062 | // before any consent record is written, so the fixture must hold a live |
| 11063 | // token (far-future JWT exp) for the grant to be saved at all. |
| 11064 | std::fs::write( |
| 11065 | &external_path, |
| 11066 | "{\"tokens\":{\"access_token\":\"header.eyJleHAiOjk5OTk5OTk5OTl9.sig\"}}", |
| 11067 | ) |
| 11068 | .expect("seed external credential"); |
| 11069 | // The secure adapter rejects symlinked path components; macOS `/var` is |
| 11070 | // one, so the confirmed path must be the canonical one. |
| 11071 | let external_path = external_path |
| 11072 | .canonicalize() |
| 11073 | .expect("canonical external credential path"); |
| 11074 | let mut live = Config { |
| 11075 | provider: Some(ProviderKind::OpenaiCodex.as_str().to_string()), |
| 11076 | ..Config::default() |
| 11077 | }; |
| 11078 | |
| 11079 | crate::external_credentials::reset_side_effect_trap(); |
| 11080 | { |
| 11081 | let captured_fixture_identity = (live).test_identity_for_kind(ProviderKind::OpenaiCodex); |
| 11082 | persist_external_credential_consent_for_at( |
| 11083 | Some(&config_path), |
| 11084 | &mut live, |
| 11085 | &captured_fixture_identity, |
| 11086 | codewhale_config::ProviderKind::OpenaiCodex, |
| 11087 | codewhale_config::ExternalCredentialSource::CodexCli, |
| 11088 | &external_path, |
| 11089 | ) |
| 11090 | } |
| 11091 | .expect("persist confirmed consent"); |
| 11092 | let saved = std::fs::read_to_string(&config_path).expect("saved config"); |
| 11093 | assert!(saved.contains("# preserve operator comment")); |
| 11094 | assert!(saved.contains("model = \"gpt-5-codex\" # preserve model")); |
| 11095 | assert!(saved.contains("access = \"read_only\"")); |
| 11096 | assert!(saved.contains("source = \"codex_cli\"")); |
| 11097 | assert!(saved.contains(&external_path.display().to_string())); |
| 11098 | let consent = live |
| 11099 | .provider_config_for(&live.test_identity_for_kind(ProviderKind::OpenaiCodex)) |
| 11100 | .and_then(|entry| entry.external_credentials.as_ref()) |
| 11101 | .expect("live consent"); |
| 11102 | assert_eq!(consent.path, external_path); |
| 11103 | assert_eq!( |
| 11104 | crate::external_credentials::complete_side_effect_trap_counts(), |
| 11105 | (1, 1, 0, 0, 0), |
| 11106 | "grant persistence performs exactly the confirmed read (one secure open, one \ |
| 11107 | bounded read) and never writes, refreshes, or reaches the network" |
| 11108 | ); |
| 11109 | |
| 11110 | crate::external_credentials::reset_side_effect_trap(); |
| 11111 | { |
| 11112 | let captured_fixture_identity = (live).test_identity_for_kind(ProviderKind::OpenaiCodex); |
| 11113 | revoke_external_credential_consent_for_at( |
| 11114 | Some(&config_path), |
| 11115 | &mut live, |
| 11116 | &captured_fixture_identity, |
| 11117 | ) |
| 11118 | } |
| 11119 | .expect("one-step revoke"); |
| 11120 | let revoked = std::fs::read_to_string(&config_path).expect("revoked config"); |
| 11121 | assert!(!revoked.contains("external_credentials")); |
| 11122 | assert!( |
| 11123 | live.provider_config_for(&live.test_identity_for_kind(ProviderKind::OpenaiCodex)) |
| 11124 | .and_then(|entry| entry.external_credentials.as_ref()) |
| 11125 | .is_none() |
| 11126 | ); |
| 11127 | assert_eq!( |
| 11128 | crate::external_credentials::complete_side_effect_trap_counts(), |
| 11129 | (0, 0, 0, 0, 0) |
| 11130 | ); |
| 11131 | } |
| 11132 | |
| 11133 | /// Every provider must accept the model ids it advertises for itself. |
| 11134 | /// |
| 11135 | /// Regression for #4829: `validate()` checked `default_text_model` against the |
| 11136 | /// DeepSeek-only normalizer, so a config our own setup wizard writes |
| 11137 | /// (`provider = "zai"`, `default_text_model = "GLM-5.2"`) was rejected on every |
| 11138 | /// startup — the CLI could not launch at all. This asserts the equal-treatment |
| 11139 | /// contract from CLAUDE.md: no provider's own models are second-class. |
| 11140 | #[test] |
| 11141 | fn validate_accepts_every_providers_own_advertised_models() { |
| 11142 | for &provider in ProviderKind::all() { |
| 11143 | for model in model_completion_names_for_provider(provider) { |
| 11144 | let config = Config { |
| 11145 | provider: Some(provider.as_str().to_string()), |
| 11146 | default_text_model: Some(model.to_string()), |
| 11147 | ..Default::default() |
| 11148 | }; |
| 11149 | assert!( |
| 11150 | config.validate().is_ok(), |
| 11151 | "provider {} rejected its own advertised model {model}: {:?}", |
| 11152 | provider.as_str(), |
| 11153 | config.validate().unwrap_err().to_string(), |
| 11154 | ); |
| 11155 | } |
| 11156 | } |
| 11157 | } |
| 11158 | |
| 11159 | /// The exact config that bricked the CLI in the field. |
| 11160 | #[test] |
| 11161 | fn validate_accepts_zai_glm_model_from_setup_wizard() { |
| 11162 | let config = Config { |
| 11163 | provider: Some("zai".to_string()), |
| 11164 | default_text_model: Some(DEFAULT_ZAI_MODEL.to_string()), |
| 11165 | ..Default::default() |
| 11166 | }; |
| 11167 | config |
| 11168 | .validate() |
| 11169 | .expect("setup-wizard zai/GLM config must validate"); |
| 11170 | } |
| 11171 | |
| 11172 | /// The official DeepSeek gate is the one legitimate per-family rejection and |
| 11173 | /// must survive the fix — this is what keeps the validation meaningful. |
| 11174 | #[test] |
| 11175 | fn validate_still_rejects_unknown_model_on_official_deepseek() { |
| 11176 | let config = Config { |
| 11177 | provider: Some("deepseek".to_string()), |
| 11178 | default_text_model: Some("definitely-not-a-deepseek-model".to_string()), |
| 11179 | ..Default::default() |
| 11180 | }; |
| 11181 | let err = config |
| 11182 | .validate() |
| 11183 | .expect_err("official DeepSeek must reject foreign ids") |
| 11184 | .to_string(); |
| 11185 | assert!( |
| 11186 | err.contains("definitely-not-a-deepseek-model") && err.contains("deepseek"), |
| 11187 | "error should name the model and the active provider, got: {err}" |
| 11188 | ); |
| 11189 | } |
| 11190 | |
| 11191 | #[test] |
| 11192 | fn validate_checks_the_selected_provider_model_before_the_root_fallback() { |
| 11193 | for (model, root, valid) in [ |
| 11194 | ("deepseek-v4-pro", "old-provider-model", true), |
| 11195 | ("auto", "old-provider-model", true), |
| 11196 | ("not-a-deepseek-model", "deepseek-v4-pro", false), |
| 11197 | ("", "deepseek-v4-pro", false), |
| 11198 | (" ", "deepseek-v4-pro", false), |
| 11199 | ] { |
| 11200 | let mut config = Config { |
| 11201 | provider: Some("deepseek".to_string()), |
| 11202 | default_text_model: Some(root.to_string()), |
| 11203 | ..Default::default() |
| 11204 | }; |
| 11205 | config |
| 11206 | .provider_config_for_mut(&config.test_identity_for_kind(ProviderKind::Deepseek)) |
| 11207 | .unwrap() |
| 11208 | .model = Some(model.to_string()); |
| 11209 | let result = config.validate(); |
| 11210 | assert_eq!( |
| 11211 | result.is_ok(), |
| 11212 | valid, |
| 11213 | "selected {model:?}, root {root:?}: {result:?}" |
| 11214 | ); |
| 11215 | if valid { |
| 11216 | assert_eq!(config.default_model(), model); |
| 11217 | } |
| 11218 | assert_eq!(config.default_text_model.as_deref(), Some(root)); |
| 11219 | } |
| 11220 | |
| 11221 | // Exact route declarations remain first-class; a declaration for another |
| 11222 | // provider cannot make an unknown model valid on this route. |
| 11223 | let mut declared: Config = toml::from_str( |
| 11224 | r#"provider = "deepseek" |
| 11225 | default_text_model = "old-provider-model" |
| 11226 | [providers.deepseek] |
| 11227 | base_url = "https://api.deepseek.com" |
| 11228 | model = "account-model" |
| 11229 | [[custom_models]] |
| 11230 | provider = "deepseek" |
| 11231 | base_url = "https://api.deepseek.com" |
| 11232 | id = "account-model" |
| 11233 | "#, |
| 11234 | ) |
| 11235 | .unwrap(); |
| 11236 | declared.validate().expect("matching declared model"); |
| 11237 | assert_eq!(declared.default_model(), "account-model"); |
| 11238 | declared.custom_models.as_mut().unwrap()[0].provider = "zai".to_string(); |
| 11239 | assert!(declared.validate().is_err()); |
| 11240 | } |
| 11241 | |
| 11242 | #[test] |
| 11243 | fn native_memory_scenario() { |
| 11244 | // Scenario consolidation of: native_memory_backend_owns_explicit_path, native_memory_path_honours_an_already_native_setting |
| 11245 | // from native_memory_backend_owns_explicit_path |
| 11246 | { |
| 11247 | let tmp = tempfile::tempdir().unwrap(); |
| 11248 | let legacy = tmp.path().join("legacy-memory.md"); |
| 11249 | let config = Config { |
| 11250 | memory_path: Some(legacy.to_string_lossy().into_owned()), |
| 11251 | memory: Some(MemoryConfig { |
| 11252 | backend: Some(MemoryBackend::Native), |
| 11253 | ..Default::default() |
| 11254 | }), |
| 11255 | ..Default::default() |
| 11256 | }; |
| 11257 | assert_eq!(config.memory_backend(), MemoryBackend::Native); |
| 11258 | assert!(config.memory_enabled()); |
| 11259 | assert_eq!( |
| 11260 | config.memory_path(), |
| 11261 | tmp.path().join("memory/global/MEMORY.md") |
| 11262 | ); |
| 11263 | } |
| 11264 | // from native_memory_path_honours_an_already_native_setting |
| 11265 | { |
| 11266 | // Pointing `memory_path` at a native store is the obvious reading of the |
| 11267 | // name; it used to nest a second store inside and write to the wrong file. |
| 11268 | let mut config = Config::default(); |
| 11269 | config.memory = Some(crate::config::MemoryConfig { |
| 11270 | enabled: Some(true), |
| 11271 | ..Default::default() |
| 11272 | }); |
| 11273 | config.memory_path = Some("/tmp/cw-test/memory/global/MEMORY.md".to_string()); |
| 11274 | assert_eq!( |
| 11275 | config.memory_path(), |
| 11276 | std::path::PathBuf::from("/tmp/cw-test/memory/global/MEMORY.md") |
| 11277 | ); |
| 11278 | |
| 11279 | // A legacy single-file setting still anchors the store beside it. |
| 11280 | config.memory_path = Some("/tmp/cw-test/memory.md".to_string()); |
| 11281 | assert_eq!( |
| 11282 | config.memory_path(), |
| 11283 | std::path::PathBuf::from("/tmp/cw-test/memory/global/MEMORY.md") |
| 11284 | ); |
| 11285 | } |
| 11286 | } |
| 11287 | |
| 11288 | /// Pins the v0.9.4 memory consolidation: with `[memory] enabled = true` |
| 11289 | /// (no explicit backend), the resolved memory path is always the native |
| 11290 | /// `memory/global/MEMORY.md` layout, so `NativeMemoryStore::from_global_path` |
| 11291 | /// accepts it and the deleted legacy single-file branch can never be taken. |
| 11292 | #[test] |
| 11293 | fn enabled_memory_always_resolves_to_native_store_path() { |
| 11294 | let tmp = tempfile::tempdir().unwrap(); |
| 11295 | let config: Config = toml::from_str( |
| 11296 | r#" |
| 11297 | [memory] |
| 11298 | enabled = true |
| 11299 | "#, |
| 11300 | ) |
| 11301 | .expect("parse enabled memory config"); |
| 11302 | assert_eq!(config.memory_backend(), MemoryBackend::Native); |
| 11303 | let path = config.memory_path(); |
| 11304 | assert!( |
| 11305 | path.ends_with("memory/global/MEMORY.md"), |
| 11306 | "enabled memory must resolve to the native layout, got {}", |
| 11307 | path.display() |
| 11308 | ); |
| 11309 | assert!( |
| 11310 | crate::native_memory::NativeMemoryStore::from_global_path(&path).is_some(), |
| 11311 | "native store must accept the resolved memory path" |
| 11312 | ); |
| 11313 | |
| 11314 | // Even an explicitly configured single-file path is re-rooted into the |
| 11315 | // native layout under the native backend. |
| 11316 | let custom = Config { |
| 11317 | memory_path: Some(tmp.path().join("memory.md").to_string_lossy().into_owned()), |
| 11318 | memory: Some(MemoryConfig { |
| 11319 | enabled: Some(true), |
| 11320 | ..Default::default() |
| 11321 | }), |
| 11322 | ..Default::default() |
| 11323 | }; |
| 11324 | let custom_path = custom.memory_path(); |
| 11325 | assert!( |
| 11326 | crate::native_memory::NativeMemoryStore::from_global_path(&custom_path).is_some(), |
| 11327 | "custom memory paths are re-rooted into the native layout, got {}", |
| 11328 | custom_path.display() |
| 11329 | ); |
| 11330 | } |
| 11331 | |
| 11332 | /// v0.9.1 kimi-k3 dogfood report: a dogfood user ran `codewhale --provider moonshot --model kimi-k3` |
| 11333 | /// and the session kept reporting `kimi-k2.7-code`. The `--model` flag reaches |
| 11334 | /// this binary as `CODEWHALE_MODEL`, so the route it produces is asserted here |
| 11335 | /// end to end: the effective model, the endpoint, and the id that goes on the |
| 11336 | /// wire must all be the one the user named. |
| 11337 | #[test] |
| 11338 | fn cli_model_flag_selects_kimi_k3_on_the_moonshot_platform_route() -> Result<()> { |
| 11339 | let _lock = lock_test_env(); |
| 11340 | let nanos = SystemTime::now() |
| 11341 | .duration_since(UNIX_EPOCH) |
| 11342 | .unwrap() |
| 11343 | .as_nanos(); |
| 11344 | let temp_root = env::temp_dir().join(format!( |
| 11345 | "codewhale-tui-kimi-k3-cli-{}-{nanos}", |
| 11346 | std::process::id() |
| 11347 | )); |
| 11348 | fs::create_dir_all(&temp_root)?; |
| 11349 | let _guard = EnvGuard::new(&temp_root); |
| 11350 | |
| 11351 | // `EnvGuard` points DEEPSEEK_CONFIG_PATH at `<home>/.deepseek/config.toml`. |
| 11352 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 11353 | ensure_parent_dir(&config_path)?; |
| 11354 | fs::write( |
| 11355 | &config_path, |
| 11356 | "provider = \"moonshot\"\n\n[providers.moonshot]\napi_key = \"k\"\n", |
| 11357 | )?; |
| 11358 | // Safety: test-only env mutation guarded by lock_test_env(). |
| 11359 | unsafe { |
| 11360 | env::set_var("CODEWHALE_PROVIDER", "moonshot"); |
| 11361 | env::set_var("CODEWHALE_MODEL", MOONSHOT_KIMI_K3_MODEL); |
| 11362 | } |
| 11363 | |
| 11364 | let config = Config::load(None, None)?; |
| 11365 | |
| 11366 | assert_eq!( |
| 11367 | config.active_provider_identity().unwrap().provider, |
| 11368 | ProviderKind::Moonshot |
| 11369 | ); |
| 11370 | assert_eq!(config.default_model(), MOONSHOT_KIMI_K3_MODEL); |
| 11371 | assert_eq!(config.active_route_base_url(), DEFAULT_MOONSHOT_BASE_URL); |
| 11372 | assert_eq!( |
| 11373 | codewhale_config::route::resolve_model( |
| 11374 | ProviderKind::Moonshot, |
| 11375 | &config.default_model(), |
| 11376 | Some(&config.active_route_base_url()), |
| 11377 | ) |
| 11378 | .unwrap() |
| 11379 | .wire_id, |
| 11380 | MOONSHOT_KIMI_K3_MODEL, |
| 11381 | "the id the user named must be the id on the wire" |
| 11382 | ); |
| 11383 | assert_eq!( |
| 11384 | explicit_launch_model_override().as_deref(), |
| 11385 | Some(MOONSHOT_KIMI_K3_MODEL), |
| 11386 | "an explicit --model must remain recognizable as an explicit request" |
| 11387 | ); |
| 11388 | assert_eq!( |
| 11389 | moonshot_k3_route_display_name(&config.active_route_base_url(), &config.default_model()), |
| 11390 | Some("Moonshot direct / kimi-k3") |
| 11391 | ); |
| 11392 | Ok(()) |
| 11393 | } |
| 11394 | |
| 11395 | #[test] |
| 11396 | fn env_owned_deepseek_root_base_url_does_not_reach_the_deepseek_cn_sibling() -> Result<()> { |
| 11397 | let _lock = lock_test_env(); |
| 11398 | let temp_root = tempfile::tempdir()?; |
| 11399 | let _guard = EnvGuard::new(temp_root.path()); |
| 11400 | let _managed = no_managed_config(temp_root.path()); |
| 11401 | let config_path = temp_root.path().join("config.toml"); |
| 11402 | fs::write(&config_path, "provider = \"deepseek\"\n")?; |
| 11403 | let _base = EnvVarGuard::set("CODEWHALE_BASE_URL", "https://env-gateway.example.test/v1"); |
| 11404 | |
| 11405 | let config = Config::load(Some(config_path), None)?; |
| 11406 | |
| 11407 | // The env override owns the route it was addressed to. |
| 11408 | assert_eq!( |
| 11409 | config.active_provider_identity().unwrap().provider, |
| 11410 | ProviderKind::Deepseek |
| 11411 | ); |
| 11412 | assert_eq!( |
| 11413 | config.active_route_base_url(), |
| 11414 | "https://env-gateway.example.test/v1" |
| 11415 | ); |
| 11416 | assert!( |
| 11417 | config |
| 11418 | .provider_uses_custom_endpoint(&config.test_identity_for_kind(ProviderKind::Deepseek)) |
| 11419 | ); |
| 11420 | |
| 11421 | // The sibling identity shares the same legacy root field but is a |
| 11422 | // different route: it must fall through to its own canonical endpoint. |
| 11423 | assert_eq!( |
| 11424 | config.base_url_for_route( |
| 11425 | &config |
| 11426 | .resolve_provider_selection_identity("deepseek-cn") |
| 11427 | .unwrap() |
| 11428 | ), |
| 11429 | DEFAULT_DEEPSEEKCN_BASE_URL |
| 11430 | ); |
| 11431 | assert!( |
| 11432 | !config.provider_uses_custom_endpoint( |
| 11433 | &config |
| 11434 | .resolve_provider_selection_identity("deepseek-cn") |
| 11435 | .unwrap() |
| 11436 | ) |
| 11437 | ); |
| 11438 | assert!( |
| 11439 | !config.model_ids_pass_through_for_provider( |
| 11440 | &config |
| 11441 | .resolve_provider_selection_identity("deepseek-cn") |
| 11442 | .unwrap() |
| 11443 | ) |
| 11444 | ); |
| 11445 | Ok(()) |
| 11446 | } |
| 11447 | |
| 11448 | #[test] |
| 11449 | fn env_owned_deepseek_cn_root_base_url_does_not_reach_the_deepseek_sibling() -> Result<()> { |
| 11450 | let _lock = lock_test_env(); |
| 11451 | let temp_root = tempfile::tempdir()?; |
| 11452 | let _guard = EnvGuard::new(temp_root.path()); |
| 11453 | let _managed = no_managed_config(temp_root.path()); |
| 11454 | let config_path = temp_root.path().join("config.toml"); |
| 11455 | fs::write(&config_path, "provider = \"deepseek-cn\"\n")?; |
| 11456 | let _base = EnvVarGuard::set( |
| 11457 | "DEEPSEEK_BASE_URL", |
| 11458 | "https://cn-env-gateway.example.test/v1", |
| 11459 | ); |
| 11460 | |
| 11461 | let config = Config::load(Some(config_path), None)?; |
| 11462 | |
| 11463 | assert_eq!( |
| 11464 | config.active_provider_identity().unwrap().key.as_str(), |
| 11465 | "deepseek-cn" |
| 11466 | ); |
| 11467 | assert_eq!( |
| 11468 | config.active_provider_identity().unwrap().provider, |
| 11469 | ProviderKind::Deepseek |
| 11470 | ); |
| 11471 | assert_eq!( |
| 11472 | config.active_route_base_url(), |
| 11473 | "https://cn-env-gateway.example.test/v1" |
| 11474 | ); |
| 11475 | assert!( |
| 11476 | config.provider_uses_custom_endpoint( |
| 11477 | &config |
| 11478 | .resolve_provider_selection_identity("deepseek-cn") |
| 11479 | .unwrap() |
| 11480 | ) |
| 11481 | ); |
| 11482 | |
| 11483 | assert_eq!( |
| 11484 | config.base_url_for_route( |
| 11485 | &config |
| 11486 | .resolve_provider_selection_identity("deepseek") |
| 11487 | .unwrap() |
| 11488 | ), |
| 11489 | DEFAULT_DEEPSEEK_BASE_URL |
| 11490 | ); |
| 11491 | assert!( |
| 11492 | !config.provider_uses_custom_endpoint( |
| 11493 | &config |
| 11494 | .resolve_provider_selection_identity("deepseek") |
| 11495 | .unwrap() |
| 11496 | ) |
| 11497 | ); |
| 11498 | Ok(()) |
| 11499 | } |
| 11500 | |
| 11501 | #[test] |
| 11502 | fn file_owned_legacy_root_base_url_stays_shared_by_both_deepseek_identities() -> Result<()> { |
| 11503 | let _lock = lock_test_env(); |
| 11504 | let temp_root = tempfile::tempdir()?; |
| 11505 | let _guard = EnvGuard::new(temp_root.path()); |
| 11506 | let _managed = no_managed_config(temp_root.path()); |
| 11507 | let config_path = temp_root.path().join("config.toml"); |
| 11508 | fs::write( |
| 11509 | &config_path, |
| 11510 | "provider = \"deepseek\"\nbase_url = \"https://file-gateway.example.test/v1\"\n", |
| 11511 | )?; |
| 11512 | |
| 11513 | let config = Config::load(Some(config_path), None)?; |
| 11514 | |
| 11515 | // No environment write, so the value is the user's own. Parsing moved it |
| 11516 | // to `[providers.deepseek]` (#6394), which DeepSeek-CN also reads, so |
| 11517 | // both identities keep the endpoint exactly as they always have. |
| 11518 | for key in ["deepseek", "deepseek-cn"] { |
| 11519 | let provider = config.resolve_provider_selection_identity(key).unwrap(); |
| 11520 | assert_eq!( |
| 11521 | config.base_url_for_route(&provider), |
| 11522 | "https://file-gateway.example.test/v1", |
| 11523 | "{provider:?} must keep the file-owned legacy root endpoint" |
| 11524 | ); |
| 11525 | assert!(config.provider_uses_custom_endpoint(&provider)); |
| 11526 | } |
| 11527 | Ok(()) |
| 11528 | } |
| 11529 | |
| 11530 | #[test] |
| 11531 | fn managed_overlay_keeps_pinned_children_off_the_ambient_generic_host() -> Result<()> { |
| 11532 | let _lock = lock_test_env(); |
| 11533 | let temp_root = tempfile::tempdir()?; |
| 11534 | let _guard = EnvGuard::new(temp_root.path()); |
| 11535 | let config_path = temp_root.path().join("config.toml"); |
| 11536 | let managed_path = temp_root.path().join("managed.toml"); |
| 11537 | fs::write(&config_path, "provider = \"deepseek\"\n")?; |
| 11538 | fs::write( |
| 11539 | &managed_path, |
| 11540 | "provider = \"openrouter\"\n\n[providers.openrouter]\nbase_url = \"https://managed-gateway.example.test/v1\"\n", |
| 11541 | )?; |
| 11542 | let _managed = EnvVarGuard::set("DEEPSEEK_MANAGED_CONFIG_PATH", &managed_path); |
| 11543 | let _base = EnvVarGuard::set("CODEWHALE_BASE_URL", "https://env-gateway.example.test/v1"); |
| 11544 | |
| 11545 | let config = Config::load(Some(config_path), None)?; |
| 11546 | |
| 11547 | // Managed routing is authoritative for the active route. |
| 11548 | assert_eq!( |
| 11549 | config.active_provider_identity().unwrap().provider, |
| 11550 | ProviderKind::Openrouter |
| 11551 | ); |
| 11552 | assert_eq!( |
| 11553 | config.active_route_base_url(), |
| 11554 | "https://managed-gateway.example.test/v1" |
| 11555 | ); |
| 11556 | |
| 11557 | // The receipt must say "nobody owns the generic override" rather than |
| 11558 | // being cleared: a cleared receipt reads as "never met the environment |
| 11559 | // layer" and re-enables the generic fallback for every pinned child. |
| 11560 | assert_eq!(config.base_url_env_receipt, BaseUrlEnvReceipt::NoOwner); |
| 11561 | for provider in [ |
| 11562 | ProviderKind::Moonshot, |
| 11563 | ProviderKind::Zai, |
| 11564 | ProviderKind::Minimax, |
| 11565 | ProviderKind::Deepseek, |
| 11566 | ProviderKind::Deepseek, |
| 11567 | ] { |
| 11568 | assert_eq!( |
| 11569 | config.base_url_for_route(&config.test_identity_for_kind(provider)), |
| 11570 | provider.provider().default_base_url(), |
| 11571 | "{provider:?} must not borrow the ambient generic host under managed routing" |
| 11572 | ); |
| 11573 | assert!(!config.provider_uses_custom_endpoint(&config.test_identity_for_kind(provider))); |
| 11574 | } |
| 11575 | Ok(()) |
| 11576 | } |
| 11577 | |
| 11578 | #[test] |
| 11579 | fn named_custom_children_resolve_by_identity_not_by_the_active_custom_route() -> Result<()> { |
| 11580 | let _lock = lock_test_env(); |
| 11581 | let temp_root = tempfile::tempdir()?; |
| 11582 | let _guard = EnvGuard::new(temp_root.path()); |
| 11583 | let _managed = no_managed_config(temp_root.path()); |
| 11584 | let config_path = temp_root.path().join("config.toml"); |
| 11585 | fs::write( |
| 11586 | &config_path, |
| 11587 | r#"provider = "acme" |
| 11588 | |
| 11589 | [providers.acme] |
| 11590 | kind = "openai-compatible" |
| 11591 | base_url = "https://acme.example.test/v1" |
| 11592 | model = "acme-1" |
| 11593 | |
| 11594 | [providers.beta] |
| 11595 | kind = "openai-compatible" |
| 11596 | base_url = "https://beta.example.test/v1" |
| 11597 | model = "beta-1" |
| 11598 | "#, |
| 11599 | )?; |
| 11600 | |
| 11601 | let config = Config::load(Some(config_path), None)?; |
| 11602 | |
| 11603 | assert_eq!( |
| 11604 | config.active_provider_identity().unwrap().provider, |
| 11605 | ProviderKind::Custom |
| 11606 | ); |
| 11607 | assert_eq!( |
| 11608 | config.active_route_base_url(), |
| 11609 | "https://acme.example.test/v1" |
| 11610 | ); |
| 11611 | // A pinned child of the other named custom table resolves its own host. |
| 11612 | assert_eq!( |
| 11613 | config.base_url_for_route(&config.resolve_provider_pin_identity("beta").unwrap()), |
| 11614 | "https://beta.example.test/v1" |
| 11615 | ); |
| 11616 | assert!(config.custom_identity_is_resolvable("beta")); |
| 11617 | Ok(()) |
| 11618 | } |
| 11619 | |
| 11620 | #[test] |
| 11621 | fn missing_custom_identity_fails_closed_instead_of_reading_the_active_custom() -> Result<()> { |
| 11622 | let _lock = lock_test_env(); |
| 11623 | let temp_root = tempfile::tempdir()?; |
| 11624 | let _guard = EnvGuard::new(temp_root.path()); |
| 11625 | let _managed = no_managed_config(temp_root.path()); |
| 11626 | let config_path = temp_root.path().join("config.toml"); |
| 11627 | fs::write( |
| 11628 | &config_path, |
| 11629 | r#"provider = "acme" |
| 11630 | |
| 11631 | [providers.acme] |
| 11632 | kind = "openai-compatible" |
| 11633 | base_url = "https://acme.example.test/v1" |
| 11634 | model = "acme-1" |
| 11635 | "#, |
| 11636 | )?; |
| 11637 | |
| 11638 | let config = Config::load(Some(config_path), None)?; |
| 11639 | for identity in ["ghost", "", " ", "custom"] { |
| 11640 | assert!( |
| 11641 | config.resolve_provider_pin_identity(identity).is_err(), |
| 11642 | "{identity:?}" |
| 11643 | ); |
| 11644 | assert!(!config.custom_identity_is_resolvable(identity)); |
| 11645 | } |
| 11646 | Ok(()) |
| 11647 | } |
| 11648 | |
| 11649 | #[test] |
| 11650 | fn legacy_literal_custom_root_endpoint_belongs_only_to_the_literal_identity() -> Result<()> { |
| 11651 | let _lock = lock_test_env(); |
| 11652 | let temp_root = tempfile::tempdir()?; |
| 11653 | let _guard = EnvGuard::new(temp_root.path()); |
| 11654 | let _managed = no_managed_config(temp_root.path()); |
| 11655 | let config_path = temp_root.path().join("config.toml"); |
| 11656 | fs::write( |
| 11657 | &config_path, |
| 11658 | r#"provider = "custom" |
| 11659 | base_url = "https://legacy-root.example.test/v1" |
| 11660 | default_text_model = "legacy-1" |
| 11661 | "#, |
| 11662 | )?; |
| 11663 | |
| 11664 | let config = Config::load(Some(config_path), None)?; |
| 11665 | |
| 11666 | assert!(config.selects_literal_custom_provider()); |
| 11667 | assert_eq!( |
| 11668 | config.base_url_for_route(&config.active_provider_identity().unwrap()), |
| 11669 | "https://legacy-root.example.test/v1" |
| 11670 | ); |
| 11671 | assert!(config.resolve_provider_pin_identity("acme").is_err()); |
| 11672 | Ok(()) |
| 11673 | } |
| 11674 | |
| 11675 | /// The bare `k3` id belongs to the Kimi Code coding-plan endpoint. A config |
| 11676 | /// that selects it there must resolve, and must be labelled as the membership |
| 11677 | /// product rather than the direct platform one (v0.9.1 kimi-k3 dogfood report). |
| 11678 | #[test] |
| 11679 | fn config_selects_bare_k3_on_the_kimi_code_route() { |
| 11680 | let config = Config { |
| 11681 | provider: Some("moonshot".to_string()), |
| 11682 | providers: Some(ProvidersConfig { |
| 11683 | moonshot: ProviderConfig { |
| 11684 | api_key: Some("k".to_string()), |
| 11685 | base_url: Some(DEFAULT_KIMI_CODE_BASE_URL.to_string()), |
| 11686 | model: Some(KIMI_CODE_K3_MODEL.to_string()), |
| 11687 | ..ProviderConfig::default() |
| 11688 | }, |
| 11689 | ..ProvidersConfig::default() |
| 11690 | }), |
| 11691 | ..Config::default() |
| 11692 | }; |
| 11693 | |
| 11694 | assert_eq!(config.default_model(), KIMI_CODE_K3_MODEL); |
| 11695 | assert_eq!( |
| 11696 | codewhale_config::route::resolve_model( |
| 11697 | ProviderKind::Moonshot, |
| 11698 | &config.default_model(), |
| 11699 | Some(&config.active_route_base_url()), |
| 11700 | ) |
| 11701 | .unwrap() |
| 11702 | .wire_id, |
| 11703 | KIMI_CODE_K3_MODEL |
| 11704 | ); |
| 11705 | assert_eq!( |
| 11706 | moonshot_k3_route_display_name(&config.active_route_base_url(), &config.default_model()), |
| 11707 | Some("Kimi Code membership / k3") |
| 11708 | ); |
| 11709 | } |
| 11710 | |
| 11711 | /// Neither K3 id may be silently served by the other product's endpoint. The |
| 11712 | /// two are different plans with different context windows, so an unservable |
| 11713 | /// pairing has to fail loudly and name both routes (v0.9.1 kimi-k3 dogfood report). |
| 11714 | #[test] |
| 11715 | fn k3_and_kimi_k3_never_cross_products_and_fail_visibly() { |
| 11716 | let crossed = validate_kimi_code_api_model_id( |
| 11717 | ProviderKind::Moonshot, |
| 11718 | DEFAULT_KIMI_CODE_BASE_URL, |
| 11719 | MOONSHOT_KIMI_K3_MODEL, |
| 11720 | ) |
| 11721 | .expect_err("kimi-k3 is not a Kimi Code model id"); |
| 11722 | assert!(crossed.contains("api.kimi.com/coding/v1"), "{crossed}"); |
| 11723 | assert!(crossed.contains("api.moonshot.ai/v1"), "{crossed}"); |
| 11724 | assert!(crossed.contains(KIMI_CODE_K3_MODEL), "{crossed}"); |
| 11725 | |
| 11726 | let reversed = validate_kimi_code_api_model_id( |
| 11727 | ProviderKind::Moonshot, |
| 11728 | DEFAULT_MOONSHOT_BASE_URL, |
| 11729 | KIMI_CODE_K3_MODEL, |
| 11730 | ) |
| 11731 | .expect_err("bare k3 is not a direct-platform model id"); |
| 11732 | assert!(reversed.contains("api.moonshot.ai/v1"), "{reversed}"); |
| 11733 | assert!(reversed.contains("api.kimi.com/coding/v1"), "{reversed}"); |
| 11734 | assert!(reversed.contains(MOONSHOT_KIMI_K3_MODEL), "{reversed}"); |
| 11735 | |
| 11736 | // The exact-route predicates stay disjoint. |
| 11737 | assert!(is_exact_direct_moonshot_k3_route( |
| 11738 | ProviderKind::Moonshot, |
| 11739 | DEFAULT_MOONSHOT_BASE_URL, |
| 11740 | MOONSHOT_KIMI_K3_MODEL |
| 11741 | )); |
| 11742 | assert!(!is_exact_kimi_code_k3_route( |
| 11743 | ProviderKind::Moonshot, |
| 11744 | DEFAULT_MOONSHOT_BASE_URL, |
| 11745 | MOONSHOT_KIMI_K3_MODEL |
| 11746 | )); |
| 11747 | assert!(is_exact_kimi_code_k3_route( |
| 11748 | ProviderKind::Moonshot, |
| 11749 | DEFAULT_KIMI_CODE_BASE_URL, |
| 11750 | KIMI_CODE_K3_MODEL |
| 11751 | )); |
| 11752 | assert!(is_exact_kimi_code_k3_route( |
| 11753 | ProviderKind::Moonshot, |
| 11754 | DEFAULT_KIMI_CODE_BASE_URL, |
| 11755 | KIMI_CODE_K3_256K_MODEL |
| 11756 | )); |
| 11757 | assert!(!is_exact_kimi_code_bare_k3_route( |
| 11758 | ProviderKind::Moonshot, |
| 11759 | DEFAULT_KIMI_CODE_BASE_URL, |
| 11760 | KIMI_CODE_K3_256K_MODEL |
| 11761 | )); |
| 11762 | assert!(!is_exact_direct_moonshot_k3_route( |
| 11763 | ProviderKind::Moonshot, |
| 11764 | DEFAULT_KIMI_CODE_BASE_URL, |
| 11765 | KIMI_CODE_K3_MODEL |
| 11766 | )); |
| 11767 | } |
| 11768 | |
| 11769 | #[test] |
| 11770 | fn unknown_models_pass_through_on_canonical_moonshot_endpoints() { |
| 11771 | for base_url in [DEFAULT_KIMI_CODE_BASE_URL, DEFAULT_MOONSHOT_BASE_URL] { |
| 11772 | validate_kimi_code_api_model_id(ProviderKind::Moonshot, base_url, "future-kimi-model") |
| 11773 | .expect("unknown model IDs remain provider-owned"); |
| 11774 | } |
| 11775 | } |
| 11776 | |
| 11777 | /// Preserving the user's spelling must not turn alias resolution |
| 11778 | /// case-sensitive: normalize for comparison, never mutate what is stored or |
| 11779 | /// sent. A first-party/catalog route still canonicalizes to its documented id. |
| 11780 | #[test] |
| 11781 | fn model_alias_matching_stays_case_insensitive() { |
| 11782 | assert_eq!( |
| 11783 | codewhale_config::route::resolve_model(ProviderKind::NvidiaNim, "DeepSeek-V4-Pro", None) |
| 11784 | .ok() |
| 11785 | .map(|resolved| resolved.wire_id) |
| 11786 | .as_deref(), |
| 11787 | Some(DEFAULT_NVIDIA_NIM_MODEL) |
| 11788 | ); |
| 11789 | assert_eq!( |
| 11790 | codewhale_config::route::resolve_model( |
| 11791 | ProviderKind::Openrouter, |
| 11792 | "DeepSeek-V4-Flash", |
| 11793 | None, |
| 11794 | ) |
| 11795 | .ok() |
| 11796 | .map(|resolved| resolved.wire_id) |
| 11797 | .as_deref(), |
| 11798 | Some(DEFAULT_OPENROUTER_FLASH_MODEL) |
| 11799 | ); |
| 11800 | assert_eq!( |
| 11801 | codewhale_config::route::resolve_model(ProviderKind::Zai, "GLM-5.1", None) |
| 11802 | .ok() |
| 11803 | .map(|resolved| resolved.logical), |
| 11804 | codewhale_config::route::resolve_model(ProviderKind::Zai, "glm-5.1", None) |
| 11805 | .ok() |
| 11806 | .map(|resolved| resolved.logical) |
| 11807 | ); |
| 11808 | |
| 11809 | for alias in ["deepseek-chat", "DeepSeek-Chat", "DEEPSEEK-REASONER"] { |
| 11810 | assert_eq!( |
| 11811 | codewhale_config::route::resolve_model( |
| 11812 | ProviderKind::Deepseek, |
| 11813 | alias, |
| 11814 | Some("https://api.deepseek.com"), |
| 11815 | ) |
| 11816 | .unwrap() |
| 11817 | .wire_id, |
| 11818 | DEEPSEEK_ALIAS_REPLACEMENT, |
| 11819 | "first-party DeepSeek must canonicalize {alias}" |
| 11820 | ); |
| 11821 | } |
| 11822 | |
| 11823 | assert_eq!( |
| 11824 | codewhale_config::route::resolve_model( |
| 11825 | ProviderKind::Deepseek, |
| 11826 | "DeepSeek-Chat", |
| 11827 | Some("https://llm.corp.internal/v1"), |
| 11828 | ) |
| 11829 | .unwrap() |
| 11830 | .wire_id, |
| 11831 | "DeepSeek-Chat" |
| 11832 | ); |
| 11833 | } |
| 11834 | |
| 11835 | /// The remembered `/model` pick outranks `config.toml` on the next launch. It |
| 11836 | /// must not silently restyle the configured id: two spellings of one model are |
| 11837 | /// the config file's call, a genuinely different model stays the memory's. |
| 11838 | #[test] |
| 11839 | fn remembered_model_pick_defers_to_the_configured_spelling() { |
| 11840 | assert_eq!( |
| 11841 | prefer_configured_model_spelling("DeepSeek-V4-Flash", "deepseek-v4-flash".to_string()), |
| 11842 | "DeepSeek-V4-Flash", |
| 11843 | "a case-only disagreement belongs to config.toml" |
| 11844 | ); |
| 11845 | assert_eq!( |
| 11846 | prefer_configured_model_spelling(" DeepSeek-V4-Flash ", "DEEPSEEK-V4-FLASH".to_string()), |
| 11847 | "DeepSeek-V4-Flash" |
| 11848 | ); |
| 11849 | assert_eq!( |
| 11850 | prefer_configured_model_spelling("DeepSeek-V4-Flash", "deepseek-v4-pro".to_string()), |
| 11851 | "deepseek-v4-pro", |
| 11852 | "a different model is still a real remembered selection" |
| 11853 | ); |
| 11854 | assert_eq!( |
| 11855 | prefer_configured_model_spelling("DeepSeek-V4-Flash", "auto".to_string()), |
| 11856 | "auto" |
| 11857 | ); |
| 11858 | assert_eq!( |
| 11859 | prefer_configured_model_spelling("DeepSeek-V4-Flash", "DeepSeek-V4-Flash".to_string()), |
| 11860 | "DeepSeek-V4-Flash" |
| 11861 | ); |
| 11862 | } |
| 11863 | |
| 11864 | /// #5956: `[compaction]` is absent by default, and absent must mean the |
| 11865 | /// historical hard-coded 20 000-token verbatim retention budget with no |
| 11866 | /// operator prompt suffix. |
| 11867 | #[test] |
| 11868 | fn compaction_tuning_defaults_to_todays_behavior() { |
| 11869 | let config = Config::default(); |
| 11870 | assert_eq!( |
| 11871 | config.compaction_retained_user_message_tokens(), |
| 11872 | DEFAULT_COMPACTION_RETAINED_USER_MESSAGE_TOKENS |
| 11873 | ); |
| 11874 | assert_eq!(config.compaction_retained_user_message_tokens(), 20_000); |
| 11875 | assert_eq!(config.compaction_summary_instructions(), None); |
| 11876 | } |
| 11877 | |
| 11878 | /// #5956: an explicit budget is honored inside the clamp and pulled back to |
| 11879 | /// the nearest bound outside it, so neither a useless floor nor a |
| 11880 | /// re-triggering ceiling can be configured. |
| 11881 | #[test] |
| 11882 | fn compaction_retained_user_message_tokens_clamps_to_the_documented_range() { |
| 11883 | let parse = |body: &str| toml::from_str::<Config>(body).expect("config parses"); |
| 11884 | |
| 11885 | let in_range = parse("[compaction]\nretained_user_message_tokens = 60000\n"); |
| 11886 | assert_eq!(in_range.compaction_retained_user_message_tokens(), 60_000); |
| 11887 | |
| 11888 | let too_small = parse("[compaction]\nretained_user_message_tokens = 1\n"); |
| 11889 | assert_eq!( |
| 11890 | too_small.compaction_retained_user_message_tokens(), |
| 11891 | MIN_COMPACTION_RETAINED_USER_MESSAGE_TOKENS |
| 11892 | ); |
| 11893 | |
| 11894 | let too_large = parse("[compaction]\nretained_user_message_tokens = 9000000\n"); |
| 11895 | assert_eq!( |
| 11896 | too_large.compaction_retained_user_message_tokens(), |
| 11897 | MAX_COMPACTION_RETAINED_USER_MESSAGE_TOKENS |
| 11898 | ); |
| 11899 | |
| 11900 | // The pre-#5956 issue text spelled the key `retained_user_message_max_tokens`; |
| 11901 | // it stays accepted as an alias so early adopters' files keep working. |
| 11902 | let alias = parse("[compaction]\nretained_user_message_max_tokens = 40000\n"); |
| 11903 | assert_eq!(alias.compaction_retained_user_message_tokens(), 40_000); |
| 11904 | } |
| 11905 | |
| 11906 | /// #5956: a blank or whitespace-only key must read as unset, not as an empty |
| 11907 | /// delimited section appended to every summarizer prompt. |
| 11908 | #[test] |
| 11909 | fn compaction_summary_instructions_trims_and_treats_blank_as_unset() { |
| 11910 | let configured: Config = toml::from_str( |
| 11911 | "[compaction]\nsummary_instructions = \" Always list exact file:line. \"\n", |
| 11912 | ) |
| 11913 | .expect("config parses"); |
| 11914 | assert_eq!( |
| 11915 | configured.compaction_summary_instructions().as_deref(), |
| 11916 | Some("Always list exact file:line.") |
| 11917 | ); |
| 11918 | |
| 11919 | let blank: Config = toml::from_str("[compaction]\nsummary_instructions = \" \\n \"\n") |
| 11920 | .expect("config parses"); |
| 11921 | assert_eq!(blank.compaction_summary_instructions(), None); |
| 11922 | } |
| 11923 | |
| 11924 | /// The Codewhale route must attach its account key on every origin it is |
| 11925 | /// allowed to reach, from every documented source. |
| 11926 | /// |
| 11927 | /// Regression: `CODEWHALE_API_BASE` is the route's *own* documented override, |
| 11928 | /// but it made the endpoint look "custom", which suppressed the saved and |
| 11929 | /// exported key; the loopback arm below then returned an empty key and the |
| 11930 | /// request went out with no `Authorization` header at all. |
| 11931 | #[test] |
| 11932 | fn codewhale_route_resolves_its_key_from_every_documented_source() -> Result<()> { |
| 11933 | let _lock = lock_test_env(); |
| 11934 | let temp_root = tempfile::tempdir()?; |
| 11935 | let _guard = EnvGuard::new(temp_root.path()); |
| 11936 | let home = temp_root.path().join("codewhale-home"); |
| 11937 | fs::create_dir_all(&home)?; |
| 11938 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 11939 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 11940 | |
| 11941 | let route = |base: Option<&str>| Config { |
| 11942 | provider: Some("codewhale".to_string()), |
| 11943 | providers: Some(ProvidersConfig { |
| 11944 | codewhale: ProviderConfig { |
| 11945 | base_url: base.map(str::to_string), |
| 11946 | ..ProviderConfig::default() |
| 11947 | }, |
| 11948 | ..ProvidersConfig::default() |
| 11949 | }), |
| 11950 | ..Config::default() |
| 11951 | }; |
| 11952 | |
| 11953 | // Both the default origin and a loopback origin the operator declared in |
| 11954 | // CODEWHALE_API_BASE are the route's own authenticated endpoint. |
| 11955 | for declared in [None, Some("http://127.0.0.1:8901/v1")] { |
| 11956 | let _base = declared.map(|value| EnvVarGuard::set("CODEWHALE_API_BASE", value)); |
| 11957 | { |
| 11958 | let _env = EnvVarGuard::set("CODEWHALE_API_KEY", "cwc_key_from_env"); |
| 11959 | assert_eq!( |
| 11960 | route(None).active_route_api_key()?, |
| 11961 | "cwc_key_from_env", |
| 11962 | "env key, declared base {declared:?}" |
| 11963 | ); |
| 11964 | } |
| 11965 | |
| 11966 | // The slot `codewhale account api-keys create --use` writes. |
| 11967 | let secrets = codewhale_secrets::Secrets::auto_detect(); |
| 11968 | secrets.set("codewhale", "cwc_key_from_slot")?; |
| 11969 | assert_eq!( |
| 11970 | route(None).active_route_api_key()?, |
| 11971 | "cwc_key_from_slot", |
| 11972 | "secret store, declared base {declared:?}" |
| 11973 | ); |
| 11974 | |
| 11975 | let mut configured = route(None); |
| 11976 | if let Some(providers) = configured.providers.as_mut() { |
| 11977 | providers.codewhale.api_key = Some("cwc_key_from_config".to_string()); |
| 11978 | } |
| 11979 | assert_eq!( |
| 11980 | configured.active_route_api_key()?, |
| 11981 | "cwc_key_from_config", |
| 11982 | "config api_key, declared base {declared:?}" |
| 11983 | ); |
| 11984 | |
| 11985 | let mut bound = route(None); |
| 11986 | if let Some(providers) = bound.providers.as_mut() { |
| 11987 | providers.codewhale.api_key_env = Some("MY_CODEWHALE_KEY".to_string()); |
| 11988 | } |
| 11989 | let _bound_env = EnvVarGuard::set("MY_CODEWHALE_KEY", "cwc_key_from_api_key_env"); |
| 11990 | assert_eq!( |
| 11991 | bound.active_route_api_key()?, |
| 11992 | "cwc_key_from_api_key_env", |
| 11993 | "api_key_env, declared base {declared:?}" |
| 11994 | ); |
| 11995 | |
| 11996 | secrets.delete("codewhale")?; |
| 11997 | } |
| 11998 | Ok(()) |
| 11999 | } |
| 12000 | |
| 12001 | /// Widening the official-endpoint family must not widen where the key goes. |
| 12002 | /// |
| 12003 | /// A base URL the operator did not declare in `CODEWHALE_API_BASE` is still a |
| 12004 | /// foreign host: the ambient account key must not follow it. |
| 12005 | #[test] |
| 12006 | fn codewhale_ambient_key_never_follows_an_undeclared_host() -> Result<()> { |
| 12007 | let _lock = lock_test_env(); |
| 12008 | let temp_root = tempfile::tempdir()?; |
| 12009 | let _guard = EnvGuard::new(temp_root.path()); |
| 12010 | let home = temp_root.path().join("codewhale-home"); |
| 12011 | fs::create_dir_all(&home)?; |
| 12012 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 12013 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 12014 | let _env = EnvVarGuard::set("CODEWHALE_API_KEY", "cwc_key_must_not_travel"); |
| 12015 | codewhale_secrets::Secrets::auto_detect().set("codewhale", "cwc_key_saved_must_not_travel")?; |
| 12016 | // The operator declared one origin; the config table names a different one. |
| 12017 | let _base = EnvVarGuard::set("CODEWHALE_API_BASE", "http://127.0.0.1:8901/v1"); |
| 12018 | |
| 12019 | let config = Config { |
| 12020 | provider: Some("codewhale".to_string()), |
| 12021 | providers: Some(ProvidersConfig { |
| 12022 | codewhale: ProviderConfig { |
| 12023 | base_url: Some("https://not-declared.example/v1".to_string()), |
| 12024 | ..ProviderConfig::default() |
| 12025 | }, |
| 12026 | ..ProvidersConfig::default() |
| 12027 | }), |
| 12028 | ..Config::default() |
| 12029 | }; |
| 12030 | let error = config |
| 12031 | .active_route_api_key() |
| 12032 | .expect_err("an undeclared host must not inherit the account key"); |
| 12033 | let text = error.to_string(); |
| 12034 | assert!(!text.contains("cwc_key_must_not_travel"), "{text}"); |
| 12035 | assert!(!text.contains("cwc_key_saved_must_not_travel"), "{text}"); |
| 12036 | Ok(()) |
| 12037 | } |
| 12038 | |
| 12039 | /// A missing Codewhale key must fail before any request, naming the exact fix. |
| 12040 | /// |
| 12041 | /// Regression: the loopback branch treated this route as a keyless local |
| 12042 | /// runtime and returned an empty key, so the request was dispatched with no |
| 12043 | /// credential and the service answered 401 instead of the CLI answering first. |
| 12044 | #[test] |
| 12045 | fn codewhale_route_without_a_key_fails_before_any_request() -> Result<()> { |
| 12046 | let _lock = lock_test_env(); |
| 12047 | let temp_root = tempfile::tempdir()?; |
| 12048 | let _guard = EnvGuard::new(temp_root.path()); |
| 12049 | let home = temp_root.path().join("codewhale-home"); |
| 12050 | fs::create_dir_all(&home)?; |
| 12051 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.as_os_str()); |
| 12052 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 12053 | let _base = EnvVarGuard::set("CODEWHALE_API_BASE", "http://127.0.0.1:8901/v1"); |
| 12054 | |
| 12055 | let config = Config { |
| 12056 | provider: Some("codewhale".to_string()), |
| 12057 | ..Config::default() |
| 12058 | }; |
| 12059 | let error = config |
| 12060 | .active_route_api_key() |
| 12061 | .expect_err("a keyless Codewhale route must not dispatch"); |
| 12062 | let text = error.to_string(); |
| 12063 | assert!(text.contains("CODEWHALE_API_KEY"), "{text}"); |
| 12064 | assert!( |
| 12065 | text.contains("codewhale account api-keys create --name <name> --scope models:infer --use"), |
| 12066 | "{text}" |
| 12067 | ); |
| 12068 | assert!( |
| 12069 | text.contains("https://app.codewhale.net/settings?section=api"), |
| 12070 | "{text}" |
| 12071 | ); |
| 12072 | // The only `cwc_key_` in the message is the placeholder in the export |
| 12073 | // example, never a resolved value. |
| 12074 | assert_eq!(text.matches("cwc_key_").count(), 1, "{text}"); |
| 12075 | assert!(text.contains("cwc_key_..."), "{text}"); |
| 12076 | Ok(()) |
| 12077 | } |
| 12078 | |
| 12079 | #[test] |
| 12080 | fn openrouter_vendor_profile_override_clear_and_provider_boundary() { |
| 12081 | let base: Config = toml::from_str( |
| 12082 | r#" |
| 12083 | provider = "openrouter" |
| 12084 | [providers.openrouter] |
| 12085 | vendor = "deepinfra/turbo" |
| 12086 | "#, |
| 12087 | ) |
| 12088 | .unwrap(); |
| 12089 | let unrelated: Config = toml::from_str( |
| 12090 | r#" |
| 12091 | [providers.openrouter] |
| 12092 | model = "deepseek/deepseek-v4-pro" |
| 12093 | "#, |
| 12094 | ) |
| 12095 | .unwrap(); |
| 12096 | let retained = merge_config(base.clone(), unrelated); |
| 12097 | assert_eq!( |
| 12098 | retained.openrouter_vendor().unwrap().as_deref(), |
| 12099 | Some("deepinfra/turbo") |
| 12100 | ); |
| 12101 | let clear: Config = toml::from_str("[providers.openrouter]\nvendor = \"\"\n").unwrap(); |
| 12102 | assert_eq!( |
| 12103 | merge_config(base.clone(), clear) |
| 12104 | .openrouter_vendor() |
| 12105 | .unwrap(), |
| 12106 | None |
| 12107 | ); |
| 12108 | let mut switched = base; |
| 12109 | switched.provider = Some("openai".into()); |
| 12110 | assert_eq!(switched.openrouter_vendor().unwrap(), None); |
| 12111 | switched |
| 12112 | .provider_config_for_mut(&switched.test_identity_for_kind(ProviderKind::Openai)) |
| 12113 | .unwrap() |
| 12114 | .vendor = Some("deepinfra".into()); |
| 12115 | assert!(switched.openrouter_vendor().is_err()); |
| 12116 | } |
| 12117 | |
| 12118 | #[test] |
| 12119 | fn notifications_saved_profile_edit_roundtrips_the_actual_tui_loader() { |
| 12120 | let _guard = crate::test_support::lock_test_env(); |
| 12121 | let temp = tempfile::tempdir().unwrap(); |
| 12122 | let path = temp.path().join("config.toml"); |
| 12123 | std::fs::write(&path, "[notifications]\nmethod = \"kitty\"\nsound = \"bell\"\n[profiles.work.notifications]\nquiet = true\nsound = \"off\"\n[profiles.inherited]\n").unwrap(); |
| 12124 | let edit = NotificationConfigUpdate::Sound(Some(CompletionSound::Whale)); |
| 12125 | edit.persist_for_profile(&path, Some("work")).unwrap(); |
| 12126 | let work = Config::load(Some(path.clone()), Some("work")) |
| 12127 | .unwrap() |
| 12128 | .notifications_config(); |
| 12129 | assert_eq!(work.sound, Some(CompletionSound::Whale)); |
| 12130 | assert!(work.quiet); |
| 12131 | let root = Config::load(Some(path.clone()), None) |
| 12132 | .unwrap() |
| 12133 | .notifications_config(); |
| 12134 | assert_eq!(root.sound, Some(CompletionSound::Bell)); |
| 12135 | NotificationConfigUpdate::Quiet(true) |
| 12136 | .persist_for_profile(&path, Some("inherited")) |
| 12137 | .unwrap(); |
| 12138 | let inherited = Config::load(Some(path.clone()), Some("inherited")) |
| 12139 | .unwrap() |
| 12140 | .notifications_config(); |
| 12141 | assert!(inherited.quiet); |
| 12142 | assert_eq!(inherited.method, NotificationMethod::Kitty); |
| 12143 | let raw: toml::Value = toml::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); |
| 12144 | assert!(raw["profiles"]["inherited"].get("notifications").is_none()); |
| 12145 | let before = std::fs::read(&path).unwrap(); |
| 12146 | assert!(edit.persist_for_profile(&path, Some("missing")).is_err()); |
| 12147 | assert_eq!(std::fs::read(&path).unwrap(), before); |
| 12148 | } |
| 12149 | |
| 12150 | #[test] |
| 12151 | #[ignore = "requires CODEWHALE_TEST_NOTIFICATION_CLI pointing at the built CLI"] |
| 12152 | fn notifications_real_cli_file_is_consumed_by_actual_tui_loader() { |
| 12153 | let _guard = crate::test_support::lock_test_env(); |
| 12154 | let binary = std::env::var_os("CODEWHALE_TEST_NOTIFICATION_CLI").expect("supply built CLI"); |
| 12155 | let temp = tempfile::tempdir().unwrap(); |
| 12156 | let path = temp.path().join("config.toml"); |
| 12157 | for (key, value) in [ |
| 12158 | ("sound", "whale"), |
| 12159 | ("quiet", "true"), |
| 12160 | ("events.approval-needed", "false"), |
| 12161 | ("condition", "always"), |
| 12162 | ("threshold_secs", "17"), |
| 12163 | ("event_sound.events", r#"["model-notify", "input-needed"]"#), |
| 12164 | ] { |
| 12165 | let result = std::process::Command::new(&binary) |
| 12166 | .env_clear() |
| 12167 | .env("HOME", temp.path()) |
| 12168 | .env("USERPROFILE", temp.path()) |
| 12169 | .env("CODEWHALE_HOME", temp.path().join("state")) |
| 12170 | .env("CODEWHALE_SECRET_BACKEND", "file") |
| 12171 | .current_dir(temp.path()) |
| 12172 | .arg("--config") |
| 12173 | .arg(&path) |
| 12174 | .args(["config", "set", &format!("notifications.{key}"), value]) |
| 12175 | .output() |
| 12176 | .unwrap(); |
| 12177 | assert!( |
| 12178 | result.status.success(), |
| 12179 | "{key}: {}", |
| 12180 | String::from_utf8_lossy(&result.stderr) |
| 12181 | ); |
| 12182 | } |
| 12183 | let loaded = Config::load(Some(path), None) |
| 12184 | .unwrap() |
| 12185 | .notifications_config(); |
| 12186 | assert_eq!(loaded.sound, Some(CompletionSound::Whale)); |
| 12187 | assert!(loaded.quiet); |
| 12188 | assert!(!loaded.events.approval_needed); |
| 12189 | assert_eq!(loaded.condition, Some(NotificationCondition::Always)); |
| 12190 | assert_eq!(loaded.threshold_secs, 17); |
| 12191 | assert_eq!(loaded.event_sound.events, ["model-notify", "input-needed"]); |
| 12192 | } |
| 12193 | |
| 12194 | /// Parse a config layer the way a file is loaded, so legacy top-level keys |
| 12195 | /// go through the #6394 canonicalizer. |
| 12196 | fn legacy_config(body: &str) -> Config { |
| 12197 | crate::config::parse_config_base(body).expect("legacy config parses") |
| 12198 | } |
| 12199 | |
| 12200 | #[test] |
| 12201 | fn official_chatgpt_api_on_legacy_root_belongs_to_chatgpt_in_both_crates() -> Result<()> { |
| 12202 | // The config crate always let Codex read an official Codex endpoint from |
| 12203 | // the top level; the TUI refused it. One rule now: it is Codex's (#6394). |
| 12204 | let body = "provider = \"openai-codex\"\nbase_url = \"https://api.openai.com/v1\"\n"; |
| 12205 | let config = legacy_config(body); |
| 12206 | assert_eq!( |
| 12207 | config |
| 12208 | .provider_config_for(&config.test_identity_for_kind(ProviderKind::OpenaiCodex)) |
| 12209 | .and_then(|entry| entry.base_url.as_deref()), |
| 12210 | Some("https://api.openai.com/v1") |
| 12211 | ); |
| 12212 | let store = codewhale_config::parse_config_toml(body)?; |
| 12213 | assert_eq!( |
| 12214 | store.providers.openai_codex.base_url.as_deref(), |
| 12215 | Some("https://api.openai.com/v1") |
| 12216 | ); |
| 12217 | assert!(store.providers.deepseek.base_url.is_none()); |
| 12218 | Ok(()) |
| 12219 | } |
| 12220 | |
| 12221 | // ── #6394: the TUI reads legacy top-level keys by the same rule ─────────── |
| 12222 | |
| 12223 | fn legacy_fixture(name: &str) -> String { |
| 12224 | let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) |
| 12225 | .join("../config/tests/fixtures/legacy_root") |
| 12226 | .join(name); |
| 12227 | fs::read_to_string(&path).expect("legacy fixture") |
| 12228 | } |
| 12229 | |
| 12230 | fn migrated_fixture(body: &str) -> String { |
| 12231 | codewhale_config::legacy_root::migrated_document_text(body).unwrap_or_else(|| body.to_string()) |
| 12232 | } |
| 12233 | |
| 12234 | #[test] |
| 12235 | fn legacy_upgrade_fixtures_resolve_the_same_route_before_and_after_migrate() -> Result<()> { |
| 12236 | let _lock = lock_test_env(); |
| 12237 | let _source = EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 12238 | let _cli_key = EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 12239 | for (fixture, profile, provider, base_url, key) in [ |
| 12240 | ( |
| 12241 | "v0_10_0_example.toml", |
| 12242 | None, |
| 12243 | ProviderKind::Deepseek, |
| 12244 | "https://api.deepseek.com/beta", |
| 12245 | Some("YOUR_DEEPSEEK_API_KEY"), |
| 12246 | ), |
| 12247 | ( |
| 12248 | // The shipped profile's key finally reaches NIM. |
| 12249 | "v0_10_0_example.toml", |
| 12250 | Some("nvidia-nim"), |
| 12251 | ProviderKind::NvidiaNim, |
| 12252 | "https://integrate.api.nvidia.com/v1", |
| 12253 | Some("YOUR_NVIDIA_API_KEY"), |
| 12254 | ), |
| 12255 | ( |
| 12256 | "v0_9_9_auth_set.toml", |
| 12257 | None, |
| 12258 | ProviderKind::Deepseek, |
| 12259 | DEFAULT_DEEPSEEK_BASE_URL, |
| 12260 | Some("sk-legacy-auth-set"), |
| 12261 | ), |
| 12262 | ( |
| 12263 | "config_base_url_save.toml", |
| 12264 | None, |
| 12265 | ProviderKind::Deepseek, |
| 12266 | "https://proxy.example.test/v1", |
| 12267 | Some("sk-proxy-key"), |
| 12268 | ), |
| 12269 | ( |
| 12270 | "literal_custom.toml", |
| 12271 | None, |
| 12272 | ProviderKind::Custom, |
| 12273 | "http://127.0.0.1:18181/v1", |
| 12274 | Some("sk-literal-custom"), |
| 12275 | ), |
| 12276 | ( |
| 12277 | "url_guessed_nim.toml", |
| 12278 | None, |
| 12279 | ProviderKind::NvidiaNim, |
| 12280 | "https://integrate.api.nvidia.com/v1", |
| 12281 | None, |
| 12282 | ), |
| 12283 | ] { |
| 12284 | let body = legacy_fixture(fixture); |
| 12285 | for (stage, text) in [("before", body.clone()), ("after", migrated_fixture(&body))] { |
| 12286 | let config = Config::from_saved_document(&text, profile)?; |
| 12287 | let label = format!("{fixture} {profile:?} {stage}"); |
| 12288 | assert_eq!( |
| 12289 | config.active_provider_identity().unwrap().provider, |
| 12290 | provider, |
| 12291 | "{label}" |
| 12292 | ); |
| 12293 | assert_eq!( |
| 12294 | config.active_route_base_url().trim_end_matches('/'), |
| 12295 | base_url.trim_end_matches('/'), |
| 12296 | "{label}" |
| 12297 | ); |
| 12298 | let configured_key = config.provider_route_string_with_deepseek_fallback( |
| 12299 | &config.test_identity_for_kind(provider), |
| 12300 | |entry| entry.api_key.clone(), |
| 12301 | ); |
| 12302 | assert_eq!(configured_key.as_deref(), key, "{label}"); |
| 12303 | } |
| 12304 | } |
| 12305 | Ok(()) |
| 12306 | } |
| 12307 | |
| 12308 | #[test] |
| 12309 | fn a_profile_endpoint_now_overrides_the_base_deepseek_table() -> Result<()> { |
| 12310 | // v0.10 let the base `[providers.deepseek] base_url` silently win over a |
| 12311 | // profile's top-level `base_url`; the profile's value now lands in the |
| 12312 | // profile's own table and overrides it (#6394). |
| 12313 | let body = r#" |
| 12314 | [providers.deepseek] |
| 12315 | base_url = "https://api.deepseek.com/beta" |
| 12316 | |
| 12317 | [profiles.work] |
| 12318 | base_url = "https://work.example.test/v1" |
| 12319 | "#; |
| 12320 | let work = Config::from_saved_document(body, Some("work"))?; |
| 12321 | assert_eq!(work.active_route_base_url(), "https://work.example.test/v1"); |
| 12322 | let base = Config::from_saved_document(body, None)?; |
| 12323 | assert_eq!( |
| 12324 | base.active_route_base_url(), |
| 12325 | "https://api.deepseek.com/beta" |
| 12326 | ); |
| 12327 | Ok(()) |
| 12328 | } |
| 12329 | |
| 12330 | #[test] |
| 12331 | fn conflicting_top_level_key_wins_in_memory_like_before() -> Result<()> { |
| 12332 | let _lock = lock_test_env(); |
| 12333 | let _source = EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 12334 | let _cli_key = EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 12335 | let config = Config::from_saved_document( |
| 12336 | r#" |
| 12337 | api_key = "sk-top-level" |
| 12338 | base_url = "https://top.example.test/v1" |
| 12339 | |
| 12340 | [providers.deepseek] |
| 12341 | api_key = "sk-table" |
| 12342 | base_url = "https://table.example.test/v1" |
| 12343 | "#, |
| 12344 | None, |
| 12345 | )?; |
| 12346 | // The key the TUI always sent, and the endpoint both crates always used. |
| 12347 | assert_eq!(config.deepseek_table_api_key(), Some("sk-top-level")); |
| 12348 | assert_eq!( |
| 12349 | config.active_route_base_url(), |
| 12350 | "https://table.example.test/v1" |
| 12351 | ); |
| 12352 | assert_eq!(config.legacy_root.unresolved_conflicts().count(), 2); |
| 12353 | Ok(()) |
| 12354 | } |
| 12355 | |
| 12356 | #[test] |
| 12357 | fn deepseek_cn_shares_the_deepseek_endpoint_and_key_but_not_its_model() -> Result<()> { |
| 12358 | let config = Config::from_saved_document( |
| 12359 | r#" |
| 12360 | provider = "deepseek-cn" |
| 12361 | |
| 12362 | [providers.deepseek] |
| 12363 | api_key = "sk-shared" |
| 12364 | base_url = "https://gateway.example.test/v1" |
| 12365 | model = "deepseek-only-model" |
| 12366 | "#, |
| 12367 | None, |
| 12368 | )?; |
| 12369 | assert_eq!( |
| 12370 | config.active_provider_identity().unwrap().key.as_str(), |
| 12371 | "deepseek-cn" |
| 12372 | ); |
| 12373 | assert_eq!( |
| 12374 | config.active_provider_identity().unwrap().provider, |
| 12375 | ProviderKind::Deepseek |
| 12376 | ); |
| 12377 | assert_eq!( |
| 12378 | config.active_route_base_url(), |
| 12379 | "https://gateway.example.test/v1" |
| 12380 | ); |
| 12381 | assert_eq!( |
| 12382 | config |
| 12383 | .provider_route_string_with_deepseek_fallback( |
| 12384 | &config.active_provider_identity().unwrap(), |
| 12385 | |entry| { entry.api_key.clone() } |
| 12386 | ) |
| 12387 | .as_deref(), |
| 12388 | Some("sk-shared") |
| 12389 | ); |
| 12390 | assert_eq!( |
| 12391 | config.provider_config_string_with_runtime_fallback( |
| 12392 | &config.active_provider_identity().unwrap(), |
| 12393 | |entry| { entry.model.clone() } |
| 12394 | ), |
| 12395 | None, |
| 12396 | "the model is not shared" |
| 12397 | ); |
| 12398 | Ok(()) |
| 12399 | } |
| 12400 | |
| 12401 | #[test] |
| 12402 | fn vision_keeps_the_top_level_key_it_inherited_and_nothing_more() -> Result<()> { |
| 12403 | let legacy = Config::from_saved_document( |
| 12404 | "api_key = \"sk-root\"\n[vision_model]\nmodel = \"vision-x\"\nbase_url = \"https://vision.example.test/v1\"\n", |
| 12405 | None, |
| 12406 | )?; |
| 12407 | assert_eq!( |
| 12408 | legacy |
| 12409 | .vision_model_config() |
| 12410 | .and_then(|vision| vision.api_key) |
| 12411 | .as_deref(), |
| 12412 | Some("sk-root") |
| 12413 | ); |
| 12414 | // A new-shape DeepSeek key is not handed to the vision host. |
| 12415 | let current = Config::from_saved_document( |
| 12416 | "[providers.deepseek]\napi_key = \"sk-deepseek\"\n[vision_model]\nmodel = \"vision-x\"\nbase_url = \"https://vision.example.test/v1\"\n", |
| 12417 | None, |
| 12418 | )?; |
| 12419 | assert_eq!( |
| 12420 | current |
| 12421 | .vision_model_config() |
| 12422 | .and_then(|vision| vision.api_key), |
| 12423 | None |
| 12424 | ); |
| 12425 | Ok(()) |
| 12426 | } |
| 12427 | |
| 12428 | #[test] |
| 12429 | fn a_mimo_host_on_the_top_level_moves_to_mimo_and_a_deepseek_host_does_not() -> Result<()> { |
| 12430 | let mimo = Config::from_saved_document( |
| 12431 | "provider = \"xiaomi-mimo\"\nbase_url = \"https://api.xiaomimimo.com/v1\"\n", |
| 12432 | None, |
| 12433 | )?; |
| 12434 | assert_eq!( |
| 12435 | mimo.provider_config_for(&mimo.test_identity_for_kind(ProviderKind::XiaomiMimo)) |
| 12436 | .and_then(|entry| entry.base_url.as_deref()), |
| 12437 | Some("https://api.xiaomimimo.com/v1") |
| 12438 | ); |
| 12439 | let deepseek_host = Config::from_saved_document( |
| 12440 | "provider = \"xiaomi-mimo\"\nbase_url = \"https://api.deepseek.com\"\n", |
| 12441 | None, |
| 12442 | )?; |
| 12443 | assert_eq!( |
| 12444 | deepseek_host.active_route_base_url(), |
| 12445 | DEFAULT_XIAOMI_MIMO_BASE_URL |
| 12446 | ); |
| 12447 | Ok(()) |
| 12448 | } |
| 12449 | |
| 12450 | #[test] |
| 12451 | fn no_parse_leaves_a_top_level_key_behind() -> Result<()> { |
| 12452 | let body = legacy_fixture("v0_10_0_example.toml"); |
| 12453 | let parsed = parse_config_file(&body)?; |
| 12454 | assert!(!parsed.legacy_root.is_empty()); |
| 12455 | let (text, _) = codewhale_config::legacy_root::canonicalize_text(&body)?; |
| 12456 | let table: toml::Table = toml::from_str(&text)?; |
| 12457 | assert!(!codewhale_config::legacy_root::has_legacy_root_keys(&table)); |
| 12458 | Ok(()) |
| 12459 | } |
| 12460 | |
| 12461 | #[test] |
| 12462 | fn config_set_provider_typo_reuses_the_invalid_provider_wording() { |
| 12463 | let config = Config::default(); |
| 12464 | let error = config |
| 12465 | .resolve_provider_selection_identity("deepsek") |
| 12466 | .expect_err("a typo is not a provider"); |
| 12467 | assert!( |
| 12468 | error.starts_with("Invalid provider 'deepsek': expected deepseek"), |
| 12469 | "{error}" |
| 12470 | ); |
| 12471 | assert!(!error.contains("saved session"), "{error}"); |
| 12472 | // The resume path keeps its own saved-session wording. |
| 12473 | let resume = config |
| 12474 | .resolve_provider_pin_identity("deepsek") |
| 12475 | .expect_err("missing custom route"); |
| 12476 | assert!(resume.starts_with("saved session requires"), "{resume}"); |
| 12477 | assert_eq!( |
| 12478 | config |
| 12479 | .resolve_provider_selection_identity("deepseek") |
| 12480 | .expect("built-in provider") |
| 12481 | .provider, |
| 12482 | ProviderKind::Deepseek |
| 12483 | ); |
| 12484 | } |
| 12485 | |
| 12486 | #[test] |
| 12487 | fn deepseek_missing_key_message_keeps_commands_copyable_and_harness_advice_conditional() { |
| 12488 | let plain = deepseek_missing_key_message(); |
| 12489 | assert_eq!(plain.lines().count(), 2, "{plain}"); |
| 12490 | assert!( |
| 12491 | plain.contains("codewhale auth set --provider deepseek"), |
| 12492 | "{plain}" |
| 12493 | ); |
| 12494 | assert!(plain.contains("codewhale login"), "{plain}"); |
| 12495 | assert!( |
| 12496 | plain.contains("codewhale auth external-consent --provider deepseek --mode read-only"), |
| 12497 | "{plain}" |
| 12498 | ); |
| 12499 | } |
| 12500 | |
| 12501 | #[test] |
| 12502 | fn ambient_default_provider_detects_cloud_env_keys_in_priority_order() { |
| 12503 | struct RestoreEnv(Vec<(&'static str, Option<OsString>)>); |
| 12504 | impl Drop for RestoreEnv { |
| 12505 | fn drop(&mut self) { |
| 12506 | for (key, value) in self.0.drain(..) { |
| 12507 | unsafe { EnvGuard::restore_var(key, value) }; |
| 12508 | } |
| 12509 | } |
| 12510 | } |
| 12511 | |
| 12512 | let _guard = lock_test_env(); |
| 12513 | let keys = [ |
| 12514 | "CODEWHALE_PROVIDER", |
| 12515 | "DEEPSEEK_PROVIDER", |
| 12516 | "CODEWHALE_BASE_URL", |
| 12517 | "DEEPSEEK_BASE_URL", |
| 12518 | "ANTHROPIC_API_KEY", |
| 12519 | "OPENAI_API_KEY", |
| 12520 | "GEMINI_API_KEY", |
| 12521 | "DEEPSEEK_API_KEY", |
| 12522 | "OPENROUTER_API_KEY", |
| 12523 | ]; |
| 12524 | let _restore = RestoreEnv(keys.iter().map(|&k| (k, env::var_os(k))).collect()); |
| 12525 | for key in keys { |
| 12526 | unsafe { env::remove_var(key) }; |
| 12527 | } |
| 12528 | |
| 12529 | let mut cfg = Config::default(); |
| 12530 | apply_env_overrides_unlocked(&mut cfg, ConfigEnvironmentPolicy::Runtime); |
| 12531 | assert_eq!(cfg.provider, None); |
| 12532 | assert_eq!( |
| 12533 | cfg.active_provider_identity().expect("default").provider, |
| 12534 | ProviderKind::Deepseek |
| 12535 | ); |
| 12536 | |
| 12537 | unsafe { env::set_var("OPENROUTER_API_KEY", "sk-or-test") }; |
| 12538 | assert_eq!( |
| 12539 | Config::default() |
| 12540 | .active_provider_identity() |
| 12541 | .expect("pure default") |
| 12542 | .provider, |
| 12543 | ProviderKind::Deepseek |
| 12544 | ); |
| 12545 | |
| 12546 | let mut openrouter_cfg = Config::default(); |
| 12547 | apply_env_overrides_unlocked(&mut openrouter_cfg, ConfigEnvironmentPolicy::Runtime); |
| 12548 | assert_eq!(openrouter_cfg.provider.as_deref(), Some("openrouter")); |
| 12549 | assert!(openrouter_cfg.route_provenance.provider_from_env); |
| 12550 | |
| 12551 | unsafe { env::set_var("ANTHROPIC_API_KEY", "sk-ant-test") }; |
| 12552 | let mut anthropic_cfg = Config::default(); |
| 12553 | apply_env_overrides_unlocked(&mut anthropic_cfg, ConfigEnvironmentPolicy::Runtime); |
| 12554 | assert_eq!(anthropic_cfg.provider.as_deref(), Some("anthropic")); |
| 12555 | assert!(anthropic_cfg.route_provenance.provider_from_env); |
| 12556 | |
| 12557 | let mut diagnostic_cfg = Config::default(); |
| 12558 | apply_env_overrides_unlocked( |
| 12559 | &mut diagnostic_cfg, |
| 12560 | ConfigEnvironmentPolicy::StructuralDiagnostic, |
| 12561 | ); |
| 12562 | assert_eq!(diagnostic_cfg.provider, None); |
| 12563 | |
| 12564 | let mut explicit_model_cfg = Config { |
| 12565 | default_text_model: Some("deepseek-chat".to_string()), |
| 12566 | ..Config::default() |
| 12567 | }; |
| 12568 | apply_env_overrides_unlocked(&mut explicit_model_cfg, ConfigEnvironmentPolicy::Runtime); |
| 12569 | assert_eq!(explicit_model_cfg.provider, None); |
| 12570 | } |
| 12571 | |
| 12572 | #[test] |
| 12573 | fn invalid_value_fixes_are_commands_that_work_and_name_overriding_layers() { |
| 12574 | assert_eq!( |
| 12575 | user_config_fix("tui.posture_bar", "full", None), |
| 12576 | "set posture_bar = \"full\" in the [tui] table of config.toml (if a profile or managed config sets it, correct it there)" |
| 12577 | ); |
| 12578 | |
| 12579 | let error = Config { |
| 12580 | sandbox_mode: Some("bogus".to_string()), |
| 12581 | ..Config::default() |
| 12582 | } |
| 12583 | .validate() |
| 12584 | .expect_err("unknown sandbox_mode"); |
| 12585 | let fix = SafeConfigDiagnostic::find_in(&error) |
| 12586 | .and_then(SafeConfigDiagnostic::fix) |
| 12587 | .expect("fix"); |
| 12588 | assert!( |
| 12589 | fix.starts_with("codewhale config set sandbox_mode workspace-write (if CODEWHALE_SANDBOX_MODE, a profile, or managed config sets it"), |
| 12590 | "{fix}" |
| 12591 | ); |
| 12592 | } |
| 12593 | |
| 12594 | #[test] |
| 12595 | fn missing_profile_diagnostic_does_not_show_the_requested_name() { |
| 12596 | let mut profiles = HashMap::new(); |
| 12597 | profiles.insert("work".to_string(), Config::default()); |
| 12598 | let config = ConfigFile { |
| 12599 | base: Box::default(), |
| 12600 | profiles: Some(profiles), |
| 12601 | legacy_root: Default::default(), |
| 12602 | }; |
| 12603 | let error = apply_profile(config, Some("sk-pasted-token")).expect_err("no such profile"); |
| 12604 | let diagnostic = SafeConfigDiagnostic::find_in(&error).expect("safe diagnostic"); |
| 12605 | let shown = diagnostic.display_message(); |
| 12606 | assert_eq!( |
| 12607 | shown, |
| 12608 | "Profile not found (name not shown). Available profiles: work" |
| 12609 | ); |
| 12610 | // The local error keeps the typed name for the person at the terminal. |
| 12611 | assert!(error.to_string().contains("sk-pasted-token"), "{error}"); |
| 12612 | } |
| 12613 | |
| 12614 | /// #6700: `[tui].force_http1 = true` pins HTTP/1.1 without the env var. |
| 12615 | /// (The env-only path is covered by `force_http1_scenario` under its lock.) |
| 12616 | #[test] |
| 12617 | fn tui_force_http1_key_pins_http1() { |
| 12618 | let config: Config = toml::from_str("[tui]\nforce_http1 = true\n").expect("config parses"); |
| 12619 | assert!(config.force_http1()); |
| 12620 | } |
| 12621 | |
| 12622 | #[test] |
| 12623 | fn canonical_stream_config_preserves_legacy_resolution_and_precedence() { |
| 12624 | let _lock = lock_test_env(); |
| 12625 | let _pin = EnvVarGuard::remove("CODEWHALE_FORCE_HTTP1"); |
| 12626 | let _legacy_pin = EnvVarGuard::remove("DEEPSEEK_FORCE_HTTP1"); |
| 12627 | let legacy = "[tui]\nstream_open_timeout_secs=80\nstream_chunk_timeout_secs=120\nforce_http1=true\nstream_max_resumes=4\nstream_max_transparent_retries=3\nstream_max_errors=7\nstream_max_duration_secs=900\nstream_max_content_mb=12\nconnect_timeout_secs=60\n"; |
| 12628 | let canonical = "[stream]\nopen_timeout_secs=80\nchunk_timeout_secs=120\nforce_http1=true\nmax_resumes=4\nmax_transparent_retries=3\nmax_stream_errors=7\nmax_duration_secs=900\nmax_content_mb=12\nconnect_timeout_secs=60\n"; |
| 12629 | let parse = |body: &str| toml::from_str::<Config>(body).unwrap(); |
| 12630 | assert_eq!( |
| 12631 | toml::Value::try_from(parse(legacy).resolved_stream_settings()).unwrap(), |
| 12632 | toml::Value::try_from(parse(canonical).resolved_stream_settings()).unwrap(), |
| 12633 | ); |
| 12634 | let mixed = parse(&format!( |
| 12635 | "{legacy}\n[stream]\nmax_resumes=0\nforce_http1=false\n" |
| 12636 | )); |
| 12637 | assert_eq!(mixed.stream_retry_limits().max_resumes, 0); |
| 12638 | assert_eq!(mixed.stream_retry_limits().max_errors, 7); |
| 12639 | assert_eq!(mixed.stream_open_timeout(), Duration::from_secs(80)); |
| 12640 | assert!(!mixed.force_http1()); |
| 12641 | let _pin = EnvVarGuard::set("CODEWHALE_FORCE_HTTP1", "1"); |
| 12642 | assert!( |
| 12643 | mixed.force_http1(), |
| 12644 | "the existing environment pin still wins" |
| 12645 | ); |
| 12646 | } |
| 12647 | |
| 12648 | #[test] |
| 12649 | fn canonical_stream_config_env_clamps_and_keepalive_disable() { |
| 12650 | let _lock = lock_test_env(); |
| 12651 | let _open = EnvVarGuard::set("CODEWHALE_STREAM_OPEN_TIMEOUT_SECS", "70"); |
| 12652 | let _idle = EnvVarGuard::set("CODEWHALE_STREAM_IDLE_TIMEOUT_SECS", "90"); |
| 12653 | let config: Config = toml::from_str("[stream]\nopen_timeout_secs=0\nchunk_timeout_secs=0\nmax_resumes=99\nmax_transparent_retries=99\nmax_stream_errors=0\nmax_duration_secs=999999\nmax_content_mb=999999\nconnect_timeout_secs=999999\ntcp_keepalive_secs=0\nhttp2_keep_alive_interval_secs=0\nhttp2_keep_alive_timeout_secs=0\n").unwrap(); |
| 12654 | assert_eq!(config.stream_open_timeout(), Duration::from_secs(70)); |
| 12655 | assert_eq!( |
| 12656 | config.stream_chunk_timeout_secs(), |
| 12657 | 900, |
| 12658 | "zero retains idle default semantics" |
| 12659 | ); |
| 12660 | assert_eq!(config.stream_retry_limits().max_resumes, 10); |
| 12661 | assert_eq!(config.stream_retry_limits().max_transparent_retries, 10); |
| 12662 | assert_eq!(config.stream_retry_limits().max_errors, 5); |
| 12663 | assert_eq!(config.stream_max_duration(), Duration::from_secs(86400)); |
| 12664 | assert_eq!(config.stream_max_content_bytes(), 512 * 1024 * 1024); |
| 12665 | assert_eq!(config.connect_timeout(), Duration::from_secs(300)); |
| 12666 | assert_eq!(config.tcp_keepalive(), None); |
| 12667 | assert_eq!(config.http2_keep_alive_interval(), None); |
| 12668 | assert_eq!(config.http2_keep_alive_timeout(), Duration::from_secs(20)); |
| 12669 | let positive: Config = toml::from_str("[stream]\nopen_timeout_secs=12\nopen_retries=0\nunknown_outcome_retries=2\nchunk_timeout_secs=14\ntcp_keepalive_secs=9000\nhttp2_keep_alive_interval_secs=9000\nhttp2_keep_alive_timeout_secs=9000\n").unwrap(); |
| 12670 | assert_eq!(positive.stream_open_timeout(), Duration::from_secs(12)); |
| 12671 | assert_eq!(config.stream_retry_limits().open_retries, 1); |
| 12672 | assert_eq!(positive.stream_retry_limits().open_retries, 0); |
| 12673 | assert_eq!(config.stream_retry_limits().unknown_outcome_retries, 0); |
| 12674 | assert_eq!(positive.stream_retry_limits().unknown_outcome_retries, 2); |
| 12675 | assert_eq!(positive.stream_chunk_timeout_secs(), 14); |
| 12676 | assert_eq!(positive.tcp_keepalive(), Some(Duration::from_secs(3600))); |
| 12677 | assert_eq!( |
| 12678 | positive.http2_keep_alive_interval(), |
| 12679 | Some(Duration::from_secs(3600)) |
| 12680 | ); |
| 12681 | assert_eq!( |
| 12682 | positive.http2_keep_alive_timeout(), |
| 12683 | Duration::from_secs(3600) |
| 12684 | ); |
| 12685 | for invalid in [ |
| 12686 | "open_timeout_secs=-1", |
| 12687 | "max_resumes=4294967296", |
| 12688 | "force_http1='yes'", |
| 12689 | "open_timout_secs=45", |
| 12690 | ] { |
| 12691 | assert!( |
| 12692 | toml::from_str::<Config>(&format!("[stream]\n{invalid}\n")).is_err(), |
| 12693 | "{invalid}" |
| 12694 | ); |
| 12695 | } |
| 12696 | } |
| 12697 | |
| 12698 | #[test] |
| 12699 | fn canonical_stream_config_profile_merges_independent_keys() { |
| 12700 | let config = parse_config_file("[stream]\nmax_resumes=7\ntcp_keepalive_secs=41\n[profiles.mobile.stream]\nopen_timeout_secs=240\n").unwrap(); |
| 12701 | let resolved = apply_profile(config, Some("mobile")).unwrap(); |
| 12702 | assert_eq!(resolved.stream_retry_limits().max_resumes, 7); |
| 12703 | assert_eq!(resolved.tcp_keepalive(), Some(Duration::from_secs(41))); |
| 12704 | assert_eq!(resolved.stream_open_timeout(), Duration::from_secs(240)); |
| 12705 | } |
| 12706 | |
| 12707 | #[test] |
| 12708 | fn migrated_root_custom_provenance_cannot_bless_replaced_added_or_profile_tables() { |
| 12709 | let root = Config::from_saved_document( |
| 12710 | r#"provider = "custom" |
| 12711 | base_url = "http://127.0.0.1:18180/v1" |
| 12712 | api_key = "fixture-key" |
| 12713 | default_text_model = "legacy-model" |
| 12714 | "#, |
| 12715 | None, |
| 12716 | ) |
| 12717 | .unwrap(); |
| 12718 | let captured = root.active_provider_identity().unwrap(); |
| 12719 | for change in ["endpoint", "credential", "model", "replacement", "removed"] { |
| 12720 | let mut changed = root.clone(); |
| 12721 | let tables = &mut changed.providers.as_mut().unwrap().custom; |
| 12722 | match change { |
| 12723 | "endpoint" => { |
| 12724 | tables.get_mut("custom").unwrap().base_url = |
| 12725 | Some("http://127.0.0.1:19191/v1".into()) |
| 12726 | } |
| 12727 | "credential" => { |
| 12728 | tables.get_mut("custom").unwrap().api_key = Some("replacement-key".into()) |
| 12729 | } |
| 12730 | "model" => tables.get_mut("custom").unwrap().model = Some("replacement-model".into()), |
| 12731 | "replacement" => { |
| 12732 | tables.insert( |
| 12733 | "custom".into(), |
| 12734 | ProviderConfig { |
| 12735 | kind: Some("openai-compatible".into()), |
| 12736 | base_url: Some("http://127.0.0.1:19191/v1".into()), |
| 12737 | ..ProviderConfig::default() |
| 12738 | }, |
| 12739 | ); |
| 12740 | } |
| 12741 | "removed" => { |
| 12742 | tables.remove("custom"); |
| 12743 | } |
| 12744 | _ => unreachable!(), |
| 12745 | } |
| 12746 | assert!( |
| 12747 | changed |
| 12748 | .resolve_persisted_provider_identity(Some("custom"), None) |
| 12749 | .is_err(), |
| 12750 | "{change}" |
| 12751 | ); |
| 12752 | assert!( |
| 12753 | changed.verify_provider_identity(&captured).is_err(), |
| 12754 | "{change}" |
| 12755 | ); |
| 12756 | assert!(changed.provider_config_for(&captured).is_none(), "{change}"); |
| 12757 | assert_eq!(changed.base_url_for_route(&captured), "", "{change}"); |
| 12758 | } |
| 12759 | let added = Config { |
| 12760 | provider: Some("custom".into()), |
| 12761 | legacy_root: root.legacy_root.clone(), // diagnostic notes are not authority. |
| 12762 | providers: root.providers.clone(), |
| 12763 | ..Config::default() |
| 12764 | }; |
| 12765 | assert!( |
| 12766 | added |
| 12767 | .resolve_persisted_provider_identity(Some("custom"), None) |
| 12768 | .is_err() |
| 12769 | ); |
| 12770 | let profile = Config::from_saved_document( |
| 12771 | r#"provider = "deepseek" |
| 12772 | [profiles.local] |
| 12773 | provider = "custom" |
| 12774 | base_url = "http://127.0.0.1:18180/v1" |
| 12775 | default_text_model = "profile-model" |
| 12776 | "#, |
| 12777 | Some("local"), |
| 12778 | ) |
| 12779 | .unwrap(); |
| 12780 | assert!( |
| 12781 | profile |
| 12782 | .resolve_persisted_provider_identity(Some("custom"), None) |
| 12783 | .is_err() |
| 12784 | ); |
| 12785 | assert_eq!( |
| 12786 | profile |
| 12787 | .resolve_persisted_provider_identity(Some("custom"), Some("custom")) |
| 12788 | .unwrap() |
| 12789 | .persisted_id(), |
| 12790 | Some("custom") |
| 12791 | ); |
| 12792 | let dropped = Config::from_saved_document( |
| 12793 | r#"provider = "custom" |
| 12794 | base_url = "" |
| 12795 | [providers.custom] |
| 12796 | kind = "openai-compatible" |
| 12797 | base_url = "http://127.0.0.1:18180/v1" |
| 12798 | "#, |
| 12799 | None, |
| 12800 | ) |
| 12801 | .unwrap(); |
| 12802 | assert!( |
| 12803 | dropped |
| 12804 | .resolve_persisted_provider_identity(Some("custom"), None) |
| 12805 | .is_err() |
| 12806 | ); |
| 12807 | } |
| 12808 | |
| 12809 | #[test] |
| 12810 | fn custom_id_case_is_not_migration_or_builtin_authority() { |
| 12811 | let config = Config::from_saved_document( |
| 12812 | r#"provider = "CustomA" |
| 12813 | [providers.CustomA] |
| 12814 | kind = "openai-compatible" |
| 12815 | base_url = "http://127.0.0.1:18180/v1" |
| 12816 | [providers.customa] |
| 12817 | kind = "openai-compatible" |
| 12818 | base_url = "http://127.0.0.1:19191/v1" |
| 12819 | "#, |
| 12820 | None, |
| 12821 | ) |
| 12822 | .unwrap(); |
| 12823 | assert!( |
| 12824 | config |
| 12825 | .resolve_persisted_provider_identity(Some("custom"), None) |
| 12826 | .is_err() |
| 12827 | ); |
| 12828 | let a = config |
| 12829 | .resolve_persisted_provider_identity(Some("custom"), Some("CustomA")) |
| 12830 | .unwrap(); |
| 12831 | let b = config |
| 12832 | .resolve_persisted_provider_identity(Some("custom"), Some("customa")) |
| 12833 | .unwrap(); |
| 12834 | assert_ne!(a, b); |
| 12835 | assert_eq!(a.key.as_str(), "CustomA"); |
| 12836 | assert_eq!(b.key.as_str(), "customa"); |
| 12837 | assert_ne!(config.base_url_for_route(&a), config.base_url_for_route(&b)); |
| 12838 | } |
| 12839 | |
| 12840 | #[test] |
| 12841 | fn legacy_root_model_preparation_remints_only_after_verified_model_selection() { |
| 12842 | let mut config = Config::from_saved_document( |
| 12843 | r#"provider = "custom" |
| 12844 | base_url = "http://127.0.0.1:18180/v1" |
| 12845 | default_text_model = "original-model" |
| 12846 | "#, |
| 12847 | None, |
| 12848 | ) |
| 12849 | .unwrap(); |
| 12850 | let original = config.active_provider_identity().unwrap(); |
| 12851 | config |
| 12852 | .set_provider_model_override(&original, Some("selected-model".into())) |
| 12853 | .unwrap(); |
| 12854 | assert!(config.verify_provider_identity(&original).is_err()); |
| 12855 | let prepared = config.active_provider_identity().unwrap(); |
| 12856 | assert!(prepared.persisted_id().is_none()); |
| 12857 | assert_ne!(prepared, original); |
| 12858 | assert_eq!( |
| 12859 | config |
| 12860 | .provider_config_for(&prepared) |
| 12861 | .unwrap() |
| 12862 | .model |
| 12863 | .as_deref(), |
| 12864 | Some("selected-model") |
| 12865 | ); |
| 12866 | config |
| 12867 | .set_provider_base_url_override(&prepared, Some("http://127.0.0.1:19191/v1".into())) |
| 12868 | .unwrap(); |
| 12869 | assert!( |
| 12870 | config |
| 12871 | .resolve_persisted_provider_identity(Some("custom"), None) |
| 12872 | .is_err() |
| 12873 | ); |
| 12874 | assert_eq!( |
| 12875 | config.active_provider_identity().unwrap().persisted_id(), |
| 12876 | Some("custom") |
| 12877 | ); |
| 12878 | } |
| 12879 | |
| 12880 | #[test] |
| 12881 | fn custom_provider_responses_profile_round_trips() { |
| 12882 | let config: Config = toml::from_str( |
| 12883 | r#" |
| 12884 | [providers.my-gateway] |
| 12885 | kind = "openai-compatible" |
| 12886 | wire = "responses" |
| 12887 | responses_profile = "standard" |
| 12888 | "#, |
| 12889 | ) |
| 12890 | .expect("custom responses profile parses"); |
| 12891 | let entry = config |
| 12892 | .providers |
| 12893 | .as_ref() |
| 12894 | .expect("providers") |
| 12895 | .custom_provider_config("my-gateway") |
| 12896 | .expect("named table"); |
| 12897 | assert_eq!(entry.responses_profile.as_deref(), Some("standard")); |
| 12898 | let rendered = toml::to_string(entry).expect("serialize"); |
| 12899 | assert!(rendered.contains("responses_profile = \"standard\"")); |
| 12900 | } |
| 12901 | |
| 12902 | #[test] |
| 12903 | fn tool_launcher_is_refused_outside_the_managed_layer() -> Result<()> { |
| 12904 | let _lock = lock_test_env(); |
| 12905 | let temp_root = tempfile::tempdir()?; |
| 12906 | let _guard = EnvGuard::new(temp_root.path()); |
| 12907 | let _managed = no_managed_config(temp_root.path()); |
| 12908 | let config_path = temp_root.path().join("config.toml"); |
| 12909 | for document in [ |
| 12910 | "tool_launcher = [\"/usr/bin/sudo\", \"-n\", \"-u\", \"agent\", \"--\"]\n", |
| 12911 | "[profiles.work]\ntool_launcher = [\"/usr/bin/sudo\"]\n", |
| 12912 | ] { |
| 12913 | fs::write(&config_path, document)?; |
| 12914 | let error = Config::load(Some(config_path.clone()), None) |
| 12915 | .expect_err("user-layer tool_launcher is a load error"); |
| 12916 | assert!( |
| 12917 | format!("{error:#}").contains("read only from the managed configuration"), |
| 12918 | "{error:#}" |
| 12919 | ); |
| 12920 | } |
| 12921 | fs::write(&config_path, "prefer_bwrap = true\n")?; |
| 12922 | assert_eq!(Config::load(Some(config_path), None)?.tool_launcher, None); |
| 12923 | Ok(()) |
| 12924 | } |
| 12925 | |
| 12926 | #[test] |
| 12927 | fn tool_launcher_is_refused_from_a_managed_file_the_engine_can_write() -> Result<()> { |
| 12928 | let _lock = lock_test_env(); |
| 12929 | let temp_root = tempfile::tempdir()?; |
| 12930 | let _guard = EnvGuard::new(temp_root.path()); |
| 12931 | let managed_path = temp_root.path().join("managed.toml"); |
| 12932 | fs::write( |
| 12933 | &managed_path, |
| 12934 | "sandbox_mode = \"workspace-write\"\ntool_launcher = [\"/usr/bin/sudo\", \"-n\"]\n", |
| 12935 | )?; |
| 12936 | let _managed = EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", &managed_path); |
| 12937 | let config_path = temp_root.path().join("config.toml"); |
| 12938 | fs::write(&config_path, "")?; |
| 12939 | let error = Config::load(Some(config_path), None).expect_err("refused"); |
| 12940 | let expected = if cfg!(all(target_os = "linux", not(target_env = "ohos"))) { |
| 12941 | "the Engine's own user can change that file" |
| 12942 | } else { |
| 12943 | "supported only on Linux" |
| 12944 | }; |
| 12945 | assert!(format!("{error:#}").contains(expected), "{error:#}"); |
| 12946 | Ok(()) |
| 12947 | } |
| 12948 | |
| 12949 | #[cfg(unix)] |
| 12950 | #[test] |
| 12951 | fn a_managed_file_is_replaceable_through_any_writable_ancestor() -> Result<()> { |
| 12952 | use std::os::unix::fs::PermissionsExt; |
| 12953 | let temp_root = tempfile::tempdir()?; |
| 12954 | let sealed_dir = temp_root.path().join("etc"); |
| 12955 | fs::create_dir(&sealed_dir)?; |
| 12956 | let file = sealed_dir.join("managed.toml"); |
| 12957 | fs::write(&file, "")?; |
| 12958 | assert!(engine_can_replace(&file)); |
| 12959 | fs::set_permissions(&file, fs::Permissions::from_mode(0o444))?; |
| 12960 | fs::set_permissions(&sealed_dir, fs::Permissions::from_mode(0o555))?; |
| 12961 | let through_grandparent = engine_can_replace(&file); |
| 12962 | fs::set_permissions(&sealed_dir, fs::Permissions::from_mode(0o755))?; |
| 12963 | assert!(through_grandparent); |
| 12964 | if !engine_can_replace(Path::new("/")) { |
| 12965 | assert!(!engine_can_replace(Path::new("/etc/passwd"))); |
| 12966 | } |
| 12967 | Ok(()) |
| 12968 | } |
| 12969 | |
| 12970 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 12971 | #[test] |
| 12972 | fn tool_launcher_is_read_from_a_sealed_managed_file() -> Result<()> { |
| 12973 | struct Sealed; |
| 12974 | impl Drop for Sealed { |
| 12975 | fn drop(&mut self) { |
| 12976 | TEST_TREAT_MANAGED_FILE_AS_SEALED.store(false, std::sync::atomic::Ordering::SeqCst); |
| 12977 | } |
| 12978 | } |
| 12979 | let _lock = lock_test_env(); |
| 12980 | let temp_root = tempfile::tempdir()?; |
| 12981 | let _guard = EnvGuard::new(temp_root.path()); |
| 12982 | let managed_path = temp_root.path().join("managed.toml"); |
| 12983 | let config_path = temp_root.path().join("config.toml"); |
| 12984 | fs::write(&config_path, "")?; |
| 12985 | let _managed = EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", &managed_path); |
| 12986 | TEST_TREAT_MANAGED_FILE_AS_SEALED.store(true, std::sync::atomic::Ordering::SeqCst); |
| 12987 | let _sealed = Sealed; |
| 12988 | |
| 12989 | fs::write( |
| 12990 | &managed_path, |
| 12991 | "sandbox_mode = \"workspace-write\"\nsandbox_network_access = true\ntool_launcher = [\"/usr/bin/sudo\", \"-n\", \"-u\", \"agent\", \"--\", \"/opt/exec\"]\n", |
| 12992 | )?; |
| 12993 | let config = Config::load(Some(config_path.clone()), None)?; |
| 12994 | assert_eq!( |
| 12995 | config.tool_launcher.as_deref(), |
| 12996 | Some( |
| 12997 | ["/usr/bin/sudo", "-n", "-u", "agent", "--", "/opt/exec"] |
| 12998 | .map(str::to_string) |
| 12999 | .as_slice() |
| 13000 | ) |
| 13001 | ); |
| 13002 | assert_eq!(config.sandbox_mode.as_deref(), Some("workspace-write")); |
| 13003 | assert_eq!(config.sandbox_network_access, Some(true)); |
| 13004 | |
| 13005 | for (document, expected) in [ |
| 13006 | ( |
| 13007 | "tool_launcher = [\"/usr/bin/sudo\"]\n", |
| 13008 | "needs `sandbox_mode", |
| 13009 | ), |
| 13010 | ( |
| 13011 | "sandbox_mode = \"danger-full-access\"\ntool_launcher = [\"/usr/bin/sudo\"]\n", |
| 13012 | "needs `sandbox_mode", |
| 13013 | ), |
| 13014 | ( |
| 13015 | "sandbox_mode = \"workspace-write\"\ntool_launcher = [\"sudo\"]\n", |
| 13016 | "absolute program path", |
| 13017 | ), |
| 13018 | ( |
| 13019 | "sandbox_mode = \"workspace-write\"\ntool_launcher = \"/usr/bin/sudo\"\n", |
| 13020 | "absolute program path", |
| 13021 | ), |
| 13022 | ( |
| 13023 | "sandbox_mode = \"workspace-write\"\n[profiles.work]\ntool_launcher = [\"/usr/bin/sudo\"]\n", |
| 13024 | "not in a profile", |
| 13025 | ), |
| 13026 | ] { |
| 13027 | fs::write(&managed_path, document)?; |
| 13028 | let error = Config::load(Some(config_path.clone()), None).expect_err(document); |
| 13029 | assert!(format!("{error:#}").contains(expected), "{error:#}"); |
| 13030 | } |
| 13031 | Ok(()) |
| 13032 | } |
| 13033 | |
| 13034 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 13035 | #[test] |
| 13036 | fn the_managed_file_named_by_the_host_survives_a_provider_that_resolves_late() -> Result<()> { |
| 13037 | struct Sealed; |
| 13038 | impl Drop for Sealed { |
| 13039 | fn drop(&mut self) { |
| 13040 | TEST_TREAT_MANAGED_FILE_AS_SEALED.store(false, std::sync::atomic::Ordering::SeqCst); |
| 13041 | } |
| 13042 | } |
| 13043 | let _lock = lock_test_env(); |
| 13044 | let temp_root = tempfile::tempdir()?; |
| 13045 | let _guard = EnvGuard::new(temp_root.path()); |
| 13046 | let managed_path = temp_root.path().join("managed.toml"); |
| 13047 | let config_path = temp_root.path().join("config.toml"); |
| 13048 | let _managed = EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", &managed_path); |
| 13049 | TEST_TREAT_MANAGED_FILE_AS_SEALED.store(true, std::sync::atomic::Ordering::SeqCst); |
| 13050 | let _sealed = Sealed; |
| 13051 | fs::write( |
| 13052 | &managed_path, |
| 13053 | "sandbox_mode = \"workspace-write\"\ntool_launcher = [\"/usr/bin/sudo\", \"-n\"]\n", |
| 13054 | )?; |
| 13055 | |
| 13056 | let mut late_provider = |config: &mut Config| -> Result<()> { |
| 13057 | let entry: ProviderConfig = toml::from_str( |
| 13058 | "base_url = \"https://example.invalid/v1\"\nmodel = \"m\"\nkind = \"openai-compatible\"\n", |
| 13059 | )?; |
| 13060 | config |
| 13061 | .providers |
| 13062 | .get_or_insert_with(Default::default) |
| 13063 | .custom |
| 13064 | .insert("ghostplug".to_string(), entry); |
| 13065 | Ok(()) |
| 13066 | }; |
| 13067 | for user_file in [ |
| 13068 | "provider = \"ghostplug\"\n", |
| 13069 | "provider = \"ghostplug\"\nmanaged_config_path = \"/nonexistent/managed.toml\"\n", |
| 13070 | ] { |
| 13071 | fs::write(&config_path, user_file)?; |
| 13072 | let loaded = Config::load_with( |
| 13073 | Some(config_path.clone()), |
| 13074 | None, |
| 13075 | ConfigEnvironmentPolicy::Runtime, |
| 13076 | &mut late_provider, |
| 13077 | ); |
| 13078 | let error = loaded.expect_err("a plugin provider does not load under a managed file"); |
| 13079 | assert!( |
| 13080 | format!("{error:#}").contains("a provider that only a plugin declares"), |
| 13081 | "{user_file}: {error:#}" |
| 13082 | ); |
| 13083 | } |
| 13084 | Ok(()) |
| 13085 | } |
| 13086 | |
| 13087 | #[test] |
| 13088 | fn a_named_managed_file_that_cannot_be_read_is_a_load_error() -> Result<()> { |
| 13089 | let _lock = lock_test_env(); |
| 13090 | let temp_root = tempfile::tempdir()?; |
| 13091 | let _guard = EnvGuard::new(temp_root.path()); |
| 13092 | let _legacy_managed = EnvVarGuard::remove("DEEPSEEK_MANAGED_CONFIG_PATH"); |
| 13093 | let config_path = temp_root.path().join("config.toml"); |
| 13094 | fs::write(&config_path, "")?; |
| 13095 | let missing = temp_root.path().join("missing-managed.toml"); |
| 13096 | for named in [missing.clone(), temp_root.path().to_path_buf()] { |
| 13097 | let _managed = EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", &named); |
| 13098 | let error = Config::load(Some(config_path.clone()), None).expect_err("closed"); |
| 13099 | assert!( |
| 13100 | format!("{error:#}").contains("does not start without a managed configuration"), |
| 13101 | "{error:#}" |
| 13102 | ); |
| 13103 | } |
| 13104 | |
| 13105 | let _managed = EnvVarGuard::remove("CODEWHALE_MANAGED_CONFIG_PATH"); |
| 13106 | fs::write( |
| 13107 | &config_path, |
| 13108 | format!( |
| 13109 | "managed_config_path = {}\n", |
| 13110 | toml::Value::String(missing.display().to_string()) |
| 13111 | ), |
| 13112 | )?; |
| 13113 | let error = Config::load(Some(config_path.clone()), None).expect_err("closed"); |
| 13114 | assert!( |
| 13115 | format!("{error:#}").contains("does not start without a managed configuration"), |
| 13116 | "{error:#}" |
| 13117 | ); |
| 13118 | |
| 13119 | fs::write(&config_path, "")?; |
| 13120 | let empty = temp_root.path().join("empty-managed.toml"); |
| 13121 | fs::write(&empty, "")?; |
| 13122 | let _blank = EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", ""); |
| 13123 | let _legacy = EnvVarGuard::set("DEEPSEEK_MANAGED_CONFIG_PATH", &missing); |
| 13124 | let error = Config::load(Some(config_path.clone()), None).expect_err("blank defers"); |
| 13125 | assert!( |
| 13126 | format!("{error:#}").contains("missing-managed.toml"), |
| 13127 | "{error:#}" |
| 13128 | ); |
| 13129 | let _legacy = EnvVarGuard::set("DEEPSEEK_MANAGED_CONFIG_PATH", &empty); |
| 13130 | Config::load(Some(config_path), None)?; |
| 13131 | Ok(()) |
| 13132 | } |
| 13133 | |
| 13134 | #[cfg(all(target_os = "linux", not(target_env = "ohos")))] |
| 13135 | #[test] |
| 13136 | fn tool_launcher_is_refused_from_a_managed_file_the_user_config_names() -> Result<()> { |
| 13137 | struct Sealed; |
| 13138 | impl Drop for Sealed { |
| 13139 | fn drop(&mut self) { |
| 13140 | TEST_TREAT_MANAGED_FILE_AS_SEALED.store(false, std::sync::atomic::Ordering::SeqCst); |
| 13141 | } |
| 13142 | } |
| 13143 | let _lock = lock_test_env(); |
| 13144 | let temp_root = tempfile::tempdir()?; |
| 13145 | let _guard = EnvGuard::new(temp_root.path()); |
| 13146 | let _managed = EnvVarGuard::remove("CODEWHALE_MANAGED_CONFIG_PATH"); |
| 13147 | let _legacy_managed = EnvVarGuard::remove("DEEPSEEK_MANAGED_CONFIG_PATH"); |
| 13148 | let managed_path = temp_root.path().join("elsewhere.toml"); |
| 13149 | fs::write( |
| 13150 | &managed_path, |
| 13151 | "sandbox_mode = \"workspace-write\"\ntool_launcher = [\"/usr/bin/sudo\", \"-n\"]\n", |
| 13152 | )?; |
| 13153 | let config_path = temp_root.path().join("config.toml"); |
| 13154 | fs::write( |
| 13155 | &config_path, |
| 13156 | format!( |
| 13157 | "managed_config_path = {}\n", |
| 13158 | toml::Value::String(managed_path.display().to_string()) |
| 13159 | ), |
| 13160 | )?; |
| 13161 | TEST_TREAT_MANAGED_FILE_AS_SEALED.store(true, std::sync::atomic::Ordering::SeqCst); |
| 13162 | let _sealed = Sealed; |
| 13163 | let error = Config::load(Some(config_path.clone()), None).expect_err("refused"); |
| 13164 | assert!( |
| 13165 | format!("{error:#}") |
| 13166 | .contains("not CODEWHALE_MANAGED_CONFIG_PATH or the default managed path"), |
| 13167 | "{error:#}" |
| 13168 | ); |
| 13169 | |
| 13170 | let _named = EnvVarGuard::set("CODEWHALE_MANAGED_CONFIG_PATH", &managed_path); |
| 13171 | fs::write( |
| 13172 | &managed_path, |
| 13173 | "tool_launcher = [\"/usr/bin/sudo\", \"-n\"]\n", |
| 13174 | )?; |
| 13175 | fs::write(&config_path, "sandbox_mode = \"workspace-write\"\n")?; |
| 13176 | let error = |
| 13177 | Config::load(Some(config_path), None).expect_err("user sandbox_mode does not count"); |
| 13178 | assert!( |
| 13179 | format!("{error:#}").contains("needs `sandbox_mode"), |
| 13180 | "{error:#}" |
| 13181 | ); |
| 13182 | Ok(()) |
| 13183 | } |
| 13184 | |
| 13185 | #[test] |
| 13186 | fn env_bool_overrides_accept_yes_and_on() { |
| 13187 | let _lock = lock_test_env(); |
| 13188 | let _legacy_shell = EnvVarGuard::remove("DEEPSEEK_ALLOW_SHELL"); |
| 13189 | let _legacy_yolo = EnvVarGuard::remove("DEEPSEEK_YOLO"); |
| 13190 | let _legacy_net = EnvVarGuard::remove("DEEPSEEK_SANDBOX_NETWORK_ACCESS"); |
| 13191 | let _legacy_bwrap = EnvVarGuard::remove("DEEPSEEK_PREFER_BWRAP"); |
| 13192 | |
| 13193 | for truthy in ["yes", "YES", "on", " ON ", "1", "true"] { |
| 13194 | let _shell = EnvVarGuard::set("CODEWHALE_ALLOW_SHELL", truthy); |
| 13195 | let _yolo = EnvVarGuard::set("CODEWHALE_YOLO", truthy); |
| 13196 | let _net = EnvVarGuard::set("CODEWHALE_SANDBOX_NETWORK_ACCESS", truthy); |
| 13197 | let _bwrap = EnvVarGuard::set("CODEWHALE_PREFER_BWRAP", truthy); |
| 13198 | let mut config = Config::default(); |
| 13199 | apply_env_overrides_unlocked(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 13200 | assert_eq!(config.allow_shell, Some(true), "allow_shell={truthy}"); |
| 13201 | assert_eq!(config.yolo, Some(true), "yolo={truthy}"); |
| 13202 | assert_eq!(config.sandbox_network_access, Some(true), "net={truthy}"); |
| 13203 | assert_eq!(config.prefer_bwrap, Some(true), "bwrap={truthy}"); |
| 13204 | } |
| 13205 | |
| 13206 | for falsy in ["no", "off", "0", "false", ""] { |
| 13207 | let _shell = EnvVarGuard::set("CODEWHALE_ALLOW_SHELL", falsy); |
| 13208 | let mut config = Config::default(); |
| 13209 | apply_env_overrides_unlocked(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 13210 | assert_eq!(config.allow_shell, Some(false), "allow_shell={falsy}"); |
| 13211 | } |
| 13212 | } |
| 13213 | |
| 13214 | #[test] |
| 13215 | fn unknown_provider_env_does_not_skip_later_env_overrides() { |
| 13216 | let _lock = lock_test_env(); |
| 13217 | let _provider = EnvVarGuard::set("CODEWHALE_PROVIDER", "nonexistent-provider-id"); |
| 13218 | let _shell = EnvVarGuard::set("CODEWHALE_ALLOW_SHELL", "yes"); |
| 13219 | let _verbosity = EnvVarGuard::set("CODEWHALE_VERBOSITY", "concise"); |
| 13220 | let _max_subagents = EnvVarGuard::set("CODEWHALE_MAX_SUBAGENTS", "5"); |
| 13221 | |
| 13222 | let mut config = Config::default(); |
| 13223 | apply_env_overrides_unlocked(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 13224 | |
| 13225 | assert_eq!(config.provider.as_deref(), Some("nonexistent-provider-id")); |
| 13226 | assert_eq!(config.allow_shell, Some(true)); |
| 13227 | assert_eq!(config.verbosity.as_deref(), Some("concise")); |
| 13228 | assert_eq!(config.max_subagents(), 5); |
| 13229 | assert_eq!(config.base_url_env_receipt, BaseUrlEnvReceipt::NoOwner); |
| 13230 | } |
| 13231 | |
| 13232 | #[test] |
| 13233 | fn max_subagents_env_and_overlay_override_file_subagents_max_concurrent() { |
| 13234 | let _lock = lock_test_env(); |
| 13235 | let _legacy = EnvVarGuard::remove("DEEPSEEK_MAX_SUBAGENTS"); |
| 13236 | let _env = EnvVarGuard::set("CODEWHALE_MAX_SUBAGENTS", "4"); |
| 13237 | |
| 13238 | let mut config = Config { |
| 13239 | subagents: Some(SubagentsConfig { |
| 13240 | max_concurrent: Some(12), |
| 13241 | ..SubagentsConfig::default() |
| 13242 | }), |
| 13243 | ..Config::default() |
| 13244 | }; |
| 13245 | assert_eq!(config.max_subagents(), 12); |
| 13246 | apply_env_overrides_unlocked(&mut config, ConfigEnvironmentPolicy::Runtime); |
| 13247 | assert_eq!(config.max_subagents(), 4); |
| 13248 | |
| 13249 | let mut project_target = Config { |
| 13250 | subagents: Some(SubagentsConfig { |
| 13251 | max_concurrent: Some(12), |
| 13252 | ..SubagentsConfig::default() |
| 13253 | }), |
| 13254 | ..Config::default() |
| 13255 | }; |
| 13256 | project_target.set_max_subagents_override(6); |
| 13257 | assert_eq!(project_target.max_subagents(), 6); |
| 13258 | |
| 13259 | let merged = merge_config( |
| 13260 | Config { |
| 13261 | subagents: Some(SubagentsConfig { |
| 13262 | max_concurrent: Some(12), |
| 13263 | ..SubagentsConfig::default() |
| 13264 | }), |
| 13265 | ..Config::default() |
| 13266 | }, |
| 13267 | Config { |
| 13268 | max_subagents: Some(7), |
| 13269 | ..Config::default() |
| 13270 | }, |
| 13271 | ); |
| 13272 | assert_eq!(merged.max_subagents(), 7); |
| 13273 | } |
| 13274 | |
| 13275 | #[test] |
| 13276 | fn skills_always_load_trims_dedups_merges_and_validates() { |
| 13277 | let cfg = Config { |
| 13278 | skills: Some(SkillsConfig { |
| 13279 | always_load: Some(vec![ |
| 13280 | " Alpha ".to_string(), |
| 13281 | "alpha".to_string(), |
| 13282 | "Beta".to_string(), |
| 13283 | ]), |
| 13284 | ..Default::default() |
| 13285 | }), |
| 13286 | ..Default::default() |
| 13287 | }; |
| 13288 | assert_eq!(cfg.skills_always_load(), vec!["Alpha", "Beta"]); |
| 13289 | assert!(cfg.validate().is_ok()); |
| 13290 | |
| 13291 | let empty_entry = Config { |
| 13292 | skills: Some(SkillsConfig { |
| 13293 | always_load: Some(vec![" ".to_string()]), |
| 13294 | ..Default::default() |
| 13295 | }), |
| 13296 | ..Default::default() |
| 13297 | }; |
| 13298 | assert!(empty_entry.validate().is_err()); |
| 13299 | |
| 13300 | let disabled_bundled_with_always_load = Config { |
| 13301 | skills: Some(SkillsConfig { |
| 13302 | always_load: Some(vec!["debug".to_string()]), |
| 13303 | bundled: BundledSkillsConfig { |
| 13304 | disabled: Some(vec!["DEBUG".to_string()]), |
| 13305 | ..Default::default() |
| 13306 | }, |
| 13307 | ..Default::default() |
| 13308 | }), |
| 13309 | ..Default::default() |
| 13310 | }; |
| 13311 | assert!(disabled_bundled_with_always_load.validate().is_ok()); |
| 13312 | |
| 13313 | let merged = merge_config( |
| 13314 | Config { |
| 13315 | skills: Some(SkillsConfig { |
| 13316 | always_load: Some(vec!["base-skill".to_string()]), |
| 13317 | ..Default::default() |
| 13318 | }), |
| 13319 | ..Default::default() |
| 13320 | }, |
| 13321 | Config { |
| 13322 | skills: Some(SkillsConfig { |
| 13323 | always_load: Some(vec!["override-skill".to_string()]), |
| 13324 | ..Default::default() |
| 13325 | }), |
| 13326 | ..Default::default() |
| 13327 | }, |
| 13328 | ); |
| 13329 | assert_eq!(merged.skills_always_load(), vec!["override-skill"]); |
| 13330 | } |
| 13331 | |
| 13332 | #[test] |
| 13333 | fn empty_profile_skill_preloads_clear_the_base_list() { |
| 13334 | let base: Config = |
| 13335 | toml::from_str("[skills]\nalways_load = [\"base-skill\"]").expect("parse base skills"); |
| 13336 | let inherited: Config = toml::from_str("[skills]\nlisting_budget_fraction = 0.01") |
| 13337 | .expect("parse profile without preloads"); |
| 13338 | let cleared: Config = |
| 13339 | toml::from_str("[skills]\nalways_load = []").expect("parse profile clearing preloads"); |
| 13340 | |
| 13341 | assert_eq!( |
| 13342 | merge_config(base.clone(), inherited).skills_always_load(), |
| 13343 | vec!["base-skill"] |
| 13344 | ); |
| 13345 | assert!(merge_config(base, cleared).skills_always_load().is_empty()); |
| 13346 | } |
| 13347 | |
| 13348 | #[test] |
| 13349 | fn bundled_descriptor_resolves_in_runtime_config_without_provider_table() -> Result<()> { |
| 13350 | let _lock = lock_test_env(); |
| 13351 | let temp_root = tempfile::tempdir()?; |
| 13352 | let _guard = EnvGuard::new(temp_root.path()); |
| 13353 | let _managed = no_managed_config(temp_root.path()); |
| 13354 | let _tinker_clear = EnvVarGuard::remove("TINKER_API_KEY"); |
| 13355 | let _tr_clear = EnvVarGuard::remove("TRUSTEDROUTER_API_KEY"); |
| 13356 | let _prime_key = EnvVarGuard::set("PRIME_API_KEY", "prime-runtime-test-key"); |
| 13357 | let config_path = temp_root.path().join("config.toml"); |
| 13358 | |
| 13359 | for (id, expected_url, expected_model) in [ |
| 13360 | ( |
| 13361 | "prime", |
| 13362 | "https://api.pinference.ai/api/v1", |
| 13363 | "thinkingmachines/inkling-2-small", |
| 13364 | ), |
| 13365 | ( |
| 13366 | "tinker", |
| 13367 | "https://tinker.thinkingmachines.dev/services/tinker-prod/oai/api/v1", |
| 13368 | "thinkingmachines/Inkling-2-Small:peft:262144:sampling-nvfp4", |
| 13369 | ), |
| 13370 | ( |
| 13371 | "trustedrouter", |
| 13372 | "https://api.trustedrouter.com/v1", |
| 13373 | "deepseek/deepseek-v4-flash", |
| 13374 | ), |
| 13375 | ] { |
| 13376 | fs::write(&config_path, format!("provider = \"{id}\"\n"))?; |
| 13377 | let mut config = Config::load(Some(config_path.clone()), None)?; |
| 13378 | let identity = config |
| 13379 | .active_provider_identity() |
| 13380 | .expect("bundled descriptor active identity"); |
| 13381 | assert_eq!(identity.provider, ProviderKind::Custom, "{id}"); |
| 13382 | assert_eq!(identity.key.as_str(), id); |
| 13383 | assert_eq!(identity.persisted_id(), Some(id)); |
| 13384 | assert_eq!(config.base_url_for_route(&identity), expected_url, "{id}"); |
| 13385 | assert_eq!(config.default_model(), expected_model, "{id}"); |
| 13386 | assert!(config.configured_model_error().is_none(), "{id}"); |
| 13387 | |
| 13388 | if id == "prime" { |
| 13389 | let resolution = resolve_credential_source(&config, &identity); |
| 13390 | assert_eq!( |
| 13391 | resolution.source, |
| 13392 | crate::credentials::CredentialSource::ProviderConfigEnv { |
| 13393 | var: "PRIME_API_KEY".to_string(), |
| 13394 | } |
| 13395 | ); |
| 13396 | assert_eq!(config.active_route_api_key()?, "prime-runtime-test-key"); |
| 13397 | |
| 13398 | config.set_provider_model_override(&identity, Some("prime-override".to_string()))?; |
| 13399 | assert_eq!(config.default_model(), "prime-override"); |
| 13400 | assert_eq!(config.base_url_for_route(&identity), expected_url); |
| 13401 | assert_eq!(config.active_route_api_key()?, "prime-runtime-test-key"); |
| 13402 | |
| 13403 | config.set_provider_base_url_override( |
| 13404 | &identity, |
| 13405 | Some("https://proxy.example/v1".to_string()), |
| 13406 | )?; |
| 13407 | assert_eq!( |
| 13408 | config.base_url_for_route(&identity), |
| 13409 | "https://proxy.example/v1" |
| 13410 | ); |
| 13411 | assert!( |
| 13412 | !matches!( |
| 13413 | resolve_credential_source(&config, &identity).source, |
| 13414 | crate::credentials::CredentialSource::ProviderConfigEnv { .. } |
| 13415 | ), |
| 13416 | "descriptor api_key_env must not follow an overridden custom host" |
| 13417 | ); |
| 13418 | } |
| 13419 | } |
| 13420 | |
| 13421 | fs::write(&config_path, "provider = \"prime\"\n")?; |
| 13422 | let base_config = Config::load(Some(config_path.clone()), None)?; |
| 13423 | assert_eq!( |
| 13424 | base_config |
| 13425 | .resolve_provider_selection_identity("prime") |
| 13426 | .expect("select prime") |
| 13427 | .key |
| 13428 | .as_str(), |
| 13429 | "prime" |
| 13430 | ); |
| 13431 | assert_eq!( |
| 13432 | base_config |
| 13433 | .resolve_provider_selection_identity("trusted_router") |
| 13434 | .expect("select trusted_router alias") |
| 13435 | .key |
| 13436 | .as_str(), |
| 13437 | "trustedrouter" |
| 13438 | ); |
| 13439 | assert!( |
| 13440 | base_config |
| 13441 | .resolve_provider_selection_identity("typo-provider") |
| 13442 | .is_err() |
| 13443 | ); |
| 13444 | |
| 13445 | fs::write(&config_path, "provider = \"qwen\"\n")?; |
| 13446 | let qwen_config = Config::load(Some(config_path.clone()), None)?; |
| 13447 | let qwen_identity = qwen_config |
| 13448 | .active_provider_identity() |
| 13449 | .expect("qwen descriptor identity"); |
| 13450 | assert_eq!(qwen_identity.provider, ProviderKind::Custom); |
| 13451 | assert_eq!(qwen_identity.key.as_str(), "qwen"); |
| 13452 | assert_eq!( |
| 13453 | qwen_config.base_url_for_route(&qwen_identity), |
| 13454 | "https://dashscope-intl.aliyuncs.com/compatible-mode/v1" |
| 13455 | ); |
| 13456 | assert_eq!(qwen_config.default_model(), "qwen3.8-flash"); |
| 13457 | |
| 13458 | fs::write(&config_path, "provider = \"dashscope\"\n")?; |
| 13459 | let dashscope_config = Config::load(Some(config_path.clone()), None)?; |
| 13460 | assert_eq!( |
| 13461 | dashscope_config |
| 13462 | .active_provider_identity() |
| 13463 | .expect("builtin dashscope") |
| 13464 | .provider, |
| 13465 | ProviderKind::ModelstudioTokenPlan |
| 13466 | ); |
| 13467 | |
| 13468 | fs::write( |
| 13469 | &config_path, |
| 13470 | "provider = \"prime\"\n\n[providers.prime]\nmodel = \"partial-prime\"\n", |
| 13471 | )?; |
| 13472 | let partial = Config::load(Some(config_path.clone()), None)?; |
| 13473 | assert_eq!(partial.default_model(), "partial-prime"); |
| 13474 | assert_eq!( |
| 13475 | partial.active_route_base_url(), |
| 13476 | "https://api.pinference.ai/api/v1" |
| 13477 | ); |
| 13478 | assert_eq!(partial.active_route_api_key()?, "prime-runtime-test-key"); |
| 13479 | |
| 13480 | fs::write( |
| 13481 | &config_path, |
| 13482 | "provider = \"prime-intellect\"\n\n[providers.prime]\nmodel = \"alias-partial-prime\"\n", |
| 13483 | )?; |
| 13484 | let alias_partial = Config::load(Some(config_path.clone()), None)?; |
| 13485 | assert_eq!( |
| 13486 | alias_partial |
| 13487 | .active_provider_identity() |
| 13488 | .expect("alias resolves canonical table") |
| 13489 | .key |
| 13490 | .as_str(), |
| 13491 | "prime" |
| 13492 | ); |
| 13493 | assert_eq!(alias_partial.default_model(), "alias-partial-prime"); |
| 13494 | assert_eq!( |
| 13495 | alias_partial.active_route_base_url(), |
| 13496 | "https://api.pinference.ai/api/v1" |
| 13497 | ); |
| 13498 | assert_eq!( |
| 13499 | alias_partial.active_route_api_key()?, |
| 13500 | "prime-runtime-test-key" |
| 13501 | ); |
| 13502 | |
| 13503 | fs::write( |
| 13504 | &config_path, |
| 13505 | "provider = \"prime-intellect\"\n\n[providers.prime]\nkind = \"anthropic\"\n", |
| 13506 | )?; |
| 13507 | assert!( |
| 13508 | Config::load(Some(config_path.clone()), None).is_err(), |
| 13509 | "bundled alias must validate an existing canonical table fail-closed" |
| 13510 | ); |
| 13511 | |
| 13512 | fs::write( |
| 13513 | &config_path, |
| 13514 | "provider = \"prime\"\n\n[providers.prime]\nkind = \"anthropic\"\n", |
| 13515 | )?; |
| 13516 | assert!(Config::load(Some(config_path.clone()), None).is_err()); |
| 13517 | |
| 13518 | fs::write(&config_path, "provider = \"typo-provider\"\n")?; |
| 13519 | assert!(Config::load(Some(config_path), None).is_err()); |
| 13520 | |
| 13521 | Ok(()) |
| 13522 | } |
| 13523 |