| 1 | use codewhale_config::provider_preserves_custom_base_url_model; |
| 2 | |
| 3 | use std::collections::HashMap; |
| 4 | |
| 5 | use std::fs; |
| 6 | |
| 7 | use std::time::SystemTime; |
| 8 | |
| 9 | use anyhow::Result; |
| 10 | |
| 11 | use serde_json::json; |
| 12 | |
| 13 | #[cfg(test)] |
| 14 | use codewhale_config::API_KEYRING_SENTINEL; |
| 15 | |
| 16 | use codewhale_config::ConfigApiKeyValueKind; |
| 17 | |
| 18 | use codewhale_config::classify_config_api_key_value; |
| 19 | |
| 20 | use codewhale_config::ProviderKind; |
| 21 | |
| 22 | use codewhale_config::catalog::reviewed::constants::*; |
| 23 | |
| 24 | use codewhale_config::descriptors::defaults::*; |
| 25 | |
| 26 | #[cfg(test)] |
| 27 | use codewhale_config::notifications::CompletionSound; |
| 28 | |
| 29 | use codewhale_config::notifications::NotificationCondition; |
| 30 | use codewhale_runtime::config::*; |
| 31 | |
| 32 | use codewhale_engine::provider_readiness::has_api_key; |
| 33 | |
| 34 | use codewhale_engine::provider_readiness::has_api_key_for; |
| 35 | |
| 36 | use codewhale_engine::provider_lake::ProviderCapability; |
| 37 | |
| 38 | use codewhale_engine::provider_lake::RequestPayloadMode; |
| 39 | |
| 40 | use codewhale_engine::provider_lake::provider_capability; |
| 41 | |
| 42 | use crate::test_support::EnvVarGuard; |
| 43 | |
| 44 | use crate::test_support::lock_test_env; |
| 45 | |
| 46 | use std::env; |
| 47 | |
| 48 | use codewhale_runtime::config::test_support::*; |
| 49 | use std::time::UNIX_EPOCH; |
| 50 | |
| 51 | #[test] |
| 52 | fn remembered_deepseek_cn_and_layered_root_models_keep_their_precedence() { |
| 53 | let _lock = lock_test_env(); |
| 54 | let home = tempfile::tempdir().unwrap(); |
| 55 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 56 | let _overrides: Vec<_> = [ |
| 57 | "CODEWHALE_CONFIG_PATH", |
| 58 | "DEEPSEEK_CONFIG_PATH", |
| 59 | "CODEWHALE_PROVIDER", |
| 60 | "DEEPSEEK_PROVIDER", |
| 61 | "CODEWHALE_MODEL", |
| 62 | "DEEPSEEK_MODEL", |
| 63 | "DEEPSEEK_DEFAULT_TEXT_MODEL", |
| 64 | ] |
| 65 | .into_iter() |
| 66 | .map(EnvVarGuard::remove) |
| 67 | .collect(); |
| 68 | let path = home.path().join("config.toml"); |
| 69 | fs::write( |
| 70 | &path, |
| 71 | "provider = 'deepseek-cn'\ndefault_text_model = 'deepseek-v4-flash'\n", |
| 72 | ) |
| 73 | .unwrap(); |
| 74 | fs::write( |
| 75 | home.path().join("settings.toml"), |
| 76 | "default_model = 'deepseek-v4-pro'\n", |
| 77 | ) |
| 78 | .unwrap(); |
| 79 | assert_eq!( |
| 80 | codewhale_plugins::providers::load_config(None, None) |
| 81 | .unwrap() |
| 82 | .default_model(), |
| 83 | "deepseek-v4-pro" |
| 84 | ); |
| 85 | codewhale_runtime::config_persistence::persist_root_bool_key(Some(&path), "allow_shell", false) |
| 86 | .unwrap(); |
| 87 | assert_eq!( |
| 88 | codewhale_plugins::providers::load_config(None, None) |
| 89 | .unwrap() |
| 90 | .default_model(), |
| 91 | "deepseek-v4-pro" |
| 92 | ); |
| 93 | |
| 94 | fs::write(&path, "route_preferences_version = 1\nprovider = 'deepseek'\n[providers.deepseek]\nmodel = 'deepseek-v4-flash'\n[profiles.pro]\ndefault_text_model = 'deepseek-v4-pro'\n").unwrap(); |
| 95 | let profile = codewhale_plugins::providers::load_config(None, Some("pro")).unwrap(); |
| 96 | assert_eq!(profile.default_model(), "deepseek-v4-pro"); |
| 97 | assert_eq!( |
| 98 | codewhale_engine::route_runtime::resolve_runtime_route( |
| 99 | &profile, |
| 100 | ProviderKind::Deepseek, |
| 101 | None |
| 102 | ) |
| 103 | .unwrap() |
| 104 | .model, |
| 105 | "deepseek-v4-pro" |
| 106 | ); |
| 107 | |
| 108 | let managed = home.path().join("managed.toml"); |
| 109 | fs::write(&managed, "default_text_model = 'deepseek-v4-pro'\n").unwrap(); |
| 110 | let source = format!( |
| 111 | "route_preferences_version = 1\nprovider = 'deepseek'\nmanaged_config_path = '{}'\n[providers.deepseek]\nmodel = 'deepseek-v4-flash'\n", |
| 112 | managed.display() |
| 113 | ); |
| 114 | fs::write(&path, source).unwrap(); |
| 115 | assert_eq!( |
| 116 | codewhale_plugins::providers::load_config(None, None) |
| 117 | .unwrap() |
| 118 | .default_model(), |
| 119 | "deepseek-v4-pro" |
| 120 | ); |
| 121 | } |
| 122 | |
| 123 | #[test] |
| 124 | fn loaded_startup_selection_is_shared_and_does_not_rewrite_saved_files() { |
| 125 | let _lock = lock_test_env(); |
| 126 | let home = tempfile::tempdir().unwrap(); |
| 127 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 128 | let _overrides: Vec<_> = [ |
| 129 | "CODEWHALE_CONFIG_PATH", |
| 130 | "DEEPSEEK_CONFIG_PATH", |
| 131 | "CODEWHALE_PROVIDER", |
| 132 | "DEEPSEEK_PROVIDER", |
| 133 | "CODEWHALE_MODEL", |
| 134 | "DEEPSEEK_MODEL", |
| 135 | "DEEPSEEK_DEFAULT_TEXT_MODEL", |
| 136 | ] |
| 137 | .into_iter() |
| 138 | .map(EnvVarGuard::remove) |
| 139 | .collect(); |
| 140 | let path = home.path().join("config.toml"); |
| 141 | let source = "provider = 'zai'\n[providers.zai]\nmodel = 'GLM-5.2'\n"; |
| 142 | let saved = "[provider_models]\nzai = 'GLM-5.3'\n"; |
| 143 | fs::write(&path, source).unwrap(); |
| 144 | fs::write(home.path().join("settings.toml"), saved).unwrap(); |
| 145 | let mut config = codewhale_plugins::providers::load_config(None, None).unwrap(); |
| 146 | assert_eq!(config.default_model(), "GLM-5.3"); |
| 147 | assert_eq!( |
| 148 | codewhale_engine::model_inventory::provider_default_model( |
| 149 | &config, |
| 150 | &(config).test_identity_for_kind(ProviderKind::Zai) |
| 151 | ), |
| 152 | "GLM-5.3" |
| 153 | ); |
| 154 | let route = |
| 155 | codewhale_engine::route_runtime::resolve_runtime_route(&config, ProviderKind::Zai, None) |
| 156 | .unwrap(); |
| 157 | assert_eq!( |
| 158 | route.model, "GLM-5.3", |
| 159 | "an omitted new-thread model uses the same selection" |
| 160 | ); |
| 161 | let explicit = codewhale_engine::route_runtime::resolve_runtime_route( |
| 162 | &config, |
| 163 | ProviderKind::Zai, |
| 164 | Some("GLM-5.2"), |
| 165 | ) |
| 166 | .unwrap(); |
| 167 | assert_eq!(explicit.model, "GLM-5.2"); |
| 168 | let other = { |
| 169 | let __cw_config_init_0_0 = Some(HashMap::from([("zai".into(), "GLM-5.1".into())])); |
| 170 | let mut __cw_config_init_0_value: codewhale_runtime::settings::Settings = |
| 171 | Default::default(); |
| 172 | __cw_config_init_0_value.provider_models = __cw_config_init_0_0; |
| 173 | __cw_config_init_0_value |
| 174 | }; |
| 175 | assert!( |
| 176 | !config.apply_saved_selection(&other), |
| 177 | "loaded route snapshots never reread preferences" |
| 178 | ); |
| 179 | assert_eq!(config.default_model(), "GLM-5.3"); |
| 180 | assert_eq!(fs::read_to_string(path).unwrap(), source); |
| 181 | assert_eq!( |
| 182 | fs::read_to_string(home.path().join("settings.toml")).unwrap(), |
| 183 | saved |
| 184 | ); |
| 185 | } |
| 186 | |
| 187 | #[test] |
| 188 | fn startup_memory_yields_to_explicit_launch_scoped_config_and_profile() { |
| 189 | let _lock = lock_test_env(); |
| 190 | let home = tempfile::tempdir().unwrap(); |
| 191 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 192 | let _overrides: Vec<_> = [ |
| 193 | "CODEWHALE_CONFIG_PATH", |
| 194 | "DEEPSEEK_CONFIG_PATH", |
| 195 | "CODEWHALE_PROVIDER", |
| 196 | "DEEPSEEK_PROVIDER", |
| 197 | "CODEWHALE_MODEL", |
| 198 | "DEEPSEEK_MODEL", |
| 199 | "DEEPSEEK_DEFAULT_TEXT_MODEL", |
| 200 | ] |
| 201 | .into_iter() |
| 202 | .map(EnvVarGuard::remove) |
| 203 | .collect(); |
| 204 | let source = "provider = 'zai'\n[providers.zai]\nmodel = 'GLM-5.2'\n[profiles.pinned.providers.zai]\nmodel = 'GLM-5.1'\n"; |
| 205 | fs::write(home.path().join("config.toml"), source).unwrap(); |
| 206 | fs::write( |
| 207 | home.path().join("settings.toml"), |
| 208 | "[provider_models]\nzai = 'GLM-5.3'\n", |
| 209 | ) |
| 210 | .unwrap(); |
| 211 | { |
| 212 | let _explicit = EnvVarGuard::set("CODEWHALE_MODEL", "GLM-5.2"); |
| 213 | let config = codewhale_plugins::providers::load_config(None, None).unwrap(); |
| 214 | assert_eq!(config.default_model(), "GLM-5.2"); |
| 215 | assert_eq!( |
| 216 | codewhale_engine::route_runtime::resolve_runtime_route( |
| 217 | &config, |
| 218 | ProviderKind::Zai, |
| 219 | None |
| 220 | ) |
| 221 | .unwrap() |
| 222 | .model, |
| 223 | "GLM-5.2" |
| 224 | ); |
| 225 | } |
| 226 | let profile = codewhale_plugins::providers::load_config(None, Some("pinned")).unwrap(); |
| 227 | assert_eq!(profile.default_model(), "GLM-5.1"); |
| 228 | assert!(!profile.remembered_selection_is_applicable()); |
| 229 | let project = home.path().join("project"); |
| 230 | fs::create_dir(&project).unwrap(); |
| 231 | let path = project.join("config.toml"); |
| 232 | fs::write(&path, source).unwrap(); |
| 233 | let config = codewhale_plugins::providers::load_config(Some(path), None).unwrap(); |
| 234 | assert_eq!(config.default_model(), "GLM-5.2"); |
| 235 | assert!(!config.remembered_selection_is_applicable()); |
| 236 | } |
| 237 | |
| 238 | #[test] |
| 239 | fn startup_memory_preserves_named_and_custom_endpoint_wire_ids() { |
| 240 | let _lock = lock_test_env(); |
| 241 | let settings = { |
| 242 | let __cw_config_init_1_0 = Some("TeamA".into()); |
| 243 | let __cw_config_init_1_1 = Some(HashMap::from([ |
| 244 | ("TeamA".into(), "memory-upper".into()), |
| 245 | ("teama".into(), "memory-lower".into()), |
| 246 | ("zai".into(), "GLM-5.3".into()), |
| 247 | ])); |
| 248 | let mut __cw_config_init_1_value: codewhale_runtime::settings::Settings = |
| 249 | Default::default(); |
| 250 | __cw_config_init_1_value.default_provider = __cw_config_init_1_0; |
| 251 | __cw_config_init_1_value.provider_models = __cw_config_init_1_1; |
| 252 | __cw_config_init_1_value |
| 253 | }; |
| 254 | let mut config: Config = toml::from_str("provider = 'teama'\n[providers.TeamA]\nkind = 'openai-compatible'\nbase_url = 'https://upper.example.test/v1'\nmodel = 'Wire-Upper'\n[providers.teama]\nkind = 'openai-compatible'\nbase_url = 'https://lower.example.test/v1'\nmodel = 'wire-lower'\n[providers.zai]\nbase_url = 'https://proxy.example.test/v1'\nmodel = 'Exact-Zai-ID'\n").unwrap(); |
| 255 | let _provider = EnvVarGuard::remove("CODEWHALE_PROVIDER"); |
| 256 | let _legacy_provider = EnvVarGuard::remove("DEEPSEEK_PROVIDER"); |
| 257 | assert!(config.apply_saved_selection(&settings)); |
| 258 | assert_eq!(config.provider.as_deref(), Some("TeamA")); |
| 259 | let identity = config.active_provider_identity().unwrap(); |
| 260 | let route = codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 261 | &config, &identity, None, |
| 262 | ) |
| 263 | .unwrap(); |
| 264 | assert_eq!(route.model, "memory-upper"); |
| 265 | assert_eq!( |
| 266 | route.candidate.endpoint().base_url, |
| 267 | "https://upper.example.test/v1" |
| 268 | ); |
| 269 | let lower = config.resolve_provider_identity("teama").unwrap(); |
| 270 | assert_eq!( |
| 271 | codewhale_engine::route_runtime::resolve_runtime_route_for_identity(&config, &lower, None) |
| 272 | .unwrap() |
| 273 | .model, |
| 274 | "memory-lower" |
| 275 | ); |
| 276 | assert_eq!( |
| 277 | config |
| 278 | .provider_config_for(&config.test_identity_for_kind(ProviderKind::Zai)) |
| 279 | .unwrap() |
| 280 | .model |
| 281 | .as_deref(), |
| 282 | Some("GLM-5.3") |
| 283 | ); |
| 284 | } |
| 285 | |
| 286 | #[test] |
| 287 | fn named_custom_table_wire_responses_reaches_the_runtime_route() { |
| 288 | let _lock = lock_test_env(); |
| 289 | let _provider = EnvVarGuard::remove("CODEWHALE_PROVIDER"); |
| 290 | let _legacy_provider = EnvVarGuard::remove("DEEPSEEK_PROVIDER"); |
| 291 | let config: Config = toml::from_str( |
| 292 | "provider = 'relay'\n[providers.relay]\nkind = 'openai-compatible'\nbase_url = 'https://relay.example.test/v1'\nmodel = 'gpt-5.5'\nwire = 'responses'\n", |
| 293 | ) |
| 294 | .unwrap(); |
| 295 | let identity = config.active_provider_identity().unwrap(); |
| 296 | let route = codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 297 | &config, &identity, None, |
| 298 | ) |
| 299 | .expect("custom table runtime route"); |
| 300 | assert_eq!(route.identity.provider, ProviderKind::Custom); |
| 301 | assert_eq!( |
| 302 | route.candidate.protocol(), |
| 303 | codewhale_config::provider::WireFormat::Responses, |
| 304 | "the table's wire dialect must reach the minted candidate instead of \ |
| 305 | Custom's static Chat policy" |
| 306 | ); |
| 307 | assert_eq!( |
| 308 | route.candidate.endpoint().base_url, |
| 309 | "https://relay.example.test/v1" |
| 310 | ); |
| 311 | |
| 312 | // A table without a wire dialect keeps the backward-compatible static |
| 313 | // Chat policy, and an unrecognized dialect degrades to it deliberately. |
| 314 | let config: Config = toml::from_str( |
| 315 | "provider = 'relay'\n[providers.relay]\nkind = 'openai-compatible'\nbase_url = 'https://relay.example.test/v1'\nmodel = 'gpt-5.5'\nwire = 'respones'\n", |
| 316 | ) |
| 317 | .unwrap(); |
| 318 | let identity = config.active_provider_identity().unwrap(); |
| 319 | let route = codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 320 | &config, &identity, None, |
| 321 | ) |
| 322 | .expect("typo'd table still resolves"); |
| 323 | assert_eq!( |
| 324 | route.candidate.protocol(), |
| 325 | codewhale_config::provider::WireFormat::ChatCompletions, |
| 326 | "an unrecognized dialect must degrade to the static policy" |
| 327 | ); |
| 328 | } |
| 329 | |
| 330 | #[test] |
| 331 | fn provider_environment_model_outranks_startup_memory() { |
| 332 | let _lock = lock_test_env(); |
| 333 | let home = tempfile::tempdir().unwrap(); |
| 334 | let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 335 | let _overrides: Vec<_> = [ |
| 336 | "CODEWHALE_CONFIG_PATH", |
| 337 | "DEEPSEEK_CONFIG_PATH", |
| 338 | "CODEWHALE_PROVIDER", |
| 339 | "DEEPSEEK_PROVIDER", |
| 340 | "CODEWHALE_MODEL", |
| 341 | "DEEPSEEK_MODEL", |
| 342 | ] |
| 343 | .into_iter() |
| 344 | .map(EnvVarGuard::remove) |
| 345 | .collect(); |
| 346 | fs::write( |
| 347 | home.path().join("config.toml"), |
| 348 | "provider = 'openai'\n[providers.openai]\nmodel = 'gpt-5.6-sol'\n", |
| 349 | ) |
| 350 | .unwrap(); |
| 351 | fs::write( |
| 352 | home.path().join("settings.toml"), |
| 353 | "[provider_models]\nopenai = 'gpt-5.6-terra'\n", |
| 354 | ) |
| 355 | .unwrap(); |
| 356 | let _model = EnvVarGuard::set("OPENAI_MODEL", "gpt-5.6-luna"); |
| 357 | let config = codewhale_plugins::providers::load_config(None, None).unwrap(); |
| 358 | assert_eq!(config.default_model(), "gpt-5.6-luna"); |
| 359 | assert_eq!( |
| 360 | codewhale_engine::route_runtime::resolve_runtime_route(&config, ProviderKind::Openai, None) |
| 361 | .unwrap() |
| 362 | .model, |
| 363 | "gpt-5.6-luna" |
| 364 | ); |
| 365 | } |
| 366 | |
| 367 | #[test] |
| 368 | fn retired_antigravity_credentials_are_never_read_and_no_client_is_built() { |
| 369 | let _guard = lock_test_env(); |
| 370 | // The retired private credential plane: neither variable is consulted. |
| 371 | let _api_key = EnvVarGuard::set("ANTIGRAVITY_API_KEY", "must-never-be-read"); |
| 372 | let _adc = EnvVarGuard::set("AGY_ADC_AUTH", "must-never-be-read"); |
| 373 | assert!(ProviderKind::Antigravity.provider().env_vars().is_empty()); |
| 374 | assert_eq!( |
| 375 | ProviderKind::parse_config_identity("antigravity"), |
| 376 | Some(ProviderKind::Antigravity) |
| 377 | ); |
| 378 | for identity in ["antigravity", "agy"] { |
| 379 | let config = { |
| 380 | let __cw_config_init_2_0 = Some(identity.to_string()); |
| 381 | let mut __cw_config_init_2_value: Config = Config::default(); |
| 382 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 383 | __cw_config_init_2_value |
| 384 | }; |
| 385 | assert_eq!( |
| 386 | config.active_provider_identity().unwrap().provider, |
| 387 | ProviderKind::Antigravity, |
| 388 | "{identity}" |
| 389 | ); |
| 390 | } |
| 391 | let mut config = { |
| 392 | let __cw_config_init_3_0 = Some("antigravity".to_string()); |
| 393 | let mut __cw_config_init_3_value: Config = Config::default(); |
| 394 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 395 | __cw_config_init_3_value |
| 396 | }; |
| 397 | let providers = config.providers.get_or_insert_with(Default::default); |
| 398 | providers.antigravity.api_key = Some("legacy-literal-left-behind".to_string()); |
| 399 | |
| 400 | let captured = config.active_provider_identity().unwrap(); |
| 401 | assert_eq!( |
| 402 | codewhale_engine::provider_readiness::credential_state_for_provider(&config, &captured), |
| 403 | codewhale_engine::provider_readiness::CredentialState::Legacy |
| 404 | ); |
| 405 | assert!( |
| 406 | codewhale_engine::model_inventory::ModelInventory::from_config(&config) |
| 407 | .unwrap() |
| 408 | .candidates |
| 409 | .iter() |
| 410 | .all(|candidate| candidate.provider != ProviderKind::Antigravity) |
| 411 | ); |
| 412 | |
| 413 | // No transport can be constructed for the tombstone; the refusal happens |
| 414 | // before any network or credential I/O. |
| 415 | let error = codewhale_engine::client::CodewhaleClient::new(&config) |
| 416 | .err() |
| 417 | .expect("constructing a client for the tombstone must fail") |
| 418 | .to_string(); |
| 419 | assert!(error.contains("non-runnable"), "{error}"); |
| 420 | assert!(error.contains("GEMINI_API_KEY"), "{error}"); |
| 421 | } |
| 422 | |
| 423 | #[test] |
| 424 | fn auto_review_config_builds_runtime_policy() -> Result<()> { |
| 425 | let config: Config = toml::from_str( |
| 426 | r#" |
| 427 | [auto_review] |
| 428 | natural_language_guidance = "retired compatibility key" |
| 429 | |
| 430 | [[auto_review.block]] |
| 431 | id = "block-shell" |
| 432 | action_kind = "shell" |
| 433 | reason = "shell requires maintainer review" |
| 434 | |
| 435 | [[auto_review.allow]] |
| 436 | id = "allow-read-file" |
| 437 | tool = "read_file" |
| 438 | reason = "read_file is allowed" |
| 439 | "#, |
| 440 | )?; |
| 441 | config.validate()?; |
| 442 | |
| 443 | let policy = |
| 444 | codewhale_engine::core::authority::auto_review::AutoReviewPolicy::from_config(&config); |
| 445 | let shell_context = |
| 446 | codewhale_engine::core::authority::auto_review::AutoReviewContext::from_tool_call( |
| 447 | "exec_shell", |
| 448 | &serde_json::json!({"command": "cargo test"}), |
| 449 | codewhale_engine::core::authority::auto_review::RunOrigin::Interactive, |
| 450 | codewhale_execpolicy::ApprovalMode::Auto, |
| 451 | true, |
| 452 | None, |
| 453 | ); |
| 454 | let shell_decision = policy.evaluate(&shell_context); |
| 455 | assert_eq!( |
| 456 | shell_decision.action, |
| 457 | codewhale_engine::core::authority::auto_review::AutoReviewAction::Block |
| 458 | ); |
| 459 | assert_eq!(shell_decision.rule_id.as_deref(), Some("block-shell")); |
| 460 | |
| 461 | let read_context = |
| 462 | codewhale_engine::core::authority::auto_review::AutoReviewContext::from_tool_call( |
| 463 | "read_file", |
| 464 | &serde_json::json!({"path": "README.md"}), |
| 465 | codewhale_engine::core::authority::auto_review::RunOrigin::Interactive, |
| 466 | codewhale_execpolicy::ApprovalMode::Auto, |
| 467 | true, |
| 468 | None, |
| 469 | ); |
| 470 | let read_decision = policy.evaluate(&read_context); |
| 471 | assert_eq!( |
| 472 | read_decision.action, |
| 473 | codewhale_engine::core::authority::auto_review::AutoReviewAction::Allow |
| 474 | ); |
| 475 | assert_eq!(read_decision.rule_id.as_deref(), Some("allow-read-file")); |
| 476 | |
| 477 | Ok(()) |
| 478 | } |
| 479 | |
| 480 | #[test] |
| 481 | fn auto_review_scenario() -> Result<()> { |
| 482 | // Scenario consolidation of: auto_review_profile_overrides_base_policy, auto_review_text_contains_fails_closed_instead_of_broadening_a_rule, auto_review_legacy_allow_kind_fails_closed_instead_of_widening, auto_review_config_rejects_invalid_rule_shapes |
| 483 | // from auto_review_profile_overrides_base_policy |
| 484 | { |
| 485 | let merged = Config::from_saved_document( |
| 486 | r#" |
| 487 | [[auto_review.block]] |
| 488 | action_kind = "shell" |
| 489 | |
| 490 | [[profiles.strict.auto_review.block]] |
| 491 | action_kind = "network" |
| 492 | "#, |
| 493 | Some("strict"), |
| 494 | )?; |
| 495 | let policy = |
| 496 | codewhale_engine::core::authority::auto_review::AutoReviewPolicy::from_config(&merged); |
| 497 | |
| 498 | assert_eq!(policy.block_rules.len(), 1); |
| 499 | assert_eq!( |
| 500 | policy.block_rules[0].action_kind, |
| 501 | Some(codewhale_engine::core::authority::auto_review::ToolActionKind::External) |
| 502 | ); |
| 503 | } |
| 504 | // from auto_review_text_contains_fails_closed_instead_of_broadening_a_rule |
| 505 | { |
| 506 | let error = toml::from_str::<Config>( |
| 507 | r#" |
| 508 | [[auto_review.allow]] |
| 509 | tool = "exec_shell" |
| 510 | text_contains = "run tests" |
| 511 | "#, |
| 512 | ) |
| 513 | .expect("shape parses") |
| 514 | .validate() |
| 515 | .expect_err("retired user-intent matcher must not disappear"); |
| 516 | |
| 517 | assert!( |
| 518 | error |
| 519 | .to_string() |
| 520 | .contains("user-intent matching was retired") |
| 521 | ); |
| 522 | } |
| 523 | // from auto_review_legacy_allow_kind_fails_closed_instead_of_widening |
| 524 | { |
| 525 | let error = toml::from_str::<Config>( |
| 526 | r#" |
| 527 | [[auto_review.allow]] |
| 528 | action_kind = "git" |
| 529 | "#, |
| 530 | ) |
| 531 | .expect("shape parses") |
| 532 | .validate() |
| 533 | .expect_err("narrow legacy allow kind must not widen to external"); |
| 534 | |
| 535 | assert!(error.to_string().contains("cannot safely widen")); |
| 536 | } |
| 537 | // from auto_review_config_rejects_invalid_rule_shapes |
| 538 | { |
| 539 | let invalid_kind: Config = toml::from_str( |
| 540 | r#" |
| 541 | [[auto_review.block]] |
| 542 | action_kind = "teleport" |
| 543 | "#, |
| 544 | ) |
| 545 | .expect("parse config"); |
| 546 | let err = invalid_kind.validate().expect_err("invalid kind"); |
| 547 | assert!( |
| 548 | err.to_string() |
| 549 | .contains("Invalid auto_review.block[0].action_kind") |
| 550 | ); |
| 551 | |
| 552 | let global_allow: Config = toml::from_str( |
| 553 | r#" |
| 554 | [[auto_review.allow]] |
| 555 | reason = "too broad" |
| 556 | "#, |
| 557 | ) |
| 558 | .expect("parse config"); |
| 559 | let err = global_allow.validate().expect_err("missing matcher"); |
| 560 | assert!(err.to_string().contains("set at least one of tool")); |
| 561 | } |
| 562 | Ok(()) |
| 563 | } |
| 564 | |
| 565 | #[test] |
| 566 | fn network_policy_toml_maps_proxy_hosts_to_runtime_policy() { |
| 567 | let policy: codewhale_config::NetworkPolicyToml = toml::from_str( |
| 568 | r#" |
| 569 | default = "allow" |
| 570 | proxy = ["github.com", ".githubusercontent.com"] |
| 571 | proxy_fake_ip_cidrs = ["198.18.0.0/15"] |
| 572 | "#, |
| 573 | ) |
| 574 | .expect("network policy toml"); |
| 575 | |
| 576 | let runtime = codewhale_net::network_policy::NetworkPolicy::from(policy); |
| 577 | |
| 578 | assert_eq!(runtime.proxy, ["github.com", ".githubusercontent.com"]); |
| 579 | assert_eq!(runtime.proxy_fake_ip_cidrs, ["198.18.0.0/15"]); |
| 580 | assert!(runtime.trusts_proxy_fakeip_host("github.com")); |
| 581 | assert!(runtime.trusts_proxy_fakeip_host("raw.githubusercontent.com")); |
| 582 | } |
| 583 | |
| 584 | #[test] |
| 585 | fn user_input_limits_default_when_tools_table_is_absent() { |
| 586 | let parsed = Config::from_saved_document("", None).expect("empty config"); |
| 587 | let limits = codewhale_engine::tools::user_input::UserInputLimits::from_config(&parsed); |
| 588 | assert_eq!(limits.max_questions, 6); |
| 589 | assert_eq!(limits.max_options, 4); |
| 590 | } |
| 591 | |
| 592 | #[test] |
| 593 | fn user_input_limits_read_from_tools_table_and_clamp() { |
| 594 | let parsed = Config::from_saved_document( |
| 595 | r#" |
| 596 | [tools] |
| 597 | user_input_max_questions = 9 |
| 598 | user_input_max_options = 6 |
| 599 | "#, |
| 600 | None, |
| 601 | ) |
| 602 | .expect("tools config"); |
| 603 | let limits = codewhale_engine::tools::user_input::UserInputLimits::from_config(&parsed); |
| 604 | assert_eq!(limits.max_questions, 9); |
| 605 | assert_eq!(limits.max_options, 6); |
| 606 | |
| 607 | let clamped = Config::from_saved_document( |
| 608 | r#" |
| 609 | [tools] |
| 610 | user_input_max_questions = 50 |
| 611 | user_input_max_options = 0 |
| 612 | "#, |
| 613 | None, |
| 614 | ) |
| 615 | .expect("tools config"); |
| 616 | let clamped = codewhale_engine::tools::user_input::UserInputLimits::from_config(&clamped); |
| 617 | assert_eq!(clamped.max_questions, 10); |
| 618 | assert_eq!(clamped.max_options, 2); |
| 619 | } |
| 620 | |
| 621 | #[test] |
| 622 | fn goal_max_steps_default_and_zero_are_uncapped() { |
| 623 | for source in ["", "[goal]", "[goal]\nmax_steps = 0\n"] { |
| 624 | let parsed = Config::from_saved_document(source, None).expect("goal config"); |
| 625 | let resolved = parsed.goal_max_steps(); |
| 626 | assert_eq!(resolved, u32::MAX, "{source:?}"); |
| 627 | |
| 628 | // Hosts pass this resolved value directly to the goal turn. It must |
| 629 | // remain uncapped beyond the old 1,000-step ceiling and at saturation. |
| 630 | let mut turn = codewhale_engine::core::turn::TurnContext::with_budget_source( |
| 631 | resolved, |
| 632 | codewhale_engine::core::turn::StepBudgetSource::Goal, |
| 633 | ); |
| 634 | assert_eq!(turn.step_limit(), None); |
| 635 | turn.step = 1_000; |
| 636 | assert!(turn.next_step(), "{source:?}"); |
| 637 | assert!(!turn.at_max_steps(), "{source:?}"); |
| 638 | turn.step = u32::MAX; |
| 639 | assert!(turn.next_step(), "{source:?}"); |
| 640 | assert!(!turn.at_max_steps(), "{source:?}"); |
| 641 | } |
| 642 | } |
| 643 | |
| 644 | #[test] |
| 645 | fn goal_max_steps_preserves_positive_limits() { |
| 646 | for (configured, expected) in [(1, 1), (50, 50), (100_000, 100_000), (500_000, 500_000)] { |
| 647 | let source = format!("[goal]\nmax_steps = {configured}\n"); |
| 648 | let parsed = Config::from_saved_document(&source, None).expect("goal config"); |
| 649 | let resolved = parsed.goal_max_steps(); |
| 650 | assert_eq!(resolved, expected, "{source:?}"); |
| 651 | |
| 652 | let mut turn = codewhale_engine::core::turn::TurnContext::with_budget_source( |
| 653 | resolved, |
| 654 | codewhale_engine::core::turn::StepBudgetSource::Goal, |
| 655 | ); |
| 656 | assert_eq!(turn.step_limit(), Some(expected)); |
| 657 | turn.step = expected; |
| 658 | assert!(turn.at_max_steps(), "{source:?}"); |
| 659 | assert!(!turn.next_step(), "{source:?}"); |
| 660 | } |
| 661 | } |
| 662 | |
| 663 | #[test] |
| 664 | fn has_api_key_detects_in_memory_override_and_env_var() -> Result<()> { |
| 665 | // Pins the v0.8.8 contract: `has_api_key` covers the prompt-free |
| 666 | // sources used by `Config::active_route_api_key` (in-memory override, |
| 667 | // env var, config-file slot). |
| 668 | let _lock = lock_test_env(); |
| 669 | // Explicit in-memory key wins over every other source per |
| 670 | // `Config::active_route_api_key`'s "Path 0" override. |
| 671 | let cfg = <Config as Default>::default() |
| 672 | .with_legacy_root(Some("sk-in-memory-override".to_string()), None); |
| 673 | assert!( |
| 674 | has_api_key(&cfg), |
| 675 | "in-memory override must be detected as a usable key" |
| 676 | ); |
| 677 | |
| 678 | // Env var path. |
| 679 | let env_cfg = Config::default(); |
| 680 | unsafe { |
| 681 | std::env::set_var("DEEPSEEK_API_KEY", "env-key"); |
| 682 | } |
| 683 | assert!( |
| 684 | has_api_key(&env_cfg), |
| 685 | "env-var key must be detected even with empty config" |
| 686 | ); |
| 687 | unsafe { |
| 688 | std::env::remove_var("DEEPSEEK_API_KEY"); |
| 689 | } |
| 690 | Ok(()) |
| 691 | } |
| 692 | |
| 693 | #[test] |
| 694 | fn provider_neutral_scenario() -> Result<()> { |
| 695 | // Scenario consolidation of: provider_neutral_cli_key_wins_after_profile_provider_switch, provider_neutral_cli_key_requires_dispatcher_source_marker |
| 696 | // from provider_neutral_cli_key_wins_after_profile_provider_switch |
| 697 | { |
| 698 | let _lock = lock_test_env(); |
| 699 | let _source = EnvVarGuard::set(codewhale_config::CLI_API_KEY_SOURCE_ENV, "cli"); |
| 700 | let _cli_key = EnvVarGuard::set(codewhale_config::CLI_API_KEY_ENV, "explicit-profile-key"); |
| 701 | let _anthropic_env = EnvVarGuard::remove("ANTHROPIC_API_KEY"); |
| 702 | let mut providers = ProvidersConfig::default(); |
| 703 | providers.anthropic.api_key = Some("saved-anthropic-key".to_string()); |
| 704 | let config = { |
| 705 | let __cw_config_init_5_0 = Some("anthropic".to_string()); |
| 706 | let __cw_config_init_5_1 = Some(providers); |
| 707 | let mut __cw_config_init_5_value: Config = Default::default(); |
| 708 | __cw_config_init_5_value.provider = __cw_config_init_5_0; |
| 709 | __cw_config_init_5_value.providers = __cw_config_init_5_1; |
| 710 | __cw_config_init_5_value |
| 711 | }; |
| 712 | |
| 713 | assert_eq!(config.active_route_api_key()?, "explicit-profile-key"); |
| 714 | assert!(has_api_key(&config)); |
| 715 | assert!(active_provider_has_env_api_key(&config)); |
| 716 | } |
| 717 | // from provider_neutral_cli_key_requires_dispatcher_source_marker |
| 718 | { |
| 719 | let _lock = lock_test_env(); |
| 720 | let _source = EnvVarGuard::remove(codewhale_config::CLI_API_KEY_SOURCE_ENV); |
| 721 | let _legacy_source = EnvVarGuard::remove(codewhale_config::LEGACY_CLI_API_KEY_SOURCE_ENV); |
| 722 | let _cli_key = EnvVarGuard::set(codewhale_config::CLI_API_KEY_ENV, "untrusted-generic-key"); |
| 723 | let _anthropic_env = EnvVarGuard::remove("ANTHROPIC_API_KEY"); |
| 724 | let mut providers = ProvidersConfig::default(); |
| 725 | providers.anthropic.api_key = Some("saved-anthropic-key".to_string()); |
| 726 | let config = { |
| 727 | let __cw_config_init_6_0 = Some("anthropic".to_string()); |
| 728 | let __cw_config_init_6_1 = Some(providers); |
| 729 | let mut __cw_config_init_6_value: Config = Default::default(); |
| 730 | __cw_config_init_6_value.provider = __cw_config_init_6_0; |
| 731 | __cw_config_init_6_value.providers = __cw_config_init_6_1; |
| 732 | __cw_config_init_6_value |
| 733 | }; |
| 734 | |
| 735 | assert_eq!(config.active_route_api_key()?, "saved-anthropic-key"); |
| 736 | } |
| 737 | Ok(()) |
| 738 | } |
| 739 | |
| 740 | fn config_with_provider_scoped_key(provider: &str, api_key: &str) -> Config { |
| 741 | let mut providers = ProvidersConfig::default(); |
| 742 | match provider { |
| 743 | "deepseek" | "deepseek-cn" => { |
| 744 | providers.deepseek.api_key = Some(api_key.to_string()); |
| 745 | } |
| 746 | "nvidia-nim" => { |
| 747 | providers.nvidia_nim.api_key = Some(api_key.to_string()); |
| 748 | } |
| 749 | "openai" => { |
| 750 | providers.openai.api_key = Some(api_key.to_string()); |
| 751 | } |
| 752 | "wanjie-ark" => { |
| 753 | providers.wanjie_ark.api_key = Some(api_key.to_string()); |
| 754 | } |
| 755 | "openrouter" => { |
| 756 | providers.openrouter.api_key = Some(api_key.to_string()); |
| 757 | } |
| 758 | "novita" => { |
| 759 | providers.novita.api_key = Some(api_key.to_string()); |
| 760 | } |
| 761 | "fireworks" => { |
| 762 | providers.fireworks.api_key = Some(api_key.to_string()); |
| 763 | } |
| 764 | "siliconflow" => { |
| 765 | providers.siliconflow.api_key = Some(api_key.to_string()); |
| 766 | } |
| 767 | "sglang" => { |
| 768 | providers.sglang.api_key = Some(api_key.to_string()); |
| 769 | } |
| 770 | "vllm" => { |
| 771 | providers.vllm.api_key = Some(api_key.to_string()); |
| 772 | } |
| 773 | "ollama" => { |
| 774 | providers.ollama.api_key = Some(api_key.to_string()); |
| 775 | } |
| 776 | "huggingface" => { |
| 777 | providers.huggingface.api_key = Some(api_key.to_string()); |
| 778 | } |
| 779 | "qianfan" => { |
| 780 | providers.qianfan.api_key = Some(api_key.to_string()); |
| 781 | } |
| 782 | _ => panic!("unexpected provider {provider}"), |
| 783 | } |
| 784 | |
| 785 | { |
| 786 | let __cw_config_init_7_0 = Some(provider.to_string()); |
| 787 | let __cw_config_init_7_1 = Some(providers); |
| 788 | let mut __cw_config_init_7_value: Config = Config::default(); |
| 789 | __cw_config_init_7_value.provider = __cw_config_init_7_0; |
| 790 | __cw_config_init_7_value.providers = __cw_config_init_7_1; |
| 791 | __cw_config_init_7_value |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | #[test] |
| 796 | fn has_api_scenario() -> Result<()> { |
| 797 | // Scenario consolidation of: has_api_key_uses_active_provider_scoped_config_key, has_api_key_uses_root_config_key_for_deepseek_variants, has_api_key_for_uses_deepseek_cn_provider_table, has_api_key_for_uses_root_config_key_for_deepseek_variants |
| 798 | // from has_api_key_uses_active_provider_scoped_config_key |
| 799 | { |
| 800 | // `has_api_key` intentionally consults live endpoint env overrides. Keep |
| 801 | // this config-only assertion out of the windows where another test owns a |
| 802 | // process-global custom endpoint. |
| 803 | let _lock = lock_test_env(); |
| 804 | for provider in [ |
| 805 | "openai", |
| 806 | "wanjie-ark", |
| 807 | "openrouter", |
| 808 | "novita", |
| 809 | "fireworks", |
| 810 | "siliconflow", |
| 811 | "qianfan", |
| 812 | ] { |
| 813 | let config = config_with_provider_scoped_key(provider, "provider-config-key"); |
| 814 | |
| 815 | assert!( |
| 816 | has_api_key(&config), |
| 817 | "active provider config key must satisfy onboarding auth check for {provider}" |
| 818 | ); |
| 819 | } |
| 820 | } |
| 821 | // from has_api_key_uses_root_config_key_for_deepseek_variants |
| 822 | { |
| 823 | // A concurrent CODEWHALE_BASE_URL override deliberately unbinds the saved |
| 824 | // root key from the active endpoint. Serialize this assertion with the |
| 825 | // tests that install those process-global overrides. |
| 826 | let _lock = lock_test_env(); |
| 827 | for provider in ["deepseek", "deepseek-cn"] { |
| 828 | let config = { |
| 829 | let __cw_config_init_8_0 = Some(provider.to_string()); |
| 830 | let mut __cw_config_init_8_value: Config = Config::default(); |
| 831 | __cw_config_init_8_value.provider = __cw_config_init_8_0; |
| 832 | __cw_config_init_8_value |
| 833 | } |
| 834 | .with_legacy_root(Some("root-config-key".to_string()), None); |
| 835 | |
| 836 | assert!( |
| 837 | has_api_key(&config), |
| 838 | "root config api_key must satisfy onboarding auth check for {provider}" |
| 839 | ); |
| 840 | } |
| 841 | } |
| 842 | // from has_api_key_for_uses_deepseek_cn_provider_table |
| 843 | { |
| 844 | let _lock = lock_test_env(); |
| 845 | let nanos = SystemTime::now() |
| 846 | .duration_since(UNIX_EPOCH) |
| 847 | .unwrap() |
| 848 | .as_nanos(); |
| 849 | let temp_root = env::temp_dir().join(format!( |
| 850 | "codewhale-tui-has-key-cn-{}-{}", |
| 851 | std::process::id(), |
| 852 | nanos |
| 853 | )); |
| 854 | fs::create_dir_all(&temp_root)?; |
| 855 | let _guard = EnvGuard::new(&temp_root); |
| 856 | |
| 857 | let mut providers = ProvidersConfig::default(); |
| 858 | providers.deepseek_cn.api_key = Some("cn-file-key".to_string()); |
| 859 | let config = { |
| 860 | let __cw_config_init_9_0 = Some(providers); |
| 861 | let mut __cw_config_init_9_value: Config = Config::default(); |
| 862 | __cw_config_init_9_value.providers = __cw_config_init_9_0; |
| 863 | __cw_config_init_9_value |
| 864 | }; |
| 865 | |
| 866 | assert!(has_api_key_for( |
| 867 | &config, |
| 868 | &(config) |
| 869 | .resolve_provider_selection_identity("deepseek-cn") |
| 870 | .unwrap() |
| 871 | )); |
| 872 | } |
| 873 | // from has_api_key_for_uses_root_config_key_for_deepseek_variants |
| 874 | { |
| 875 | let _lock = lock_test_env(); |
| 876 | let config = Config::default().with_legacy_root(Some("root-config-key".to_string()), None); |
| 877 | |
| 878 | assert!(has_api_key_for( |
| 879 | &config, |
| 880 | &(config).test_identity_for_kind(ProviderKind::Deepseek) |
| 881 | )); |
| 882 | assert!(has_api_key_for( |
| 883 | &config, |
| 884 | &(config) |
| 885 | .resolve_provider_selection_identity("deepseek-cn") |
| 886 | .unwrap() |
| 887 | )); |
| 888 | } |
| 889 | Ok(()) |
| 890 | } |
| 891 | |
| 892 | #[test] |
| 893 | fn has_api_key_uses_active_provider_env_key() -> Result<()> { |
| 894 | let _lock = lock_test_env(); |
| 895 | for (provider, env_var) in [ |
| 896 | ("openai", "OPENAI_API_KEY"), |
| 897 | ("wanjie-ark", "WANJIE_ARK_API_KEY"), |
| 898 | ("openrouter", "OPENROUTER_API_KEY"), |
| 899 | ("novita", "NOVITA_API_KEY"), |
| 900 | ("fireworks", "FIREWORKS_API_KEY"), |
| 901 | ("siliconflow", "SILICONFLOW_API_KEY"), |
| 902 | ("qianfan", "QIANFAN_API_KEY"), |
| 903 | ] { |
| 904 | unsafe { |
| 905 | std::env::set_var(env_var, "provider-env-key"); |
| 906 | } |
| 907 | |
| 908 | let config = { |
| 909 | let __cw_config_init_11_0 = Some(provider.to_string()); |
| 910 | let mut __cw_config_init_11_value: Config = Config::default(); |
| 911 | __cw_config_init_11_value.provider = __cw_config_init_11_0; |
| 912 | __cw_config_init_11_value |
| 913 | }; |
| 914 | |
| 915 | assert!( |
| 916 | has_api_key(&config), |
| 917 | "active provider env key must satisfy onboarding auth check for {provider}" |
| 918 | ); |
| 919 | |
| 920 | unsafe { |
| 921 | std::env::remove_var(env_var); |
| 922 | } |
| 923 | } |
| 924 | Ok(()) |
| 925 | } |
| 926 | |
| 927 | #[test] |
| 928 | fn standalone_tui_reads_saved_secret_before_ambient_env() -> Result<()> { |
| 929 | let _lock = lock_test_env(); |
| 930 | let temp_root = tempfile::tempdir()?; |
| 931 | let _guard = EnvGuard::new(temp_root.path()); |
| 932 | let codewhale_home = temp_root.path().join("isolated-codewhale"); |
| 933 | fs::create_dir_all(&codewhale_home)?; |
| 934 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 935 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 936 | let _ambient_key = EnvVarGuard::set("DEEPSEEK_API_KEY", "stale-env-key"); |
| 937 | |
| 938 | let secrets = codewhale_secrets::Secrets::auto_detect(); |
| 939 | secrets.set("deepseek", "saved-secret-key")?; |
| 940 | |
| 941 | let config = Config::default(); |
| 942 | assert_eq!(config.active_route_api_key()?, "saved-secret-key"); |
| 943 | assert!(has_api_key(&config)); |
| 944 | assert!(active_provider_has_config_api_key(&config)); |
| 945 | |
| 946 | let configured = Config::default().with_legacy_root(Some("fresh-config-key".to_string()), None); |
| 947 | assert_eq!(configured.active_route_api_key()?, "fresh-config-key"); |
| 948 | Ok(()) |
| 949 | } |
| 950 | |
| 951 | #[test] |
| 952 | fn authenticated_local_provider_reads_saved_secret() -> Result<()> { |
| 953 | let _lock = lock_test_env(); |
| 954 | let temp_root = tempfile::tempdir()?; |
| 955 | let _guard = EnvGuard::new(temp_root.path()); |
| 956 | let codewhale_home = temp_root.path().join("isolated-codewhale"); |
| 957 | fs::create_dir_all(&codewhale_home)?; |
| 958 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 959 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 960 | let _ambient_key = EnvVarGuard::remove("VLLM_API_KEY"); |
| 961 | |
| 962 | codewhale_secrets::Secrets::auto_detect().set("vllm", "saved-local-secret")?; |
| 963 | |
| 964 | let mut providers = ProvidersConfig::default(); |
| 965 | providers.vllm.base_url = Some("http://127.0.0.1:8000/v1".to_string()); |
| 966 | providers.vllm.auth_mode = Some("api_key".to_string()); |
| 967 | let config = { |
| 968 | let __cw_config_init_13_0 = Some("vllm".to_string()); |
| 969 | let __cw_config_init_13_1 = Some(providers); |
| 970 | let mut __cw_config_init_13_value: Config = Config::default(); |
| 971 | __cw_config_init_13_value.provider = __cw_config_init_13_0; |
| 972 | __cw_config_init_13_value.providers = __cw_config_init_13_1; |
| 973 | __cw_config_init_13_value |
| 974 | }; |
| 975 | |
| 976 | assert_eq!(config.active_route_api_key()?, "saved-local-secret"); |
| 977 | assert!(has_api_key(&config)); |
| 978 | assert!(active_provider_has_config_api_key(&config)); |
| 979 | Ok(()) |
| 980 | } |
| 981 | |
| 982 | #[test] |
| 983 | fn named_custom_provider_never_reuses_generic_custom_secret() -> Result<()> { |
| 984 | let _lock = lock_test_env(); |
| 985 | let temp_root = tempfile::tempdir()?; |
| 986 | let _guard = EnvGuard::new(temp_root.path()); |
| 987 | let codewhale_home = temp_root.path().join("isolated-codewhale"); |
| 988 | fs::create_dir_all(&codewhale_home)?; |
| 989 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 990 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 991 | |
| 992 | codewhale_secrets::Secrets::auto_detect().set("custom", "endpoint-a-secret")?; |
| 993 | |
| 994 | let mut providers = ProvidersConfig::default(); |
| 995 | providers.custom.insert( |
| 996 | "endpoint-b".to_string(), |
| 997 | ProviderConfig { |
| 998 | kind: Some("openai-compatible".to_string()), |
| 999 | base_url: Some("https://endpoint-b.example.test/v1".to_string()), |
| 1000 | model: Some("endpoint-b-model".to_string()), |
| 1001 | auth_mode: Some("api_key".to_string()), |
| 1002 | ..ProviderConfig::default() |
| 1003 | }, |
| 1004 | ); |
| 1005 | let config = { |
| 1006 | let __cw_config_init_14_0 = Some("endpoint-b".to_string()); |
| 1007 | let __cw_config_init_14_1 = Some(providers); |
| 1008 | let mut __cw_config_init_14_value: Config = Config::default(); |
| 1009 | __cw_config_init_14_value.provider = __cw_config_init_14_0; |
| 1010 | __cw_config_init_14_value.providers = __cw_config_init_14_1; |
| 1011 | __cw_config_init_14_value |
| 1012 | }; |
| 1013 | |
| 1014 | assert!(config.should_skip_secret_store_for_provider( |
| 1015 | &config.test_identity_for_kind(ProviderKind::Custom) |
| 1016 | )); |
| 1017 | assert!( |
| 1018 | provider_secret_store_api_key( |
| 1019 | &config, |
| 1020 | &(config).test_identity_for_kind(ProviderKind::Custom) |
| 1021 | ) |
| 1022 | .is_none() |
| 1023 | ); |
| 1024 | assert!(config.active_route_api_key().is_err()); |
| 1025 | assert!(!has_api_key(&config)); |
| 1026 | assert!(!active_provider_has_config_api_key(&config)); |
| 1027 | Ok(()) |
| 1028 | } |
| 1029 | |
| 1030 | #[test] |
| 1031 | fn built_in_provider_custom_endpoint_never_reuses_global_credentials() -> Result<()> { |
| 1032 | let _lock = lock_test_env(); |
| 1033 | let temp_root = tempfile::tempdir()?; |
| 1034 | let _guard = EnvGuard::new(temp_root.path()); |
| 1035 | let codewhale_home = temp_root.path().join("isolated-codewhale"); |
| 1036 | fs::create_dir_all(&codewhale_home)?; |
| 1037 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 1038 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 1039 | let _ambient = EnvVarGuard::set("OPENROUTER_API_KEY", "ambient-official-key"); |
| 1040 | codewhale_secrets::Secrets::auto_detect().set("openrouter", "saved-official-key")?; |
| 1041 | |
| 1042 | let mut providers = ProvidersConfig::default(); |
| 1043 | providers.openrouter.base_url = Some("https://gateway.example.test/v1".to_string()); |
| 1044 | let config = { |
| 1045 | let __cw_config_init_15_0 = Some("openrouter".to_string()); |
| 1046 | let __cw_config_init_15_1 = Some(providers); |
| 1047 | let mut __cw_config_init_15_value: Config = Config::default(); |
| 1048 | __cw_config_init_15_value.provider = __cw_config_init_15_0; |
| 1049 | __cw_config_init_15_value.providers = __cw_config_init_15_1; |
| 1050 | __cw_config_init_15_value |
| 1051 | }; |
| 1052 | |
| 1053 | assert!( |
| 1054 | config.provider_uses_custom_endpoint( |
| 1055 | &config.test_identity_for_kind(ProviderKind::Openrouter) |
| 1056 | ) |
| 1057 | ); |
| 1058 | assert!(config.should_skip_secret_store_for_provider( |
| 1059 | &config.test_identity_for_kind(ProviderKind::Openrouter) |
| 1060 | )); |
| 1061 | assert!(config.active_route_api_key().is_err()); |
| 1062 | assert!(!has_api_key(&config)); |
| 1063 | assert!(!active_provider_has_config_api_key(&config)); |
| 1064 | assert!(!active_provider_has_env_api_key(&config)); |
| 1065 | Ok(()) |
| 1066 | } |
| 1067 | |
| 1068 | #[test] |
| 1069 | fn custom_endpoint_accepts_route_bound_api_key_env_and_reports_ready() -> Result<()> { |
| 1070 | let _lock = lock_test_env(); |
| 1071 | let temp_root = tempfile::tempdir()?; |
| 1072 | let _guard = EnvGuard::new(temp_root.path()); |
| 1073 | let _route_key = EnvVarGuard::set("MY_GATEWAY_ROUTE_KEY", "route-bound-key"); |
| 1074 | let _ambient = EnvVarGuard::set("OPENROUTER_API_KEY", "ambient-official-key"); |
| 1075 | |
| 1076 | let mut providers = ProvidersConfig::default(); |
| 1077 | providers.openrouter.base_url = Some("https://gateway.example.test/v1".to_string()); |
| 1078 | providers.openrouter.api_key_env = Some("MY_GATEWAY_ROUTE_KEY".to_string()); |
| 1079 | let config = { |
| 1080 | let __cw_config_init_16_0 = Some("openrouter".to_string()); |
| 1081 | let __cw_config_init_16_1 = Some(providers); |
| 1082 | let mut __cw_config_init_16_value: Config = Config::default(); |
| 1083 | __cw_config_init_16_value.provider = __cw_config_init_16_0; |
| 1084 | __cw_config_init_16_value.providers = __cw_config_init_16_1; |
| 1085 | __cw_config_init_16_value |
| 1086 | }; |
| 1087 | |
| 1088 | assert_eq!(config.active_route_api_key()?, "route-bound-key"); |
| 1089 | assert!(has_api_key_for( |
| 1090 | &config, |
| 1091 | &(config).test_identity_for_kind(ProviderKind::Openrouter) |
| 1092 | )); |
| 1093 | assert!(active_provider_has_env_api_key(&config)); |
| 1094 | assert!(active_provider_uses_env_only_api_key(&config)); |
| 1095 | Ok(()) |
| 1096 | } |
| 1097 | |
| 1098 | #[test] |
| 1099 | fn env_selected_custom_endpoints_do_not_rebind_file_credentials() -> Result<()> { |
| 1100 | let _lock = lock_test_env(); |
| 1101 | let temp_root = tempfile::tempdir()?; |
| 1102 | let _guard = EnvGuard::new(temp_root.path()); |
| 1103 | let config_path = temp_root.path().join("config.toml"); |
| 1104 | let _route_key = EnvVarGuard::set("MY_GATEWAY_ROUTE_KEY", "route-bound-file-key"); |
| 1105 | let _source = EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 1106 | let _cli_key = EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 1107 | |
| 1108 | fs::write( |
| 1109 | &config_path, |
| 1110 | r#"api_key = "saved-root-deepseek-key" |
| 1111 | default_text_model = "deepseek-chat" |
| 1112 | "#, |
| 1113 | )?; |
| 1114 | { |
| 1115 | let _generic_base = EnvVarGuard::set( |
| 1116 | "CODEWHALE_BASE_URL", |
| 1117 | "https://generic-gateway.example.test/v1", |
| 1118 | ); |
| 1119 | let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 1120 | assert!( |
| 1121 | config.provider_uses_custom_endpoint( |
| 1122 | &config.test_identity_for_kind(ProviderKind::Deepseek) |
| 1123 | ) |
| 1124 | ); |
| 1125 | assert!(config.active_route_api_key().is_err()); |
| 1126 | assert!(!active_provider_has_config_api_key(&config)); |
| 1127 | assert!(!active_provider_has_env_api_key(&config)); |
| 1128 | assert!(!has_api_key_for( |
| 1129 | &config, |
| 1130 | &(config).test_identity_for_kind(ProviderKind::Deepseek) |
| 1131 | )); |
| 1132 | } |
| 1133 | |
| 1134 | fs::write( |
| 1135 | &config_path, |
| 1136 | r#"provider = "openrouter" |
| 1137 | |
| 1138 | [providers.openrouter] |
| 1139 | api_key = "saved-openrouter-route-key" |
| 1140 | api_key_env = "MY_GATEWAY_ROUTE_KEY" |
| 1141 | model = "openai/gpt-5" |
| 1142 | "#, |
| 1143 | )?; |
| 1144 | for (env_name, endpoint) in [ |
| 1145 | ( |
| 1146 | "CODEWHALE_BASE_URL", |
| 1147 | "https://generic-openrouter-gateway.example.test/v1", |
| 1148 | ), |
| 1149 | ( |
| 1150 | "OPENROUTER_BASE_URL", |
| 1151 | "https://provider-openrouter-gateway.example.test/v1", |
| 1152 | ), |
| 1153 | ] { |
| 1154 | let _base = EnvVarGuard::set(env_name, endpoint); |
| 1155 | let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 1156 | assert_eq!(config.active_route_base_url(), endpoint); |
| 1157 | assert!(config.provider_uses_custom_endpoint( |
| 1158 | &config.test_identity_for_kind(ProviderKind::Openrouter) |
| 1159 | )); |
| 1160 | assert!(config.active_route_api_key().is_err()); |
| 1161 | assert!(!active_provider_has_config_api_key(&config)); |
| 1162 | assert!(!active_provider_has_env_api_key(&config)); |
| 1163 | assert!(!has_api_key_for( |
| 1164 | &config, |
| 1165 | &(config).test_identity_for_kind(ProviderKind::Openrouter) |
| 1166 | )); |
| 1167 | } |
| 1168 | |
| 1169 | Ok(()) |
| 1170 | } |
| 1171 | |
| 1172 | #[test] |
| 1173 | fn file_bound_custom_endpoints_keep_route_credentials() -> Result<()> { |
| 1174 | let _lock = lock_test_env(); |
| 1175 | let temp_root = tempfile::tempdir()?; |
| 1176 | let _guard = EnvGuard::new(temp_root.path()); |
| 1177 | let config_path = temp_root.path().join("config.toml"); |
| 1178 | let _route_key = EnvVarGuard::set("MY_GATEWAY_ROUTE_KEY", "file-env-route-key"); |
| 1179 | |
| 1180 | fs::write( |
| 1181 | &config_path, |
| 1182 | r#"api_key = "file-root-key" |
| 1183 | base_url = "https://file-deepseek-gateway.example.test/v1" |
| 1184 | default_text_model = "private-deepseek-model" |
| 1185 | "#, |
| 1186 | )?; |
| 1187 | let root = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 1188 | assert_eq!(root.active_route_api_key()?, "file-root-key"); |
| 1189 | assert!(active_provider_has_config_api_key(&root)); |
| 1190 | assert!(has_api_key_for( |
| 1191 | &root, |
| 1192 | &(root).test_identity_for_kind(ProviderKind::Deepseek) |
| 1193 | )); |
| 1194 | |
| 1195 | fs::write( |
| 1196 | &config_path, |
| 1197 | r#"provider = "openrouter" |
| 1198 | |
| 1199 | [providers.openrouter] |
| 1200 | api_key = "file-provider-key" |
| 1201 | base_url = "https://file-openrouter-gateway.example.test/v1" |
| 1202 | model = "private-openrouter-model" |
| 1203 | "#, |
| 1204 | )?; |
| 1205 | let provider_key = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 1206 | assert_eq!(provider_key.active_route_api_key()?, "file-provider-key"); |
| 1207 | assert!(active_provider_has_config_api_key(&provider_key)); |
| 1208 | assert!(has_api_key_for( |
| 1209 | &provider_key, |
| 1210 | &(provider_key).test_identity_for_kind(ProviderKind::Openrouter) |
| 1211 | )); |
| 1212 | |
| 1213 | fs::write( |
| 1214 | &config_path, |
| 1215 | r#"provider = "openrouter" |
| 1216 | |
| 1217 | [providers.openrouter] |
| 1218 | api_key_env = "MY_GATEWAY_ROUTE_KEY" |
| 1219 | base_url = "https://file-openrouter-gateway.example.test/v1" |
| 1220 | model = "private-openrouter-model" |
| 1221 | "#, |
| 1222 | )?; |
| 1223 | let route_env = codewhale_plugins::providers::load_config(Some(config_path), None)?; |
| 1224 | assert_eq!(route_env.active_route_api_key()?, "file-env-route-key"); |
| 1225 | assert!(active_provider_has_env_api_key(&route_env)); |
| 1226 | assert!(has_api_key_for( |
| 1227 | &route_env, |
| 1228 | &(route_env).test_identity_for_kind(ProviderKind::Openrouter) |
| 1229 | )); |
| 1230 | Ok(()) |
| 1231 | } |
| 1232 | |
| 1233 | /// A session-scoped `[providers.*]` fixture with credentials but no endpoints, |
| 1234 | /// so every base URL in these tests comes from the resolver rather than a file. |
| 1235 | const CROSS_PROVIDER_ROUTE_FIXTURE: &str = r#"api_key = "session-deepseek-key" |
| 1236 | default_text_model = "deepseek-chat" |
| 1237 | |
| 1238 | [providers.moonshot] |
| 1239 | api_key = "moonshot-route-key" |
| 1240 | |
| 1241 | [providers.zai] |
| 1242 | api_key = "zai-route-key" |
| 1243 | |
| 1244 | [providers.minimax] |
| 1245 | api_key = "minimax-route-key" |
| 1246 | "#; |
| 1247 | |
| 1248 | #[test] |
| 1249 | fn generic_base_url_override_never_reaches_pinned_child_routes() -> Result<()> { |
| 1250 | // #4093-class routing truth: every cross-provider seam (pinned subagent / |
| 1251 | // fleet child, per-turn auto-router, tool routing, picker preview) clones |
| 1252 | // the session config and re-points `provider`. The generic endpoint |
| 1253 | // override belongs to the DeepSeek session that set it and must never |
| 1254 | // follow a child to another vendor's route. |
| 1255 | let _lock = lock_test_env(); |
| 1256 | let temp_root = tempfile::tempdir()?; |
| 1257 | let _guard = EnvGuard::new(temp_root.path()); |
| 1258 | let config_path = temp_root.path().join("config.toml"); |
| 1259 | fs::write(&config_path, CROSS_PROVIDER_ROUTE_FIXTURE)?; |
| 1260 | |
| 1261 | for env_name in ["CODEWHALE_BASE_URL", "DEEPSEEK_BASE_URL"] { |
| 1262 | let session_host = "https://session-gateway.example.test/v1"; |
| 1263 | let _base = EnvVarGuard::set(env_name, session_host); |
| 1264 | let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 1265 | |
| 1266 | // Documented behavior for the active DeepSeek route is unchanged. |
| 1267 | assert_eq!( |
| 1268 | config.active_provider_identity().unwrap().provider, |
| 1269 | ProviderKind::Deepseek |
| 1270 | ); |
| 1271 | assert_eq!(config.active_route_base_url(), session_host); |
| 1272 | assert!( |
| 1273 | config.provider_uses_custom_endpoint( |
| 1274 | &config.test_identity_for_kind(ProviderKind::Deepseek) |
| 1275 | ) |
| 1276 | ); |
| 1277 | |
| 1278 | for (provider, expected) in [ |
| 1279 | (ProviderKind::Moonshot, DEFAULT_MOONSHOT_BASE_URL), |
| 1280 | (ProviderKind::Zai, DEFAULT_ZAI_BASE_URL), |
| 1281 | (ProviderKind::Minimax, DEFAULT_MINIMAX_BASE_URL), |
| 1282 | ] { |
| 1283 | assert_eq!( |
| 1284 | config.base_url_for_route(&config.test_identity_for_kind(provider)), |
| 1285 | expected, |
| 1286 | "{env_name}: {provider:?} must resolve from its own identity table" |
| 1287 | ); |
| 1288 | assert!( |
| 1289 | !config.provider_uses_custom_endpoint(&config.test_identity_for_kind(provider)), |
| 1290 | "{env_name}: {provider:?} is on its canonical host, not a custom one" |
| 1291 | ); |
| 1292 | |
| 1293 | let route = |
| 1294 | codewhale_engine::route_runtime::resolve_runtime_route(&config, provider, None) |
| 1295 | .unwrap_or_else(|err| panic!("{env_name}: {provider:?} child route: {err}")); |
| 1296 | // The scoped config and the executable candidate must agree, and |
| 1297 | // neither may name the session host. |
| 1298 | assert_eq!(route.config.active_route_base_url(), expected); |
| 1299 | assert_eq!(route.candidate.endpoint().base_url, expected); |
| 1300 | assert_ne!(route.candidate.endpoint().base_url, session_host); |
| 1301 | } |
| 1302 | |
| 1303 | assert!( |
| 1304 | config |
| 1305 | .resolve_provider_selection_identity("custom") |
| 1306 | .is_err() |
| 1307 | ); |
| 1308 | } |
| 1309 | |
| 1310 | Ok(()) |
| 1311 | } |
| 1312 | |
| 1313 | #[test] |
| 1314 | fn provider_scoped_base_url_env_applies_only_to_its_own_route() -> Result<()> { |
| 1315 | let _lock = lock_test_env(); |
| 1316 | let temp_root = tempfile::tempdir()?; |
| 1317 | let _guard = EnvGuard::new(temp_root.path()); |
| 1318 | let config_path = temp_root.path().join("config.toml"); |
| 1319 | fs::write(&config_path, CROSS_PROVIDER_ROUTE_FIXTURE)?; |
| 1320 | |
| 1321 | let moonshot_host = "https://moonshot-gateway.example.test/v1"; |
| 1322 | let _moonshot = EnvVarGuard::set("MOONSHOT_BASE_URL", moonshot_host); |
| 1323 | |
| 1324 | // Without a generic override the active DeepSeek route keeps its default: |
| 1325 | // a provider-scoped variable names exactly one provider. |
| 1326 | let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 1327 | assert_eq!(config.active_route_base_url(), DEFAULT_DEEPSEEK_BASE_URL); |
| 1328 | assert_eq!( |
| 1329 | config.base_url_for_route(&config.test_identity_for_kind(ProviderKind::Zai)), |
| 1330 | DEFAULT_ZAI_BASE_URL |
| 1331 | ); |
| 1332 | assert_eq!( |
| 1333 | config.base_url_for_route(&config.test_identity_for_kind(ProviderKind::Moonshot)), |
| 1334 | moonshot_host |
| 1335 | ); |
| 1336 | let route = codewhale_engine::route_runtime::resolve_runtime_route( |
| 1337 | &config, |
| 1338 | ProviderKind::Moonshot, |
| 1339 | None, |
| 1340 | ) |
| 1341 | .expect("Moonshot child route"); |
| 1342 | assert_eq!(route.candidate.endpoint().base_url, moonshot_host); |
| 1343 | |
| 1344 | // With both set, each override stays on its own route. |
| 1345 | let session_host = "https://session-gateway.example.test/v1"; |
| 1346 | let _base = EnvVarGuard::set("CODEWHALE_BASE_URL", session_host); |
| 1347 | let config = codewhale_plugins::providers::load_config(Some(config_path), None)?; |
| 1348 | assert_eq!(config.active_route_base_url(), session_host); |
| 1349 | assert_eq!( |
| 1350 | config.base_url_for_route(&config.test_identity_for_kind(ProviderKind::Moonshot)), |
| 1351 | moonshot_host |
| 1352 | ); |
| 1353 | assert_eq!( |
| 1354 | config.base_url_for_route(&config.test_identity_for_kind(ProviderKind::Zai)), |
| 1355 | DEFAULT_ZAI_BASE_URL |
| 1356 | ); |
| 1357 | let route = codewhale_engine::route_runtime::resolve_runtime_route( |
| 1358 | &config, |
| 1359 | ProviderKind::Moonshot, |
| 1360 | None, |
| 1361 | ) |
| 1362 | .expect("Moonshot child route"); |
| 1363 | assert_eq!(route.config.active_route_base_url(), moonshot_host); |
| 1364 | assert_eq!(route.candidate.endpoint().base_url, moonshot_host); |
| 1365 | assert_ne!(route.candidate.endpoint().base_url, session_host); |
| 1366 | |
| 1367 | Ok(()) |
| 1368 | } |
| 1369 | |
| 1370 | #[test] |
| 1371 | fn source_marked_cli_key_can_follow_cli_forwarded_custom_base_url() -> Result<()> { |
| 1372 | let _lock = lock_test_env(); |
| 1373 | let temp_root = tempfile::tempdir()?; |
| 1374 | let _guard = EnvGuard::new(temp_root.path()); |
| 1375 | let config_path = temp_root.path().join("config.toml"); |
| 1376 | fs::write( |
| 1377 | &config_path, |
| 1378 | r#"api_key = "saved-root-key" |
| 1379 | base_url = "https://api.deepseek.com/v1" |
| 1380 | default_text_model = "deepseek-chat" |
| 1381 | "#, |
| 1382 | )?; |
| 1383 | let _base = EnvVarGuard::set( |
| 1384 | "DEEPSEEK_BASE_URL", |
| 1385 | "https://explicit-cli-gateway.example.test/v1", |
| 1386 | ); |
| 1387 | let _source = EnvVarGuard::set(codewhale_config::CLI_API_KEY_SOURCE_ENV, "cli"); |
| 1388 | let _cli_key = EnvVarGuard::set(codewhale_config::CLI_API_KEY_ENV, "explicit-cli-key"); |
| 1389 | |
| 1390 | let config = codewhale_plugins::providers::load_config(Some(config_path), None)?; |
| 1391 | assert_eq!(config.active_route_api_key()?, "explicit-cli-key"); |
| 1392 | assert!(!active_provider_has_config_api_key(&config)); |
| 1393 | assert!(active_provider_has_env_api_key(&config)); |
| 1394 | assert!(active_provider_uses_env_only_api_key(&config)); |
| 1395 | assert!(has_api_key_for( |
| 1396 | &config, |
| 1397 | &(config).test_identity_for_kind(ProviderKind::Deepseek) |
| 1398 | )); |
| 1399 | Ok(()) |
| 1400 | } |
| 1401 | |
| 1402 | #[test] |
| 1403 | fn managed_file_endpoint_replaces_lower_env_provenance() -> Result<()> { |
| 1404 | let _lock = lock_test_env(); |
| 1405 | let temp_root = tempfile::tempdir()?; |
| 1406 | let _guard = EnvGuard::new(temp_root.path()); |
| 1407 | let config_path = temp_root.path().join("config.toml"); |
| 1408 | let managed_path = temp_root.path().join("managed.toml"); |
| 1409 | fs::write( |
| 1410 | &managed_path, |
| 1411 | r#"[providers.openrouter] |
| 1412 | api_key = "managed-route-key" |
| 1413 | base_url = "https://managed-gateway.example.test/v1" |
| 1414 | model = "managed-model" |
| 1415 | "#, |
| 1416 | )?; |
| 1417 | fs::write( |
| 1418 | &config_path, |
| 1419 | format!( |
| 1420 | "provider = \"openrouter\"\nmanaged_config_path = {:?}\n", |
| 1421 | managed_path.display().to_string() |
| 1422 | ), |
| 1423 | )?; |
| 1424 | let _base = EnvVarGuard::set( |
| 1425 | "CODEWHALE_BASE_URL", |
| 1426 | "https://lower-env-gateway.example.test/v1", |
| 1427 | ); |
| 1428 | |
| 1429 | let config = codewhale_plugins::providers::load_config(Some(config_path), None)?; |
| 1430 | assert_eq!( |
| 1431 | config.active_route_base_url(), |
| 1432 | "https://managed-gateway.example.test/v1" |
| 1433 | ); |
| 1434 | assert_eq!(config.active_route_api_key()?, "managed-route-key"); |
| 1435 | assert!(active_provider_has_config_api_key(&config)); |
| 1436 | assert!(has_api_key_for( |
| 1437 | &config, |
| 1438 | &(config).test_identity_for_kind(ProviderKind::Openrouter) |
| 1439 | )); |
| 1440 | Ok(()) |
| 1441 | } |
| 1442 | |
| 1443 | #[test] |
| 1444 | fn managed_config_cannot_grant_external_credential_consent() -> Result<()> { |
| 1445 | let _lock = lock_test_env(); |
| 1446 | let temp_root = tempfile::tempdir()?; |
| 1447 | let _guard = EnvGuard::new(temp_root.path()); |
| 1448 | let config_path = temp_root.path().join("config.toml"); |
| 1449 | let managed_path = temp_root.path().join("managed.toml"); |
| 1450 | let external_path = temp_root.path().join("codex-auth.json"); |
| 1451 | let external_raw = r#"{"tokens":{"access_token":"must-never-be-read"}}"#; |
| 1452 | fs::write(&external_path, external_raw)?; |
| 1453 | fs::write( |
| 1454 | &managed_path, |
| 1455 | format!( |
| 1456 | r#"[providers.openai_codex.external_credentials] |
| 1457 | access = "read_only" |
| 1458 | provider = "openai-codex" |
| 1459 | source = "codex_cli" |
| 1460 | path = {:?} |
| 1461 | consent_version = 1 |
| 1462 | "#, |
| 1463 | external_path.display().to_string() |
| 1464 | ), |
| 1465 | )?; |
| 1466 | fs::write( |
| 1467 | &config_path, |
| 1468 | format!( |
| 1469 | "provider = \"openai-codex\"\nmanaged_config_path = {:?}\n", |
| 1470 | managed_path.display().to_string() |
| 1471 | ), |
| 1472 | )?; |
| 1473 | |
| 1474 | codewhale_runtime::external_credentials::reset_side_effect_trap(); |
| 1475 | let config = codewhale_plugins::providers::load_config(Some(config_path), None)?; |
| 1476 | assert!( |
| 1477 | config |
| 1478 | .provider_config_for(&config.test_identity_for_kind(ProviderKind::OpenaiCodex)) |
| 1479 | .and_then(|provider| provider.external_credentials.as_ref()) |
| 1480 | .is_none() |
| 1481 | ); |
| 1482 | assert!(!has_api_key_for( |
| 1483 | &config, |
| 1484 | &(config).test_identity_for_kind(ProviderKind::OpenaiCodex) |
| 1485 | )); |
| 1486 | assert_eq!( |
| 1487 | codewhale_runtime::external_credentials::side_effect_trap_counts(), |
| 1488 | (0, 0), |
| 1489 | "managed config must not consent to user-owned external credentials" |
| 1490 | ); |
| 1491 | assert_eq!(fs::read_to_string(external_path)?, external_raw); |
| 1492 | Ok(()) |
| 1493 | } |
| 1494 | |
| 1495 | #[test] |
| 1496 | fn managed_disabled_external_policy_tightens_lower_user_consent() -> Result<()> { |
| 1497 | let _lock = lock_test_env(); |
| 1498 | let temp_root = tempfile::tempdir()?; |
| 1499 | let _guard = EnvGuard::new(temp_root.path()); |
| 1500 | let config_path = temp_root.path().join("config.toml"); |
| 1501 | let managed_path = temp_root.path().join("managed.toml"); |
| 1502 | let external_path = temp_root.path().join("codex-auth.json"); |
| 1503 | fs::write( |
| 1504 | &external_path, |
| 1505 | r#"{"tokens":{"access_token":"must-not-read"}}"#, |
| 1506 | )?; |
| 1507 | fs::write( |
| 1508 | &managed_path, |
| 1509 | format!( |
| 1510 | r#"[providers.openai_codex.external_credentials] |
| 1511 | access = "disabled" |
| 1512 | provider = "openai-codex" |
| 1513 | source = "codex_cli" |
| 1514 | path = {:?} |
| 1515 | consent_version = 1 |
| 1516 | "#, |
| 1517 | external_path.display().to_string() |
| 1518 | ), |
| 1519 | )?; |
| 1520 | fs::write( |
| 1521 | &config_path, |
| 1522 | format!( |
| 1523 | r#"provider = "openai-codex" |
| 1524 | managed_config_path = {:?} |
| 1525 | |
| 1526 | [providers.openai_codex] |
| 1527 | auth_mode = "oauth" |
| 1528 | |
| 1529 | [providers.openai_codex.external_credentials] |
| 1530 | access = "read_only" |
| 1531 | provider = "openai-codex" |
| 1532 | source = "codex_cli" |
| 1533 | path = {:?} |
| 1534 | consent_version = 1 |
| 1535 | "#, |
| 1536 | managed_path.display().to_string(), |
| 1537 | external_path.display().to_string(), |
| 1538 | ), |
| 1539 | )?; |
| 1540 | let _auth_path = EnvVarGuard::set("OPENAI_CODEX_AUTH_FILE", &external_path); |
| 1541 | codewhale_runtime::external_credentials::reset_side_effect_trap(); |
| 1542 | let config = codewhale_plugins::providers::load_config(Some(config_path), None)?; |
| 1543 | let effective = config |
| 1544 | .provider_config_for(&config.test_identity_for_kind(ProviderKind::OpenaiCodex)) |
| 1545 | .and_then(|provider| provider.external_credentials.as_ref()) |
| 1546 | .expect("managed disabled tombstone"); |
| 1547 | assert_eq!( |
| 1548 | effective.access, |
| 1549 | codewhale_config::ExternalCredentialAccess::Disabled |
| 1550 | ); |
| 1551 | assert!(!has_api_key_for( |
| 1552 | &config, |
| 1553 | &(config).test_identity_for_kind(ProviderKind::OpenaiCodex) |
| 1554 | )); |
| 1555 | assert_eq!( |
| 1556 | codewhale_runtime::external_credentials::complete_side_effect_trap_counts(), |
| 1557 | (0, 0, 0, 0, 0), |
| 1558 | "managed deny must suppress lower consent before every side effect" |
| 1559 | ); |
| 1560 | Ok(()) |
| 1561 | } |
| 1562 | |
| 1563 | #[test] |
| 1564 | fn named_custom_api_key_env_satisfies_runtime_and_onboarding_readiness() -> Result<()> { |
| 1565 | let _lock = lock_test_env(); |
| 1566 | let temp_root = tempfile::tempdir()?; |
| 1567 | let _guard = EnvGuard::new(temp_root.path()); |
| 1568 | let _route_key = EnvVarGuard::set("NAMED_CUSTOM_ROUTE_KEY", "named-route-key"); |
| 1569 | |
| 1570 | let mut providers = ProvidersConfig::default(); |
| 1571 | providers.custom.insert( |
| 1572 | "acme".to_string(), |
| 1573 | ProviderConfig { |
| 1574 | kind: Some("openai-compatible".to_string()), |
| 1575 | base_url: Some("https://acme.example.test/v1".to_string()), |
| 1576 | model: Some("acme-model".to_string()), |
| 1577 | api_key_env: Some("NAMED_CUSTOM_ROUTE_KEY".to_string()), |
| 1578 | ..ProviderConfig::default() |
| 1579 | }, |
| 1580 | ); |
| 1581 | let config = { |
| 1582 | let __cw_config_init_17_0 = Some("acme".to_string()); |
| 1583 | let __cw_config_init_17_1 = Some(providers); |
| 1584 | let mut __cw_config_init_17_value: Config = Config::default(); |
| 1585 | __cw_config_init_17_value.provider = __cw_config_init_17_0; |
| 1586 | __cw_config_init_17_value.providers = __cw_config_init_17_1; |
| 1587 | __cw_config_init_17_value |
| 1588 | }; |
| 1589 | |
| 1590 | assert_eq!(config.active_route_api_key()?, "named-route-key"); |
| 1591 | assert!(has_api_key_for( |
| 1592 | &config, |
| 1593 | &(config).test_identity_for_kind(ProviderKind::Custom) |
| 1594 | )); |
| 1595 | assert!(has_api_key(&config)); |
| 1596 | Ok(()) |
| 1597 | } |
| 1598 | |
| 1599 | #[test] |
| 1600 | fn auth_mode_none_suppresses_config_env_secret_and_oauth_credentials() -> Result<()> { |
| 1601 | let _lock = lock_test_env(); |
| 1602 | let temp_root = tempfile::tempdir()?; |
| 1603 | let _guard = EnvGuard::new(temp_root.path()); |
| 1604 | let codewhale_home = temp_root.path().join("isolated-codewhale"); |
| 1605 | fs::create_dir_all(&codewhale_home)?; |
| 1606 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 1607 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 1608 | let _ambient = EnvVarGuard::set("XAI_API_KEY", "ambient-xai-key"); |
| 1609 | let oauth_path = temp_root.path().join("grok-auth.json"); |
| 1610 | fs::write(&oauth_path, r#"{"access_token":"oauth-token"}"#)?; |
| 1611 | let _oauth_path = EnvVarGuard::set("GROK_AUTH_PATH", oauth_path.as_os_str()); |
| 1612 | codewhale_secrets::Secrets::auto_detect().set("xai", "saved-xai-key")?; |
| 1613 | |
| 1614 | let mut providers = ProvidersConfig::default(); |
| 1615 | providers.xai.auth_mode = Some("none".to_string()); |
| 1616 | providers.xai.api_key = Some("configured-xai-key".to_string()); |
| 1617 | providers.xai.http_headers = Some(HashMap::from([ |
| 1618 | ("X-API-Key".to_string(), "configured-x-key".to_string()), |
| 1619 | ("Api-Key".to_string(), "configured-key".to_string()), |
| 1620 | ( |
| 1621 | "Proxy-Authorization".to_string(), |
| 1622 | "Basic configured-proxy-secret".to_string(), |
| 1623 | ), |
| 1624 | ( |
| 1625 | "X-Auth-Token".to_string(), |
| 1626 | "configured-auth-token".to_string(), |
| 1627 | ), |
| 1628 | ( |
| 1629 | "X-Access-Token".to_string(), |
| 1630 | "configured-access-token".to_string(), |
| 1631 | ), |
| 1632 | ( |
| 1633 | "X-Goog-Api-Key".to_string(), |
| 1634 | "configured-google-key".to_string(), |
| 1635 | ), |
| 1636 | ("Cookie".to_string(), "session=secret".to_string()), |
| 1637 | ("X-Route-Metadata".to_string(), "safe".to_string()), |
| 1638 | ])); |
| 1639 | let config = { |
| 1640 | let __cw_config_init_18_0 = Some("xai".to_string()); |
| 1641 | let __cw_config_init_18_1 = Some(HashMap::from([( |
| 1642 | "aUtHoRiZaTiOn".to_string(), |
| 1643 | "Bearer configured-secret".to_string(), |
| 1644 | )])); |
| 1645 | let __cw_config_init_18_2 = Some(providers); |
| 1646 | let mut __cw_config_init_18_value: Config = Config::default(); |
| 1647 | __cw_config_init_18_value.provider = __cw_config_init_18_0; |
| 1648 | __cw_config_init_18_value.http_headers = __cw_config_init_18_1; |
| 1649 | __cw_config_init_18_value.providers = __cw_config_init_18_2; |
| 1650 | __cw_config_init_18_value |
| 1651 | }; |
| 1652 | |
| 1653 | assert_eq!(config.active_route_api_key()?, ""); |
| 1654 | assert!( |
| 1655 | has_api_key(&config), |
| 1656 | "no-auth routes are ready without a key" |
| 1657 | ); |
| 1658 | assert!(!active_provider_has_config_api_key(&config)); |
| 1659 | assert!(!active_provider_has_env_api_key(&config)); |
| 1660 | let headers = config.http_headers(); |
| 1661 | for name in [ |
| 1662 | "authorization", |
| 1663 | "x-api-key", |
| 1664 | "api-key", |
| 1665 | "proxy-authorization", |
| 1666 | "x-auth-token", |
| 1667 | "x-access-token", |
| 1668 | "x-goog-api-key", |
| 1669 | "cookie", |
| 1670 | ] { |
| 1671 | assert!( |
| 1672 | !headers |
| 1673 | .keys() |
| 1674 | .any(|candidate| candidate.eq_ignore_ascii_case(name)), |
| 1675 | "disabled auth leaked {name}: {headers:?}" |
| 1676 | ); |
| 1677 | } |
| 1678 | assert_eq!( |
| 1679 | headers.get("X-Route-Metadata").map(String::as_str), |
| 1680 | Some("safe") |
| 1681 | ); |
| 1682 | Ok(()) |
| 1683 | } |
| 1684 | |
| 1685 | #[test] |
| 1686 | fn provider_sentinel_falls_through_to_route_env_then_fixture_store() -> Result<()> { |
| 1687 | let _lock = lock_test_env(); |
| 1688 | let temp_root = tempfile::tempdir()?; |
| 1689 | let _guard = EnvGuard::new(temp_root.path()); |
| 1690 | let codewhale_home = temp_root.path().join("isolated-codewhale"); |
| 1691 | fs::create_dir_all(&codewhale_home)?; |
| 1692 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", &codewhale_home); |
| 1693 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 1694 | let config_path = temp_root.path().join("config.toml"); |
| 1695 | let secrets = codewhale_secrets::Secrets::auto_detect(); |
| 1696 | |
| 1697 | for sentinel in [API_KEYRING_SENTINEL, " __KEYRING__ "] { |
| 1698 | fs::write( |
| 1699 | &config_path, |
| 1700 | format!("provider = \"openai\"\n\n[providers.openai]\napi_key = {sentinel:?}\n"), |
| 1701 | )?; |
| 1702 | let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 1703 | assert_eq!( |
| 1704 | config |
| 1705 | .provider_config() |
| 1706 | .and_then(|entry| entry.api_key.as_deref()) |
| 1707 | .map(classify_config_api_key_value), |
| 1708 | Some(ConfigApiKeyValueKind::SecretStoreSentinel) |
| 1709 | ); |
| 1710 | assert!(!active_provider_has_config_api_key(&config)); |
| 1711 | assert!(!has_api_key_for( |
| 1712 | &config, |
| 1713 | &(config).test_identity_for_kind(ProviderKind::Openai) |
| 1714 | )); |
| 1715 | |
| 1716 | secrets.set("openai", "FIXTURE-STORED-KEY")?; |
| 1717 | assert_eq!( |
| 1718 | config.active_route_api_key()?, |
| 1719 | "FIXTURE-STORED-KEY", |
| 1720 | "{sentinel:?} must fall through to the allowed fixture store" |
| 1721 | ); |
| 1722 | assert!(active_provider_has_config_api_key(&config)); |
| 1723 | assert!(has_api_key_for( |
| 1724 | &config, |
| 1725 | &(config).test_identity_for_kind(ProviderKind::Openai) |
| 1726 | )); |
| 1727 | secrets.delete("openai")?; |
| 1728 | |
| 1729 | let _route_env = EnvVarGuard::set("OFFICIAL_SENTINEL_ROUTE_KEY", "FIXTURE-ENV-KEY"); |
| 1730 | fs::write( |
| 1731 | &config_path, |
| 1732 | format!( |
| 1733 | "provider = \"openai\"\n\n[providers.openai]\napi_key = {sentinel:?}\napi_key_env = \"OFFICIAL_SENTINEL_ROUTE_KEY\"\n" |
| 1734 | ), |
| 1735 | )?; |
| 1736 | let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 1737 | assert_eq!( |
| 1738 | config.active_route_api_key()?, |
| 1739 | "FIXTURE-ENV-KEY", |
| 1740 | "route-bound api_key_env must outrank the store after {sentinel:?}" |
| 1741 | ); |
| 1742 | assert!(!active_provider_has_config_api_key(&config)); |
| 1743 | assert!(active_provider_has_env_api_key(&config)); |
| 1744 | |
| 1745 | fs::write(&config_path, format!("api_key = {sentinel:?}\n"))?; |
| 1746 | let root = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 1747 | assert!(!active_provider_has_config_api_key(&root)); |
| 1748 | assert!(!has_api_key_for( |
| 1749 | &root, |
| 1750 | &(root).test_identity_for_kind(ProviderKind::Deepseek) |
| 1751 | )); |
| 1752 | secrets.set("deepseek", "FIXTURE-DEEPSEEK-STORED-KEY")?; |
| 1753 | assert_eq!( |
| 1754 | root.active_route_api_key()?, |
| 1755 | "FIXTURE-DEEPSEEK-STORED-KEY", |
| 1756 | "root {sentinel:?} must also fall through to the allowed fixture store" |
| 1757 | ); |
| 1758 | assert!(active_provider_has_config_api_key(&root)); |
| 1759 | secrets.delete("deepseek")?; |
| 1760 | } |
| 1761 | Ok(()) |
| 1762 | } |
| 1763 | |
| 1764 | #[test] |
| 1765 | fn custom_route_sentinel_is_never_a_key_and_requires_a_route_binding() -> Result<()> { |
| 1766 | let _lock = lock_test_env(); |
| 1767 | let temp_root = tempfile::tempdir()?; |
| 1768 | let _guard = EnvGuard::new(temp_root.path()); |
| 1769 | let config_path = temp_root.path().join("config.toml"); |
| 1770 | |
| 1771 | for sentinel in [API_KEYRING_SENTINEL, " __KEYRING__ "] { |
| 1772 | fs::write( |
| 1773 | &config_path, |
| 1774 | format!( |
| 1775 | "provider = \"acme\"\n\n[providers.acme]\nkind = \"openai-compatible\"\nbase_url = \"https://acme.example.test/v1\"\nmodel = \"acme-model\"\napi_key = {sentinel:?}\n" |
| 1776 | ), |
| 1777 | )?; |
| 1778 | let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 1779 | assert!(config.should_skip_secret_store_for_provider( |
| 1780 | &config.test_identity_for_kind(ProviderKind::Custom) |
| 1781 | )); |
| 1782 | let error = config |
| 1783 | .active_route_api_key() |
| 1784 | .expect_err("named custom sentinel must not become a bearer key"); |
| 1785 | assert!(error.to_string().contains("must be bound explicitly")); |
| 1786 | assert!(!active_provider_has_config_api_key(&config)); |
| 1787 | assert!(!has_api_key_for( |
| 1788 | &config, |
| 1789 | &(config).test_identity_for_kind(ProviderKind::Custom) |
| 1790 | )); |
| 1791 | |
| 1792 | let _route_env = EnvVarGuard::set("CUSTOM_SENTINEL_ROUTE_KEY", "FIXTURE-CUSTOM-ENV-KEY"); |
| 1793 | fs::write( |
| 1794 | &config_path, |
| 1795 | format!( |
| 1796 | "provider = \"acme\"\n\n[providers.acme]\nkind = \"openai-compatible\"\nbase_url = \"https://acme.example.test/v1\"\nmodel = \"acme-model\"\napi_key = {sentinel:?}\napi_key_env = \"CUSTOM_SENTINEL_ROUTE_KEY\"\n" |
| 1797 | ), |
| 1798 | )?; |
| 1799 | let config = codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 1800 | assert_eq!(config.active_route_api_key()?, "FIXTURE-CUSTOM-ENV-KEY"); |
| 1801 | assert!(!active_provider_has_config_api_key(&config)); |
| 1802 | assert!(active_provider_has_env_api_key(&config)); |
| 1803 | } |
| 1804 | |
| 1805 | fs::write( |
| 1806 | &config_path, |
| 1807 | format!( |
| 1808 | "provider = \"openrouter\"\n\n[providers.openrouter]\nbase_url = \"https://gateway.example.test/v1\"\napi_key = {API_KEYRING_SENTINEL:?}\n" |
| 1809 | ), |
| 1810 | )?; |
| 1811 | let custom_endpoint = codewhale_plugins::providers::load_config(Some(config_path), None)?; |
| 1812 | assert!(custom_endpoint.should_skip_secret_store_for_provider( |
| 1813 | &custom_endpoint.test_identity_for_kind(ProviderKind::Openrouter) |
| 1814 | )); |
| 1815 | assert!(custom_endpoint.active_route_api_key().is_err()); |
| 1816 | assert!(!active_provider_has_config_api_key(&custom_endpoint)); |
| 1817 | assert!(!has_api_key_for( |
| 1818 | &custom_endpoint, |
| 1819 | &(custom_endpoint).test_identity_for_kind(ProviderKind::Openrouter) |
| 1820 | )); |
| 1821 | Ok(()) |
| 1822 | } |
| 1823 | |
| 1824 | #[test] |
| 1825 | fn loopback_deepseek_base_url_runs_without_api_key() -> Result<()> { |
| 1826 | let _lock = lock_test_env(); |
| 1827 | let config = <Config as Default>::default() |
| 1828 | .with_legacy_root(None, Some("http://127.0.0.1:8000/v1".to_string())); |
| 1829 | |
| 1830 | assert_eq!( |
| 1831 | config.active_provider_identity().unwrap().provider, |
| 1832 | ProviderKind::Deepseek |
| 1833 | ); |
| 1834 | assert!(has_api_key(&config)); |
| 1835 | assert_eq!(config.active_route_api_key()?, ""); |
| 1836 | Ok(()) |
| 1837 | } |
| 1838 | |
| 1839 | #[test] |
| 1840 | fn xiaomi_mimo_custom_env_url_does_not_inherit_ambient_key() -> Result<()> { |
| 1841 | let _lock = lock_test_env(); |
| 1842 | let nanos = SystemTime::now() |
| 1843 | .duration_since(UNIX_EPOCH) |
| 1844 | .unwrap() |
| 1845 | .as_nanos(); |
| 1846 | let temp_root = env::temp_dir().join(format!( |
| 1847 | "codewhale-tui-xiaomi-mimo-env-test-{}-{}", |
| 1848 | std::process::id(), |
| 1849 | nanos |
| 1850 | )); |
| 1851 | fs::create_dir_all(&temp_root)?; |
| 1852 | let _guard = EnvGuard::new(&temp_root); |
| 1853 | |
| 1854 | // Safety: test-only environment mutation guarded by a global mutex. |
| 1855 | unsafe { |
| 1856 | env::set_var("DEEPSEEK_PROVIDER", "mimo"); |
| 1857 | env::set_var("MIMO_API_KEY", "mimo-env-key"); |
| 1858 | env::set_var("MIMO_BASE_URL", "https://mimo-gateway.example/v1"); |
| 1859 | env::set_var("MIMO_MODEL", "mimo-v2.5"); |
| 1860 | } |
| 1861 | |
| 1862 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 1863 | assert_eq!( |
| 1864 | config.active_provider_identity().unwrap().provider, |
| 1865 | ProviderKind::XiaomiMimo |
| 1866 | ); |
| 1867 | let error = config |
| 1868 | .active_route_api_key() |
| 1869 | .expect_err("ambient key must not follow a custom endpoint"); |
| 1870 | assert!(error.to_string().contains("must be bound explicitly")); |
| 1871 | assert!(!has_api_key(&config)); |
| 1872 | assert_eq!( |
| 1873 | config.active_route_base_url(), |
| 1874 | "https://mimo-gateway.example/v1" |
| 1875 | ); |
| 1876 | assert_eq!(config.default_model(), "mimo-v2.5"); |
| 1877 | Ok(()) |
| 1878 | } |
| 1879 | |
| 1880 | #[test] |
| 1881 | fn wanjie_ark_custom_env_url_does_not_inherit_ambient_key() -> Result<()> { |
| 1882 | let _lock = lock_test_env(); |
| 1883 | let nanos = SystemTime::now() |
| 1884 | .duration_since(UNIX_EPOCH) |
| 1885 | .unwrap() |
| 1886 | .as_nanos(); |
| 1887 | let temp_root = env::temp_dir().join(format!( |
| 1888 | "codewhale-tui-wanjie-env-test-{}-{}", |
| 1889 | std::process::id(), |
| 1890 | nanos |
| 1891 | )); |
| 1892 | fs::create_dir_all(&temp_root)?; |
| 1893 | let _guard = EnvGuard::new(&temp_root); |
| 1894 | |
| 1895 | unsafe { |
| 1896 | env::set_var("DEEPSEEK_PROVIDER", "ark-wanjie"); |
| 1897 | env::set_var("WANJIE_ARK_API_KEY", "wanjie-env-key"); |
| 1898 | env::set_var("WANJIE_ARK_BASE_URL", "https://wanjie.example/api/v1"); |
| 1899 | env::set_var("WANJIE_ARK_MODEL", "wanjie-model-id"); |
| 1900 | } |
| 1901 | |
| 1902 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 1903 | assert_eq!( |
| 1904 | config.active_provider_identity().unwrap().provider, |
| 1905 | ProviderKind::WanjieArk |
| 1906 | ); |
| 1907 | let error = config |
| 1908 | .active_route_api_key() |
| 1909 | .expect_err("ambient key must not follow a custom endpoint"); |
| 1910 | assert!(error.to_string().contains("must be bound explicitly")); |
| 1911 | assert!(!has_api_key(&config)); |
| 1912 | assert_eq!( |
| 1913 | config.active_route_base_url(), |
| 1914 | "https://wanjie.example/api/v1" |
| 1915 | ); |
| 1916 | assert_eq!(config.default_model(), "wanjie-model-id"); |
| 1917 | Ok(()) |
| 1918 | } |
| 1919 | |
| 1920 | #[test] |
| 1921 | fn openai_custom_env_url_does_not_inherit_ambient_key() -> Result<()> { |
| 1922 | let _lock = lock_test_env(); |
| 1923 | let nanos = SystemTime::now() |
| 1924 | .duration_since(UNIX_EPOCH) |
| 1925 | .unwrap() |
| 1926 | .as_nanos(); |
| 1927 | let temp_root = env::temp_dir().join(format!( |
| 1928 | "codewhale-tui-openai-env-test-{}-{}", |
| 1929 | std::process::id(), |
| 1930 | nanos |
| 1931 | )); |
| 1932 | fs::create_dir_all(&temp_root)?; |
| 1933 | let _guard = EnvGuard::new(&temp_root); |
| 1934 | |
| 1935 | // Safety: test-only environment mutation guarded by a global mutex. |
| 1936 | unsafe { |
| 1937 | env::set_var("DEEPSEEK_PROVIDER", "openai"); |
| 1938 | env::set_var("OPENAI_API_KEY", "openai-env-key"); |
| 1939 | env::set_var("OPENAI_BASE_URL", "https://openai-compatible.example/v4"); |
| 1940 | env::set_var("OPENAI_MODEL", "glm-5"); |
| 1941 | } |
| 1942 | |
| 1943 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 1944 | assert_eq!( |
| 1945 | config.active_provider_identity().unwrap().provider, |
| 1946 | ProviderKind::Openai |
| 1947 | ); |
| 1948 | let error = config |
| 1949 | .active_route_api_key() |
| 1950 | .expect_err("ambient key must not follow a custom endpoint"); |
| 1951 | assert!(error.to_string().contains("must be bound explicitly")); |
| 1952 | assert!(!has_api_key(&config)); |
| 1953 | assert_eq!( |
| 1954 | config.active_route_base_url(), |
| 1955 | "https://openai-compatible.example/v4" |
| 1956 | ); |
| 1957 | assert_eq!(config.default_model(), "glm-5"); |
| 1958 | Ok(()) |
| 1959 | } |
| 1960 | |
| 1961 | #[test] |
| 1962 | fn openai_facade_custom_url_does_not_inherit_ambient_key() -> Result<()> { |
| 1963 | let _lock = lock_test_env(); |
| 1964 | let nanos = SystemTime::now() |
| 1965 | .duration_since(UNIX_EPOCH) |
| 1966 | .unwrap() |
| 1967 | .as_nanos(); |
| 1968 | let temp_root = env::temp_dir().join(format!( |
| 1969 | "codewhale-tui-openai-forwarded-base-url-test-{}-{}", |
| 1970 | std::process::id(), |
| 1971 | nanos |
| 1972 | )); |
| 1973 | fs::create_dir_all(&temp_root)?; |
| 1974 | let _guard = EnvGuard::new(&temp_root); |
| 1975 | |
| 1976 | // Safety: test-only environment mutation guarded by a global mutex. |
| 1977 | unsafe { |
| 1978 | env::set_var("DEEPSEEK_PROVIDER", "openai"); |
| 1979 | env::set_var("OPENAI_API_KEY", "forwarded-openai-key"); |
| 1980 | env::set_var("DEEPSEEK_BASE_URL", "https://forwarded-openai.example/v4"); |
| 1981 | env::set_var("DEEPSEEK_MODEL", "glm-5"); |
| 1982 | } |
| 1983 | |
| 1984 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 1985 | assert_eq!( |
| 1986 | config.active_provider_identity().unwrap().provider, |
| 1987 | ProviderKind::Openai |
| 1988 | ); |
| 1989 | let error = config |
| 1990 | .active_route_api_key() |
| 1991 | .expect_err("ambient key must not follow a custom endpoint"); |
| 1992 | assert!(error.to_string().contains("must be bound explicitly")); |
| 1993 | assert!(!has_api_key(&config)); |
| 1994 | assert_eq!( |
| 1995 | config.active_route_base_url(), |
| 1996 | "https://forwarded-openai.example/v4" |
| 1997 | ); |
| 1998 | assert_eq!(config.default_model(), "glm-5"); |
| 1999 | Ok(()) |
| 2000 | } |
| 2001 | |
| 2002 | #[test] |
| 2003 | fn volcengine_custom_env_url_does_not_inherit_ambient_key() -> Result<()> { |
| 2004 | let _lock = lock_test_env(); |
| 2005 | let nanos = SystemTime::now() |
| 2006 | .duration_since(UNIX_EPOCH) |
| 2007 | .unwrap() |
| 2008 | .as_nanos(); |
| 2009 | let temp_root = env::temp_dir().join(format!( |
| 2010 | "codewhale-tui-volcengine-env-test-{}-{}", |
| 2011 | std::process::id(), |
| 2012 | nanos |
| 2013 | )); |
| 2014 | fs::create_dir_all(&temp_root)?; |
| 2015 | let _guard = EnvGuard::new(&temp_root); |
| 2016 | |
| 2017 | // Safety: test-only environment mutation guarded by a global mutex. |
| 2018 | unsafe { |
| 2019 | env::set_var("DEEPSEEK_PROVIDER", "volcengine"); |
| 2020 | env::set_var("ARK_API_KEY", "volc-env-key"); |
| 2021 | env::set_var("VOLCENGINE_ARK_BASE_URL", "https://volc.example/v1"); |
| 2022 | env::set_var("VOLCENGINE_ARK_MODEL", "DeepSeek-V4-Flash"); |
| 2023 | } |
| 2024 | |
| 2025 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 2026 | assert_eq!( |
| 2027 | config.active_provider_identity().unwrap().provider, |
| 2028 | ProviderKind::Volcengine |
| 2029 | ); |
| 2030 | let error = config |
| 2031 | .active_route_api_key() |
| 2032 | .expect_err("ambient key must not follow a custom endpoint"); |
| 2033 | assert!(error.to_string().contains("must be bound explicitly")); |
| 2034 | assert!(!has_api_key(&config)); |
| 2035 | assert_eq!(config.active_route_base_url(), "https://volc.example/v1"); |
| 2036 | assert_eq!(config.default_model(), "DeepSeek-V4-Flash"); |
| 2037 | Ok(()) |
| 2038 | } |
| 2039 | |
| 2040 | #[test] |
| 2041 | fn sglang_provider_works_without_api_key() -> Result<()> { |
| 2042 | let _lock = lock_test_env(); |
| 2043 | let nanos = SystemTime::now() |
| 2044 | .duration_since(UNIX_EPOCH) |
| 2045 | .unwrap() |
| 2046 | .as_nanos(); |
| 2047 | let temp_root = env::temp_dir().join(format!( |
| 2048 | "codewhale-tui-sglang-defaults-{}-{}", |
| 2049 | std::process::id(), |
| 2050 | nanos |
| 2051 | )); |
| 2052 | fs::create_dir_all(&temp_root)?; |
| 2053 | let _guard = EnvGuard::new(&temp_root); |
| 2054 | |
| 2055 | let config = { |
| 2056 | let __cw_config_init_20_0 = Some("sglang".to_string()); |
| 2057 | let mut __cw_config_init_20_value: Config = Default::default(); |
| 2058 | __cw_config_init_20_value.provider = __cw_config_init_20_0; |
| 2059 | __cw_config_init_20_value |
| 2060 | }; |
| 2061 | config.validate()?; |
| 2062 | assert_eq!( |
| 2063 | config.active_provider_identity().unwrap().provider, |
| 2064 | ProviderKind::Sglang |
| 2065 | ); |
| 2066 | assert_eq!(config.default_model(), DEFAULT_SGLANG_MODEL); |
| 2067 | assert_eq!(config.active_route_base_url(), DEFAULT_SGLANG_BASE_URL); |
| 2068 | assert_eq!(config.active_route_api_key()?, ""); |
| 2069 | assert!(has_api_key_for( |
| 2070 | &config, |
| 2071 | &(config).test_identity_for_kind(ProviderKind::Sglang) |
| 2072 | )); |
| 2073 | Ok(()) |
| 2074 | } |
| 2075 | |
| 2076 | #[test] |
| 2077 | fn ollama_provider_uses_local_defaults_without_api_key() -> Result<()> { |
| 2078 | let _lock = lock_test_env(); |
| 2079 | let nanos = SystemTime::now() |
| 2080 | .duration_since(UNIX_EPOCH) |
| 2081 | .unwrap() |
| 2082 | .as_nanos(); |
| 2083 | let temp_root = env::temp_dir().join(format!( |
| 2084 | "codewhale-tui-ollama-defaults-{}-{}", |
| 2085 | std::process::id(), |
| 2086 | nanos |
| 2087 | )); |
| 2088 | fs::create_dir_all(&temp_root)?; |
| 2089 | let _guard = EnvGuard::new(&temp_root); |
| 2090 | |
| 2091 | let config = { |
| 2092 | let __cw_config_init_21_0 = Some("ollama".to_string()); |
| 2093 | let mut __cw_config_init_21_value: Config = Default::default(); |
| 2094 | __cw_config_init_21_value.provider = __cw_config_init_21_0; |
| 2095 | __cw_config_init_21_value |
| 2096 | }; |
| 2097 | config.validate()?; |
| 2098 | assert_eq!( |
| 2099 | config.active_provider_identity().unwrap().provider, |
| 2100 | ProviderKind::Ollama |
| 2101 | ); |
| 2102 | assert_eq!(config.default_model(), DEFAULT_OLLAMA_MODEL); |
| 2103 | assert_eq!(config.active_route_base_url(), DEFAULT_OLLAMA_BASE_URL); |
| 2104 | assert_eq!(config.active_route_api_key()?, ""); |
| 2105 | assert!(has_api_key_for( |
| 2106 | &config, |
| 2107 | &(config).test_identity_for_kind(ProviderKind::Ollama) |
| 2108 | )); |
| 2109 | Ok(()) |
| 2110 | } |
| 2111 | |
| 2112 | #[test] |
| 2113 | fn ollama_cloud_resolves_env_key_and_is_not_keyless() -> Result<()> { |
| 2114 | let _lock = lock_test_env(); |
| 2115 | let nanos = SystemTime::now() |
| 2116 | .duration_since(UNIX_EPOCH) |
| 2117 | .unwrap() |
| 2118 | .as_nanos(); |
| 2119 | let temp_root = env::temp_dir().join(format!( |
| 2120 | "codewhale-tui-ollama-cloud-env-{}-{}", |
| 2121 | std::process::id(), |
| 2122 | nanos |
| 2123 | )); |
| 2124 | fs::create_dir_all(&temp_root)?; |
| 2125 | let _guard = EnvGuard::new(&temp_root); |
| 2126 | // Safety: test-only environment mutation guarded by a global mutex. |
| 2127 | unsafe { env::set_var("OLLAMA_API_KEY", "ollama-cloud-env-key") }; |
| 2128 | |
| 2129 | let config = { |
| 2130 | let __cw_config_init_22_0 = Some("ollama".to_string()); |
| 2131 | let __cw_config_init_22_1 = Some(ProvidersConfig { |
| 2132 | ollama: ProviderConfig { |
| 2133 | base_url: Some("https://ollama.com/v1/".to_string()), |
| 2134 | ..ProviderConfig::default() |
| 2135 | }, |
| 2136 | ..ProvidersConfig::default() |
| 2137 | }); |
| 2138 | let mut __cw_config_init_22_value: Config = Config::default(); |
| 2139 | __cw_config_init_22_value.provider = __cw_config_init_22_0; |
| 2140 | __cw_config_init_22_value.providers = __cw_config_init_22_1; |
| 2141 | __cw_config_init_22_value |
| 2142 | }; |
| 2143 | |
| 2144 | assert_eq!( |
| 2145 | config.active_provider_identity().unwrap().provider, |
| 2146 | ProviderKind::OllamaCloud |
| 2147 | ); |
| 2148 | assert!(!provider_route_is_keyless_self_hosted( |
| 2149 | ProviderKind::OllamaCloud, |
| 2150 | &config.active_route_base_url() |
| 2151 | )); |
| 2152 | assert_eq!(config.active_route_api_key()?, "ollama-cloud-env-key"); |
| 2153 | assert!(has_api_key_for( |
| 2154 | &config, |
| 2155 | &(config).test_identity_for_kind(ProviderKind::OllamaCloud) |
| 2156 | )); |
| 2157 | Ok(()) |
| 2158 | } |
| 2159 | |
| 2160 | #[test] |
| 2161 | fn ollama_cloud_resolves_saved_provider_key() -> Result<()> { |
| 2162 | let _lock = lock_test_env(); |
| 2163 | let temp_root = tempfile::tempdir()?; |
| 2164 | let _guard = EnvGuard::new(temp_root.path()); |
| 2165 | let codewhale_home = temp_root.path().join("isolated-codewhale"); |
| 2166 | fs::create_dir_all(&codewhale_home)?; |
| 2167 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 2168 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 2169 | |
| 2170 | codewhale_secrets::Secrets::auto_detect().set("ollama", "ollama-cloud-saved-key")?; |
| 2171 | let config = { |
| 2172 | let __cw_config_init_23_0 = Some("ollama".to_string()); |
| 2173 | let __cw_config_init_23_1 = Some(ProvidersConfig { |
| 2174 | ollama: ProviderConfig { |
| 2175 | base_url: Some(codewhale_config::provider::OLLAMA_CLOUD_BASE_URL.to_string()), |
| 2176 | ..ProviderConfig::default() |
| 2177 | }, |
| 2178 | ..ProvidersConfig::default() |
| 2179 | }); |
| 2180 | let mut __cw_config_init_23_value: Config = Config::default(); |
| 2181 | __cw_config_init_23_value.provider = __cw_config_init_23_0; |
| 2182 | __cw_config_init_23_value.providers = __cw_config_init_23_1; |
| 2183 | __cw_config_init_23_value |
| 2184 | }; |
| 2185 | |
| 2186 | assert_eq!( |
| 2187 | config.active_provider_identity().unwrap().provider, |
| 2188 | ProviderKind::OllamaCloud |
| 2189 | ); |
| 2190 | assert_eq!(config.active_route_api_key()?, "ollama-cloud-saved-key"); |
| 2191 | assert!(has_api_key_for( |
| 2192 | &config, |
| 2193 | &(config).test_identity_for_kind(ProviderKind::OllamaCloud) |
| 2194 | )); |
| 2195 | Ok(()) |
| 2196 | } |
| 2197 | |
| 2198 | #[test] |
| 2199 | fn explicit_ollama_cloud_uses_new_secret_slot_without_local_fallback() -> Result<()> { |
| 2200 | let _lock = lock_test_env(); |
| 2201 | let temp_root = tempfile::tempdir()?; |
| 2202 | let _guard = EnvGuard::new(temp_root.path()); |
| 2203 | let codewhale_home = temp_root.path().join("isolated-codewhale"); |
| 2204 | fs::create_dir_all(&codewhale_home)?; |
| 2205 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 2206 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 2207 | |
| 2208 | let secrets = codewhale_secrets::Secrets::auto_detect(); |
| 2209 | secrets.set("ollama", "must-not-be-consumed")?; |
| 2210 | let config = { |
| 2211 | let __cw_config_init_24_0 = Some("ollama-cloud".to_string()); |
| 2212 | let __cw_config_init_24_1 = Some(ProvidersConfig { |
| 2213 | ollama: ProviderConfig { |
| 2214 | base_url: Some(codewhale_config::provider::OLLAMA_CLOUD_BASE_URL.to_string()), |
| 2215 | ..ProviderConfig::default() |
| 2216 | }, |
| 2217 | ..ProvidersConfig::default() |
| 2218 | }); |
| 2219 | let mut __cw_config_init_24_value: Config = Config::default(); |
| 2220 | __cw_config_init_24_value.provider = __cw_config_init_24_0; |
| 2221 | __cw_config_init_24_value.providers = __cw_config_init_24_1; |
| 2222 | __cw_config_init_24_value |
| 2223 | }; |
| 2224 | |
| 2225 | assert_eq!( |
| 2226 | config.active_provider_identity().unwrap().provider, |
| 2227 | ProviderKind::OllamaCloud |
| 2228 | ); |
| 2229 | let identity = config |
| 2230 | .resolve_provider_identity("ollama-cloud") |
| 2231 | .expect("explicit Cloud identity"); |
| 2232 | assert!(!identity.migrated_legacy_ollama_cloud_route()); |
| 2233 | assert!(!has_api_key_for( |
| 2234 | &config, |
| 2235 | &(config).test_identity_for_kind(ProviderKind::OllamaCloud) |
| 2236 | )); |
| 2237 | assert!(config.active_route_api_key().is_err()); |
| 2238 | |
| 2239 | secrets.set("ollama-cloud", "cloud-slot-key")?; |
| 2240 | assert!(has_api_key_for( |
| 2241 | &config, |
| 2242 | &(config).test_identity_for_kind(ProviderKind::OllamaCloud) |
| 2243 | )); |
| 2244 | assert_eq!(config.active_route_api_key()?, "cloud-slot-key"); |
| 2245 | Ok(()) |
| 2246 | } |
| 2247 | |
| 2248 | #[test] |
| 2249 | fn ollama_cloud_without_key_fails_with_cloud_guidance() -> Result<()> { |
| 2250 | let _lock = lock_test_env(); |
| 2251 | let nanos = SystemTime::now() |
| 2252 | .duration_since(UNIX_EPOCH) |
| 2253 | .unwrap() |
| 2254 | .as_nanos(); |
| 2255 | let temp_root = env::temp_dir().join(format!( |
| 2256 | "codewhale-tui-ollama-cloud-missing-key-{}-{}", |
| 2257 | std::process::id(), |
| 2258 | nanos |
| 2259 | )); |
| 2260 | fs::create_dir_all(&temp_root)?; |
| 2261 | let _guard = EnvGuard::new(&temp_root); |
| 2262 | |
| 2263 | let config = { |
| 2264 | let __cw_config_init_25_0 = Some("ollama".to_string()); |
| 2265 | let __cw_config_init_25_1 = Some(ProvidersConfig { |
| 2266 | ollama: ProviderConfig { |
| 2267 | base_url: Some("https://ollama.com/v1".to_string()), |
| 2268 | ..ProviderConfig::default() |
| 2269 | }, |
| 2270 | ..ProvidersConfig::default() |
| 2271 | }); |
| 2272 | let mut __cw_config_init_25_value: Config = Config::default(); |
| 2273 | __cw_config_init_25_value.provider = __cw_config_init_25_0; |
| 2274 | __cw_config_init_25_value.providers = __cw_config_init_25_1; |
| 2275 | __cw_config_init_25_value |
| 2276 | }; |
| 2277 | |
| 2278 | assert_eq!( |
| 2279 | config.active_provider_identity().unwrap().provider, |
| 2280 | ProviderKind::OllamaCloud |
| 2281 | ); |
| 2282 | assert!(!has_api_key_for( |
| 2283 | &config, |
| 2284 | &(config).test_identity_for_kind(ProviderKind::OllamaCloud) |
| 2285 | )); |
| 2286 | let error = config |
| 2287 | .active_route_api_key() |
| 2288 | .expect_err("Ollama Cloud must require an API key"); |
| 2289 | let message = error.to_string(); |
| 2290 | assert!(message.contains("Ollama Cloud API key not found")); |
| 2291 | assert!(message.contains("https://ollama.com/settings/keys")); |
| 2292 | assert!(message.contains("OLLAMA_CLOUD_API_KEY / OLLAMA_API_KEY")); |
| 2293 | Ok(()) |
| 2294 | } |
| 2295 | |
| 2296 | #[test] |
| 2297 | fn ollama_custom_remote_does_not_inherit_cloud_env_key() -> Result<()> { |
| 2298 | let _lock = lock_test_env(); |
| 2299 | let nanos = SystemTime::now() |
| 2300 | .duration_since(UNIX_EPOCH) |
| 2301 | .unwrap() |
| 2302 | .as_nanos(); |
| 2303 | let temp_root = env::temp_dir().join(format!( |
| 2304 | "codewhale-tui-ollama-custom-remote-{}-{}", |
| 2305 | std::process::id(), |
| 2306 | nanos |
| 2307 | )); |
| 2308 | fs::create_dir_all(&temp_root)?; |
| 2309 | let _guard = EnvGuard::new(&temp_root); |
| 2310 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 2311 | // Safety: test-only environment mutation guarded by a global mutex. |
| 2312 | unsafe { env::set_var("OLLAMA_API_KEY", "must-not-cross-routes") }; |
| 2313 | codewhale_secrets::Secrets::auto_detect().set("ollama", "must-not-cross-routes-either")?; |
| 2314 | |
| 2315 | let config = { |
| 2316 | let __cw_config_init_26_0 = Some("ollama".to_string()); |
| 2317 | let __cw_config_init_26_1 = Some(ProvidersConfig { |
| 2318 | ollama: ProviderConfig { |
| 2319 | base_url: Some("https://ollama-gateway.example/v1".to_string()), |
| 2320 | ..ProviderConfig::default() |
| 2321 | }, |
| 2322 | ..ProvidersConfig::default() |
| 2323 | }); |
| 2324 | let mut __cw_config_init_26_value: Config = Config::default(); |
| 2325 | __cw_config_init_26_value.provider = __cw_config_init_26_0; |
| 2326 | __cw_config_init_26_value.providers = __cw_config_init_26_1; |
| 2327 | __cw_config_init_26_value |
| 2328 | }; |
| 2329 | |
| 2330 | assert!( |
| 2331 | config.provider_uses_custom_endpoint(&config.test_identity_for_kind(ProviderKind::Ollama)) |
| 2332 | ); |
| 2333 | assert!(!has_api_key_for( |
| 2334 | &config, |
| 2335 | &(config).test_identity_for_kind(ProviderKind::Ollama) |
| 2336 | )); |
| 2337 | let error = config |
| 2338 | .active_route_api_key() |
| 2339 | .expect_err("custom remote must bind its credential explicitly"); |
| 2340 | assert!( |
| 2341 | error |
| 2342 | .to_string() |
| 2343 | .contains("Custom endpoint credentials for ollama must be bound explicitly") |
| 2344 | ); |
| 2345 | Ok(()) |
| 2346 | } |
| 2347 | |
| 2348 | #[test] |
| 2349 | fn siliconflow_custom_env_url_does_not_inherit_ambient_key() -> Result<()> { |
| 2350 | let _lock = lock_test_env(); |
| 2351 | let nanos = SystemTime::now() |
| 2352 | .duration_since(UNIX_EPOCH) |
| 2353 | .unwrap() |
| 2354 | .as_nanos(); |
| 2355 | let temp_root = env::temp_dir().join(format!( |
| 2356 | "codewhale-tui-siliconflow-env-test-{}-{}", |
| 2357 | std::process::id(), |
| 2358 | nanos |
| 2359 | )); |
| 2360 | fs::create_dir_all(&temp_root)?; |
| 2361 | let _guard = EnvGuard::new(&temp_root); |
| 2362 | |
| 2363 | // Safety: test-only environment mutation guarded by a global mutex. |
| 2364 | unsafe { |
| 2365 | env::set_var("CODEWHALE_PROVIDER", "siliconflow"); |
| 2366 | env::set_var("SILICONFLOW_API_KEY", "sf-env-key"); |
| 2367 | env::set_var("SILICONFLOW_BASE_URL", "https://sf-mirror.example/v1"); |
| 2368 | env::set_var("SILICONFLOW_MODEL", "deepseek-v4-flash"); |
| 2369 | } |
| 2370 | |
| 2371 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 2372 | assert_eq!( |
| 2373 | config.active_provider_identity().unwrap().provider, |
| 2374 | ProviderKind::Siliconflow |
| 2375 | ); |
| 2376 | let error = config |
| 2377 | .active_route_api_key() |
| 2378 | .expect_err("ambient key must not follow a custom endpoint"); |
| 2379 | assert!(error.to_string().contains("must be bound explicitly")); |
| 2380 | assert!(!has_api_key(&config)); |
| 2381 | assert_eq!( |
| 2382 | config.active_route_base_url(), |
| 2383 | "https://sf-mirror.example/v1" |
| 2384 | ); |
| 2385 | assert_eq!(config.default_model(), "deepseek-v4-flash"); |
| 2386 | Ok(()) |
| 2387 | } |
| 2388 | |
| 2389 | #[test] |
| 2390 | fn arcee_custom_env_url_does_not_inherit_ambient_key() -> Result<()> { |
| 2391 | let _lock = lock_test_env(); |
| 2392 | let nanos = SystemTime::now() |
| 2393 | .duration_since(UNIX_EPOCH) |
| 2394 | .unwrap() |
| 2395 | .as_nanos(); |
| 2396 | let temp_root = env::temp_dir().join(format!( |
| 2397 | "codewhale-tui-arcee-env-test-{}-{}", |
| 2398 | std::process::id(), |
| 2399 | nanos |
| 2400 | )); |
| 2401 | fs::create_dir_all(&temp_root)?; |
| 2402 | let _guard = EnvGuard::new(&temp_root); |
| 2403 | |
| 2404 | unsafe { |
| 2405 | env::set_var("CODEWHALE_PROVIDER", "arcee"); |
| 2406 | env::set_var("ARCEE_API_KEY", "arcee-env-key"); |
| 2407 | env::set_var("ARCEE_BASE_URL", "https://arcee-mirror.example/api/v1"); |
| 2408 | env::set_var("ARCEE_MODEL", "arcee-trinity-large-preview"); |
| 2409 | } |
| 2410 | |
| 2411 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 2412 | assert_eq!( |
| 2413 | config.active_provider_identity().unwrap().provider, |
| 2414 | ProviderKind::Arcee |
| 2415 | ); |
| 2416 | let error = config |
| 2417 | .active_route_api_key() |
| 2418 | .expect_err("ambient key must not follow a custom endpoint"); |
| 2419 | assert!(error.to_string().contains("must be bound explicitly")); |
| 2420 | assert!(!has_api_key(&config)); |
| 2421 | assert_eq!( |
| 2422 | config.active_route_base_url(), |
| 2423 | "https://arcee-mirror.example/api/v1" |
| 2424 | ); |
| 2425 | assert_eq!(config.default_model(), "arcee-trinity-large-preview"); |
| 2426 | Ok(()) |
| 2427 | } |
| 2428 | |
| 2429 | #[test] |
| 2430 | fn siliconflow_cn_reads_hyphenated_provider_table_from_config_file() -> Result<()> { |
| 2431 | let _lock = lock_test_env(); |
| 2432 | let nanos = SystemTime::now() |
| 2433 | .duration_since(UNIX_EPOCH) |
| 2434 | .unwrap() |
| 2435 | .as_nanos(); |
| 2436 | let temp_root = env::temp_dir().join(format!( |
| 2437 | "codewhale-tui-siliconflow-cn-table-{}-{}", |
| 2438 | std::process::id(), |
| 2439 | nanos |
| 2440 | )); |
| 2441 | fs::create_dir_all(&temp_root)?; |
| 2442 | let _guard = EnvGuard::new(&temp_root); |
| 2443 | |
| 2444 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 2445 | ensure_parent_dir(&config_path)?; |
| 2446 | fs::write( |
| 2447 | &config_path, |
| 2448 | r#"provider = "siliconflow-CN" |
| 2449 | |
| 2450 | [providers.siliconflow-CN] |
| 2451 | api_key = "sf-cn-table-key" |
| 2452 | base_url = "https://api.siliconflow.cn/v1" |
| 2453 | model = "deepseek-reasoner" |
| 2454 | "#, |
| 2455 | )?; |
| 2456 | |
| 2457 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 2458 | assert_eq!( |
| 2459 | config.active_provider_identity().unwrap().provider, |
| 2460 | ProviderKind::SiliconflowCN |
| 2461 | ); |
| 2462 | assert_eq!(config.active_route_api_key()?, "sf-cn-table-key"); |
| 2463 | assert_eq!( |
| 2464 | config.active_route_base_url(), |
| 2465 | DEFAULT_SILICONFLOW_CN_BASE_URL |
| 2466 | ); |
| 2467 | assert_eq!(config.default_model(), DEFAULT_SILICONFLOW_MODEL); |
| 2468 | assert!(has_api_key_for( |
| 2469 | &config, |
| 2470 | &(config).test_identity_for_kind(ProviderKind::SiliconflowCN) |
| 2471 | )); |
| 2472 | Ok(()) |
| 2473 | } |
| 2474 | |
| 2475 | #[test] |
| 2476 | fn moonshot_kimi_import_is_api_key_only_and_never_reads_external_credentials() -> Result<()> { |
| 2477 | let _lock = lock_test_env(); |
| 2478 | let nanos = SystemTime::now() |
| 2479 | .duration_since(UNIX_EPOCH) |
| 2480 | .unwrap() |
| 2481 | .as_nanos(); |
| 2482 | let temp_root = env::temp_dir().join(format!( |
| 2483 | "codewhale-tui-kimi-code-oauth-key-{}-{}", |
| 2484 | std::process::id(), |
| 2485 | nanos |
| 2486 | )); |
| 2487 | fs::create_dir_all(&temp_root)?; |
| 2488 | let _guard = EnvGuard::new(&temp_root); |
| 2489 | |
| 2490 | let kimi_code_home = temp_root.join(".kimi-code"); |
| 2491 | let credential_dir = kimi_code_home.join("credentials"); |
| 2492 | fs::create_dir_all(&credential_dir)?; |
| 2493 | unsafe { env::set_var("KIMI_CODE_HOME", &kimi_code_home) }; |
| 2494 | |
| 2495 | let credential = json!({ |
| 2496 | "access_token": "must-never-be-read", |
| 2497 | "refresh_token": "must-never-be-used", |
| 2498 | "expires_at": SystemTime::now() |
| 2499 | .duration_since(UNIX_EPOCH)? |
| 2500 | .as_secs_f64() |
| 2501 | + 3600.0, |
| 2502 | "scope": "openid profile email", |
| 2503 | "token_type": "Bearer", |
| 2504 | }); |
| 2505 | let credential_path = credential_dir.join("kimi-code.json"); |
| 2506 | let credential_raw = serde_json::to_string(&credential)?; |
| 2507 | fs::write(&credential_path, &credential_raw)?; |
| 2508 | |
| 2509 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 2510 | ensure_parent_dir(&config_path)?; |
| 2511 | fs::write( |
| 2512 | &config_path, |
| 2513 | r#"provider = "moonshot" |
| 2514 | |
| 2515 | [providers.moonshot] |
| 2516 | auth_mode = "kimi_oauth" |
| 2517 | api_key = "stale-api-key" |
| 2518 | "#, |
| 2519 | )?; |
| 2520 | |
| 2521 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 2522 | assert_eq!( |
| 2523 | config.active_provider_identity().unwrap().provider, |
| 2524 | ProviderKind::Moonshot |
| 2525 | ); |
| 2526 | assert_eq!(config.active_route_base_url(), DEFAULT_KIMI_CODE_BASE_URL); |
| 2527 | assert_eq!(config.default_model(), DEFAULT_KIMI_CODE_MODEL); |
| 2528 | let error = config |
| 2529 | .active_route_api_key() |
| 2530 | .expect_err("Kimi external OAuth credentials are never imported"); |
| 2531 | assert!(error.to_string().contains("does not impersonate")); |
| 2532 | assert!( |
| 2533 | error |
| 2534 | .to_string() |
| 2535 | .contains(codewhale_config::provider::KIMI_CODE_MEMBERSHIP_PLAN_CONSOLE_URL) |
| 2536 | ); |
| 2537 | assert!( |
| 2538 | !error |
| 2539 | .to_string() |
| 2540 | .contains("https://platform.kimi.ai/console/api-keys") |
| 2541 | ); |
| 2542 | assert!(!has_api_key_for( |
| 2543 | &config, |
| 2544 | &(config).test_identity_for_kind(ProviderKind::Moonshot) |
| 2545 | )); |
| 2546 | assert_eq!( |
| 2547 | fs::read_to_string(credential_path)?, |
| 2548 | credential_raw, |
| 2549 | "Codewhale must never read, refresh, or rewrite Kimi CLI credentials" |
| 2550 | ); |
| 2551 | Ok(()) |
| 2552 | } |
| 2553 | |
| 2554 | #[test] |
| 2555 | fn codex_external_credentials_are_disabled_by_default_and_managed_fails_before_io() -> Result<()> { |
| 2556 | let _lock = lock_test_env(); |
| 2557 | let temp = tempfile::tempdir()?; |
| 2558 | let temp_root = temp.path().canonicalize()?; |
| 2559 | let auth_path = temp_root.join("codex-auth.json"); |
| 2560 | let token = crate::test_support::future_test_jwt("codex"); |
| 2561 | let raw = serde_json::to_string_pretty(&json!({ |
| 2562 | "tokens": { |
| 2563 | "access_token": token.clone(), |
| 2564 | "account_id": "acct-must-not-be-read", |
| 2565 | "refresh_token": "must-never-be-used" |
| 2566 | }, |
| 2567 | "unknown": {"preserve": true} |
| 2568 | }))?; |
| 2569 | fs::write(&auth_path, &raw)?; |
| 2570 | let ambient_decoy = temp_root.join("ambient-decoy.json"); |
| 2571 | let ambient_decoy_raw = r#"{"tokens":{"access_token":"must-not-be-read"}}"#; |
| 2572 | fs::write(&ambient_decoy, ambient_decoy_raw)?; |
| 2573 | let _auth_path = EnvVarGuard::set("OPENAI_CODEX_AUTH_FILE", &ambient_decoy); |
| 2574 | let _access = EnvVarGuard::remove("OPENAI_CODEX_ACCESS_TOKEN"); |
| 2575 | let _legacy_access = EnvVarGuard::remove("CODEX_ACCESS_TOKEN"); |
| 2576 | let _account = EnvVarGuard::remove("OPENAI_CODEX_ACCOUNT_ID"); |
| 2577 | let _legacy_account = EnvVarGuard::remove("CODEX_ACCOUNT_ID"); |
| 2578 | |
| 2579 | let disabled = { |
| 2580 | let __cw_config_init_27_0 = Some(ProviderKind::OpenaiCodex.as_str().to_string()); |
| 2581 | let mut __cw_config_init_27_value: Config = Default::default(); |
| 2582 | __cw_config_init_27_value.provider = __cw_config_init_27_0; |
| 2583 | __cw_config_init_27_value |
| 2584 | }; |
| 2585 | codewhale_runtime::external_credentials::reset_side_effect_trap(); |
| 2586 | assert!(!has_api_key_for( |
| 2587 | &disabled, |
| 2588 | &(disabled).test_identity_for_kind(ProviderKind::OpenaiCodex) |
| 2589 | )); |
| 2590 | let error = disabled |
| 2591 | .active_route_api_key() |
| 2592 | .expect_err("external credentials default to disabled"); |
| 2593 | assert!(error.to_string().contains("Sign in with ChatGPT")); |
| 2594 | assert_eq!(disabled.codex_account_id(), None); |
| 2595 | assert_eq!( |
| 2596 | codewhale_runtime::external_credentials::side_effect_trap_counts(), |
| 2597 | (0, 0) |
| 2598 | ); |
| 2599 | |
| 2600 | let mut managed_consent = codewhale_config::ExternalCredentialConsentToml::read_only( |
| 2601 | codewhale_config::ProviderKind::OpenaiCodex, |
| 2602 | codewhale_config::ExternalCredentialSource::CodexCli, |
| 2603 | auth_path.clone(), |
| 2604 | ); |
| 2605 | managed_consent.access = codewhale_config::ExternalCredentialAccess::Managed; |
| 2606 | let managed = { |
| 2607 | let __cw_config_init_28_0 = Some(ProviderKind::OpenaiCodex.as_str().to_string()); |
| 2608 | let __cw_config_init_28_1 = Some(ProvidersConfig { |
| 2609 | openai_codex: ProviderConfig { |
| 2610 | auth_mode: Some("oauth".to_string()), |
| 2611 | external_credentials: Some(managed_consent), |
| 2612 | ..Default::default() |
| 2613 | }, |
| 2614 | ..Default::default() |
| 2615 | }); |
| 2616 | let mut __cw_config_init_28_value: Config = Default::default(); |
| 2617 | __cw_config_init_28_value.provider = __cw_config_init_28_0; |
| 2618 | __cw_config_init_28_value.providers = __cw_config_init_28_1; |
| 2619 | __cw_config_init_28_value |
| 2620 | }; |
| 2621 | codewhale_runtime::external_credentials::reset_side_effect_trap(); |
| 2622 | assert!(!has_api_key_for( |
| 2623 | &managed, |
| 2624 | &(managed).test_identity_for_kind(ProviderKind::OpenaiCodex) |
| 2625 | )); |
| 2626 | let error = managed |
| 2627 | .active_route_api_key() |
| 2628 | .expect_err("managed access needs a preservation adapter"); |
| 2629 | assert!(error.to_string().contains("Sign in with ChatGPT")); |
| 2630 | assert_eq!( |
| 2631 | codewhale_runtime::external_credentials::side_effect_trap_counts(), |
| 2632 | (0, 0) |
| 2633 | ); |
| 2634 | assert_eq!(fs::read_to_string(&auth_path)?, raw); |
| 2635 | Ok(()) |
| 2636 | } |
| 2637 | |
| 2638 | #[test] |
| 2639 | fn moonshot_kimi_code_api_key_uses_coding_model() -> Result<()> { |
| 2640 | let _lock = lock_test_env(); |
| 2641 | let nanos = SystemTime::now() |
| 2642 | .duration_since(UNIX_EPOCH) |
| 2643 | .unwrap() |
| 2644 | .as_nanos(); |
| 2645 | let temp_root = env::temp_dir().join(format!( |
| 2646 | "codewhale-tui-kimi-code-key-{}-{}", |
| 2647 | std::process::id(), |
| 2648 | nanos |
| 2649 | )); |
| 2650 | fs::create_dir_all(&temp_root)?; |
| 2651 | let _guard = EnvGuard::new(&temp_root); |
| 2652 | |
| 2653 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 2654 | ensure_parent_dir(&config_path)?; |
| 2655 | fs::write( |
| 2656 | &config_path, |
| 2657 | r#"provider = "moonshot" |
| 2658 | |
| 2659 | [providers.moonshot] |
| 2660 | api_key = "kimi-code-key" |
| 2661 | base_url = "https://api.kimi.com/coding/v1" |
| 2662 | "#, |
| 2663 | )?; |
| 2664 | |
| 2665 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 2666 | assert_eq!( |
| 2667 | config.active_provider_identity().unwrap().provider, |
| 2668 | ProviderKind::Moonshot |
| 2669 | ); |
| 2670 | assert_eq!(config.active_route_base_url(), DEFAULT_KIMI_CODE_BASE_URL); |
| 2671 | assert_eq!(config.default_model(), DEFAULT_KIMI_CODE_MODEL); |
| 2672 | assert_eq!(config.active_route_api_key()?, "kimi-code-key"); |
| 2673 | assert!(has_api_key_for( |
| 2674 | &config, |
| 2675 | &(config).test_identity_for_kind(ProviderKind::Moonshot) |
| 2676 | )); |
| 2677 | Ok(()) |
| 2678 | } |
| 2679 | |
| 2680 | /// Env-var-only path: `CODEWHALE_BASE_URL=https://api.kimi.com/coding/v1` |
| 2681 | /// combined with `CODEWHALE_PROVIDER=moonshot` must trigger Kimi Code |
| 2682 | /// model selection even when the TOML has no `base_url`. |
| 2683 | #[test] |
| 2684 | fn moonshot_kimi_code_env_base_url_selects_coding_model() -> Result<()> { |
| 2685 | let _lock = lock_test_env(); |
| 2686 | let nanos = SystemTime::now() |
| 2687 | .duration_since(UNIX_EPOCH) |
| 2688 | .unwrap() |
| 2689 | .as_nanos(); |
| 2690 | let temp_root = env::temp_dir().join(format!( |
| 2691 | "codewhale-tui-kimi-code-env-url-{}-{}", |
| 2692 | std::process::id(), |
| 2693 | nanos |
| 2694 | )); |
| 2695 | fs::create_dir_all(&temp_root)?; |
| 2696 | let _guard = EnvGuard::new(&temp_root); |
| 2697 | |
| 2698 | let config_path = temp_root.join(".deepseek").join("config.toml"); |
| 2699 | ensure_parent_dir(&config_path)?; |
| 2700 | fs::write( |
| 2701 | &config_path, |
| 2702 | r#"[providers.moonshot] |
| 2703 | api_key = "kimi-code-env-key" |
| 2704 | "#, |
| 2705 | )?; |
| 2706 | // Safety: test-only env mutation guarded by lock_test_env(). |
| 2707 | unsafe { |
| 2708 | env::set_var("CODEWHALE_PROVIDER", "moonshot"); |
| 2709 | env::set_var("CODEWHALE_BASE_URL", "https://api.kimi.com/coding/v1"); |
| 2710 | } |
| 2711 | |
| 2712 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 2713 | assert_eq!( |
| 2714 | config.active_provider_identity().unwrap().provider, |
| 2715 | ProviderKind::Moonshot |
| 2716 | ); |
| 2717 | assert_eq!(config.active_route_base_url(), DEFAULT_KIMI_CODE_BASE_URL); |
| 2718 | assert_eq!(config.default_model(), DEFAULT_KIMI_CODE_MODEL); |
| 2719 | assert_eq!(config.active_route_api_key()?, "kimi-code-env-key"); |
| 2720 | assert!(has_api_key_for( |
| 2721 | &config, |
| 2722 | &(config).test_identity_for_kind(ProviderKind::Moonshot) |
| 2723 | )); |
| 2724 | Ok(()) |
| 2725 | } |
| 2726 | |
| 2727 | #[test] |
| 2728 | fn has_api_key_for_detects_env_and_config_per_provider() -> Result<()> { |
| 2729 | let _lock = lock_test_env(); |
| 2730 | let nanos = SystemTime::now() |
| 2731 | .duration_since(UNIX_EPOCH) |
| 2732 | .unwrap() |
| 2733 | .as_nanos(); |
| 2734 | let temp_root = env::temp_dir().join(format!( |
| 2735 | "codewhale-tui-has-key-{}-{}", |
| 2736 | std::process::id(), |
| 2737 | nanos |
| 2738 | )); |
| 2739 | fs::create_dir_all(&temp_root)?; |
| 2740 | let _guard = EnvGuard::new(&temp_root); |
| 2741 | |
| 2742 | let mut config = Config::default(); |
| 2743 | assert!(!has_api_key_for( |
| 2744 | &config, |
| 2745 | &(config).test_identity_for_kind(ProviderKind::Openai) |
| 2746 | )); |
| 2747 | assert!(!has_api_key_for( |
| 2748 | &config, |
| 2749 | &(config).test_identity_for_kind(ProviderKind::WanjieArk) |
| 2750 | )); |
| 2751 | assert!(!has_api_key_for( |
| 2752 | &config, |
| 2753 | &(config).test_identity_for_kind(ProviderKind::Volcengine) |
| 2754 | )); |
| 2755 | assert!(!has_api_key_for( |
| 2756 | &config, |
| 2757 | &(config).test_identity_for_kind(ProviderKind::Openrouter) |
| 2758 | )); |
| 2759 | assert!(!has_api_key_for( |
| 2760 | &config, |
| 2761 | &(config).test_identity_for_kind(ProviderKind::XiaomiMimo) |
| 2762 | )); |
| 2763 | assert!(!has_api_key_for( |
| 2764 | &config, |
| 2765 | &(config).test_identity_for_kind(ProviderKind::Siliconflow) |
| 2766 | )); |
| 2767 | assert!( |
| 2768 | has_api_key_for( |
| 2769 | &config, |
| 2770 | &(config).test_identity_for_kind(ProviderKind::Sglang) |
| 2771 | ), |
| 2772 | "SGLang is self-hosted and does not require a key by default" |
| 2773 | ); |
| 2774 | assert!( |
| 2775 | has_api_key_for( |
| 2776 | &config, |
| 2777 | &(config).test_identity_for_kind(ProviderKind::Vllm) |
| 2778 | ), |
| 2779 | "vLLM is self-hosted and does not require a key by default" |
| 2780 | ); |
| 2781 | |
| 2782 | // Safety: test-only environment mutation guarded by a global mutex. |
| 2783 | unsafe { |
| 2784 | env::set_var("OPENROUTER_API_KEY", "or-env"); |
| 2785 | env::set_var("OPENAI_API_KEY", "openai-env"); |
| 2786 | env::set_var("WANJIE_API_KEY", "wanjie-env"); |
| 2787 | env::set_var("ARK_API_KEY", "volc-env"); |
| 2788 | env::set_var("MIMO_API_KEY", "mimo-env"); |
| 2789 | env::set_var("SILICONFLOW_API_KEY", "sf-env"); |
| 2790 | } |
| 2791 | assert!(has_api_key_for( |
| 2792 | &config, |
| 2793 | &(config).test_identity_for_kind(ProviderKind::Openai) |
| 2794 | )); |
| 2795 | assert!(has_api_key_for( |
| 2796 | &config, |
| 2797 | &(config).test_identity_for_kind(ProviderKind::WanjieArk) |
| 2798 | )); |
| 2799 | assert!(has_api_key_for( |
| 2800 | &config, |
| 2801 | &(config).test_identity_for_kind(ProviderKind::Volcengine) |
| 2802 | )); |
| 2803 | assert!(has_api_key_for( |
| 2804 | &config, |
| 2805 | &(config).test_identity_for_kind(ProviderKind::Openrouter) |
| 2806 | )); |
| 2807 | assert!(has_api_key_for( |
| 2808 | &config, |
| 2809 | &(config).test_identity_for_kind(ProviderKind::XiaomiMimo) |
| 2810 | )); |
| 2811 | assert!(has_api_key_for( |
| 2812 | &config, |
| 2813 | &(config).test_identity_for_kind(ProviderKind::Siliconflow) |
| 2814 | )); |
| 2815 | assert!(!has_api_key_for( |
| 2816 | &config, |
| 2817 | &(config).test_identity_for_kind(ProviderKind::Novita) |
| 2818 | )); |
| 2819 | |
| 2820 | // Safety: test-only environment mutation guarded by a global mutex. |
| 2821 | unsafe { |
| 2822 | env::remove_var("OPENROUTER_API_KEY"); |
| 2823 | env::remove_var("OPENAI_API_KEY"); |
| 2824 | env::remove_var("WANJIE_API_KEY"); |
| 2825 | env::remove_var("ARK_API_KEY"); |
| 2826 | env::remove_var("MIMO_API_KEY"); |
| 2827 | env::remove_var("SILICONFLOW_API_KEY"); |
| 2828 | } |
| 2829 | let mut providers = ProvidersConfig::default(); |
| 2830 | providers.openai.api_key = Some("file-openai".to_string()); |
| 2831 | providers.wanjie_ark.api_key = Some("file-wanjie".to_string()); |
| 2832 | providers.xiaomi_mimo.api_key = Some("file-mimo".to_string()); |
| 2833 | providers.novita.api_key = Some("file-novita".to_string()); |
| 2834 | providers.siliconflow.api_key = Some("file-siliconflow".to_string()); |
| 2835 | config.providers = Some(providers); |
| 2836 | assert!(has_api_key_for( |
| 2837 | &config, |
| 2838 | &(config).test_identity_for_kind(ProviderKind::Openai) |
| 2839 | )); |
| 2840 | assert!(has_api_key_for( |
| 2841 | &config, |
| 2842 | &(config).test_identity_for_kind(ProviderKind::WanjieArk) |
| 2843 | )); |
| 2844 | assert!(has_api_key_for( |
| 2845 | &config, |
| 2846 | &(config).test_identity_for_kind(ProviderKind::XiaomiMimo) |
| 2847 | )); |
| 2848 | assert!(has_api_key_for( |
| 2849 | &config, |
| 2850 | &(config).test_identity_for_kind(ProviderKind::Novita) |
| 2851 | )); |
| 2852 | assert!(has_api_key_for( |
| 2853 | &config, |
| 2854 | &(config).test_identity_for_kind(ProviderKind::Siliconflow) |
| 2855 | )); |
| 2856 | assert!(!has_api_key_for( |
| 2857 | &config, |
| 2858 | &(config).test_identity_for_kind(ProviderKind::Openrouter) |
| 2859 | )); |
| 2860 | Ok(()) |
| 2861 | } |
| 2862 | |
| 2863 | #[test] |
| 2864 | fn provider_auth_source_metadata_is_not_a_runtime_credential() -> Result<()> { |
| 2865 | let _lock = lock_test_env(); |
| 2866 | let temp_root = tempfile::tempdir()?; |
| 2867 | let _guard = EnvGuard::new(temp_root.path()); |
| 2868 | let mut providers = ProvidersConfig::default(); |
| 2869 | providers.openai.auth = Some(codewhale_config::ProviderAuthSourceToml { |
| 2870 | source: codewhale_config::AuthSourceKind::Command, |
| 2871 | command: vec!["secret-tool".to_string(), "lookup".to_string()], |
| 2872 | timeout_ms: Some(2000), |
| 2873 | secret_id: None, |
| 2874 | }); |
| 2875 | let config = { |
| 2876 | let __cw_config_init_29_0 = Some("openai".to_string()); |
| 2877 | let __cw_config_init_29_1 = Some(providers); |
| 2878 | let mut __cw_config_init_29_value: Config = Config::default(); |
| 2879 | __cw_config_init_29_value.provider = __cw_config_init_29_0; |
| 2880 | __cw_config_init_29_value.providers = __cw_config_init_29_1; |
| 2881 | __cw_config_init_29_value |
| 2882 | }; |
| 2883 | |
| 2884 | assert!(!has_api_key_for( |
| 2885 | &config, |
| 2886 | &(config).test_identity_for_kind(ProviderKind::Openai) |
| 2887 | )); |
| 2888 | assert!(config.active_route_api_key().is_err()); |
| 2889 | Ok(()) |
| 2890 | } |
| 2891 | |
| 2892 | #[test] |
| 2893 | fn xai_oauth_selection_falls_back_to_explicit_api_key_without_external_io() -> Result<()> { |
| 2894 | let _lock = lock_test_env(); |
| 2895 | let nanos = SystemTime::now() |
| 2896 | .duration_since(UNIX_EPOCH) |
| 2897 | .unwrap() |
| 2898 | .as_nanos(); |
| 2899 | let temp_root = env::temp_dir().join(format!( |
| 2900 | "codewhale-tui-xai-auth-{}-{}", |
| 2901 | std::process::id(), |
| 2902 | nanos |
| 2903 | )); |
| 2904 | fs::create_dir_all(&temp_root)?; |
| 2905 | let auth_path = temp_root.join("auth.json"); |
| 2906 | let _auth_path = EnvVarGuard::set("GROK_AUTH_PATH", auth_path.as_os_str()); |
| 2907 | let _xai_key = EnvVarGuard::remove("XAI_API_KEY"); |
| 2908 | |
| 2909 | let mut providers = ProvidersConfig::default(); |
| 2910 | providers.xai.api_key = Some("fake-xai-cfg-key".to_string()); |
| 2911 | providers.xai.auth_mode = Some("oauth".to_string()); |
| 2912 | let api_key_config = { |
| 2913 | let __cw_config_init_30_0 = Some("xai".to_string()); |
| 2914 | let __cw_config_init_30_1 = Some(providers); |
| 2915 | let mut __cw_config_init_30_value: Config = Config::default(); |
| 2916 | __cw_config_init_30_value.provider = __cw_config_init_30_0; |
| 2917 | __cw_config_init_30_value.providers = __cw_config_init_30_1; |
| 2918 | __cw_config_init_30_value |
| 2919 | }; |
| 2920 | codewhale_runtime::external_credentials::reset_side_effect_trap(); |
| 2921 | assert!(has_api_key_for( |
| 2922 | &api_key_config, |
| 2923 | &(api_key_config).test_identity_for_kind(ProviderKind::Xai) |
| 2924 | )); |
| 2925 | assert_eq!(api_key_config.active_route_api_key()?, "fake-xai-cfg-key"); |
| 2926 | assert_eq!( |
| 2927 | codewhale_runtime::external_credentials::side_effect_trap_counts(), |
| 2928 | (0, 0) |
| 2929 | ); |
| 2930 | |
| 2931 | fs::write(&auth_path, "{}")?; |
| 2932 | assert!(!has_api_key_for( |
| 2933 | &Config::default(), |
| 2934 | &(Config::default()).test_identity_for_kind(ProviderKind::Xai) |
| 2935 | )); |
| 2936 | fs::remove_dir_all(temp_root)?; |
| 2937 | Ok(()) |
| 2938 | } |
| 2939 | |
| 2940 | #[test] |
| 2941 | fn modelstudio_variants_share_one_secret_slot_and_key_availability() -> Result<()> { |
| 2942 | let _lock = lock_test_env(); |
| 2943 | let temp_root = tempfile::tempdir()?; |
| 2944 | let _guard = EnvGuard::new(temp_root.path()); |
| 2945 | let codewhale_home = temp_root.path().join("codewhale-home"); |
| 2946 | let config_path = codewhale_home.join("config.toml"); |
| 2947 | let _codewhale_home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 2948 | let _config_path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 2949 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 2950 | let _ms_env = EnvVarGuard::remove("MODELSTUDIO_API_KEY"); |
| 2951 | let _dashscope_env = EnvVarGuard::remove("DASHSCOPE_API_KEY"); |
| 2952 | let _cli_source = EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 2953 | let _cli_key = EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 2954 | |
| 2955 | let variants = [ |
| 2956 | ProviderKind::ModelstudioTokenPlan, |
| 2957 | ProviderKind::ModelstudioTokenPlanAnthropic, |
| 2958 | ProviderKind::ModelstudioCodingPlan, |
| 2959 | ProviderKind::ModelstudioCodingPlanAnthropic, |
| 2960 | ]; |
| 2961 | for variant in variants { |
| 2962 | assert_eq!( |
| 2963 | provider_secret_store_slot(variant), |
| 2964 | "modelstudio-token-plan", |
| 2965 | "{variant:?} must share the family's one credential slot" |
| 2966 | ); |
| 2967 | } |
| 2968 | |
| 2969 | // Saving on the Token Plan variant writes the single family slot only. |
| 2970 | save_api_key_for(ProviderKind::ModelstudioTokenPlan, "ms-family-key")?; |
| 2971 | let secrets = codewhale_secrets::Secrets::auto_detect(); |
| 2972 | assert_eq!( |
| 2973 | secrets.get("modelstudio-token-plan")?, |
| 2974 | Some("ms-family-key".to_string()) |
| 2975 | ); |
| 2976 | assert_eq!(secrets.get("modelstudio-coding-plan")?, None); |
| 2977 | |
| 2978 | // Every variant — active or not — resolves the family key, so the picker |
| 2979 | // badge stops showing three bogus "missing key" rows after one save. |
| 2980 | let inactive_variants = |
| 2981 | codewhale_plugins::providers::load_config(Some(config_path.clone()), None)?; |
| 2982 | for variant in variants { |
| 2983 | assert_eq!( |
| 2984 | provider_secret_store_api_key( |
| 2985 | &inactive_variants, |
| 2986 | &(inactive_variants).test_identity_for_kind(variant) |
| 2987 | ) |
| 2988 | .as_deref(), |
| 2989 | Some("ms-family-key"), |
| 2990 | "{variant:?} must read the family slot" |
| 2991 | ); |
| 2992 | assert!( |
| 2993 | has_api_key_for( |
| 2994 | &inactive_variants, |
| 2995 | &(inactive_variants).test_identity_for_kind(variant) |
| 2996 | ), |
| 2997 | "{variant:?} key-availability badge must resolve the family key" |
| 2998 | ); |
| 2999 | } |
| 3000 | |
| 3001 | // Saving on any sibling variant overwrites the same shared slot. |
| 3002 | save_api_key_for( |
| 3003 | ProviderKind::ModelstudioCodingPlanAnthropic, |
| 3004 | "ms-family-key-v2", |
| 3005 | )?; |
| 3006 | assert_eq!( |
| 3007 | secrets.get("modelstudio-token-plan")?, |
| 3008 | Some("ms-family-key-v2".to_string()) |
| 3009 | ); |
| 3010 | assert_eq!(secrets.get("modelstudio-coding-plan-anthropic")?, None); |
| 3011 | let reloaded = codewhale_plugins::providers::load_config(Some(config_path), None)?; |
| 3012 | for variant in variants { |
| 3013 | assert_eq!( |
| 3014 | provider_secret_store_api_key(&reloaded, &(reloaded).test_identity_for_kind(variant)) |
| 3015 | .as_deref(), |
| 3016 | Some("ms-family-key-v2"), |
| 3017 | "{variant:?} must follow the family slot across saves" |
| 3018 | ); |
| 3019 | } |
| 3020 | Ok(()) |
| 3021 | } |
| 3022 | |
| 3023 | // ======================================================================== |
| 3024 | // Provider Capability Matrix tests |
| 3025 | // ======================================================================== |
| 3026 | |
| 3027 | #[test] |
| 3028 | fn provider_capability_scenario() { |
| 3029 | // Scenario consolidation of: provider_capability_deepseek_v4_pro_has_1m_window_and_thinking, provider_capability_deepseek_anthropic_uses_messages_payload, provider_capability_openmodel_uses_messages_payload, provider_capability_deepseek_v4_flash_has_1m_window_and_thinking, provider_capability_deepseek_chat_alias_has_v4_flash_caps_and_metadata, provider_capability_deepseek_reasoner_alias_has_v4_flash_caps_and_metadata, provider_capability_deepseek_v4_flash_has_no_alias_deprecation, provider_capability_nvidia_nim_v4_pro_maps_correctly |
| 3030 | // from provider_capability_deepseek_v4_pro_has_1m_window_and_thinking |
| 3031 | { |
| 3032 | let cap = provider_capability(ProviderKind::Deepseek, "deepseek-v4-pro"); |
| 3033 | assert_eq!( |
| 3034 | cap.context_window, |
| 3035 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3036 | ); |
| 3037 | assert_eq!(cap.max_output, Some(384_000)); |
| 3038 | assert!(cap.thinking_supported); |
| 3039 | assert!(cap.cache_telemetry_supported); |
| 3040 | assert_eq!( |
| 3041 | cap.request_payload_mode, |
| 3042 | RequestPayloadMode::ChatCompletions |
| 3043 | ); |
| 3044 | } |
| 3045 | // from provider_capability_deepseek_anthropic_uses_messages_payload |
| 3046 | { |
| 3047 | let cap = provider_capability( |
| 3048 | ProviderKind::DeepseekAnthropic, |
| 3049 | DEFAULT_DEEPSEEK_ANTHROPIC_MODEL, |
| 3050 | ); |
| 3051 | assert_eq!( |
| 3052 | cap.context_window, |
| 3053 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3054 | ); |
| 3055 | assert_eq!(cap.max_output, Some(384_000)); |
| 3056 | assert!(cap.thinking_supported); |
| 3057 | assert!(!cap.cache_telemetry_supported); |
| 3058 | assert_eq!( |
| 3059 | cap.request_payload_mode, |
| 3060 | RequestPayloadMode::AnthropicMessages |
| 3061 | ); |
| 3062 | assert!(cap.alias_deprecation.is_none()); |
| 3063 | } |
| 3064 | // from provider_capability_openmodel_uses_messages_payload |
| 3065 | { |
| 3066 | let cap = provider_capability(ProviderKind::Openmodel, DEFAULT_OPENMODEL_MODEL); |
| 3067 | assert_eq!(cap.resolved_model, DEFAULT_OPENMODEL_MODEL); |
| 3068 | assert_eq!( |
| 3069 | cap.context_window, |
| 3070 | codewhale_models::context_window_for_model(DEFAULT_OPENMODEL_MODEL).unwrap_or(200_000) |
| 3071 | ); |
| 3072 | assert_eq!( |
| 3073 | cap.max_output, |
| 3074 | Some( |
| 3075 | codewhale_models::max_output_tokens_for_model(DEFAULT_OPENMODEL_MODEL) |
| 3076 | .unwrap_or(64_000) |
| 3077 | ) |
| 3078 | ); |
| 3079 | assert!(!cap.cache_telemetry_supported); |
| 3080 | assert_eq!( |
| 3081 | cap.request_payload_mode, |
| 3082 | RequestPayloadMode::AnthropicMessages |
| 3083 | ); |
| 3084 | assert!( |
| 3085 | codewhale_config::descriptors::provider_passes_model_through(ProviderKind::Openmodel) |
| 3086 | ); |
| 3087 | } |
| 3088 | // from provider_capability_deepseek_v4_flash_has_1m_window_and_thinking |
| 3089 | { |
| 3090 | let cap = provider_capability(ProviderKind::Deepseek, "deepseek-v4-flash"); |
| 3091 | assert_eq!( |
| 3092 | cap.context_window, |
| 3093 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3094 | ); |
| 3095 | assert_eq!(cap.max_output, Some(384_000)); |
| 3096 | assert!(cap.thinking_supported); |
| 3097 | assert!(cap.cache_telemetry_supported); |
| 3098 | } |
| 3099 | // from provider_capability_deepseek_chat_alias_has_v4_flash_caps_and_metadata |
| 3100 | { |
| 3101 | let cap = provider_capability(ProviderKind::Deepseek, "deepseek-chat"); |
| 3102 | assert_eq!( |
| 3103 | cap.context_window, |
| 3104 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3105 | ); |
| 3106 | assert_eq!(cap.max_output, Some(384_000)); |
| 3107 | assert!(cap.thinking_supported); |
| 3108 | assert!(cap.cache_telemetry_supported); |
| 3109 | |
| 3110 | let deprecation = cap |
| 3111 | .alias_deprecation |
| 3112 | .as_ref() |
| 3113 | .expect("alias deprecation metadata"); |
| 3114 | assert_eq!(deprecation.alias, "deepseek-chat"); |
| 3115 | assert_eq!(deprecation.replacement, "deepseek-flash"); |
| 3116 | assert_eq!(deprecation.retirement_date, "2026-07-24"); |
| 3117 | assert_eq!(deprecation.retirement_utc, "2026-07-24T15:59:00Z"); |
| 3118 | } |
| 3119 | // from provider_capability_deepseek_reasoner_alias_has_v4_flash_caps_and_metadata |
| 3120 | { |
| 3121 | let cap = provider_capability(ProviderKind::Deepseek, "deepseek-reasoner"); |
| 3122 | assert_eq!( |
| 3123 | cap.context_window, |
| 3124 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3125 | ); |
| 3126 | assert_eq!(cap.max_output, Some(384_000)); |
| 3127 | assert!(cap.thinking_supported); |
| 3128 | assert!(cap.cache_telemetry_supported); |
| 3129 | |
| 3130 | let deprecation = cap |
| 3131 | .alias_deprecation |
| 3132 | .as_ref() |
| 3133 | .expect("alias deprecation metadata"); |
| 3134 | assert_eq!(deprecation.alias, "deepseek-reasoner"); |
| 3135 | assert_eq!(deprecation.replacement, "deepseek-flash"); |
| 3136 | } |
| 3137 | // from provider_capability_deepseek_v4_flash_has_no_alias_deprecation |
| 3138 | { |
| 3139 | let cap = provider_capability(ProviderKind::Deepseek, "deepseek-v4-flash"); |
| 3140 | assert!(cap.alias_deprecation.is_none()); |
| 3141 | } |
| 3142 | // from provider_capability_nvidia_nim_v4_pro_maps_correctly |
| 3143 | { |
| 3144 | let cap = provider_capability(ProviderKind::NvidiaNim, DEFAULT_NVIDIA_NIM_MODEL); |
| 3145 | assert_eq!( |
| 3146 | cap.context_window, |
| 3147 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3148 | ); |
| 3149 | assert_eq!(cap.max_output, Some(384_000)); |
| 3150 | assert!(cap.thinking_supported); |
| 3151 | assert!(cap.cache_telemetry_supported); |
| 3152 | assert_eq!( |
| 3153 | cap.request_payload_mode, |
| 3154 | RequestPayloadMode::ChatCompletions |
| 3155 | ); |
| 3156 | } |
| 3157 | } |
| 3158 | |
| 3159 | #[test] |
| 3160 | fn provider_capability_scenario_2() { |
| 3161 | // Scenario consolidation of: provider_capability_nvidia_nim_v4_flash_maps_correctly, provider_capability_openai_codex_uses_responses_payload, provider_capability_marks_exact_inkling_route_as_reasoning, provider_capability_xiaomi_mimo_has_thinking_no_cache, provider_capability_novita_v4_pro_has_thinking_no_cache, provider_capability_fireworks_v4_pro_has_thinking_no_cache, provider_capability_siliconflow_v4_pro_has_thinking_no_cache, provider_capability_sglang_v4_pro_has_thinking_no_cache |
| 3162 | // from provider_capability_nvidia_nim_v4_flash_maps_correctly |
| 3163 | { |
| 3164 | let cap = provider_capability(ProviderKind::NvidiaNim, DEFAULT_NVIDIA_NIM_FLASH_MODEL); |
| 3165 | assert_eq!( |
| 3166 | cap.context_window, |
| 3167 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3168 | ); |
| 3169 | assert_eq!(cap.max_output, Some(384_000)); |
| 3170 | assert!(cap.thinking_supported); |
| 3171 | assert!(cap.cache_telemetry_supported); |
| 3172 | } |
| 3173 | // from provider_capability_openai_codex_uses_responses_payload |
| 3174 | { |
| 3175 | let cap = provider_capability(ProviderKind::OpenaiCodex, DEFAULT_OPENAI_CODEX_MODEL); |
| 3176 | assert_eq!(cap.provider, ProviderKind::OpenaiCodex); |
| 3177 | assert_eq!(cap.resolved_model, DEFAULT_OPENAI_CODEX_MODEL); |
| 3178 | assert_eq!( |
| 3179 | cap.context_window, |
| 3180 | OPENAI_CODEX_EFFECTIVE_CONTEXT_WINDOW_TOKENS |
| 3181 | ); |
| 3182 | assert_eq!(cap.max_output, Some(4096)); |
| 3183 | assert!(cap.thinking_supported); |
| 3184 | assert!(!cap.cache_telemetry_supported); |
| 3185 | assert_eq!(cap.request_payload_mode, RequestPayloadMode::Responses); |
| 3186 | } |
| 3187 | // from provider_capability_marks_exact_inkling_route_as_reasoning |
| 3188 | { |
| 3189 | let cap = provider_capability(ProviderKind::Together, TOGETHER_INKLING_MODEL); |
| 3190 | assert!(cap.thinking_supported); |
| 3191 | assert_eq!( |
| 3192 | codewhale_models::context_window_for_model(TOGETHER_INKLING_MODEL), |
| 3193 | None |
| 3194 | ); |
| 3195 | assert_eq!( |
| 3196 | codewhale_models::max_output_tokens_for_model(TOGETHER_INKLING_MODEL), |
| 3197 | None |
| 3198 | ); |
| 3199 | } |
| 3200 | // from provider_capability_xiaomi_mimo_has_thinking_and_cache |
| 3201 | { |
| 3202 | let cap = provider_capability(ProviderKind::XiaomiMimo, DEFAULT_XIAOMI_MIMO_MODEL); |
| 3203 | assert_eq!(cap.context_window, 1_048_576); |
| 3204 | assert_eq!(cap.max_output, Some(131_072)); |
| 3205 | assert!(cap.thinking_supported); |
| 3206 | assert!(cap.cache_telemetry_supported); |
| 3207 | assert_eq!( |
| 3208 | cap.request_payload_mode, |
| 3209 | RequestPayloadMode::ChatCompletions |
| 3210 | ); |
| 3211 | |
| 3212 | let omni = provider_capability(ProviderKind::XiaomiMimo, XIAOMI_MIMO_V2_6_FLASH_MODEL); |
| 3213 | assert_eq!(omni.context_window, 1_048_576); |
| 3214 | assert_eq!(omni.max_output, Some(131_072)); |
| 3215 | assert!(omni.thinking_supported); |
| 3216 | assert!(omni.cache_telemetry_supported); |
| 3217 | } |
| 3218 | // from provider_capability_novita_v4_pro_has_thinking_and_cache_rate |
| 3219 | { |
| 3220 | let cap = provider_capability(ProviderKind::Novita, DEFAULT_NOVITA_MODEL); |
| 3221 | assert_eq!( |
| 3222 | cap.context_window, |
| 3223 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3224 | ); |
| 3225 | assert_eq!(cap.max_output, Some(384_000)); |
| 3226 | assert!(cap.thinking_supported); |
| 3227 | assert!(cap.cache_telemetry_supported); |
| 3228 | } |
| 3229 | // from provider_capability_fireworks_v4_pro_has_thinking_and_cache_rate |
| 3230 | { |
| 3231 | let cap = provider_capability(ProviderKind::Fireworks, DEFAULT_FIREWORKS_MODEL); |
| 3232 | assert_eq!( |
| 3233 | cap.context_window, |
| 3234 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3235 | ); |
| 3236 | assert_eq!(cap.max_output, Some(384_000)); |
| 3237 | assert!(cap.thinking_supported); |
| 3238 | assert!(cap.cache_telemetry_supported); |
| 3239 | |
| 3240 | // Only the exact provider-owned bundled row supplies this ceiling. |
| 3241 | // Neighboring IDs and a different provider cannot inherit its limit. |
| 3242 | for (provider, model) in [ |
| 3243 | ( |
| 3244 | ProviderKind::Fireworks, |
| 3245 | "accounts/fireworks/models/deepseek-v4.1-flash-expires-on-0910", |
| 3246 | ), |
| 3247 | ( |
| 3248 | ProviderKind::Fireworks, |
| 3249 | "accounts/fireworks/models/deepseek-v4-pro-custom", |
| 3250 | ), |
| 3251 | (ProviderKind::Deepseek, DEFAULT_FIREWORKS_MODEL), |
| 3252 | ] { |
| 3253 | assert_eq!( |
| 3254 | provider_capability(provider, model).max_output, |
| 3255 | None, |
| 3256 | "{model}" |
| 3257 | ); |
| 3258 | } |
| 3259 | } |
| 3260 | // from provider_capability_siliconflow_v4_pro_has_thinking_and_cache_rate |
| 3261 | { |
| 3262 | let cap = provider_capability(ProviderKind::Siliconflow, DEFAULT_SILICONFLOW_MODEL); |
| 3263 | assert_eq!( |
| 3264 | cap.context_window, |
| 3265 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3266 | ); |
| 3267 | assert_eq!(cap.max_output, Some(384_000)); |
| 3268 | assert!(cap.thinking_supported); |
| 3269 | assert!(cap.cache_telemetry_supported); |
| 3270 | assert_eq!( |
| 3271 | cap.request_payload_mode, |
| 3272 | RequestPayloadMode::ChatCompletions |
| 3273 | ); |
| 3274 | } |
| 3275 | // from provider_capability_sglang_v4_pro_has_thinking_no_cache |
| 3276 | { |
| 3277 | let cap = provider_capability(ProviderKind::Sglang, DEFAULT_SGLANG_MODEL); |
| 3278 | assert_eq!( |
| 3279 | cap.context_window, |
| 3280 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3281 | ); |
| 3282 | assert_eq!(cap.max_output, Some(384_000)); |
| 3283 | assert!(cap.thinking_supported); |
| 3284 | assert!(!cap.cache_telemetry_supported); |
| 3285 | } |
| 3286 | } |
| 3287 | |
| 3288 | #[test] |
| 3289 | fn provider_capability_openrouter_v4_pro_has_thinking_and_cache() { |
| 3290 | let cap = provider_capability(ProviderKind::Openrouter, DEFAULT_OPENROUTER_MODEL); |
| 3291 | assert_eq!( |
| 3292 | cap.context_window, |
| 3293 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3294 | ); |
| 3295 | assert_eq!(cap.max_output, Some(384_000)); |
| 3296 | assert!(cap.thinking_supported); |
| 3297 | assert!(cap.cache_telemetry_supported); |
| 3298 | assert_eq!( |
| 3299 | cap.request_payload_mode, |
| 3300 | RequestPayloadMode::ChatCompletions |
| 3301 | ); |
| 3302 | } |
| 3303 | |
| 3304 | #[test] |
| 3305 | fn provider_capability_openrouter_recent_large_models_are_reasoning_aware() { |
| 3306 | for (model, expected_window, expected_output) in [ |
| 3307 | ( |
| 3308 | OPENROUTER_ARCEE_TRINITY_LARGE_THINKING_MODEL, |
| 3309 | 262_144, |
| 3310 | 262_144, |
| 3311 | ), |
| 3312 | (OPENROUTER_QWEN_3_6_FLASH_MODEL, 1_000_000, 65_536), |
| 3313 | // Output caps vendor-verified at 65,536 (MODEL_PROVIDER_AUDIT A2/D-7). |
| 3314 | (OPENROUTER_QWEN_3_6_35B_A3B_MODEL, 262_144, 65_536), |
| 3315 | (OPENROUTER_QWEN_3_6_MAX_PREVIEW_MODEL, 262_144, 65_536), |
| 3316 | (OPENROUTER_QWEN_3_6_27B_MODEL, 262_144, 65_536), |
| 3317 | (OPENROUTER_QWEN_3_6_PLUS_MODEL, 1_000_000, 65_536), |
| 3318 | (OPENROUTER_XIAOMI_MIMO_V2_5_PRO_MODEL, 1_000_000, 131_072), |
| 3319 | (OPENROUTER_MINIMAX_M3_MODEL, 1_000_000, 524_288), |
| 3320 | (OPENROUTER_MINIMAX_M2_7_MODEL, 204_800, 131_072), |
| 3321 | (OPENROUTER_GLM_5_1_MODEL, 202_752, 131_072), |
| 3322 | (OPENROUTER_GLM_5_2_MODEL, 1_000_000, 131_072), |
| 3323 | (OPENROUTER_NEMOTRON_3_ULTRA_MODEL, 1_000_000, 16_384), |
| 3324 | ] { |
| 3325 | let cap = provider_capability(ProviderKind::Openrouter, model); |
| 3326 | |
| 3327 | assert_eq!(cap.context_window, expected_window); |
| 3328 | assert_eq!(cap.max_output, Some(expected_output)); |
| 3329 | assert!(cap.thinking_supported); |
| 3330 | assert!(cap.cache_telemetry_supported); |
| 3331 | assert_eq!( |
| 3332 | cap.request_payload_mode, |
| 3333 | RequestPayloadMode::ChatCompletions |
| 3334 | ); |
| 3335 | } |
| 3336 | } |
| 3337 | |
| 3338 | #[test] |
| 3339 | fn provider_capability_arcee_direct_models_use_api_docs_shape() { |
| 3340 | let thinking_cap = provider_capability(ProviderKind::Arcee, DEFAULT_ARCEE_MODEL); |
| 3341 | assert_eq!(thinking_cap.context_window, 262_144); |
| 3342 | assert_eq!(thinking_cap.max_output, Some(262_144)); |
| 3343 | assert!(thinking_cap.thinking_supported); |
| 3344 | assert!(thinking_cap.cache_telemetry_supported); |
| 3345 | assert_eq!( |
| 3346 | thinking_cap.request_payload_mode, |
| 3347 | RequestPayloadMode::ChatCompletions |
| 3348 | ); |
| 3349 | |
| 3350 | let preview = provider_capability(ProviderKind::Arcee, ARCEE_TRINITY_LARGE_PREVIEW_MODEL); |
| 3351 | assert_eq!(preview.context_window, 262_144); |
| 3352 | assert_eq!(preview.max_output, None); |
| 3353 | assert!(!preview.thinking_supported); |
| 3354 | |
| 3355 | let mini = provider_capability(ProviderKind::Arcee, ARCEE_TRINITY_MINI_MODEL); |
| 3356 | assert_eq!(mini.context_window, 128_000); |
| 3357 | // Trinity Mini's upstream output limit is unknown, and ProviderCapability |
| 3358 | // now says so instead of fabricating a 4K request fallback. |
| 3359 | assert_eq!(mini.max_output, None); |
| 3360 | assert_eq!( |
| 3361 | codewhale_models::max_output_tokens_for_model(ARCEE_TRINITY_MINI_MODEL), |
| 3362 | None |
| 3363 | ); |
| 3364 | assert!(mini.thinking_supported); |
| 3365 | assert!(!mini.cache_telemetry_supported); |
| 3366 | assert_eq!( |
| 3367 | mini.request_payload_mode, |
| 3368 | RequestPayloadMode::ChatCompletions |
| 3369 | ); |
| 3370 | } |
| 3371 | |
| 3372 | #[test] |
| 3373 | fn provider_capability_scenario_3() { |
| 3374 | // Scenario consolidation of: provider_capability_openai_custom_model_is_chat_completions_without_thinking, provider_capability_atlascloud_v4_model_resolves_model_metadata, provider_capability_moonshot_default_model_resolves_kimi_metadata, provider_capability_minimax_anthropic_uses_messages_shape, provider_capability_wanjie_ark_reasoner_has_thinking_no_cache, provider_capability_mistral_matches_reasoning_model_contract, provider_capability_ollama_deepseek_tag_uses_deepseek_heuristic, provider_capability_ollama_unknown_model_falls_back_to_8192 |
| 3375 | // from provider_capability_openai_custom_model_is_chat_completions_without_thinking |
| 3376 | { |
| 3377 | let cap = provider_capability(ProviderKind::Openai, "glm-5"); |
| 3378 | assert_eq!( |
| 3379 | cap.context_window, |
| 3380 | codewhale_models::LEGACY_DEEPSEEK_CONTEXT_WINDOW_TOKENS |
| 3381 | ); |
| 3382 | assert_eq!(cap.max_output, None); |
| 3383 | assert!(!cap.thinking_supported); |
| 3384 | assert!(cap.cache_telemetry_supported); |
| 3385 | assert_eq!( |
| 3386 | cap.request_payload_mode, |
| 3387 | RequestPayloadMode::ChatCompletions |
| 3388 | ); |
| 3389 | } |
| 3390 | // from provider_capability_atlascloud_v4_model_resolves_model_metadata |
| 3391 | { |
| 3392 | // #3023: Atlascloud uses the generic model-based path, so its default |
| 3393 | // DeepSeek V4 model resolves the real V4 metadata instead of the old |
| 3394 | // hardcoded legacy floor. |
| 3395 | let cap = provider_capability(ProviderKind::Atlascloud, "deepseek-ai/deepseek-v4-flash"); |
| 3396 | assert_eq!( |
| 3397 | cap.context_window, |
| 3398 | codewhale_models::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS |
| 3399 | ); |
| 3400 | assert_eq!(cap.max_output, Some(384_000)); |
| 3401 | assert!(cap.thinking_supported); |
| 3402 | assert!(!cap.cache_telemetry_supported); |
| 3403 | assert_eq!( |
| 3404 | cap.request_payload_mode, |
| 3405 | RequestPayloadMode::ChatCompletions |
| 3406 | ); |
| 3407 | } |
| 3408 | // from provider_capability_moonshot_default_model_resolves_kimi_metadata |
| 3409 | { |
| 3410 | let cap = provider_capability(ProviderKind::Moonshot, DEFAULT_MOONSHOT_MODEL); |
| 3411 | assert_eq!(cap.context_window, 262_144); |
| 3412 | assert_eq!(cap.max_output, Some(32_768)); |
| 3413 | assert!(cap.thinking_supported); |
| 3414 | assert!(cap.cache_telemetry_supported); |
| 3415 | assert_eq!( |
| 3416 | cap.request_payload_mode, |
| 3417 | RequestPayloadMode::ChatCompletions |
| 3418 | ); |
| 3419 | } |
| 3420 | // from provider_capability_minimax_anthropic_uses_messages_shape |
| 3421 | { |
| 3422 | for model in [DEFAULT_MINIMAX_MODEL, MINIMAX_M2_7_MODEL] { |
| 3423 | let cap = provider_capability(ProviderKind::MinimaxAnthropic, model); |
| 3424 | assert!(cap.thinking_supported, "{model}"); |
| 3425 | assert!(cap.cache_telemetry_supported, "{model}"); |
| 3426 | assert_eq!( |
| 3427 | cap.request_payload_mode, |
| 3428 | RequestPayloadMode::AnthropicMessages |
| 3429 | ); |
| 3430 | } |
| 3431 | } |
| 3432 | // from provider_capability_wanjie_ark_reasoner_has_thinking_no_cache |
| 3433 | { |
| 3434 | let cap = provider_capability(ProviderKind::WanjieArk, DEFAULT_WANJIE_ARK_MODEL); |
| 3435 | assert_eq!( |
| 3436 | cap.context_window, |
| 3437 | codewhale_models::LEGACY_DEEPSEEK_CONTEXT_WINDOW_TOKENS |
| 3438 | ); |
| 3439 | assert_eq!(cap.max_output, None); |
| 3440 | assert!(cap.thinking_supported); |
| 3441 | assert!(!cap.cache_telemetry_supported); |
| 3442 | assert_eq!( |
| 3443 | cap.request_payload_mode, |
| 3444 | RequestPayloadMode::ChatCompletions |
| 3445 | ); |
| 3446 | } |
| 3447 | // from provider_capability_mistral_matches_reasoning_model_contract |
| 3448 | { |
| 3449 | for model in ["mistral-medium-latest", "mistral-small-latest"] { |
| 3450 | let cap = provider_capability(ProviderKind::Mistral, model); |
| 3451 | assert_eq!(cap.context_window, 262_144, "{model}"); |
| 3452 | assert!(cap.thinking_supported, "{model}"); |
| 3453 | assert_eq!( |
| 3454 | cap.request_payload_mode, |
| 3455 | RequestPayloadMode::ChatCompletions |
| 3456 | ); |
| 3457 | } |
| 3458 | for model in ["mistral-code-latest", "mistral-large-latest"] { |
| 3459 | let cap = provider_capability(ProviderKind::Mistral, model); |
| 3460 | assert!(!cap.thinking_supported, "{model}"); |
| 3461 | } |
| 3462 | } |
| 3463 | // Unknown local tags retain an explicitly conservative budget. |
| 3464 | { |
| 3465 | // A family name does not establish this deployment's context window. |
| 3466 | let cap = provider_capability(ProviderKind::Ollama, "deepseek-v3.1:671b"); |
| 3467 | assert_eq!(cap.context_window, 8192); |
| 3468 | assert_eq!( |
| 3469 | codewhale_models::context_window_for_model("deepseek-v3.1:671b"), |
| 3470 | None |
| 3471 | ); |
| 3472 | assert_eq!(cap.max_output, None); |
| 3473 | assert!(!cap.thinking_supported); |
| 3474 | assert!(!cap.cache_telemetry_supported); |
| 3475 | assert_eq!( |
| 3476 | cap.request_payload_mode, |
| 3477 | RequestPayloadMode::ChatCompletions |
| 3478 | ); |
| 3479 | } |
| 3480 | // from provider_capability_ollama_unknown_model_falls_back_to_8192 |
| 3481 | { |
| 3482 | let cap = provider_capability(ProviderKind::Ollama, "llama3.2:3b"); |
| 3483 | assert_eq!(cap.context_window, 8192); |
| 3484 | assert_eq!(cap.max_output, None); |
| 3485 | assert!(!cap.thinking_supported); |
| 3486 | assert!(!cap.cache_telemetry_supported); |
| 3487 | assert_eq!( |
| 3488 | cap.request_payload_mode, |
| 3489 | RequestPayloadMode::ChatCompletions |
| 3490 | ); |
| 3491 | } |
| 3492 | } |
| 3493 | |
| 3494 | #[test] |
| 3495 | fn provider_capability_kimi_membership_ids_report_unknown_output_ceiling() { |
| 3496 | // The `kimi-for-coding` family is membership-only: the membership catalog |
| 3497 | // owns its output limits, so the static matrix must say "unknown" rather |
| 3498 | // than fabricating a ceiling. A placeholder here is not cosmetic — it |
| 3499 | // becomes a hard request clamp in `route_budget`. |
| 3500 | for model in ["kimi-for-coding", "kimi-for-coding-highspeed"] { |
| 3501 | let cap = provider_capability(ProviderKind::Moonshot, model); |
| 3502 | assert_eq!(cap.context_window, 262_144, "{model}"); |
| 3503 | assert_eq!(cap.max_output, None, "{model}"); |
| 3504 | assert!(cap.thinking_supported, "{model}"); |
| 3505 | |
| 3506 | // Unknown is *omitted* on the wire, never serialized as a number. |
| 3507 | let json = serde_json::to_value(&cap).expect("capability serializes"); |
| 3508 | assert!( |
| 3509 | json.get("max_output").is_none(), |
| 3510 | "{model}: unknown output ceiling must not be serialized: {json}" |
| 3511 | ); |
| 3512 | let round_tripped: ProviderCapability = |
| 3513 | serde_json::from_value(json).expect("capability round-trips with an absent max_output"); |
| 3514 | assert_eq!(round_tripped, cap, "{model}"); |
| 3515 | } |
| 3516 | |
| 3517 | // The direct-platform K2.7 Code route does publish 32K, and keeps it. |
| 3518 | assert_eq!( |
| 3519 | provider_capability(ProviderKind::Moonshot, "kimi-k2.7-code").max_output, |
| 3520 | Some(32_768) |
| 3521 | ); |
| 3522 | } |
| 3523 | |
| 3524 | #[test] |
| 3525 | fn provider_capability_zai_defaults_to_5_3_and_tracks_5_2_5_1_and_turbo() { |
| 3526 | // GLM-5.3 is now the default direct Z.AI model; its limits inherit from |
| 3527 | // GLM-5.2 (1M context window) until Z.ai publishes distinct 5.3 numbers. |
| 3528 | let default = provider_capability(ProviderKind::Zai, DEFAULT_ZAI_MODEL); |
| 3529 | assert_eq!(default.resolved_model, DEFAULT_ZAI_MODEL); |
| 3530 | assert_eq!(default.resolved_model, ZAI_GLM_5_3_MODEL); |
| 3531 | assert_eq!(default.context_window, 1_000_000); |
| 3532 | assert_eq!(default.max_output, Some(131_072)); |
| 3533 | assert!(default.thinking_supported); |
| 3534 | assert!(default.cache_telemetry_supported); |
| 3535 | |
| 3536 | // GLM-5.2 remains available as an explicit model with its own id. |
| 3537 | let v52 = provider_capability(ProviderKind::Zai, ZAI_GLM_5_2_MODEL); |
| 3538 | assert_eq!(v52.resolved_model, ZAI_GLM_5_2_MODEL); |
| 3539 | assert_eq!(v52.context_window, 1_000_000); |
| 3540 | assert_eq!(v52.max_output, Some(131_072)); |
| 3541 | assert!(v52.thinking_supported); |
| 3542 | |
| 3543 | // GLM-5.1 remains available as an explicit model (smaller window). |
| 3544 | let v51 = provider_capability(ProviderKind::Zai, ZAI_GLM_5_1_MODEL); |
| 3545 | assert_eq!(v51.resolved_model, ZAI_GLM_5_1_MODEL); |
| 3546 | assert_eq!(v51.context_window, 202_752); |
| 3547 | assert_eq!(v51.max_output, Some(131_072)); |
| 3548 | assert!(v51.thinking_supported); |
| 3549 | |
| 3550 | // GLM-5.3-Flash is the published 1M multimodal sibling. |
| 3551 | let flash = provider_capability(ProviderKind::Zai, ZAI_GLM_5_3_FLASH_MODEL); |
| 3552 | assert_eq!(flash.resolved_model, ZAI_GLM_5_3_FLASH_MODEL); |
| 3553 | assert_eq!(flash.context_window, 1_000_000); |
| 3554 | assert_eq!(flash.max_output, Some(131_072)); |
| 3555 | assert!(flash.thinking_supported); |
| 3556 | |
| 3557 | // GLM-5-Turbo is the faster sub-agent sibling of GLM-5.2. |
| 3558 | let turbo = provider_capability(ProviderKind::Zai, ZAI_GLM_5_TURBO_MODEL); |
| 3559 | assert_eq!(turbo.resolved_model, ZAI_GLM_5_TURBO_MODEL); |
| 3560 | } |
| 3561 | |
| 3562 | #[test] |
| 3563 | fn provider_capability_minimax_direct_models_use_api_docs_shape() { |
| 3564 | let m3 = provider_capability(ProviderKind::Minimax, DEFAULT_MINIMAX_MODEL); |
| 3565 | assert_eq!(m3.context_window, 1_000_000); |
| 3566 | assert_eq!(m3.max_output, Some(524_288)); |
| 3567 | assert!(m3.thinking_supported); |
| 3568 | assert!(m3.cache_telemetry_supported); |
| 3569 | assert_eq!(m3.request_payload_mode, RequestPayloadMode::ChatCompletions); |
| 3570 | |
| 3571 | for model in [ |
| 3572 | MINIMAX_M2_7_MODEL, |
| 3573 | MINIMAX_M2_7_HIGHSPEED_MODEL, |
| 3574 | MINIMAX_M2_5_MODEL, |
| 3575 | MINIMAX_M2_5_HIGHSPEED_MODEL, |
| 3576 | MINIMAX_M2_1_MODEL, |
| 3577 | MINIMAX_M2_1_HIGHSPEED_MODEL, |
| 3578 | MINIMAX_M2_MODEL, |
| 3579 | ] { |
| 3580 | let cap = provider_capability(ProviderKind::Minimax, model); |
| 3581 | assert_eq!(cap.context_window, 204_800, "{model}"); |
| 3582 | assert!(cap.thinking_supported, "{model}"); |
| 3583 | assert!(cap.cache_telemetry_supported, "{model}"); |
| 3584 | assert_eq!( |
| 3585 | cap.request_payload_mode, |
| 3586 | RequestPayloadMode::ChatCompletions |
| 3587 | ); |
| 3588 | } |
| 3589 | } |
| 3590 | |
| 3591 | #[test] |
| 3592 | fn provider_capability_scenario_4() { |
| 3593 | // Scenario consolidation of: provider_capability_non_v4_model_has_smaller_window, provider_capability_roundtrip_serialization |
| 3594 | // from provider_capability_non_v4_model_has_smaller_window |
| 3595 | { |
| 3596 | let cap = provider_capability(ProviderKind::Deepseek, "deepseek-coder"); |
| 3597 | assert_eq!( |
| 3598 | cap.context_window, |
| 3599 | codewhale_models::LEGACY_DEEPSEEK_CONTEXT_WINDOW_TOKENS |
| 3600 | ); |
| 3601 | assert_eq!(cap.max_output, None); |
| 3602 | assert!(!cap.thinking_supported); |
| 3603 | } |
| 3604 | // from provider_capability_roundtrip_serialization |
| 3605 | { |
| 3606 | let cap = provider_capability(ProviderKind::Deepseek, "deepseek-v4-pro"); |
| 3607 | let json = serde_json::to_value(&cap).unwrap(); |
| 3608 | let deserialized: ProviderCapability = serde_json::from_value(json).unwrap(); |
| 3609 | assert_eq!(cap, deserialized); |
| 3610 | } |
| 3611 | } |
| 3612 | |
| 3613 | #[test] |
| 3614 | fn huggingface_custom_env_urls_do_not_inherit_ambient_keys() -> Result<()> { |
| 3615 | let _lock = lock_test_env(); |
| 3616 | let nanos = SystemTime::now() |
| 3617 | .duration_since(UNIX_EPOCH) |
| 3618 | .unwrap() |
| 3619 | .as_nanos(); |
| 3620 | let temp_root = env::temp_dir().join(format!( |
| 3621 | "codewhale-tui-huggingface-env-test-{}-{}", |
| 3622 | std::process::id(), |
| 3623 | nanos |
| 3624 | )); |
| 3625 | |
| 3626 | { |
| 3627 | let long_form_root = temp_root.join("long-form"); |
| 3628 | fs::create_dir_all(&long_form_root)?; |
| 3629 | let _guard = EnvGuard::new(&long_form_root); |
| 3630 | |
| 3631 | unsafe { |
| 3632 | env::set_var("CODEWHALE_PROVIDER", "huggingface"); |
| 3633 | env::set_var("HUGGINGFACE_API_KEY", "hf-env-key"); |
| 3634 | env::set_var("HF_TOKEN", "hf-token-fallback"); |
| 3635 | env::set_var("HUGGINGFACE_BASE_URL", "https://custom-hf.example/v1"); |
| 3636 | env::set_var("HF_BASE_URL", "https://fallback-hf.example/v1"); |
| 3637 | env::set_var("HUGGINGFACE_MODEL", "meta-llama/Llama-3-70B"); |
| 3638 | env::set_var("HF_MODEL", "fallback/model"); |
| 3639 | } |
| 3640 | |
| 3641 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 3642 | assert_eq!( |
| 3643 | config.active_provider_identity().unwrap().provider, |
| 3644 | ProviderKind::Huggingface |
| 3645 | ); |
| 3646 | let error = config |
| 3647 | .active_route_api_key() |
| 3648 | .expect_err("ambient key must not follow a custom endpoint"); |
| 3649 | assert!(error.to_string().contains("must be bound explicitly")); |
| 3650 | assert!(!has_api_key(&config)); |
| 3651 | assert_eq!( |
| 3652 | config.active_route_base_url(), |
| 3653 | "https://custom-hf.example/v1" |
| 3654 | ); |
| 3655 | assert_eq!(config.default_model(), "meta-llama/Llama-3-70B"); |
| 3656 | } |
| 3657 | |
| 3658 | { |
| 3659 | let short_form_root = temp_root.join("short-form"); |
| 3660 | fs::create_dir_all(&short_form_root)?; |
| 3661 | let _guard = EnvGuard::new(&short_form_root); |
| 3662 | |
| 3663 | unsafe { |
| 3664 | env::set_var("CODEWHALE_PROVIDER", "huggingface"); |
| 3665 | env::set_var("HF_TOKEN", "hf-env-key"); |
| 3666 | env::set_var("HF_BASE_URL", "https://custom-hf.example/v1"); |
| 3667 | env::set_var("HF_MODEL", "meta-llama/Llama-3-70B"); |
| 3668 | } |
| 3669 | |
| 3670 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 3671 | assert_eq!( |
| 3672 | config.active_provider_identity().unwrap().provider, |
| 3673 | ProviderKind::Huggingface |
| 3674 | ); |
| 3675 | let error = config |
| 3676 | .active_route_api_key() |
| 3677 | .expect_err("ambient key must not follow a custom endpoint"); |
| 3678 | assert!(error.to_string().contains("must be bound explicitly")); |
| 3679 | assert!(!has_api_key(&config)); |
| 3680 | assert_eq!( |
| 3681 | config.active_route_base_url(), |
| 3682 | "https://custom-hf.example/v1" |
| 3683 | ); |
| 3684 | assert_eq!(config.default_model(), "meta-llama/Llama-3-70B"); |
| 3685 | } |
| 3686 | Ok(()) |
| 3687 | } |
| 3688 | |
| 3689 | #[test] |
| 3690 | fn huggingface_short_custom_env_url_does_not_inherit_ambient_key() -> Result<()> { |
| 3691 | let _lock = lock_test_env(); |
| 3692 | let nanos = SystemTime::now() |
| 3693 | .duration_since(UNIX_EPOCH) |
| 3694 | .unwrap() |
| 3695 | .as_nanos(); |
| 3696 | let temp_root = env::temp_dir().join(format!( |
| 3697 | "codewhale-tui-huggingface-short-env-test-{}-{}", |
| 3698 | std::process::id(), |
| 3699 | nanos |
| 3700 | )); |
| 3701 | fs::create_dir_all(&temp_root)?; |
| 3702 | let _guard = EnvGuard::new(&temp_root); |
| 3703 | |
| 3704 | unsafe { |
| 3705 | env::set_var("CODEWHALE_PROVIDER", "hf"); |
| 3706 | env::set_var("HF_TOKEN", "hf-token-value"); |
| 3707 | env::set_var("HF_BASE_URL", "https://short-hf.example/v1"); |
| 3708 | env::set_var("HF_MODEL", "org/short-model"); |
| 3709 | } |
| 3710 | |
| 3711 | let config = codewhale_plugins::providers::load_config(None, None)?; |
| 3712 | assert_eq!( |
| 3713 | config.active_provider_identity().unwrap().provider, |
| 3714 | ProviderKind::Huggingface |
| 3715 | ); |
| 3716 | let error = config |
| 3717 | .active_route_api_key() |
| 3718 | .expect_err("ambient key must not follow a custom endpoint"); |
| 3719 | assert!(error.to_string().contains("must be bound explicitly")); |
| 3720 | assert!(!has_api_key(&config)); |
| 3721 | assert_eq!( |
| 3722 | config.active_route_base_url(), |
| 3723 | "https://short-hf.example/v1" |
| 3724 | ); |
| 3725 | assert_eq!(config.default_model(), "org/short-model"); |
| 3726 | Ok(()) |
| 3727 | } |
| 3728 | |
| 3729 | #[test] |
| 3730 | fn literal_custom_table_round_trips_as_exact_historical_route() { |
| 3731 | let config = |
| 3732 | session_custom_provider_config("custom", "openai-compatible", "http://127.0.0.1:1234/v1"); |
| 3733 | |
| 3734 | assert_eq!( |
| 3735 | config.active_provider_identity().unwrap().provider, |
| 3736 | ProviderKind::Custom |
| 3737 | ); |
| 3738 | let identity = config |
| 3739 | .resolve_provider_identity("custom") |
| 3740 | .expect("exact [providers.custom] identity"); |
| 3741 | assert_eq!(identity.key.as_str(), "custom"); |
| 3742 | let route = codewhale_engine::route_runtime::resolve_runtime_route( |
| 3743 | &config, |
| 3744 | identity.provider, |
| 3745 | Some("local-model"), |
| 3746 | ) |
| 3747 | .expect("resolve exact literal table") |
| 3748 | .validate() |
| 3749 | .expect("preflight exact literal table"); |
| 3750 | assert_eq!(route.identity.key.as_str(), "custom"); |
| 3751 | assert_eq!(route.client.base_url(), "http://127.0.0.1:1234/v1"); |
| 3752 | assert_eq!( |
| 3753 | route |
| 3754 | .config |
| 3755 | .resolve_provider_identity(route.identity.key.as_str()) |
| 3756 | .expect("repeat exact literal table resolution"), |
| 3757 | identity |
| 3758 | ); |
| 3759 | } |
| 3760 | |
| 3761 | #[test] |
| 3762 | fn case_colliding_custom_table_preserves_exact_spelling_across_receipts() { |
| 3763 | let config = |
| 3764 | session_custom_provider_config("CUSTOM", "openai-compatible", "http://127.0.0.1:5678/v1"); |
| 3765 | |
| 3766 | assert_eq!( |
| 3767 | config.active_provider_identity().unwrap().provider, |
| 3768 | ProviderKind::Custom |
| 3769 | ); |
| 3770 | assert_eq!( |
| 3771 | config.active_provider_identity().unwrap().key.as_str(), |
| 3772 | "CUSTOM" |
| 3773 | ); |
| 3774 | let identity = config |
| 3775 | .resolve_provider_identity("CUSTOM") |
| 3776 | .expect("exact case-colliding custom identity"); |
| 3777 | assert_eq!(identity.key.as_str(), "CUSTOM"); |
| 3778 | let route = codewhale_engine::route_runtime::resolve_runtime_route( |
| 3779 | &config, |
| 3780 | identity.provider, |
| 3781 | Some("local-model"), |
| 3782 | ) |
| 3783 | .expect("resolve case-colliding custom table") |
| 3784 | .validate() |
| 3785 | .expect("preflight case-colliding custom table"); |
| 3786 | assert_eq!(route.identity.key.as_str(), "CUSTOM"); |
| 3787 | assert_eq!(route.client.base_url(), "http://127.0.0.1:5678/v1"); |
| 3788 | } |
| 3789 | |
| 3790 | #[test] |
| 3791 | fn dispatch_endpoint_and_billing_receipts_agree_for_every_resolved_route() -> Result<()> { |
| 3792 | let _lock = lock_test_env(); |
| 3793 | let temp_root = tempfile::tempdir()?; |
| 3794 | let _guard = EnvGuard::new(temp_root.path()); |
| 3795 | let _managed = no_managed_config(temp_root.path()); |
| 3796 | let config_path = temp_root.path().join("config.toml"); |
| 3797 | fs::write(&config_path, "provider = \"deepseek\"\n")?; |
| 3798 | let _base = EnvVarGuard::set("CODEWHALE_BASE_URL", "https://env-gateway.example.test/v1"); |
| 3799 | |
| 3800 | let config = codewhale_plugins::providers::load_config(Some(config_path), None)?; |
| 3801 | |
| 3802 | // `for_route` reads the ambient config; `for_dispatched_route` reads the |
| 3803 | // endpoint the client is actually built from. After the resolver became |
| 3804 | // identity-aware these must not be able to disagree for the active route. |
| 3805 | let provider = config.active_provider_identity().unwrap().provider; |
| 3806 | let resolved = config.active_route_base_url(); |
| 3807 | assert_eq!( |
| 3808 | codewhale_engine::route_billing::for_route( |
| 3809 | &config, |
| 3810 | &(config).test_identity_for_kind(provider) |
| 3811 | ), |
| 3812 | codewhale_engine::route_billing::for_dispatched_route( |
| 3813 | &config, |
| 3814 | codewhale_engine::route_billing::DispatchedRoute { |
| 3815 | provider, |
| 3816 | base_url: &resolved, |
| 3817 | }, |
| 3818 | ) |
| 3819 | ); |
| 3820 | |
| 3821 | // A pinned cross-provider child bills from its own resolved endpoint, |
| 3822 | // which is its canonical host — not the session's env-selected gateway. |
| 3823 | for child in [ProviderKind::DeepseekAnthropic, ProviderKind::Moonshot] { |
| 3824 | let child_base = config.base_url_for_route(&config.test_identity_for_kind(child)); |
| 3825 | assert_eq!(child_base, child.provider().default_base_url(), "{child:?}"); |
| 3826 | assert_eq!( |
| 3827 | codewhale_engine::route_billing::for_dispatched_route( |
| 3828 | &config, |
| 3829 | codewhale_engine::route_billing::DispatchedRoute { |
| 3830 | provider: child, |
| 3831 | base_url: &child_base, |
| 3832 | }, |
| 3833 | ), |
| 3834 | codewhale_engine::route_billing::for_route( |
| 3835 | &config, |
| 3836 | &(config).test_identity_for_kind(child) |
| 3837 | ), |
| 3838 | "{child:?} ambient and dispatch billing receipts must agree" |
| 3839 | ); |
| 3840 | } |
| 3841 | Ok(()) |
| 3842 | } |
| 3843 | |
| 3844 | #[test] |
| 3845 | fn readiness_and_inventory_classify_the_resolved_route_not_the_session_host() -> Result<()> { |
| 3846 | let _lock = lock_test_env(); |
| 3847 | let temp_root = tempfile::tempdir()?; |
| 3848 | let _guard = EnvGuard::new(temp_root.path()); |
| 3849 | let _managed = no_managed_config(temp_root.path()); |
| 3850 | let config_path = temp_root.path().join("config.toml"); |
| 3851 | fs::write(&config_path, "provider = \"deepseek\"\n")?; |
| 3852 | let _base = EnvVarGuard::set("CODEWHALE_BASE_URL", "http://127.0.0.1:11434/v1"); |
| 3853 | |
| 3854 | let config = codewhale_plugins::providers::load_config(Some(config_path), None)?; |
| 3855 | |
| 3856 | // Readiness: the active route is on a local custom host and classifies as |
| 3857 | // keyless-local; the sibling identity is still the canonical hosted |
| 3858 | // endpoint and must not inherit that classification. |
| 3859 | assert_eq!( |
| 3860 | codewhale_engine::provider_readiness::credential_state_for_provider( |
| 3861 | &config, |
| 3862 | &(config).test_identity_for_kind(ProviderKind::Deepseek) |
| 3863 | ), |
| 3864 | codewhale_engine::provider_readiness::CredentialState::Local |
| 3865 | ); |
| 3866 | assert_ne!( |
| 3867 | codewhale_engine::provider_readiness::credential_state_for_provider( |
| 3868 | &config, |
| 3869 | &(config) |
| 3870 | .resolve_provider_selection_identity("deepseek-cn") |
| 3871 | .unwrap() |
| 3872 | ), |
| 3873 | codewhale_engine::provider_readiness::CredentialState::Local |
| 3874 | ); |
| 3875 | |
| 3876 | // Inventory: the runtime route the picker/inventory reads is built by |
| 3877 | // re-pointing a clone of this config, so it must resolve the sibling's own |
| 3878 | // canonical endpoint. |
| 3879 | let route = codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 3880 | &config, |
| 3881 | &config |
| 3882 | .resolve_provider_selection_identity("deepseek-cn") |
| 3883 | .unwrap(), |
| 3884 | None, |
| 3885 | ) |
| 3886 | .expect("deepseek-cn runtime route"); |
| 3887 | assert_eq!( |
| 3888 | route.candidate.endpoint().base_url, |
| 3889 | DEFAULT_DEEPSEEKCN_BASE_URL |
| 3890 | ); |
| 3891 | assert_eq!( |
| 3892 | route.config.active_route_base_url(), |
| 3893 | DEFAULT_DEEPSEEKCN_BASE_URL |
| 3894 | ); |
| 3895 | |
| 3896 | // And a canonical/default endpoint is never reported as custom. |
| 3897 | assert!( |
| 3898 | !config.provider_uses_custom_endpoint( |
| 3899 | &config |
| 3900 | .resolve_provider_selection_identity("deepseek-cn") |
| 3901 | .unwrap() |
| 3902 | ) |
| 3903 | ); |
| 3904 | assert!( |
| 3905 | config |
| 3906 | .provider_uses_custom_endpoint(&config.test_identity_for_kind(ProviderKind::Deepseek)) |
| 3907 | ); |
| 3908 | Ok(()) |
| 3909 | } |
| 3910 | |
| 3911 | #[test] |
| 3912 | fn configured_inactive_provider_reads_its_secret_store_key() -> Result<()> { |
| 3913 | let _lock = lock_test_env(); |
| 3914 | let temp = tempfile::tempdir()?; |
| 3915 | let _home = EnvVarGuard::set("CODEWHALE_HOME", temp.path()); |
| 3916 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 3917 | let _moonshot = EnvVarGuard::remove("MOONSHOT_API_KEY"); |
| 3918 | let _kimi = EnvVarGuard::remove("KIMI_API_KEY"); |
| 3919 | |
| 3920 | // The state guided setup leaves behind: auth_mode saved to config, the |
| 3921 | // key saved to the secret store only — and the operator then switches |
| 3922 | // the active provider away (#5033). |
| 3923 | let providers = ProvidersConfig { |
| 3924 | moonshot: ProviderConfig { |
| 3925 | auth_mode: Some("api_key".to_string()), |
| 3926 | ..Default::default() |
| 3927 | }, |
| 3928 | ..Default::default() |
| 3929 | }; |
| 3930 | let config = { |
| 3931 | let __cw_config_init_31_0 = Some("deepseek".to_string()); |
| 3932 | let __cw_config_init_31_1 = Some(providers); |
| 3933 | let mut __cw_config_init_31_value: Config = Default::default(); |
| 3934 | __cw_config_init_31_value.provider = __cw_config_init_31_0; |
| 3935 | __cw_config_init_31_value.providers = __cw_config_init_31_1; |
| 3936 | __cw_config_init_31_value |
| 3937 | }; |
| 3938 | |
| 3939 | assert!( |
| 3940 | !has_api_key_for( |
| 3941 | &config, |
| 3942 | &(config).test_identity_for_kind(ProviderKind::Moonshot) |
| 3943 | ), |
| 3944 | "no stored key yet: the configured provider must still read as unconfigured" |
| 3945 | ); |
| 3946 | |
| 3947 | codewhale_secrets::Secrets::auto_detect().set("moonshot", "kimi-test-credential")?; |
| 3948 | assert!( |
| 3949 | has_api_key_for( |
| 3950 | &config, |
| 3951 | &(config).test_identity_for_kind(ProviderKind::Moonshot) |
| 3952 | ), |
| 3953 | "a configured-but-inactive provider with a stored key must read as configured (#5033)" |
| 3954 | ); |
| 3955 | Ok(()) |
| 3956 | } |
| 3957 | |
| 3958 | /// A self-hosted OpenAI-compatible gateway owns its model namespace, including |
| 3959 | /// its casing. A WeChat-community user configured `DeepSeek-V4-Flash` against |
| 3960 | /// their company's internal endpoint and reported the id coming back lowercase |
| 3961 | /// — an id that endpoint does not serve. Every stage from the parsed config to |
| 3962 | /// the resolved wire id must hand the string back byte-for-byte. |
| 3963 | #[test] |
| 3964 | fn custom_endpoint_model_id_survives_verbatim_through_the_route() { |
| 3965 | const MODEL: &str = "DeepSeek-V4-Flash"; |
| 3966 | let shapes: [(&str, &str); 6] = [ |
| 3967 | ( |
| 3968 | "provider-scoped deepseek table with a custom base_url", |
| 3969 | r#" |
| 3970 | provider = "deepseek" |
| 3971 | [providers.deepseek] |
| 3972 | base_url = "https://llm.corp.internal/v1" |
| 3973 | api_key = "k" |
| 3974 | model = "DeepSeek-V4-Flash" |
| 3975 | "#, |
| 3976 | ), |
| 3977 | ( |
| 3978 | "deepseek table with no explicit provider key", |
| 3979 | r#" |
| 3980 | [providers.deepseek] |
| 3981 | base_url = "https://llm.corp.internal/v1" |
| 3982 | api_key = "k" |
| 3983 | model = "DeepSeek-V4-Flash" |
| 3984 | "#, |
| 3985 | ), |
| 3986 | ( |
| 3987 | "root base_url with the root default_text_model", |
| 3988 | r#" |
| 3989 | base_url = "https://llm.corp.internal/v1" |
| 3990 | api_key = "k" |
| 3991 | default_text_model = "DeepSeek-V4-Flash" |
| 3992 | "#, |
| 3993 | ), |
| 3994 | ( |
| 3995 | "anthropic dialect on a custom deepseek endpoint", |
| 3996 | r#" |
| 3997 | provider = "deepseek" |
| 3998 | [providers.deepseek] |
| 3999 | base_url = "https://llm.corp.internal/anthropic" |
| 4000 | api_key = "k" |
| 4001 | model = "DeepSeek-V4-Flash" |
| 4002 | wire = "anthropic" |
| 4003 | "#, |
| 4004 | ), |
| 4005 | ( |
| 4006 | "openai-compatible provider table", |
| 4007 | r#" |
| 4008 | provider = "openai" |
| 4009 | [providers.openai] |
| 4010 | base_url = "https://llm.corp.internal/v1" |
| 4011 | api_key = "k" |
| 4012 | model = "DeepSeek-V4-Flash" |
| 4013 | "#, |
| 4014 | ), |
| 4015 | ( |
| 4016 | "literal custom provider on a root base_url", |
| 4017 | r#" |
| 4018 | provider = "custom" |
| 4019 | base_url = "https://llm.corp.internal/v1" |
| 4020 | api_key = "k" |
| 4021 | default_text_model = "DeepSeek-V4-Flash" |
| 4022 | "#, |
| 4023 | ), |
| 4024 | ]; |
| 4025 | |
| 4026 | for (label, body) in shapes { |
| 4027 | let mut config = codewhale_runtime::config::parse_config_base(body).expect("config parses"); |
| 4028 | normalize_model_config_for_test(&mut config); |
| 4029 | let provider = config.active_provider_identity().unwrap().provider; |
| 4030 | let base_url = config.base_url_for_route(&config.test_identity_for_kind(provider)); |
| 4031 | assert!( |
| 4032 | provider_preserves_custom_base_url_model(provider, &base_url), |
| 4033 | "{label}: {base_url} must classify as a custom endpoint" |
| 4034 | ); |
| 4035 | |
| 4036 | let stored = config |
| 4037 | .provider_config_for(&config.test_identity_for_kind(provider)) |
| 4038 | .and_then(|entry| entry.model.clone()) |
| 4039 | .or_else(|| config.default_text_model.clone()) |
| 4040 | .unwrap_or_default(); |
| 4041 | assert_eq!(stored, MODEL, "{label}: config load rewrote the stored id"); |
| 4042 | |
| 4043 | let resolved = config.default_model(); |
| 4044 | assert_eq!(resolved, MODEL, "{label}: default_model() rewrote the id"); |
| 4045 | |
| 4046 | assert_eq!( |
| 4047 | codewhale_config::route::resolve_model(provider, &resolved, Some(&base_url)) |
| 4048 | .expect("resolve wire model") |
| 4049 | .wire_id, |
| 4050 | MODEL, |
| 4051 | "{label}: the wire id must match the configured id byte-for-byte" |
| 4052 | ); |
| 4053 | |
| 4054 | let route = codewhale_engine::route_runtime::resolve_runtime_route( |
| 4055 | &config, |
| 4056 | provider, |
| 4057 | Some(&resolved), |
| 4058 | ) |
| 4059 | .unwrap_or_else(|err| panic!("{label}: route resolution failed: {err}")); |
| 4060 | assert_eq!( |
| 4061 | route.model, MODEL, |
| 4062 | "{label}: the resolved route rewrote the id" |
| 4063 | ); |
| 4064 | } |
| 4065 | } |
| 4066 | |
| 4067 | /// Reproduces the report that started the credential-resolution lane: a home |
| 4068 | /// whose secret store holds a working DeepSeek key, where the provider picker |
| 4069 | /// reads "missing key" while a real turn from the same home resolves that key. |
| 4070 | /// |
| 4071 | /// The asymmetry is #5033's marker gate. For a provider that is not currently |
| 4072 | /// active, `has_api_key_for` reads the durable slot only when some sibling's |
| 4073 | /// `[providers.<name>]` table carries the api-key auth-mode marker. The request |
| 4074 | /// path has no such gate — it reads the slot for whatever provider is active. |
| 4075 | /// Any home where the marker is absent but the slot is populated (a config |
| 4076 | /// written by an older CodeWhale, a workspace config loaded in place of the |
| 4077 | /// user-global one, a key written straight into the store) makes the two |
| 4078 | /// surfaces contradict each other, and nothing in the old picker output let a |
| 4079 | /// user tell which one was lying. |
| 4080 | /// |
| 4081 | /// This test does not change that policy — the gate is what keeps catalog |
| 4082 | /// rendering from opening a write-capable keyring for 40 providers. It pins |
| 4083 | /// the contradiction, and pins the part that is now fixed: the row says the |
| 4084 | /// slot was skipped, and why. |
| 4085 | #[test] |
| 4086 | fn picker_and_request_path_disagree_when_the_secret_slot_marker_is_missing() -> Result<()> { |
| 4087 | use codewhale_runtime::credentials::CredentialSource; |
| 4088 | |
| 4089 | let _lock = lock_test_env(); |
| 4090 | let temp_root = tempfile::tempdir()?; |
| 4091 | let temp_root = temp_root.path().canonicalize()?; |
| 4092 | let _guard = EnvGuard::new(&temp_root); |
| 4093 | let codewhale_home = temp_root.join("codewhale-home"); |
| 4094 | let config_path = codewhale_home.join("config.toml"); |
| 4095 | let _home = EnvVarGuard::set("CODEWHALE_HOME", codewhale_home.as_os_str()); |
| 4096 | let _path = EnvVarGuard::set("CODEWHALE_CONFIG_PATH", config_path.as_os_str()); |
| 4097 | let _backend = EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file"); |
| 4098 | |
| 4099 | save_api_key("deepseek-working-key")?; |
| 4100 | assert_eq!( |
| 4101 | codewhale_secrets::Secrets::auto_detect().get("deepseek")?, |
| 4102 | Some("deepseek-working-key".to_string()), |
| 4103 | "precondition: the durable slot holds a usable key" |
| 4104 | ); |
| 4105 | // Drop the marker the save wrote, standing in for a home whose config was |
| 4106 | // written by an older CodeWhale or replaced by a workspace-scoped file. |
| 4107 | fs::write(&config_path, "provider = \"openrouter\"\n")?; |
| 4108 | |
| 4109 | let active_deepseek = { |
| 4110 | let __cw_config_init_32_0 = Some("deepseek".to_string()); |
| 4111 | let mut __cw_config_init_32_value: Config = Config::default(); |
| 4112 | __cw_config_init_32_value.provider = __cw_config_init_32_0; |
| 4113 | __cw_config_init_32_value |
| 4114 | }; |
| 4115 | assert_eq!( |
| 4116 | active_deepseek.active_route_api_key().ok(), |
| 4117 | Some("deepseek-working-key".to_string()), |
| 4118 | "the request path still resolves the stored key" |
| 4119 | ); |
| 4120 | |
| 4121 | let viewing_config = { |
| 4122 | let __cw_config_init_33_0 = Some("openrouter".to_string()); |
| 4123 | let mut __cw_config_init_33_value: Config = Config::default(); |
| 4124 | __cw_config_init_33_value.provider = __cw_config_init_33_0; |
| 4125 | __cw_config_init_33_value |
| 4126 | }; |
| 4127 | assert!( |
| 4128 | !has_api_key_for( |
| 4129 | &viewing_config, |
| 4130 | &(viewing_config).test_identity_for_kind(ProviderKind::Deepseek) |
| 4131 | ), |
| 4132 | "the reported contradiction: readiness reports no key for the same home" |
| 4133 | ); |
| 4134 | |
| 4135 | let resolution = resolve_credential_source( |
| 4136 | &viewing_config, |
| 4137 | &(viewing_config).test_identity_for_kind(ProviderKind::Deepseek), |
| 4138 | ); |
| 4139 | assert!(matches!( |
| 4140 | resolution.source, |
| 4141 | CredentialSource::Missing { .. } |
| 4142 | )); |
| 4143 | let checked = resolution.checked_places(); |
| 4144 | assert!( |
| 4145 | checked |
| 4146 | .contains("secret store \"deepseek\" (not read: inactive provider, no api-key marker)"), |
| 4147 | "the row must explain the skip instead of implying an empty slot: {checked}" |
| 4148 | ); |
| 4149 | assert!( |
| 4150 | resolution.source.probed().iter().any(|probe| probe |
| 4151 | .fix |
| 4152 | .as_deref() |
| 4153 | .is_some_and(|fix| fix.contains("codewhale auth set"))), |
| 4154 | "the row must offer the command that resolves it: {resolution:?}" |
| 4155 | ); |
| 4156 | println!("CAPTURED checked-places: {checked}"); |
| 4157 | println!("CAPTURED first-fix: {:?}", resolution.first_fix()); |
| 4158 | Ok(()) |
| 4159 | } |
| 4160 | |
| 4161 | #[test] |
| 4162 | fn notifications_canonical_condition_overrides_and_unsets_to_legacy() { |
| 4163 | let config: Config = toml::from_str("[tui]\nnotification_condition = \"never\"\n[notifications]\ncondition = \"always\"\nsound = \"off\"\ncompletion_sound = \"whale\"\n").unwrap(); |
| 4164 | assert_eq!( |
| 4165 | config.notifications_config().condition, |
| 4166 | Some(NotificationCondition::Always) |
| 4167 | ); |
| 4168 | assert_eq!( |
| 4169 | config.notifications_config().sound, |
| 4170 | Some(CompletionSound::Off) |
| 4171 | ); |
| 4172 | assert_eq!( |
| 4173 | codewhale_notify::settings_projection(&config.notifications_config()) |
| 4174 | .unwrap() |
| 4175 | .1, |
| 4176 | std::time::Duration::ZERO |
| 4177 | ); |
| 4178 | } |
| 4179 | |
| 4180 | /// #6700: `[retry].jitter`, `jitter_factor` and `respect_retry_after` reach |
| 4181 | /// the resolved policy (and the client's `RetryConfig`) instead of being |
| 4182 | /// dropped for compiled-in defaults. |
| 4183 | #[test] |
| 4184 | fn retry_policy_reads_jitter_and_retry_after_keys() { |
| 4185 | let parse = |body: &str| toml::from_str::<Config>(body).expect("config parses"); |
| 4186 | |
| 4187 | let defaults = parse("[retry]\nmax_retries = 2\n").retry_policy(); |
| 4188 | assert!(defaults.jitter); |
| 4189 | assert!((defaults.jitter_factor - 0.1).abs() < f64::EPSILON); |
| 4190 | assert!(defaults.respect_retry_after); |
| 4191 | |
| 4192 | let tuned = |
| 4193 | parse("[retry]\njitter = false\njitter_factor = 0.3\nrespect_retry_after = false\n") |
| 4194 | .retry_policy(); |
| 4195 | assert!(!tuned.jitter); |
| 4196 | assert!((tuned.jitter_factor - 0.3).abs() < f64::EPSILON); |
| 4197 | assert!(!tuned.respect_retry_after); |
| 4198 | let client: codewhale_engine::llm_client::RetryConfig = tuned.into(); |
| 4199 | assert!(!client.jitter); |
| 4200 | assert!((client.jitter_factor - 0.3).abs() < f64::EPSILON); |
| 4201 | assert!(!client.respect_retry_after); |
| 4202 | |
| 4203 | let high = parse("[retry]\njitter_factor = 7.5\n").retry_policy(); |
| 4204 | assert!((high.jitter_factor - 1.0).abs() < f64::EPSILON); |
| 4205 | let negative = parse("[retry]\njitter_factor = -0.5\n").retry_policy(); |
| 4206 | assert!(negative.jitter_factor.abs() < f64::EPSILON); |
| 4207 | } |
| 4208 | |
| 4209 | // Exact released enum counterpart, retained only for actual serde conservation. |
| 4210 | // Source SHA256 a56bc5bd8b93fbb465ea4db075272746c94c38bf466821e11eeda9f5105d65ef. |
| 4211 | mod released_provider_serde { |
| 4212 | use super::*; |
| 4213 | use serde::Serialize; |
| 4214 | #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 4215 | #[serde(rename_all = "snake_case")] |
| 4216 | enum ApiProvider { |
| 4217 | Deepseek, |
| 4218 | DeepseekCN, |
| 4219 | DeepseekAnthropic, |
| 4220 | NvidiaNim, |
| 4221 | Openai, |
| 4222 | Atlascloud, |
| 4223 | WanjieArk, |
| 4224 | Volcengine, |
| 4225 | Openrouter, |
| 4226 | Orcarouter, |
| 4227 | XiaomiMimo, |
| 4228 | Novita, |
| 4229 | Fireworks, |
| 4230 | Siliconflow, |
| 4231 | SiliconflowCn, |
| 4232 | Arcee, |
| 4233 | Moonshot, |
| 4234 | Sglang, |
| 4235 | Vllm, |
| 4236 | Ollama, |
| 4237 | OllamaCloud, |
| 4238 | Huggingface, |
| 4239 | Together, |
| 4240 | Qianfan, |
| 4241 | OpenaiCodex, |
| 4242 | Anthropic, |
| 4243 | Openmodel, |
| 4244 | Zai, |
| 4245 | Stepfun, |
| 4246 | Minimax, |
| 4247 | MinimaxAnthropic, |
| 4248 | Deepinfra, |
| 4249 | Sakana, |
| 4250 | LongCat, |
| 4251 | OpencodeGo, |
| 4252 | OpencodeZen, |
| 4253 | Meta, |
| 4254 | Xai, |
| 4255 | /// Mistral AI — la Plateforme (OpenAI-compatible Chat Completions). |
| 4256 | Mistral, |
| 4257 | /// Google Gemini — official OpenAI-compatible endpoint. A distinct |
| 4258 | /// backend, not an OpenAI alias: thought signatures on tool calls are |
| 4259 | /// captured and replayed per Google's contract. |
| 4260 | Google, |
| 4261 | /// Retired Antigravity identity retained only to deserialize and clear |
| 4262 | /// legacy Codewhale configuration. It is never selectable or runnable. |
| 4263 | Antigravity, |
| 4264 | /// ModelScope — Alibaba's ModelScope inference API (OpenAI-compatible). |
| 4265 | Modelscope, |
| 4266 | /// Jiangsu Telecom TokenHub — OpenAI-compatible AI gateway. |
| 4267 | Telecomjs, |
| 4268 | /// Eden AI — OpenAI-compatible AI gateway (aggregator). |
| 4269 | Edenai, |
| 4270 | /// ZenMux — OpenAI-compatible AI gateway (aggregator). |
| 4271 | Zenmux, |
| 4272 | /// CSDN 星图 — OpenAI-compatible hosted platform and Coding Plan. |
| 4273 | Csdn, |
| 4274 | /// Concentrate — OpenAI Responses-compatible AI gateway (aggregator; BYOK only). |
| 4275 | Concentrate, |
| 4276 | /// Codewhale API — account-backed model access over connected provider keys. |
| 4277 | Codewhale, |
| 4278 | /// Alibaba Cloud Model Studio — Token Plan (OpenAI-compatible Chat Completions). |
| 4279 | ModelstudioTokenPlan, |
| 4280 | /// Alibaba Cloud Model Studio — Token Plan Anthropic-compatible endpoint. |
| 4281 | ModelstudioTokenPlanAnthropic, |
| 4282 | /// Alibaba Cloud Model Studio — Coding Plan (OpenAI-compatible Chat Completions). |
| 4283 | ModelstudioCodingPlan, |
| 4284 | /// Alibaba Cloud Model Studio — Coding Plan Anthropic-compatible endpoint. |
| 4285 | ModelstudioCodingPlanAnthropic, |
| 4286 | /// User-defined OpenAI-compatible endpoint (#1519). |
| 4287 | /// |
| 4288 | /// Selected when `provider = "<name>"` names a `[providers.<name>] |
| 4289 | /// kind="openai-compatible"` table. A single dynamic identity that maps to |
| 4290 | /// [`codewhale_config::ProviderKind::Custom`] and routes via the OpenAI Chat |
| 4291 | /// Completions wire protocol; the concrete endpoint/model/auth come from the |
| 4292 | /// named config table, not from this variant. |
| 4293 | Custom, |
| 4294 | } |
| 4295 | |
| 4296 | #[derive(Serialize)] |
| 4297 | struct LegacySaved { |
| 4298 | provider: ApiProvider, |
| 4299 | provider_identity: String, |
| 4300 | model: String, |
| 4301 | receipt: codewhale_engine::model_routing::AutoRouteReceipt, |
| 4302 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 4303 | effective_reasoning_effort: |
| 4304 | Option<codewhale_models::reasoning_effort_tier::ReasoningEffortTier>, |
| 4305 | } |
| 4306 | #[derive(Serialize)] |
| 4307 | #[serde(tag = "kind", rename_all = "snake_case")] |
| 4308 | enum LegacyActivity { |
| 4309 | ReasoningEffortChanged { |
| 4310 | requested: codewhale_models::reasoning_effort_tier::ReasoningEffortTier, |
| 4311 | effective: codewhale_models::reasoning_effort_tier::ReasoningEffortTier, |
| 4312 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 4313 | provider_kind: Option<ApiProvider>, |
| 4314 | provider: String, |
| 4315 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 4316 | endpoint_identity: Option<String>, |
| 4317 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 4318 | model: Option<String>, |
| 4319 | ts: i64, |
| 4320 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 4321 | operation: Option<codewhale_engine::work_graph::WorkNodeId>, |
| 4322 | }, |
| 4323 | } |
| 4324 | #[derive(Serialize)] |
| 4325 | struct LegacyPricing { |
| 4326 | provider: ApiProvider, |
| 4327 | provider_identity: String, |
| 4328 | wire_model: String, |
| 4329 | endpoint_fingerprint: String, |
| 4330 | catalog_fetched_at: u64, |
| 4331 | catalog_revision: String, |
| 4332 | currency: codewhale_config::pricing::Currency, |
| 4333 | provenance: codewhale_config::pricing::PricingProvenance, |
| 4334 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 4335 | cloud_facts: Option<codewhale_engine::provider_catalog_live::CloudFactsPricingSource>, |
| 4336 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 4337 | input_per_million: Option<String>, |
| 4338 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 4339 | output_per_million: Option<String>, |
| 4340 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 4341 | cache_read_per_million: Option<String>, |
| 4342 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 4343 | cache_write_per_million: Option<String>, |
| 4344 | } |
| 4345 | fn cases() -> [(ApiProvider, ProviderKind, &'static str); 53] { |
| 4346 | [ |
| 4347 | (ApiProvider::Deepseek, ProviderKind::Deepseek, "deepseek"), |
| 4348 | ( |
| 4349 | ApiProvider::DeepseekCN, |
| 4350 | ProviderKind::Deepseek, |
| 4351 | "deepseek-cn", |
| 4352 | ), |
| 4353 | ( |
| 4354 | ApiProvider::DeepseekAnthropic, |
| 4355 | ProviderKind::DeepseekAnthropic, |
| 4356 | "deepseek-anthropic", |
| 4357 | ), |
| 4358 | ( |
| 4359 | ApiProvider::NvidiaNim, |
| 4360 | ProviderKind::NvidiaNim, |
| 4361 | "nvidia-nim", |
| 4362 | ), |
| 4363 | (ApiProvider::Openai, ProviderKind::Openai, "openai"), |
| 4364 | ( |
| 4365 | ApiProvider::Atlascloud, |
| 4366 | ProviderKind::Atlascloud, |
| 4367 | "atlascloud", |
| 4368 | ), |
| 4369 | ( |
| 4370 | ApiProvider::WanjieArk, |
| 4371 | ProviderKind::WanjieArk, |
| 4372 | "wanjie-ark", |
| 4373 | ), |
| 4374 | ( |
| 4375 | ApiProvider::Volcengine, |
| 4376 | ProviderKind::Volcengine, |
| 4377 | "volcengine", |
| 4378 | ), |
| 4379 | ( |
| 4380 | ApiProvider::Openrouter, |
| 4381 | ProviderKind::Openrouter, |
| 4382 | "openrouter", |
| 4383 | ), |
| 4384 | ( |
| 4385 | ApiProvider::Orcarouter, |
| 4386 | ProviderKind::Orcarouter, |
| 4387 | "orcarouter", |
| 4388 | ), |
| 4389 | ( |
| 4390 | ApiProvider::XiaomiMimo, |
| 4391 | ProviderKind::XiaomiMimo, |
| 4392 | "xiaomi-mimo", |
| 4393 | ), |
| 4394 | (ApiProvider::Novita, ProviderKind::Novita, "novita"), |
| 4395 | (ApiProvider::Fireworks, ProviderKind::Fireworks, "fireworks"), |
| 4396 | ( |
| 4397 | ApiProvider::Siliconflow, |
| 4398 | ProviderKind::Siliconflow, |
| 4399 | "siliconflow", |
| 4400 | ), |
| 4401 | ( |
| 4402 | ApiProvider::SiliconflowCn, |
| 4403 | ProviderKind::SiliconflowCN, |
| 4404 | "siliconflow-CN", |
| 4405 | ), |
| 4406 | (ApiProvider::Arcee, ProviderKind::Arcee, "arcee"), |
| 4407 | (ApiProvider::Moonshot, ProviderKind::Moonshot, "moonshot"), |
| 4408 | (ApiProvider::Sglang, ProviderKind::Sglang, "sglang"), |
| 4409 | (ApiProvider::Vllm, ProviderKind::Vllm, "vllm"), |
| 4410 | (ApiProvider::Ollama, ProviderKind::Ollama, "ollama"), |
| 4411 | ( |
| 4412 | ApiProvider::OllamaCloud, |
| 4413 | ProviderKind::OllamaCloud, |
| 4414 | "ollama-cloud", |
| 4415 | ), |
| 4416 | ( |
| 4417 | ApiProvider::Huggingface, |
| 4418 | ProviderKind::Huggingface, |
| 4419 | "huggingface", |
| 4420 | ), |
| 4421 | (ApiProvider::Together, ProviderKind::Together, "together"), |
| 4422 | (ApiProvider::Qianfan, ProviderKind::Qianfan, "qianfan"), |
| 4423 | ( |
| 4424 | ApiProvider::OpenaiCodex, |
| 4425 | ProviderKind::OpenaiCodex, |
| 4426 | "openai-codex", |
| 4427 | ), |
| 4428 | (ApiProvider::Anthropic, ProviderKind::Anthropic, "anthropic"), |
| 4429 | (ApiProvider::Openmodel, ProviderKind::Openmodel, "openmodel"), |
| 4430 | (ApiProvider::Zai, ProviderKind::Zai, "zai"), |
| 4431 | (ApiProvider::Stepfun, ProviderKind::Stepfun, "stepfun"), |
| 4432 | (ApiProvider::Minimax, ProviderKind::Minimax, "minimax"), |
| 4433 | ( |
| 4434 | ApiProvider::MinimaxAnthropic, |
| 4435 | ProviderKind::MinimaxAnthropic, |
| 4436 | "minimax-anthropic", |
| 4437 | ), |
| 4438 | (ApiProvider::Deepinfra, ProviderKind::Deepinfra, "deepinfra"), |
| 4439 | (ApiProvider::Sakana, ProviderKind::Sakana, "sakana"), |
| 4440 | (ApiProvider::LongCat, ProviderKind::LongCat, "longcat"), |
| 4441 | ( |
| 4442 | ApiProvider::OpencodeGo, |
| 4443 | ProviderKind::OpencodeGo, |
| 4444 | "opencode-go", |
| 4445 | ), |
| 4446 | ( |
| 4447 | ApiProvider::OpencodeZen, |
| 4448 | ProviderKind::OpencodeZen, |
| 4449 | "opencode-zen", |
| 4450 | ), |
| 4451 | (ApiProvider::Meta, ProviderKind::Meta, "meta"), |
| 4452 | (ApiProvider::Xai, ProviderKind::Xai, "xai"), |
| 4453 | (ApiProvider::Mistral, ProviderKind::Mistral, "mistral"), |
| 4454 | (ApiProvider::Google, ProviderKind::Google, "google"), |
| 4455 | ( |
| 4456 | ApiProvider::Antigravity, |
| 4457 | ProviderKind::Antigravity, |
| 4458 | "antigravity", |
| 4459 | ), |
| 4460 | ( |
| 4461 | ApiProvider::Modelscope, |
| 4462 | ProviderKind::Modelscope, |
| 4463 | "modelscope", |
| 4464 | ), |
| 4465 | (ApiProvider::Telecomjs, ProviderKind::Telecomjs, "telecomjs"), |
| 4466 | (ApiProvider::Edenai, ProviderKind::Edenai, "edenai"), |
| 4467 | (ApiProvider::Zenmux, ProviderKind::Zenmux, "zenmux"), |
| 4468 | (ApiProvider::Csdn, ProviderKind::Csdn, "csdn"), |
| 4469 | ( |
| 4470 | ApiProvider::Concentrate, |
| 4471 | ProviderKind::Concentrate, |
| 4472 | "concentrate", |
| 4473 | ), |
| 4474 | (ApiProvider::Codewhale, ProviderKind::Codewhale, "codewhale"), |
| 4475 | ( |
| 4476 | ApiProvider::ModelstudioTokenPlan, |
| 4477 | ProviderKind::ModelstudioTokenPlan, |
| 4478 | "modelstudio-token-plan", |
| 4479 | ), |
| 4480 | ( |
| 4481 | ApiProvider::ModelstudioTokenPlanAnthropic, |
| 4482 | ProviderKind::ModelstudioTokenPlanAnthropic, |
| 4483 | "modelstudio-token-plan-anthropic", |
| 4484 | ), |
| 4485 | ( |
| 4486 | ApiProvider::ModelstudioCodingPlan, |
| 4487 | ProviderKind::ModelstudioCodingPlan, |
| 4488 | "modelstudio-coding-plan", |
| 4489 | ), |
| 4490 | ( |
| 4491 | ApiProvider::ModelstudioCodingPlanAnthropic, |
| 4492 | ProviderKind::ModelstudioCodingPlanAnthropic, |
| 4493 | "modelstudio-coding-plan-anthropic", |
| 4494 | ), |
| 4495 | (ApiProvider::Custom, ProviderKind::Custom, "custom"), |
| 4496 | ] |
| 4497 | } |
| 4498 | #[test] |
| 4499 | fn released_all_53_provider_wrappers_keep_actual_serde_and_revision_bytes() { |
| 4500 | use codewhale_config::pricing::{Currency, PricingProvenance}; |
| 4501 | use codewhale_engine::model_routing::{ |
| 4502 | AutoRouteDataPath, AutoRouteHeuristicReason, AutoRoutePair, AutoRouteReason, |
| 4503 | AutoRouteReceipt, AutoRouteScope, AutoRouteTier, |
| 4504 | }; |
| 4505 | use codewhale_engine::work_graph::WorkActivityEvent; |
| 4506 | use codewhale_models::reasoning_effort_tier::ReasoningEffortTier; |
| 4507 | let receipt = AutoRouteReceipt { |
| 4508 | tier: AutoRouteTier::Selected, |
| 4509 | pair: AutoRoutePair { |
| 4510 | strong: "model-A".into(), |
| 4511 | fast: None, |
| 4512 | }, |
| 4513 | scope: AutoRouteScope::ResolvedProvider, |
| 4514 | data_path: AutoRouteDataPath::LocalHeuristic, |
| 4515 | reason: AutoRouteReason::LocalFallback(AutoRouteHeuristicReason::DeclaredDefault), |
| 4516 | decision: None, |
| 4517 | router_failure: None, |
| 4518 | }; |
| 4519 | for (legacy, provider, id) in cases() { |
| 4520 | let old_saved = LegacySaved { |
| 4521 | provider: legacy, |
| 4522 | provider_identity: id.into(), |
| 4523 | model: "model-A".into(), |
| 4524 | receipt: receipt.clone(), |
| 4525 | effective_reasoning_effort: Some(ReasoningEffortTier::High), |
| 4526 | }; |
| 4527 | let saved = codewhale_engine::session_manager::SavedAutoRouteReceipt { |
| 4528 | context_window: None, |
| 4529 | provider, |
| 4530 | provider_identity: id.into(), |
| 4531 | model: "model-A".into(), |
| 4532 | receipt: receipt.clone(), |
| 4533 | effective_reasoning_effort: Some(ReasoningEffortTier::High), |
| 4534 | }; |
| 4535 | let expected = serde_json::to_vec(&old_saved).unwrap(); |
| 4536 | assert_eq!(serde_json::to_vec(&saved).unwrap(), expected, "saved {id}"); |
| 4537 | let restored: codewhale_engine::session_manager::SavedAutoRouteReceipt = |
| 4538 | serde_json::from_slice(&expected).unwrap(); |
| 4539 | assert_eq!(restored, saved, "saved decode {id}"); |
| 4540 | assert_eq!(serde_json::to_vec(&restored).unwrap(), expected); |
| 4541 | let old_activity = LegacyActivity::ReasoningEffortChanged { |
| 4542 | requested: ReasoningEffortTier::High, |
| 4543 | effective: ReasoningEffortTier::Unavailable, |
| 4544 | provider_kind: Some(legacy), |
| 4545 | provider: id.into(), |
| 4546 | endpoint_identity: Some("https://example.test/v1".into()), |
| 4547 | model: Some("model-A".into()), |
| 4548 | ts: 71, |
| 4549 | operation: None, |
| 4550 | }; |
| 4551 | let activity = WorkActivityEvent::ReasoningEffortChanged { |
| 4552 | requested: ReasoningEffortTier::High, |
| 4553 | effective: ReasoningEffortTier::Unavailable, |
| 4554 | provider_kind: Some(provider), |
| 4555 | provider: id.into(), |
| 4556 | endpoint_identity: Some("https://example.test/v1".into()), |
| 4557 | model: Some("model-A".into()), |
| 4558 | ts: 71, |
| 4559 | operation: None, |
| 4560 | }; |
| 4561 | let expected = serde_json::to_vec(&old_activity).unwrap(); |
| 4562 | assert_eq!( |
| 4563 | serde_json::to_vec(&activity).unwrap(), |
| 4564 | expected, |
| 4565 | "activity {id}" |
| 4566 | ); |
| 4567 | let restored: WorkActivityEvent = serde_json::from_slice(&expected).unwrap(); |
| 4568 | assert_eq!(restored, activity, "activity decode {id}"); |
| 4569 | let input = Some("1.25".to_string()); |
| 4570 | let output = Some("2.5".to_string()); |
| 4571 | let empty: Option<String> = None; |
| 4572 | let old_payload = serde_json::to_vec(&( |
| 4573 | "codewhale-provider-live-pricing-quote-v1", |
| 4574 | legacy, |
| 4575 | id, |
| 4576 | "model-A", |
| 4577 | "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", |
| 4578 | 73_u64, |
| 4579 | Currency::Usd, |
| 4580 | PricingProvenance::UserOverride, |
| 4581 | &input, |
| 4582 | &output, |
| 4583 | &empty, |
| 4584 | &empty, |
| 4585 | )) |
| 4586 | .unwrap(); |
| 4587 | let revision = format!( |
| 4588 | "sha256:{}", |
| 4589 | codewhale_runtime::hashing::sha256_hex(&old_payload) |
| 4590 | ); |
| 4591 | let old_quote = LegacyPricing { |
| 4592 | provider: legacy, |
| 4593 | provider_identity: id.into(), |
| 4594 | wire_model: "model-A".into(), |
| 4595 | endpoint_fingerprint: |
| 4596 | "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(), |
| 4597 | catalog_fetched_at: 73, |
| 4598 | catalog_revision: revision.clone(), |
| 4599 | currency: Currency::Usd, |
| 4600 | provenance: PricingProvenance::UserOverride, |
| 4601 | cloud_facts: None, |
| 4602 | input_per_million: input.clone(), |
| 4603 | output_per_million: output.clone(), |
| 4604 | cache_read_per_million: None, |
| 4605 | cache_write_per_million: None, |
| 4606 | }; |
| 4607 | let quote = codewhale_engine::provider_catalog_live::ProviderLivePricingQuote { |
| 4608 | provider, |
| 4609 | provider_identity: id.into(), |
| 4610 | wire_model: "model-A".into(), |
| 4611 | endpoint_fingerprint: |
| 4612 | "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(), |
| 4613 | catalog_fetched_at: 73, |
| 4614 | catalog_revision: revision, |
| 4615 | currency: Currency::Usd, |
| 4616 | provenance: PricingProvenance::UserOverride, |
| 4617 | cloud_facts: None, |
| 4618 | pricing_schedule: None, |
| 4619 | input_per_million: input, |
| 4620 | output_per_million: output, |
| 4621 | cache_read_per_million: None, |
| 4622 | cache_write_per_million: None, |
| 4623 | }; |
| 4624 | let expected = serde_json::to_vec(&old_quote).unwrap(); |
| 4625 | assert_eq!( |
| 4626 | serde_json::to_vec("e).unwrap(), |
| 4627 | expected, |
| 4628 | "pricing {id}" |
| 4629 | ); |
| 4630 | let restored: codewhale_engine::provider_catalog_live::ProviderLivePricingQuote = |
| 4631 | serde_json::from_slice(&expected).unwrap(); |
| 4632 | assert_eq!(restored, quote, "pricing decode {id}"); |
| 4633 | } |
| 4634 | } |
| 4635 | #[test] |
| 4636 | fn released_classifier_data_path_retains_every_source_identity_tag() { |
| 4637 | #[derive(Serialize)] |
| 4638 | #[serde(rename_all = "snake_case")] |
| 4639 | enum LegacyDataPath { |
| 4640 | Classifier { |
| 4641 | provider: ApiProvider, |
| 4642 | model: String, |
| 4643 | }, |
| 4644 | } |
| 4645 | for (legacy, kind, id) in cases() { |
| 4646 | let old = LegacyDataPath::Classifier { |
| 4647 | provider: legacy, |
| 4648 | model: "router-model".into(), |
| 4649 | }; |
| 4650 | let current = codewhale_engine::model_routing::AutoRouteDataPath::Classifier { |
| 4651 | provider: id.into(), |
| 4652 | provider_kind: kind, |
| 4653 | model: "router-model".into(), |
| 4654 | }; |
| 4655 | let expected = serde_json::to_vec(&old).unwrap(); |
| 4656 | assert_eq!(serde_json::to_vec(¤t).unwrap(), expected, "{id}"); |
| 4657 | let decoded: codewhale_engine::model_routing::AutoRouteDataPath = |
| 4658 | serde_json::from_slice(&expected).unwrap(); |
| 4659 | assert_eq!(decoded, current, "{id}"); |
| 4660 | } |
| 4661 | } |
| 4662 | |
| 4663 | #[test] |
| 4664 | fn released_provider_wrappers_do_not_infer_brand_authority_from_custom_names() { |
| 4665 | use codewhale_engine::work_graph::WorkActivityEvent; |
| 4666 | use codewhale_models::reasoning_effort_tier::ReasoningEffortTier; |
| 4667 | for id in ["openai", "CustomA", "customa"] { |
| 4668 | let event = WorkActivityEvent::ReasoningEffortChanged { |
| 4669 | requested: ReasoningEffortTier::High, |
| 4670 | effective: ReasoningEffortTier::Unavailable, |
| 4671 | provider_kind: Some(ProviderKind::Custom), |
| 4672 | provider: id.into(), |
| 4673 | endpoint_identity: Some("https://example.test/v1".into()), |
| 4674 | model: Some("model".into()), |
| 4675 | ts: 1, |
| 4676 | operation: None, |
| 4677 | }; |
| 4678 | let json = serde_json::to_value(&event).unwrap(); |
| 4679 | assert_eq!(json["provider_kind"], "custom"); |
| 4680 | assert_eq!( |
| 4681 | serde_json::from_value::<WorkActivityEvent>(json).unwrap(), |
| 4682 | event |
| 4683 | ); |
| 4684 | } |
| 4685 | for (tag, id) in [ |
| 4686 | ("openai", "CustomA"), |
| 4687 | ("deepseek_c_n", "deepseek"), |
| 4688 | ("custom", ""), |
| 4689 | ("unknown", "openai"), |
| 4690 | ] { |
| 4691 | let malformed = serde_json::json!({"kind":"reasoning_effort_changed", "requested":"high", "effective":"high", |
| 4692 | "provider_kind":tag,"provider":id,"endpoint_identity":"https://example.test/v1","model":"model","ts":1}); |
| 4693 | assert!( |
| 4694 | serde_json::from_value::<WorkActivityEvent>(malformed).is_err(), |
| 4695 | "{tag}/{id}" |
| 4696 | ); |
| 4697 | } |
| 4698 | let legacy = serde_json::json!({"kind":"reasoning_effort_changed", "requested":"high", "effective":"high", "provider":"openai", "ts":1}); |
| 4699 | let WorkActivityEvent::ReasoningEffortChanged { |
| 4700 | provider_kind, |
| 4701 | effective, |
| 4702 | .. |
| 4703 | } = serde_json::from_value(legacy).unwrap(); |
| 4704 | assert!(provider_kind.is_none()); |
| 4705 | assert_eq!(effective, ReasoningEffortTier::Unavailable); |
| 4706 | } |
| 4707 | #[test] |
| 4708 | fn released_all_53_effective_envelopes_keep_actual_serde_bytes() { |
| 4709 | #[derive(Serialize)] |
| 4710 | struct LegacyEnvelope { |
| 4711 | provider: ApiProvider, |
| 4712 | provider_identity: String, |
| 4713 | model: String, |
| 4714 | #[serde(skip_serializing_if = "Option::is_none")] |
| 4715 | openrouter_vendor: Option<String>, |
| 4716 | billing_surface: Option<String>, |
| 4717 | endpoint_fingerprint: Option<String>, |
| 4718 | provider_live_pricing: |
| 4719 | Option<codewhale_engine::provider_catalog_live::ProviderLivePricingQuote>, |
| 4720 | billing_mode: codewhale_engine::cost_status::RouteBillingMode, |
| 4721 | dispatched_at: chrono::DateTime<chrono::Utc>, |
| 4722 | } |
| 4723 | let at = chrono::DateTime::from_timestamp(73, 0).unwrap(); |
| 4724 | for (legacy, kind, id) in cases() { |
| 4725 | for vendor in [None, Some("exact-upstream".to_string())] { |
| 4726 | let old = LegacyEnvelope { |
| 4727 | provider: legacy, |
| 4728 | provider_identity: id.into(), |
| 4729 | model: "model-A".into(), |
| 4730 | openrouter_vendor: vendor.clone(), |
| 4731 | billing_surface: None, |
| 4732 | endpoint_fingerprint: None, |
| 4733 | provider_live_pricing: None, |
| 4734 | billing_mode: codewhale_engine::cost_status::RouteBillingMode::Unknown, |
| 4735 | dispatched_at: at, |
| 4736 | }; |
| 4737 | let current = codewhale_engine::cost_status::EffectiveRouteEnvelope { |
| 4738 | provider: kind, |
| 4739 | provider_identity: id.into(), |
| 4740 | model: "model-A".into(), |
| 4741 | openrouter_vendor: vendor, |
| 4742 | billing_surface: None, |
| 4743 | endpoint_fingerprint: None, |
| 4744 | provider_live_pricing: None, |
| 4745 | billing_mode: codewhale_engine::cost_status::RouteBillingMode::Unknown, |
| 4746 | dispatched_at: at, |
| 4747 | }; |
| 4748 | let expected = serde_json::to_vec(&old).unwrap(); |
| 4749 | assert_eq!(serde_json::to_vec(¤t).unwrap(), expected, "{id}"); |
| 4750 | let decoded: codewhale_engine::cost_status::EffectiveRouteEnvelope = |
| 4751 | serde_json::from_slice(&expected).unwrap(); |
| 4752 | assert_eq!(decoded, current, "decode {id}"); |
| 4753 | assert_eq!( |
| 4754 | serde_json::to_vec(&decoded).unwrap(), |
| 4755 | expected, |
| 4756 | "reencode {id}" |
| 4757 | ); |
| 4758 | } |
| 4759 | } |
| 4760 | } |
| 4761 | |
| 4762 | #[test] |
| 4763 | fn china_wire_tag_config_leaf_and_route_identity_are_distinct_contracts() { |
| 4764 | let config = { |
| 4765 | let __cw_config_init_34_0 = Some("deepseek-cn".into()); |
| 4766 | let mut __cw_config_init_34_value: Config = Default::default(); |
| 4767 | __cw_config_init_34_value.provider = __cw_config_init_34_0; |
| 4768 | __cw_config_init_34_value |
| 4769 | }; |
| 4770 | let identity = config.active_provider_identity().unwrap(); |
| 4771 | assert_eq!(identity.provider, ProviderKind::Deepseek); |
| 4772 | assert_eq!(identity.key.as_str(), "deepseek-cn"); |
| 4773 | assert_eq!(identity.persisted_kind(), "deepseek-cn"); |
| 4774 | assert_eq!(identity.persisted_id(), Some("deepseek-cn")); |
| 4775 | assert_eq!(identity.config_table_key().unwrap(), "deepseek_cn"); |
| 4776 | assert_eq!(provider_config_key(&identity).unwrap(), "deepseek_cn"); |
| 4777 | assert_eq!( |
| 4778 | serde_json::to_string(&ApiProvider::DeepseekCN).unwrap(), |
| 4779 | "\"deepseek_c_n\"" |
| 4780 | ); |
| 4781 | assert_eq!( |
| 4782 | identity.compatibility().unwrap().tui_wire_tag, |
| 4783 | "deepseek_c_n" |
| 4784 | ); |
| 4785 | assert!( |
| 4786 | provider_config_key(&Config::default().active_provider_identity().unwrap()).is_err() |
| 4787 | ); |
| 4788 | } |
| 4789 | |
| 4790 | #[test] |
| 4791 | fn classifier_exact_custom_receipts_keep_case_and_refuse_contradictions() { |
| 4792 | use codewhale_engine::model_routing::AutoRouteDataPath; |
| 4793 | for id in ["openai", "CustomA", "customa"] { |
| 4794 | let source = AutoRouteDataPath::Classifier { |
| 4795 | provider: id.into(), |
| 4796 | provider_kind: ProviderKind::Custom, |
| 4797 | model: "router-model".into(), |
| 4798 | }; |
| 4799 | let value = serde_json::to_value(&source).unwrap(); |
| 4800 | assert_eq!(value["classifier"]["provider"], "custom"); |
| 4801 | assert_eq!(value["classifier"]["provider_id"], id); |
| 4802 | assert_eq!( |
| 4803 | serde_json::from_value::<AutoRouteDataPath>(value).unwrap(), |
| 4804 | source |
| 4805 | ); |
| 4806 | } |
| 4807 | for value in [ |
| 4808 | serde_json::json!({"classifier":{"provider":"openai","provider_id":"CustomA","model":"router-model"}}), |
| 4809 | serde_json::json!({"classifier":{"provider":"custom","provider_id":"","model":"router-model"}}), |
| 4810 | serde_json::json!({"classifier":{"provider":"unknown","model":"router-model"}}), |
| 4811 | ] { |
| 4812 | assert!(serde_json::from_value::<AutoRouteDataPath>(value).is_err()); |
| 4813 | } |
| 4814 | } |
| 4815 | } |
| 4816 |