| 1 | //! Config file path resolution and TOML persistence helpers. |
| 2 | //! |
| 3 | //! These helpers are used by command handlers and non-command UI code, so |
| 4 | //! persistence lives outside the command tree. |
| 5 | //! |
| 6 | //! Every `config.toml` mutation funnels through [`mutate_config_document`]: |
| 7 | //! the file is edited in place with `toml_edit` so unrelated comments, |
| 8 | //! ordering, and formatting survive, and the result is replaced atomically |
| 9 | //! (same-directory temp file + rename) with owner-only permissions. |
| 10 | |
| 11 | use std::path::{Path, PathBuf}; |
| 12 | |
| 13 | use anyhow::Context; |
| 14 | |
| 15 | use crate::config::{ProviderIdentity, StatusItem, expand_path}; |
| 16 | use codewhale_config::ProviderKind; |
| 17 | |
| 18 | /// Parse the TOML document at `path` (an absent or empty file yields an empty |
| 19 | /// document), apply `mutate`, and atomically persist the result. |
| 20 | /// |
| 21 | /// This is the single write path for TUI config mutations: `toml_edit` keeps |
| 22 | /// user comments and formatting intact, and the temp-file + rename write can |
| 23 | /// never leave a half-written config behind. |
| 24 | pub fn mutate_config_document<F>(path: &Path, mutate: F) -> anyhow::Result<()> |
| 25 | where |
| 26 | F: FnOnce(&mut toml_edit::DocumentMut) -> anyhow::Result<()>, |
| 27 | { |
| 28 | mutate_config_document_with_migration(path, |doc, _| mutate(doc)) |
| 29 | } |
| 30 | |
| 31 | /// [`mutate_config_document`], also handing `mutate` the receipt of the legacy |
| 32 | /// top-level `base_url` / `api_key` move this same write made (#6394). |
| 33 | pub(crate) fn mutate_config_document_with_migration<F>(path: &Path, mutate: F) -> anyhow::Result<()> |
| 34 | where |
| 35 | F: FnOnce( |
| 36 | &mut toml_edit::DocumentMut, |
| 37 | &codewhale_config::legacy_root::LegacyRootMigration, |
| 38 | ) -> anyhow::Result<()>, |
| 39 | { |
| 40 | codewhale_config::mutate_config_document_with_migration(path, |doc, moved| { |
| 41 | migrate_legacy_route_preferences(path, doc)?; |
| 42 | mutate(doc, moved) |
| 43 | }) |
| 44 | } |
| 45 | |
| 46 | /// Commit the legacy effective startup selection with its receipt in the same |
| 47 | /// atomic config write. Settings remains untouched, so an interrupted cleanup |
| 48 | /// or an older binary cannot erase the user's historical choices. After this |
| 49 | /// marker, Config never consults those legacy route fields again. |
| 50 | pub fn migrate_legacy_route_preferences( |
| 51 | path: &Path, |
| 52 | doc: &mut toml_edit::DocumentMut, |
| 53 | ) -> anyhow::Result<()> { |
| 54 | if !crate::config::is_home_config_path(path) |
| 55 | || doc |
| 56 | .get("route_preferences_version") |
| 57 | .and_then(toml_edit::Item::as_integer) |
| 58 | .is_some() |
| 59 | { |
| 60 | return Ok(()); |
| 61 | } |
| 62 | let mut config = crate::config::parse_config_base_diagnosed( |
| 63 | "Could not parse configuration for route preference migration", |
| 64 | &doc.to_string(), |
| 65 | )?; |
| 66 | let previous_config = config.clone(); |
| 67 | let settings = |
| 68 | crate::settings::Settings::load_legacy_route_preferences_read_only().map_err(|_| { |
| 69 | anyhow::anyhow!( |
| 70 | "Could not read legacy route preferences; configuration was not changed" |
| 71 | ) |
| 72 | })?; |
| 73 | // An unparsable settings.toml loads as defaults carrying `load_error`, which |
| 74 | // keeps the UI usable but is not evidence that no preferences were saved. |
| 75 | // This migration is one-way: stamping the version over defaults would retire |
| 76 | // the user's real legacy choices unread. Refuse instead, exactly as |
| 77 | // `Settings::save_to_path` refuses to overwrite an unreadable document. |
| 78 | // Contents stay omitted; the file may hold private text. |
| 79 | anyhow::ensure!( |
| 80 | settings.load_error.is_none(), |
| 81 | "Could not read legacy route preferences; configuration was not changed" |
| 82 | ); |
| 83 | if let Some(provider) = settings |
| 84 | .default_provider |
| 85 | .as_deref() |
| 86 | .filter(|provider| !provider.trim().is_empty()) |
| 87 | { |
| 88 | let identity = config.resolve_provider_identity(provider).map_err(|_| anyhow::anyhow!("Legacy saved provider is unavailable in this configuration; route preference migration did not change files"))?; |
| 89 | let mut scoped = config.clone(); |
| 90 | scoped.scope_to_provider_identity(&identity).map_err(|_| anyhow::anyhow!("Legacy saved provider cannot be selected from this configuration; route preference migration did not change files"))?; |
| 91 | } |
| 92 | config.apply_saved_selection(&settings); |
| 93 | if let Some(models) = &settings.provider_models { |
| 94 | for (provider, model) in models { |
| 95 | let model = model.trim(); |
| 96 | if model.is_empty() || model.chars().any(char::is_control) { |
| 97 | continue; |
| 98 | } |
| 99 | let identity = config.legacy_selection_identity(provider).map_err(|_| anyhow::anyhow!("Legacy saved model refers to an unavailable provider; route preference migration did not change files"))?; |
| 100 | let mut scoped = config.clone(); |
| 101 | scoped.scope_to_provider_identity(&identity).map_err(|_| anyhow::anyhow!("Legacy saved model provider cannot be selected from this configuration; route preference migration did not change files"))?; |
| 102 | } |
| 103 | } |
| 104 | let active_identity = config.active_provider_identity().ok(); |
| 105 | let selector = active_identity |
| 106 | .as_ref() |
| 107 | .and_then(|identity| { |
| 108 | identity |
| 109 | .migrated_legacy_ollama_cloud_route |
| 110 | .then(|| identity.persisted_id()) |
| 111 | .flatten() |
| 112 | }) |
| 113 | .or(config.provider.as_deref()); |
| 114 | if let Some(provider) = selector { |
| 115 | if previous_config.provider.as_deref() != Some(provider) |
| 116 | && let Some(previous) = previous_config.provider.as_deref() |
| 117 | { |
| 118 | set_document_value( |
| 119 | doc, |
| 120 | &["route_preferences_migration", "previous_provider"], |
| 121 | previous, |
| 122 | )?; |
| 123 | } |
| 124 | set_document_value(doc, &["provider"], provider)?; |
| 125 | } |
| 126 | let mut providers: Vec<&str> = settings |
| 127 | .provider_models |
| 128 | .as_ref() |
| 129 | .map(|models| models.keys().map(String::as_str).collect()) |
| 130 | .unwrap_or_default(); |
| 131 | if settings.default_model.is_some() { |
| 132 | for provider in [ |
| 133 | ProviderKind::Deepseek.as_str(), |
| 134 | codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id, |
| 135 | ] { |
| 136 | if !providers.contains(&provider) { |
| 137 | providers.push(provider); |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | providers.sort_unstable(); |
| 142 | for provider in providers { |
| 143 | let Ok(identity) = config.legacy_selection_identity(provider) else { |
| 144 | continue; |
| 145 | }; |
| 146 | let mut scoped = config.clone(); |
| 147 | scoped |
| 148 | .scope_to_provider_identity(&identity) |
| 149 | .map_err(anyhow::Error::msg)?; |
| 150 | let model = |
| 151 | if identity.provider == ProviderKind::Custom && identity.persisted_id().is_none() { |
| 152 | scoped.default_text_model.as_deref() |
| 153 | } else { |
| 154 | scoped |
| 155 | .provider_config_for(&identity) |
| 156 | .and_then(|entry| entry.model.as_deref()) |
| 157 | }; |
| 158 | if let Some(model) = model { |
| 159 | let mut previous = previous_config.clone(); |
| 160 | previous |
| 161 | .scope_to_provider_identity(&identity) |
| 162 | .map_err(anyhow::Error::msg)?; |
| 163 | if let Some(old_model) = previous |
| 164 | .provider_config_for(&identity) |
| 165 | .and_then(|entry| entry.model.as_deref()) |
| 166 | .or_else(|| { |
| 167 | (previous_config.active_provider_identity().ok().as_ref() == Some(&identity)) |
| 168 | .then_some(previous_config.default_text_model.as_deref()) |
| 169 | .flatten() |
| 170 | }) |
| 171 | && old_model != model |
| 172 | { |
| 173 | // Keep the displaced Config choice as an inert migration |
| 174 | // receipt. Nothing resolves routes from this archive. |
| 175 | set_document_value( |
| 176 | doc, |
| 177 | &[ |
| 178 | "route_preferences_migration", |
| 179 | "previous_models", |
| 180 | identity.key.as_str(), |
| 181 | ], |
| 182 | old_model, |
| 183 | )?; |
| 184 | } |
| 185 | set_verified_provider_model_document(doc, &config, &identity, model)?; |
| 186 | } |
| 187 | } |
| 188 | set_document_value(doc, &["route_preferences_version"], 1_i64) |
| 189 | } |
| 190 | |
| 191 | // `config` is the freshly parsed same-lock document, before any intended delta. |
| 192 | // Reuse that projection so a root receipt is not dropped by a second parse of |
| 193 | // the canonicalized document. Every path verifies before writing the delta. |
| 194 | pub fn set_verified_provider_model_document( |
| 195 | doc: &mut toml_edit::DocumentMut, |
| 196 | config: &crate::config::Config, |
| 197 | identity: &ProviderIdentity, |
| 198 | model: &str, |
| 199 | ) -> anyhow::Result<()> { |
| 200 | anyhow::ensure!( |
| 201 | !model.trim().is_empty() && !model.chars().any(char::is_control), |
| 202 | "model must be nonempty and contain no control characters" |
| 203 | ); |
| 204 | config |
| 205 | .verify_provider_identity(identity) |
| 206 | .map_err(anyhow::Error::msg)?; |
| 207 | let provider_key = identity.config_table_key()?; |
| 208 | set_document_value(doc, &["providers", provider_key, "model"], model) |
| 209 | } |
| 210 | |
| 211 | /// Atomically replace `path` with `body` via a same-directory temp file and |
| 212 | /// rename. On Unix the file lands with 0o600 permissions: config.toml can |
| 213 | /// hold API keys, so this matches `ConfigStore::save` and the auth save path. |
| 214 | pub(crate) fn write_config_toml_atomic(path: &Path, body: &str) -> anyhow::Result<()> { |
| 215 | codewhale_config::create_config_document(path, body) |
| 216 | } |
| 217 | |
| 218 | /// Set the value at `segments` (parent tables plus the final key), creating |
| 219 | /// missing intermediate tables. Replacing an existing value keeps its decor, |
| 220 | /// so comments above the key and trailing same-line comments survive. |
| 221 | /// |
| 222 | /// Segments are separate strings rather than one dotted key, so table names |
| 223 | /// that need quoting (`[providers."my.provider"]`) resolve correctly. |
| 224 | pub fn set_document_value( |
| 225 | doc: &mut toml_edit::DocumentMut, |
| 226 | segments: &[&str], |
| 227 | value: impl Into<toml_edit::Value>, |
| 228 | ) -> anyhow::Result<()> { |
| 229 | codewhale_config::set_config_document_value(doc, segments, value) |
| 230 | } |
| 231 | |
| 232 | /// Remove the value at `segments`. Returns `Ok(true)` when an entry was |
| 233 | /// removed; missing keys and missing (or non-table) parents are a no-op. |
| 234 | pub fn unset_document_value( |
| 235 | doc: &mut toml_edit::DocumentMut, |
| 236 | segments: &[&str], |
| 237 | ) -> anyhow::Result<bool> { |
| 238 | codewhale_config::unset_config_document_value(doc, segments) |
| 239 | } |
| 240 | |
| 241 | /// Remove every entry named `key` from `table` and, recursively, from nested |
| 242 | /// tables, inline tables, and arrays of tables. Used by `/logout` to strip |
| 243 | /// `api_key` everywhere without disturbing keys like `api_key_env`. |
| 244 | pub(crate) fn remove_document_key_recursive(table: &mut dyn toml_edit::TableLike, key: &str) { |
| 245 | remove_key_preserving_leading_decor(table, key); |
| 246 | for (_, item) in table.iter_mut() { |
| 247 | if let toml_edit::Item::ArrayOfTables(tables) = item { |
| 248 | for nested in tables.iter_mut() { |
| 249 | remove_document_key_recursive(nested, key); |
| 250 | } |
| 251 | } else if let Some(nested) = item.as_table_like_mut() { |
| 252 | remove_document_key_recursive(nested, key); |
| 253 | } |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | fn remove_key_preserving_leading_decor(table: &mut dyn toml_edit::TableLike, key: &str) -> bool { |
| 258 | let mut found = false; |
| 259 | let next_key = table.iter().find_map(|(candidate, _)| { |
| 260 | if found { |
| 261 | Some(candidate.to_owned()) |
| 262 | } else { |
| 263 | found = candidate == key; |
| 264 | None |
| 265 | } |
| 266 | }); |
| 267 | let leading_prefix = leading_prefix_for_key(table, key); |
| 268 | if table.remove(key).is_none() { |
| 269 | return false; |
| 270 | } |
| 271 | let Some(prefix) = leading_prefix else { |
| 272 | return true; |
| 273 | }; |
| 274 | let Some(next_key) = next_key else { |
| 275 | return true; |
| 276 | }; |
| 277 | if prefix.as_str() == Some("") { |
| 278 | return true; |
| 279 | } |
| 280 | if let Some(mut next_key_decor) = table.key_mut(&next_key) |
| 281 | && decor_prefix_is_empty(next_key_decor.leaf_decor()) |
| 282 | { |
| 283 | next_key_decor.leaf_decor_mut().set_prefix(prefix); |
| 284 | } |
| 285 | true |
| 286 | } |
| 287 | |
| 288 | fn decor_prefix_is_empty(decor: &toml_edit::Decor) -> bool { |
| 289 | match decor.prefix() { |
| 290 | Some(prefix) => prefix.as_str() == Some(""), |
| 291 | None => true, |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | fn leading_prefix_for_key( |
| 296 | table: &dyn toml_edit::TableLike, |
| 297 | key: &str, |
| 298 | ) -> Option<toml_edit::RawString> { |
| 299 | table |
| 300 | .key(key) |
| 301 | .and_then(|key| key.leaf_decor().prefix().cloned()) |
| 302 | .or_else(|| { |
| 303 | table |
| 304 | .get(key) |
| 305 | .and_then(|item| item.as_value()) |
| 306 | .and_then(|value| value.decor().prefix().cloned()) |
| 307 | }) |
| 308 | } |
| 309 | |
| 310 | pub fn persist_status_items(items: &[StatusItem]) -> anyhow::Result<PathBuf> { |
| 311 | let path = config_toml_path(None)?; |
| 312 | let items: toml_edit::Array = items.iter().map(|item| item.key()).collect(); |
| 313 | mutate_config_document(&path, |doc| { |
| 314 | set_document_value(doc, &["tui", "status_items"], items) |
| 315 | })?; |
| 316 | Ok(path) |
| 317 | } |
| 318 | |
| 319 | pub fn persist_root_string_key( |
| 320 | config_path: Option<&Path>, |
| 321 | key: &str, |
| 322 | value: &str, |
| 323 | ) -> anyhow::Result<PathBuf> { |
| 324 | let path = config_toml_path(config_path)?; |
| 325 | mutate_config_document(&path, |doc| set_document_value(doc, &[key], value))?; |
| 326 | Ok(path) |
| 327 | } |
| 328 | |
| 329 | pub fn persist_unset_root_key(config_path: Option<&Path>, key: &str) -> anyhow::Result<PathBuf> { |
| 330 | let path = config_toml_path(config_path)?; |
| 331 | mutate_config_document(&path, |doc| unset_document_value(doc, &[key]).map(|_| ()))?; |
| 332 | Ok(path) |
| 333 | } |
| 334 | |
| 335 | pub fn persist_unset_table_key( |
| 336 | config_path: Option<&Path>, |
| 337 | table_name: &str, |
| 338 | key: &str, |
| 339 | ) -> anyhow::Result<PathBuf> { |
| 340 | let path = config_toml_path(config_path)?; |
| 341 | mutate_config_document(&path, |doc| { |
| 342 | unset_document_value(doc, &[table_name, key]).map(|_| ()) |
| 343 | })?; |
| 344 | Ok(path) |
| 345 | } |
| 346 | |
| 347 | pub fn persist_root_bool_key( |
| 348 | config_path: Option<&Path>, |
| 349 | key: &str, |
| 350 | value: bool, |
| 351 | ) -> anyhow::Result<PathBuf> { |
| 352 | let path = config_toml_path(config_path)?; |
| 353 | mutate_config_document(&path, |doc| set_document_value(doc, &[key], value))?; |
| 354 | Ok(path) |
| 355 | } |
| 356 | |
| 357 | pub fn persist_subagents_bool_key( |
| 358 | config_path: Option<&Path>, |
| 359 | key: &str, |
| 360 | value: bool, |
| 361 | ) -> anyhow::Result<PathBuf> { |
| 362 | persist_table_value_key(config_path, "subagents", key, value.into()) |
| 363 | } |
| 364 | |
| 365 | pub fn persist_mini_window_bool_key( |
| 366 | config_path: Option<&Path>, |
| 367 | key: &str, |
| 368 | value: bool, |
| 369 | ) -> anyhow::Result<PathBuf> { |
| 370 | persist_table_value_key(config_path, "mini_window", key, value.into()) |
| 371 | } |
| 372 | |
| 373 | pub fn persist_subagents_integer_key( |
| 374 | config_path: Option<&Path>, |
| 375 | key: &str, |
| 376 | value: u64, |
| 377 | ) -> anyhow::Result<PathBuf> { |
| 378 | let value = i64::try_from(value).context("integer value is too large for TOML")?; |
| 379 | persist_table_value_key(config_path, "subagents", key, value.into()) |
| 380 | } |
| 381 | |
| 382 | pub fn persist_table_bool_key( |
| 383 | config_path: Option<&Path>, |
| 384 | table_name: &str, |
| 385 | key: &str, |
| 386 | value: bool, |
| 387 | ) -> anyhow::Result<PathBuf> { |
| 388 | persist_table_value_key(config_path, table_name, key, value.into()) |
| 389 | } |
| 390 | |
| 391 | pub fn persist_table_string_key( |
| 392 | config_path: Option<&Path>, |
| 393 | table_name: &str, |
| 394 | key: &str, |
| 395 | value: &str, |
| 396 | ) -> anyhow::Result<PathBuf> { |
| 397 | persist_table_value_key(config_path, table_name, key, value.into()) |
| 398 | } |
| 399 | |
| 400 | pub fn persist_table_string_key_undoable( |
| 401 | config_path: Option<&Path>, |
| 402 | table_name: &str, |
| 403 | key: &str, |
| 404 | value: &str, |
| 405 | ) -> anyhow::Result<(PathBuf, codewhale_config::ConfigDocumentUndo)> { |
| 406 | let path = config_toml_path(config_path)?; |
| 407 | let ((), undo) = |
| 408 | codewhale_config::mutate_config_document_undoable_with_migration(&path, |doc, _| { |
| 409 | migrate_legacy_route_preferences(&path, doc)?; |
| 410 | set_document_value(doc, &[table_name, key], value) |
| 411 | })?; |
| 412 | Ok((path, undo)) |
| 413 | } |
| 414 | |
| 415 | pub fn persist_table_value_key( |
| 416 | config_path: Option<&Path>, |
| 417 | table_name: &str, |
| 418 | key: &str, |
| 419 | value: toml_edit::Value, |
| 420 | ) -> anyhow::Result<PathBuf> { |
| 421 | let path = config_toml_path(config_path)?; |
| 422 | mutate_config_document(&path, |doc| { |
| 423 | set_document_value(doc, &[table_name, key], value) |
| 424 | })?; |
| 425 | Ok(path) |
| 426 | } |
| 427 | |
| 428 | /// Persist the endpoint that `GET /v1/config` reports as `base_url`. |
| 429 | /// |
| 430 | /// That value belongs to exactly one route, and the route keeps it in exactly |
| 431 | /// one place: its own `[providers.<table>]` table — the typed table for a |
| 432 | /// built-in, the exact `[providers.<name>]` table for a custom route. There is |
| 433 | /// no top-level `base_url` any more (#6394); writing one used to hand a |
| 434 | /// DeepSeek endpoint to every route that inherited it. |
| 435 | pub fn persist_route_base_url( |
| 436 | config_path: Option<&Path>, |
| 437 | identity: &ProviderIdentity, |
| 438 | value: &str, |
| 439 | ) -> anyhow::Result<PathBuf> { |
| 440 | let path = config_toml_path(config_path)?; |
| 441 | mutate_config_document_with_migration(&path, |doc, moved| { |
| 442 | let config = crate::config::parse_config_after_locked_migration_diagnosed( |
| 443 | "Could not parse destination route", |
| 444 | &doc.to_string(), |
| 445 | moved, |
| 446 | )?; |
| 447 | config |
| 448 | .verify_provider_identity(identity) |
| 449 | .map_err(anyhow::Error::msg)?; |
| 450 | let table = if identity.provider == ProviderKind::Custom { |
| 451 | identity.key.as_str() |
| 452 | } else { |
| 453 | provider_base_url_table_key(identity)? |
| 454 | }; |
| 455 | set_document_value(doc, &["providers", table, "base_url"], value) |
| 456 | })?; |
| 457 | Ok(path) |
| 458 | } |
| 459 | |
| 460 | /// Persist the model for one exact provider route without rewriting the |
| 461 | /// legacy root DeepSeek fallback used by unrelated providers. |
| 462 | /// |
| 463 | /// Built-in providers write to their typed `[providers.<name>]` table, while |
| 464 | /// named custom routes use their exact user-owned table id. The locked writer first preserves legacy root provenance, then writes the |
| 465 | /// canonical leaf created by its one-way migration. |
| 466 | pub fn persist_provider_model_key( |
| 467 | config_path: Option<&Path>, |
| 468 | identity: &ProviderIdentity, |
| 469 | value: &str, |
| 470 | ) -> anyhow::Result<PathBuf> { |
| 471 | let path = config_toml_path(config_path)?; |
| 472 | mutate_config_document_with_migration(&path, |doc, moved| { |
| 473 | let config = crate::config::parse_config_after_locked_migration_diagnosed( |
| 474 | "Could not parse destination route", |
| 475 | &doc.to_string(), |
| 476 | moved, |
| 477 | )?; |
| 478 | set_verified_provider_model_document(doc, &config, identity, value) |
| 479 | })?; |
| 480 | Ok(path) |
| 481 | } |
| 482 | |
| 483 | pub fn persist_provider_model_context_window( |
| 484 | config_path: Option<&Path>, |
| 485 | profile: Option<&str>, |
| 486 | identity: &ProviderIdentity, |
| 487 | model: &str, |
| 488 | tokens: Option<u32>, |
| 489 | ) -> anyhow::Result<PathBuf> { |
| 490 | let model = model.trim(); |
| 491 | if model.is_empty() |
| 492 | || model.eq_ignore_ascii_case("auto") |
| 493 | || model.chars().any(char::is_whitespace) |
| 494 | { |
| 495 | anyhow::bail!("invalid model id for `model_context_windows`: '{model}'"); |
| 496 | } |
| 497 | if let Some(tokens) = tokens |
| 498 | && !(4_096..=10_000_000).contains(&tokens) |
| 499 | { |
| 500 | anyhow::bail!("context window must be between 4,096 and 10,000,000 tokens (got {tokens})"); |
| 501 | } |
| 502 | let path = config_toml_path(config_path)?; |
| 503 | let table = identity.config_table_key()?; |
| 504 | anyhow::ensure!( |
| 505 | profile.is_none() || identity.legacy_root_custom_generation.is_none(), |
| 506 | "To save a profile-specific context window on this legacy custom route, select a named provider in the profile first" |
| 507 | ); |
| 508 | let edit = |doc: &mut toml_edit::DocumentMut| -> anyhow::Result<()> { |
| 509 | let mut keys = Vec::new(); |
| 510 | if let Some(profile) = profile { |
| 511 | keys.extend(["profiles", profile]); |
| 512 | } |
| 513 | if identity.legacy_root_custom_generation.is_none() { |
| 514 | keys.extend(["providers", table]); |
| 515 | } |
| 516 | keys.push("model_context_windows"); |
| 517 | let lookup = |keys: &[&str]| { |
| 518 | keys.iter() |
| 519 | .try_fold(doc.as_item(), |item, key| item.get(key)) |
| 520 | }; |
| 521 | if profile.is_some() |
| 522 | && lookup(&keys).is_none() |
| 523 | && let Some(inherited) = lookup(&["providers", table, "model_context_windows"]) |
| 524 | { |
| 525 | let inherited = inherited |
| 526 | .clone() |
| 527 | .into_value() |
| 528 | .map_err(|_| anyhow::anyhow!("Invalid inherited model context windows"))?; |
| 529 | set_document_value(doc, &keys, inherited)?; |
| 530 | } |
| 531 | keys.push(model); |
| 532 | if let Some(tokens) = tokens { |
| 533 | return set_document_value(doc, &keys, i64::from(tokens)); |
| 534 | } |
| 535 | unset_document_value(doc, &keys)?; |
| 536 | keys.pop(); |
| 537 | if profile.is_none() |
| 538 | && keys |
| 539 | .iter() |
| 540 | .try_fold(doc.as_item(), |item, key| item.get(key)) |
| 541 | .and_then(toml_edit::Item::as_table_like) |
| 542 | .is_some_and(|windows| windows.is_empty()) |
| 543 | { |
| 544 | unset_document_value(doc, &keys)?; |
| 545 | } |
| 546 | Ok(()) |
| 547 | }; |
| 548 | if identity.legacy_root_custom_generation.is_some() { |
| 549 | let original = codewhale_config::read_checked_config_file(&path)?; |
| 550 | let mut config = crate::config::parse_config_base_diagnosed( |
| 551 | "Could not parse destination route", |
| 552 | &original, |
| 553 | )?; |
| 554 | let next_identity = config |
| 555 | .set_model_context_window_for(identity, model, tokens) |
| 556 | .map_err(anyhow::Error::msg)?; |
| 557 | let mut doc = original |
| 558 | .parse::<toml_edit::DocumentMut>() |
| 559 | .map_err(|_| anyhow::anyhow!("Could not parse destination route; contents omitted"))?; |
| 560 | edit(&mut doc)?; |
| 561 | let body = doc.to_string(); |
| 562 | crate::config::parse_config_base_diagnosed("Could not parse updated route", &body)? |
| 563 | .verify_provider_identity(&next_identity) |
| 564 | .map_err(anyhow::Error::msg)?; |
| 565 | codewhale_config::replace_config_document_if_unchanged(&path, Some(&original), &body)?; |
| 566 | } else { |
| 567 | mutate_config_document(&path, |doc| { |
| 568 | let config = crate::config::Config::from_saved_document(&doc.to_string(), profile)?; |
| 569 | config |
| 570 | .verify_provider_identity(identity) |
| 571 | .map_err(anyhow::Error::msg)?; |
| 572 | edit(doc) |
| 573 | })?; |
| 574 | } |
| 575 | Ok(path) |
| 576 | } |
| 577 | |
| 578 | fn provider_base_url_table_key(identity: &ProviderIdentity) -> anyhow::Result<&'static str> { |
| 579 | identity |
| 580 | .compatibility() |
| 581 | .map(|row| row.base_url_config_key) |
| 582 | .context("custom providers store base_url in their named [providers.<name>] table") |
| 583 | } |
| 584 | |
| 585 | pub fn persist_custom_provider( |
| 586 | config_path: Option<&Path>, |
| 587 | provider_id: &str, |
| 588 | base_url: &str, |
| 589 | model: Option<&str>, |
| 590 | api_key_env: Option<&str>, |
| 591 | ) -> anyhow::Result<PathBuf> { |
| 592 | let provider_id = normalize_custom_provider_id(provider_id)?; |
| 593 | let base_url = normalize_custom_provider_base_url(base_url)?; |
| 594 | let model = model.and_then(normalize_optional_custom_provider_field); |
| 595 | let api_key_env = api_key_env.and_then(normalize_optional_custom_provider_field); |
| 596 | |
| 597 | let path = config_toml_path(config_path)?; |
| 598 | mutate_config_document(&path, |doc| { |
| 599 | let entry = ["providers", provider_id.as_str()]; |
| 600 | set_document_value(doc, &["provider"], provider_id.as_str())?; |
| 601 | set_document_value(doc, &[entry[0], entry[1], "kind"], "openai-compatible")?; |
| 602 | set_document_value(doc, &[entry[0], entry[1], "base_url"], base_url.as_str())?; |
| 603 | if provider_id == "ds4" && crate::config::base_url_uses_local_host(&base_url) { |
| 604 | // Match the documented starter server. DS4 explicitly requires |
| 605 | // clients not to budget beyond the server's --ctx value. |
| 606 | set_document_value(doc, &[entry[0], entry[1], "context_window"], 100_000)?; |
| 607 | } |
| 608 | match model.as_deref() { |
| 609 | Some(model) => set_document_value(doc, &[entry[0], entry[1], "model"], model)?, |
| 610 | None => { |
| 611 | unset_document_value(doc, &[entry[0], entry[1], "model"])?; |
| 612 | } |
| 613 | } |
| 614 | match api_key_env.as_deref() { |
| 615 | Some(env) => { |
| 616 | set_document_value(doc, &[entry[0], entry[1], "api_key_env"], env)?; |
| 617 | unset_document_value(doc, &[entry[0], entry[1], "auth_mode"])?; |
| 618 | } |
| 619 | None => { |
| 620 | unset_document_value(doc, &[entry[0], entry[1], "api_key_env"])?; |
| 621 | if provider_id == "ds4" && crate::config::base_url_uses_local_host(&base_url) { |
| 622 | set_document_value(doc, &[entry[0], entry[1], "auth_mode"], "none")?; |
| 623 | } else { |
| 624 | unset_document_value(doc, &[entry[0], entry[1], "auth_mode"])?; |
| 625 | } |
| 626 | } |
| 627 | } |
| 628 | Ok(()) |
| 629 | })?; |
| 630 | Ok(path) |
| 631 | } |
| 632 | |
| 633 | fn normalize_custom_provider_id(raw: &str) -> anyhow::Result<String> { |
| 634 | use anyhow::bail; |
| 635 | |
| 636 | let value = raw.trim(); |
| 637 | if value.is_empty() { |
| 638 | bail!("custom provider name is required"); |
| 639 | } |
| 640 | if value == "__custom__" { |
| 641 | bail!("custom provider name is reserved"); |
| 642 | } |
| 643 | if codewhale_config::ProviderKind::parse(value).is_some() { |
| 644 | bail!("custom provider name must not shadow a built-in provider"); |
| 645 | } |
| 646 | if !value |
| 647 | .chars() |
| 648 | .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-')) |
| 649 | { |
| 650 | bail!("custom provider name may only use letters, numbers, '-' and '_'"); |
| 651 | } |
| 652 | Ok(value.to_string()) |
| 653 | } |
| 654 | |
| 655 | fn normalize_custom_provider_base_url(raw: &str) -> anyhow::Result<String> { |
| 656 | use anyhow::bail; |
| 657 | |
| 658 | let value = raw.trim().trim_end_matches('/'); |
| 659 | if value.is_empty() { |
| 660 | bail!("custom provider base URL is required"); |
| 661 | } |
| 662 | let parsed = reqwest::Url::parse(value) |
| 663 | .map_err(|err| anyhow::anyhow!("custom provider base URL is invalid: {err}"))?; |
| 664 | if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() { |
| 665 | bail!("custom provider base URL must be an http(s) URL with a host"); |
| 666 | } |
| 667 | Ok(value.to_string()) |
| 668 | } |
| 669 | |
| 670 | fn normalize_optional_custom_provider_field(raw: &str) -> Option<String> { |
| 671 | let value = raw.trim(); |
| 672 | (!value.is_empty()).then(|| value.to_string()) |
| 673 | } |
| 674 | |
| 675 | pub fn persist_hotbar_bindings( |
| 676 | config_path: Option<&Path>, |
| 677 | bindings: &[codewhale_config::HotbarBindingToml], |
| 678 | ) -> anyhow::Result<PathBuf> { |
| 679 | let path = config_toml_path(config_path)?; |
| 680 | mutate_config_document(&path, |doc| { |
| 681 | let table = doc.as_table_mut(); |
| 682 | table.remove("hotbar"); |
| 683 | if bindings.is_empty() { |
| 684 | table.insert( |
| 685 | "hotbar", |
| 686 | toml_edit::Item::Value(toml_edit::Value::Array(toml_edit::Array::new())), |
| 687 | ); |
| 688 | } else { |
| 689 | let mut hotbar = toml_edit::ArrayOfTables::new(); |
| 690 | for binding in bindings { |
| 691 | let mut entry = toml_edit::Table::new(); |
| 692 | entry["slot"] = toml_edit::value(i64::from(binding.slot)); |
| 693 | entry["action"] = toml_edit::value(binding.action.clone()); |
| 694 | if let Some(label) = binding.label.as_deref() { |
| 695 | entry["label"] = toml_edit::value(label); |
| 696 | } |
| 697 | hotbar.push(entry); |
| 698 | } |
| 699 | table.insert("hotbar", toml_edit::Item::ArrayOfTables(hotbar)); |
| 700 | } |
| 701 | Ok(()) |
| 702 | })?; |
| 703 | Ok(path) |
| 704 | } |
| 705 | |
| 706 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 707 | pub struct NetworkAllowOutcome { |
| 708 | pub host: String, |
| 709 | pub default: String, |
| 710 | pub allow: Vec<String>, |
| 711 | pub deny: Vec<String>, |
| 712 | pub audit: bool, |
| 713 | } |
| 714 | |
| 715 | fn normalize_network_host_for_compare(host: &str) -> String { |
| 716 | let trimmed = host.trim().trim_end_matches('.').to_ascii_lowercase(); |
| 717 | if let Some(rest) = trimmed.strip_prefix("*.") { |
| 718 | format!(".{rest}") |
| 719 | } else { |
| 720 | trimmed |
| 721 | } |
| 722 | } |
| 723 | |
| 724 | pub fn normalize_network_allow_host(input: &str) -> anyhow::Result<String> { |
| 725 | let trimmed = input.trim(); |
| 726 | if trimmed.is_empty() |
| 727 | || trimmed |
| 728 | .chars() |
| 729 | .any(|ch| ch.is_whitespace() || ch.is_control()) |
| 730 | { |
| 731 | anyhow::bail!("host cannot be empty or contain whitespace"); |
| 732 | } |
| 733 | let host = if trimmed.starts_with("http://") || trimmed.starts_with("https://") { |
| 734 | let parsed = reqwest::Url::parse(trimmed).context("URL must include a valid host")?; |
| 735 | parsed |
| 736 | .host_str() |
| 737 | .context("URL must include a host")? |
| 738 | .to_ascii_lowercase() |
| 739 | } else { |
| 740 | if trimmed.contains("://") || trimmed.contains('/') { |
| 741 | anyhow::bail!("Pass a host like `github.com`, not a URL path"); |
| 742 | } |
| 743 | trimmed.to_string() |
| 744 | }; |
| 745 | let normalized = normalize_network_host_for_compare(&host); |
| 746 | if normalized.is_empty() || normalized == "." || normalized == "*" { |
| 747 | anyhow::bail!("host cannot be empty"); |
| 748 | } |
| 749 | Ok(normalized) |
| 750 | } |
| 751 | |
| 752 | fn network_string_array(doc: &toml_edit::DocumentMut, key: &str) -> anyhow::Result<Vec<String>> { |
| 753 | let Some(item) = doc |
| 754 | .get("network") |
| 755 | .and_then(toml_edit::Item::as_table_like) |
| 756 | .and_then(|table| table.get(key)) |
| 757 | else { |
| 758 | return Ok(Vec::new()); |
| 759 | }; |
| 760 | let array = item |
| 761 | .as_array() |
| 762 | .with_context(|| format!("`network.{key}` must be an array of strings"))?; |
| 763 | array |
| 764 | .iter() |
| 765 | .map(|value| { |
| 766 | value |
| 767 | .as_str() |
| 768 | .map(ToString::to_string) |
| 769 | .with_context(|| format!("`network.{key}` must be an array of strings")) |
| 770 | }) |
| 771 | .collect() |
| 772 | } |
| 773 | |
| 774 | pub fn persist_network_allow_host( |
| 775 | config_path: Option<&Path>, |
| 776 | raw_host: &str, |
| 777 | ) -> anyhow::Result<NetworkAllowOutcome> { |
| 778 | let host = normalize_network_allow_host(raw_host)?; |
| 779 | let path = config_toml_path(config_path)?; |
| 780 | let mut default = "prompt".to_string(); |
| 781 | let mut audit = true; |
| 782 | let mut allow_out = Vec::new(); |
| 783 | let mut deny_out = Vec::new(); |
| 784 | mutate_config_document(&path, |doc| { |
| 785 | if doc |
| 786 | .get("network") |
| 787 | .and_then(toml_edit::Item::as_table_like) |
| 788 | .and_then(|table| table.get("default")) |
| 789 | .is_none() |
| 790 | { |
| 791 | set_document_value(doc, &["network", "default"], "prompt")?; |
| 792 | } |
| 793 | if doc |
| 794 | .get("network") |
| 795 | .and_then(toml_edit::Item::as_table_like) |
| 796 | .and_then(|table| table.get("audit")) |
| 797 | .is_none() |
| 798 | { |
| 799 | set_document_value(doc, &["network", "audit"], true)?; |
| 800 | } |
| 801 | if let Some(current_default) = doc |
| 802 | .get("network") |
| 803 | .and_then(toml_edit::Item::as_table_like) |
| 804 | .and_then(|table| table.get("default")) |
| 805 | .and_then(toml_edit::Item::as_str) |
| 806 | { |
| 807 | default = current_default.to_string(); |
| 808 | } |
| 809 | if let Some(current_audit) = doc |
| 810 | .get("network") |
| 811 | .and_then(toml_edit::Item::as_table_like) |
| 812 | .and_then(|table| table.get("audit")) |
| 813 | .and_then(toml_edit::Item::as_bool) |
| 814 | { |
| 815 | audit = current_audit; |
| 816 | } |
| 817 | let mut allow = network_string_array(doc, "allow")?; |
| 818 | let mut deny = network_string_array(doc, "deny")?; |
| 819 | deny.retain(|existing| normalize_network_host_for_compare(existing) != host); |
| 820 | if !allow |
| 821 | .iter() |
| 822 | .any(|existing| normalize_network_host_for_compare(existing) == host) |
| 823 | { |
| 824 | allow.push(host.clone()); |
| 825 | } |
| 826 | let allow_arr: toml_edit::Array = allow.iter().map(String::as_str).collect(); |
| 827 | let deny_arr: toml_edit::Array = deny.iter().map(String::as_str).collect(); |
| 828 | set_document_value(doc, &["network", "allow"], allow_arr)?; |
| 829 | set_document_value(doc, &["network", "deny"], deny_arr)?; |
| 830 | allow_out = allow; |
| 831 | deny_out = deny; |
| 832 | Ok(()) |
| 833 | })?; |
| 834 | Ok(NetworkAllowOutcome { |
| 835 | host, |
| 836 | default, |
| 837 | allow: allow_out, |
| 838 | deny: deny_out, |
| 839 | audit, |
| 840 | }) |
| 841 | } |
| 842 | |
| 843 | pub fn config_toml_path(config_path: Option<&Path>) -> anyhow::Result<PathBuf> { |
| 844 | if let Some(path) = config_path { |
| 845 | return Ok(expand_path(path.to_string_lossy().as_ref())); |
| 846 | } |
| 847 | crate::config::resolve_load_config_path(None)? |
| 848 | .context("failed to resolve the active config.toml path") |
| 849 | } |
| 850 | |
| 851 | #[cfg(test)] |
| 852 | mod tests { |
| 853 | |
| 854 | use super::*; |
| 855 | |
| 856 | use std::env; |
| 857 | |
| 858 | use std::fs; |
| 859 | |
| 860 | use std::path::Path; |
| 861 | |
| 862 | use super::test_support::*; |
| 863 | |
| 864 | struct EnvGuard { |
| 865 | _home: crate::test_support::EnvVarGuard, |
| 866 | _userprofile: crate::test_support::EnvVarGuard, |
| 867 | _codewhale_home: crate::test_support::EnvVarGuard, |
| 868 | _codewhale_config_path: crate::test_support::EnvVarGuard, |
| 869 | _deepseek_config_path: crate::test_support::EnvVarGuard, |
| 870 | _lock: crate::test_support::TestEnvLock, |
| 871 | } |
| 872 | |
| 873 | impl EnvGuard { |
| 874 | fn new(home: &Path) -> Self { |
| 875 | let lock = crate::test_support::lock_test_env(); |
| 876 | let config_path = home.join(".deepseek").join("config.toml"); |
| 877 | Self { |
| 878 | _home: crate::test_support::EnvVarGuard::set("HOME", home), |
| 879 | _userprofile: crate::test_support::EnvVarGuard::set("USERPROFILE", home), |
| 880 | _codewhale_home: crate::test_support::EnvVarGuard::remove("CODEWHALE_HOME"), |
| 881 | _codewhale_config_path: crate::test_support::EnvVarGuard::remove( |
| 882 | "CODEWHALE_CONFIG_PATH", |
| 883 | ), |
| 884 | _deepseek_config_path: crate::test_support::EnvVarGuard::set( |
| 885 | "DEEPSEEK_CONFIG_PATH", |
| 886 | &config_path, |
| 887 | ), |
| 888 | _lock: lock, |
| 889 | } |
| 890 | } |
| 891 | } |
| 892 | |
| 893 | fn temp_root(prefix: &str) -> std::path::PathBuf { |
| 894 | crate::test_support::test_scratch_dir(prefix) |
| 895 | } |
| 896 | |
| 897 | #[test] |
| 898 | fn persist_status_items_writes_tui_section_to_config_toml() { |
| 899 | let temp_root = temp_root("codewhale-statusline-persist"); |
| 900 | fs::create_dir_all(&temp_root).unwrap(); |
| 901 | let _guard = EnvGuard::new(&temp_root); |
| 902 | |
| 903 | let items = vec![ |
| 904 | crate::config::StatusItem::Mode, |
| 905 | crate::config::StatusItem::Model, |
| 906 | crate::config::StatusItem::Cost, |
| 907 | ]; |
| 908 | |
| 909 | let path = persist_status_items(&items).expect("persist should succeed"); |
| 910 | let body = fs::read_to_string(&path).expect("written file should be readable"); |
| 911 | assert!(body.contains("[tui]"), "expected [tui] section in {body}"); |
| 912 | assert!( |
| 913 | body.contains("status_items"), |
| 914 | "expected status_items key in {body}" |
| 915 | ); |
| 916 | assert!(body.contains("\"mode\""), "expected mode key in {body}"); |
| 917 | assert!(body.contains("\"cost\""), "expected cost key in {body}"); |
| 918 | } |
| 919 | |
| 920 | #[test] |
| 921 | fn config_toml_path_uses_codewhale_home_for_fresh_installs() { |
| 922 | let temp_root = temp_root("codewhale-config-path-fresh"); |
| 923 | fs::create_dir_all(&temp_root).unwrap(); |
| 924 | let _guard = EnvGuard::new(&temp_root); |
| 925 | |
| 926 | unsafe { |
| 927 | env::remove_var("DEEPSEEK_CONFIG_PATH"); |
| 928 | } |
| 929 | |
| 930 | assert_eq!( |
| 931 | config_toml_path(None).unwrap(), |
| 932 | temp_root.join(".codewhale").join("config.toml") |
| 933 | ); |
| 934 | } |
| 935 | |
| 936 | #[test] |
| 937 | fn config_toml_path_preserves_legacy_config_when_it_exists() { |
| 938 | let temp_root = temp_root("codewhale-config-path-legacy"); |
| 939 | let legacy_config = temp_root.join(".deepseek").join("config.toml"); |
| 940 | fs::create_dir_all(legacy_config.parent().unwrap()).unwrap(); |
| 941 | fs::write(&legacy_config, "").unwrap(); |
| 942 | let _guard = EnvGuard::new(&temp_root); |
| 943 | |
| 944 | unsafe { |
| 945 | env::remove_var("DEEPSEEK_CONFIG_PATH"); |
| 946 | } |
| 947 | |
| 948 | assert_eq!(config_toml_path(None).unwrap(), legacy_config); |
| 949 | } |
| 950 | |
| 951 | #[test] |
| 952 | fn config_toml_path_ignores_legacy_config_when_codewhale_home_is_explicit() { |
| 953 | let temp_root = temp_root("codewhale-config-path-explicit-home"); |
| 954 | let explicit_home = temp_root.join("isolated-codewhale"); |
| 955 | let legacy_config = temp_root.join(".deepseek").join("config.toml"); |
| 956 | fs::create_dir_all(legacy_config.parent().unwrap()).unwrap(); |
| 957 | fs::write(&legacy_config, "").unwrap(); |
| 958 | let _guard = EnvGuard::new(&temp_root); |
| 959 | |
| 960 | unsafe { |
| 961 | env::remove_var("DEEPSEEK_CONFIG_PATH"); |
| 962 | env::set_var("CODEWHALE_HOME", &explicit_home); |
| 963 | } |
| 964 | |
| 965 | assert_eq!( |
| 966 | config_toml_path(None).unwrap(), |
| 967 | explicit_home.join("config.toml") |
| 968 | ); |
| 969 | } |
| 970 | |
| 971 | #[test] |
| 972 | fn config_toml_path_prefers_codewhale_env_over_legacy_env() { |
| 973 | let temp_root = temp_root("codewhale-config-path-env"); |
| 974 | fs::create_dir_all(&temp_root).unwrap(); |
| 975 | let _guard = EnvGuard::new(&temp_root); |
| 976 | let preferred = temp_root.join("preferred.toml"); |
| 977 | let legacy = temp_root.join("legacy.toml"); |
| 978 | |
| 979 | unsafe { |
| 980 | env::set_var("CODEWHALE_CONFIG_PATH", &preferred); |
| 981 | env::set_var("DEEPSEEK_CONFIG_PATH", &legacy); |
| 982 | } |
| 983 | |
| 984 | let expected = preferred |
| 985 | .parent() |
| 986 | .expect("preferred path has a parent") |
| 987 | .canonicalize() |
| 988 | .expect("preferred parent should canonicalize") |
| 989 | .join("preferred.toml"); |
| 990 | assert_eq!(config_toml_path(None).unwrap(), expected); |
| 991 | } |
| 992 | |
| 993 | #[test] |
| 994 | fn config_toml_path_keeps_missing_env_target_authoritative() { |
| 995 | let temp_root = temp_root("codewhale-config-path-missing-env-fallback"); |
| 996 | let home_config = temp_root.join(".codewhale").join("config.toml"); |
| 997 | fs::create_dir_all(home_config.parent().unwrap()).unwrap(); |
| 998 | fs::write(&home_config, "# existing fallback\n").unwrap(); |
| 999 | let _guard = EnvGuard::new(&temp_root); |
| 1000 | let missing_env = temp_root.join("override").join("missing.toml"); |
| 1001 | |
| 1002 | unsafe { |
| 1003 | env::set_var("DEEPSEEK_CONFIG_PATH", &missing_env); |
| 1004 | } |
| 1005 | |
| 1006 | assert_eq!(config_toml_path(None).unwrap(), missing_env); |
| 1007 | assert!(home_config.exists()); |
| 1008 | assert!(!missing_env.exists()); |
| 1009 | } |
| 1010 | |
| 1011 | #[test] |
| 1012 | fn persist_status_items_preserves_existing_unrelated_keys() { |
| 1013 | let temp_root = temp_root("codewhale-statusline-preserve"); |
| 1014 | fs::create_dir_all(&temp_root).unwrap(); |
| 1015 | let _guard = EnvGuard::new(&temp_root); |
| 1016 | |
| 1017 | let path = temp_root.join(".deepseek").join("config.toml"); |
| 1018 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 1019 | fs::write( |
| 1020 | &path, |
| 1021 | "api_key = \"sentinel-key\"\nmodel = \"deepseek-v4-pro\"\n", |
| 1022 | ) |
| 1023 | .unwrap(); |
| 1024 | |
| 1025 | let written = persist_status_items(&[crate::config::StatusItem::Mode]) |
| 1026 | .expect("persist should succeed"); |
| 1027 | let body = fs::read_to_string(&written).expect("written file should be readable"); |
| 1028 | assert!( |
| 1029 | body.contains("api_key = \"sentinel-key\""), |
| 1030 | "round-trip lost api_key: {body}" |
| 1031 | ); |
| 1032 | assert!( |
| 1033 | body.contains("model = \"deepseek-v4-pro\""), |
| 1034 | "round-trip lost model: {body}" |
| 1035 | ); |
| 1036 | assert!( |
| 1037 | body.contains("status_items"), |
| 1038 | "expected status_items in {body}" |
| 1039 | ); |
| 1040 | } |
| 1041 | |
| 1042 | #[test] |
| 1043 | fn persist_bool_key_preserves_comments() { |
| 1044 | let temp_root = temp_root("codewhale-persist-comments"); |
| 1045 | fs::create_dir_all(&temp_root).unwrap(); |
| 1046 | let _guard = EnvGuard::new(&temp_root); |
| 1047 | |
| 1048 | let path = temp_root.join(".deepseek").join("config.toml"); |
| 1049 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 1050 | fs::write( |
| 1051 | &path, |
| 1052 | "# my note\nmodel = \"deepseek-v4-flash\"\n# disabled = true\n", |
| 1053 | ) |
| 1054 | .unwrap(); |
| 1055 | |
| 1056 | let written = persist_root_bool_key(Some(&path), "allow_shell", true) |
| 1057 | .expect("persist should succeed"); |
| 1058 | let body = fs::read_to_string(&written).expect("written file should be readable"); |
| 1059 | assert!(body.contains("# my note"), "prefix comment lost: {body}"); |
| 1060 | assert!( |
| 1061 | body.contains("# disabled = true"), |
| 1062 | "disabled key lost: {body}" |
| 1063 | ); |
| 1064 | assert!( |
| 1065 | body.contains("allow_shell = true"), |
| 1066 | "new key not written: {body}" |
| 1067 | ); |
| 1068 | } |
| 1069 | |
| 1070 | #[test] |
| 1071 | fn persist_table_bool_key_updates_existing_memory_enabled() { |
| 1072 | let temp_root = temp_root("codewhale-persist-memory-update"); |
| 1073 | fs::create_dir_all(&temp_root).unwrap(); |
| 1074 | let _guard = EnvGuard::new(&temp_root); |
| 1075 | |
| 1076 | let path = temp_root.join(".deepseek").join("config.toml"); |
| 1077 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 1078 | fs::write(&path, "allow_shell = true\n\n[memory]\nenabled = true\n").unwrap(); |
| 1079 | |
| 1080 | let written = persist_table_bool_key(Some(&path), "memory", "enabled", false) |
| 1081 | .expect("persist should succeed"); |
| 1082 | let body = fs::read_to_string(&written).expect("written file should be readable"); |
| 1083 | assert!( |
| 1084 | body.contains("enabled = false"), |
| 1085 | "memory enabled should be false: {body}" |
| 1086 | ); |
| 1087 | assert!( |
| 1088 | !body.contains("enabled = true"), |
| 1089 | "memory enabled should not still be true: {body}" |
| 1090 | ); |
| 1091 | } |
| 1092 | |
| 1093 | #[test] |
| 1094 | fn persist_memory_enabled_round_trips_through_config_load() { |
| 1095 | let temp_root = temp_root("codewhale-persist-memory-roundtrip"); |
| 1096 | fs::create_dir_all(&temp_root).unwrap(); |
| 1097 | let _guard = EnvGuard::new(&temp_root); |
| 1098 | |
| 1099 | let path = temp_root.join(".deepseek").join("config.toml"); |
| 1100 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 1101 | // Initial config has memory enabled = true |
| 1102 | fs::write(&path, "allow_shell = true\n\n[memory]\nenabled = true\n").unwrap(); |
| 1103 | |
| 1104 | // Verify initial state |
| 1105 | let cfg0 = crate::config::Config::load(Some(path.clone()), None) |
| 1106 | .expect("initial config should load"); |
| 1107 | assert!(cfg0.memory_enabled(), "memory should be enabled initially"); |
| 1108 | |
| 1109 | // Persist memory.enabled = false (what the GUI's set_config endpoint does) |
| 1110 | persist_table_bool_key(Some(&path), "memory", "enabled", false) |
| 1111 | .expect("persist should succeed"); |
| 1112 | |
| 1113 | // Reload config from disk and verify memory_enabled() reflects the change |
| 1114 | let cfg1 = crate::config::Config::load(Some(path.clone()), None) |
| 1115 | .expect("reloaded config should load"); |
| 1116 | assert!( |
| 1117 | !cfg1.memory_enabled(), |
| 1118 | "memory should be disabled after persisting false" |
| 1119 | ); |
| 1120 | } |
| 1121 | |
| 1122 | #[test] |
| 1123 | fn persist_custom_provider_writes_named_openai_compatible_table() { |
| 1124 | let temp_root = temp_root("codewhale-custom-provider-persist"); |
| 1125 | fs::create_dir_all(&temp_root).unwrap(); |
| 1126 | let _guard = EnvGuard::new(&temp_root); |
| 1127 | |
| 1128 | let path = temp_root.join(".codewhale").join("config.toml"); |
| 1129 | let written = persist_custom_provider( |
| 1130 | Some(&path), |
| 1131 | "acme_ai", |
| 1132 | "https://api.acme.example/v1/", |
| 1133 | Some("acme/code-1"), |
| 1134 | Some("ACME_API_KEY"), |
| 1135 | ) |
| 1136 | .expect("custom provider should persist"); |
| 1137 | let body = fs::read_to_string(&written).expect("written file should be readable"); |
| 1138 | |
| 1139 | assert!(body.contains("provider = \"acme_ai\""), "{body}"); |
| 1140 | assert!(body.contains("[providers.acme_ai]"), "{body}"); |
| 1141 | assert!(body.contains("kind = \"openai-compatible\""), "{body}"); |
| 1142 | assert!( |
| 1143 | body.contains("base_url = \"https://api.acme.example/v1\""), |
| 1144 | "{body}" |
| 1145 | ); |
| 1146 | assert!(body.contains("model = \"acme/code-1\""), "{body}"); |
| 1147 | assert!(body.contains("api_key_env = \"ACME_API_KEY\""), "{body}"); |
| 1148 | assert!( |
| 1149 | !body.contains("sk-"), |
| 1150 | "helper must not persist raw secret values: {body}" |
| 1151 | ); |
| 1152 | |
| 1153 | let loaded = |
| 1154 | crate::config::Config::load(Some(written.clone()), None).expect("config should load"); |
| 1155 | assert_eq!(loaded.provider.as_deref(), Some("acme_ai")); |
| 1156 | assert_eq!( |
| 1157 | loaded.active_provider_identity().unwrap().provider, |
| 1158 | codewhale_config::ProviderKind::Custom |
| 1159 | ); |
| 1160 | let entry = loaded |
| 1161 | .providers |
| 1162 | .as_ref() |
| 1163 | .and_then(|providers| providers.custom_provider_config("acme_ai")) |
| 1164 | .expect("custom provider entry"); |
| 1165 | assert!(entry.is_openai_compatible_custom()); |
| 1166 | assert_eq!( |
| 1167 | entry.base_url.as_deref(), |
| 1168 | Some("https://api.acme.example/v1") |
| 1169 | ); |
| 1170 | assert_eq!(entry.model.as_deref(), Some("acme/code-1")); |
| 1171 | assert_eq!(entry.api_key_env.as_deref(), Some("ACME_API_KEY")); |
| 1172 | |
| 1173 | let dispatcher = codewhale_config::ConfigStore::load(Some(written)) |
| 1174 | .expect("the dispatcher must parse the exact config written by the TUI"); |
| 1175 | assert_eq!( |
| 1176 | dispatcher.config.provider, |
| 1177 | codewhale_config::ProviderKind::Custom |
| 1178 | ); |
| 1179 | assert_eq!(dispatcher.config.provider_id(), "acme_ai"); |
| 1180 | } |
| 1181 | |
| 1182 | #[test] |
| 1183 | fn persist_custom_provider_rejects_builtin_or_invalid_names() { |
| 1184 | let temp_root = temp_root("codewhale-custom-provider-invalid"); |
| 1185 | fs::create_dir_all(&temp_root).unwrap(); |
| 1186 | let _guard = EnvGuard::new(&temp_root); |
| 1187 | let path = temp_root.join(".codewhale").join("config.toml"); |
| 1188 | |
| 1189 | let builtin = persist_custom_provider( |
| 1190 | Some(&path), |
| 1191 | "openrouter", |
| 1192 | "https://api.example.invalid/v1", |
| 1193 | None, |
| 1194 | None, |
| 1195 | ) |
| 1196 | .expect_err("built-in names should be rejected"); |
| 1197 | assert!(builtin.to_string().contains("built-in provider")); |
| 1198 | |
| 1199 | let bad_chars = persist_custom_provider( |
| 1200 | Some(&path), |
| 1201 | "my provider", |
| 1202 | "https://api.example.invalid/v1", |
| 1203 | None, |
| 1204 | None, |
| 1205 | ) |
| 1206 | .expect_err("space in name should be rejected"); |
| 1207 | assert!(bad_chars.to_string().contains("letters, numbers")); |
| 1208 | } |
| 1209 | |
| 1210 | #[test] |
| 1211 | fn persist_local_custom_provider_records_keyless_auth() { |
| 1212 | let temp_root = temp_root("codewhale-custom-provider-local-keyless"); |
| 1213 | fs::create_dir_all(&temp_root).unwrap(); |
| 1214 | let _guard = EnvGuard::new(&temp_root); |
| 1215 | let path = temp_root.join(".codewhale").join("config.toml"); |
| 1216 | |
| 1217 | let written = persist_custom_provider( |
| 1218 | Some(&path), |
| 1219 | "ds4", |
| 1220 | "http://127.0.0.1:8000/v1", |
| 1221 | Some("deepseek-v4-flash"), |
| 1222 | None, |
| 1223 | ) |
| 1224 | .expect("DS4 preset should persist"); |
| 1225 | let body = fs::read_to_string(&written).expect("written config"); |
| 1226 | |
| 1227 | assert!(body.contains("provider = \"ds4\""), "{body}"); |
| 1228 | assert!(body.contains("auth_mode = \"none\""), "{body}"); |
| 1229 | assert!(body.contains("context_window = 100000"), "{body}"); |
| 1230 | assert!(!body.contains("api_key"), "{body}"); |
| 1231 | } |
| 1232 | |
| 1233 | #[test] |
| 1234 | fn persist_hotbar_bindings_writes_primary_config_path_for_fresh_installs() { |
| 1235 | let temp_root = temp_root("codewhale-hotbar-persist-fresh"); |
| 1236 | fs::create_dir_all(&temp_root).unwrap(); |
| 1237 | let _guard = EnvGuard::new(&temp_root); |
| 1238 | |
| 1239 | unsafe { |
| 1240 | env::remove_var("DEEPSEEK_CONFIG_PATH"); |
| 1241 | } |
| 1242 | |
| 1243 | let bindings = vec![codewhale_config::HotbarBindingToml { |
| 1244 | slot: 1, |
| 1245 | action: "mode.plan".to_string(), |
| 1246 | label: Some("Plan".to_string()), |
| 1247 | }]; |
| 1248 | let path = persist_hotbar_bindings(None, &bindings).expect("persist should succeed"); |
| 1249 | |
| 1250 | assert_eq!(path, temp_root.join(".codewhale").join("config.toml")); |
| 1251 | let body = fs::read_to_string(&path).expect("written file should be readable"); |
| 1252 | assert!(body.contains("[[hotbar]]"), "hotbar table missing: {body}"); |
| 1253 | let parsed: codewhale_config::ConfigToml = |
| 1254 | toml::from_str(&body).expect("written hotbar config should parse"); |
| 1255 | assert_eq!(parsed.hotbar, Some(bindings)); |
| 1256 | } |
| 1257 | |
| 1258 | #[test] |
| 1259 | fn persist_default_hotbar_bindings_round_trips_for_hotbar_on() { |
| 1260 | // #3807: `/hotbar on` persists the explicit default slots (an absent key |
| 1261 | // now means hidden), and they read back as the eight recommended slots. |
| 1262 | let temp_root = temp_root("codewhale-hotbar-on-defaults"); |
| 1263 | fs::create_dir_all(&temp_root).unwrap(); |
| 1264 | let _guard = EnvGuard::new(&temp_root); |
| 1265 | |
| 1266 | let defaults = codewhale_config::default_hotbar_bindings_toml(); |
| 1267 | assert_eq!(defaults.len(), codewhale_config::HOTBAR_SLOT_COUNT as usize); |
| 1268 | |
| 1269 | let path = persist_hotbar_bindings(None, &defaults).expect("persist should succeed"); |
| 1270 | let body = fs::read_to_string(&path).expect("written file should be readable"); |
| 1271 | assert!(body.contains("[[hotbar]]"), "hotbar table missing: {body}"); |
| 1272 | |
| 1273 | let parsed: codewhale_config::ConfigToml = |
| 1274 | toml::from_str(&body).expect("written hotbar config should parse"); |
| 1275 | assert_eq!(parsed.hotbar, Some(defaults)); |
| 1276 | |
| 1277 | // The persisted defaults resolve back to all eight recommended slots. |
| 1278 | let resolved = parsed.resolve_hotbar_bindings(&codewhale_config::DEFAULT_HOTBAR_ACTIONS); |
| 1279 | assert_eq!( |
| 1280 | resolved.bindings, |
| 1281 | codewhale_config::default_hotbar_bindings() |
| 1282 | ); |
| 1283 | } |
| 1284 | |
| 1285 | #[test] |
| 1286 | fn persist_hotbar_bindings_preserves_comments_and_replaces_existing_tables() { |
| 1287 | let temp_root = temp_root("codewhale-hotbar-persist-comments"); |
| 1288 | fs::create_dir_all(&temp_root).unwrap(); |
| 1289 | let _guard = EnvGuard::new(&temp_root); |
| 1290 | |
| 1291 | let path = temp_root.join(".codewhale").join("config.toml"); |
| 1292 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 1293 | fs::write( |
| 1294 | &path, |
| 1295 | r#"# model note |
| 1296 | model = "deepseek-v4-flash" |
| 1297 | |
| 1298 | [[hotbar]] |
| 1299 | slot = 1 |
| 1300 | action = "mode.plan" |
| 1301 | label = "Plan" |
| 1302 | |
| 1303 | # notification note |
| 1304 | [notifications] |
| 1305 | enabled = true |
| 1306 | "#, |
| 1307 | ) |
| 1308 | .unwrap(); |
| 1309 | |
| 1310 | let bindings = vec![codewhale_config::HotbarBindingToml { |
| 1311 | slot: 2, |
| 1312 | action: "session.compact".to_string(), |
| 1313 | label: Some("Compact".to_string()), |
| 1314 | }]; |
| 1315 | let written = |
| 1316 | persist_hotbar_bindings(Some(&path), &bindings).expect("persist should succeed"); |
| 1317 | let body = fs::read_to_string(&written).expect("written file should be readable"); |
| 1318 | |
| 1319 | assert!(body.contains("# model note"), "prefix comment lost: {body}"); |
| 1320 | assert!( |
| 1321 | body.contains("# notification note"), |
| 1322 | "section comment lost: {body}" |
| 1323 | ); |
| 1324 | assert!( |
| 1325 | !body.contains("mode.plan"), |
| 1326 | "old hotbar table was not replaced: {body}" |
| 1327 | ); |
| 1328 | assert!(body.contains("[[hotbar]]"), "hotbar table missing: {body}"); |
| 1329 | assert!( |
| 1330 | body.contains("action = \"session.compact\""), |
| 1331 | "new action missing: {body}" |
| 1332 | ); |
| 1333 | let parsed: codewhale_config::ConfigToml = |
| 1334 | toml::from_str(&body).expect("written hotbar config should parse"); |
| 1335 | assert_eq!(parsed.hotbar, Some(bindings)); |
| 1336 | } |
| 1337 | |
| 1338 | #[test] |
| 1339 | fn persist_hotbar_bindings_writes_empty_array_to_disable_defaults() { |
| 1340 | let temp_root = temp_root("codewhale-hotbar-persist-empty"); |
| 1341 | fs::create_dir_all(&temp_root).unwrap(); |
| 1342 | let _guard = EnvGuard::new(&temp_root); |
| 1343 | |
| 1344 | let path = temp_root.join(".codewhale").join("config.toml"); |
| 1345 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 1346 | |
| 1347 | let written = persist_hotbar_bindings(Some(&path), &[]).expect("persist should succeed"); |
| 1348 | let body = fs::read_to_string(&written).expect("written file should be readable"); |
| 1349 | |
| 1350 | assert!(body.contains("hotbar = []"), "empty hotbar missing: {body}"); |
| 1351 | let parsed: codewhale_config::ConfigToml = |
| 1352 | toml::from_str(&body).expect("written hotbar config should parse"); |
| 1353 | assert_eq!(parsed.hotbar, Some(Vec::new())); |
| 1354 | } |
| 1355 | |
| 1356 | // ------------------------------------------------------------------ |
| 1357 | // Golden-file coverage for the shared toml_edit mutation path |
| 1358 | // (findings #18/#19/#20): unrelated comments, ordering, and quoted |
| 1359 | // provider tables must survive every supported mutation. |
| 1360 | // ------------------------------------------------------------------ |
| 1361 | |
| 1362 | const GOLDEN_CONFIG: &str = r#"# CodeWhale golden config fixture, top note. |
| 1363 | # api_key = "sk-placeholder" (uncomment to set the key by hand) |
| 1364 | model = "deepseek-v4-pro" # pinned for release QA |
| 1365 | |
| 1366 | # workspace trust note |
| 1367 | [projects."/Users/example/work"] |
| 1368 | trust_level = "trusted" # granted manually |
| 1369 | |
| 1370 | # providers note |
| 1371 | [providers.openrouter] |
| 1372 | base_url = "https://openrouter.ai/api/v1" # keep in sync with docs |
| 1373 | |
| 1374 | [providers."quoted.provider"] |
| 1375 | base_url = "https://quoted.example/v1" |
| 1376 | |
| 1377 | [[hotbar]] |
| 1378 | slot = 1 |
| 1379 | action = "mode.plan" |
| 1380 | "#; |
| 1381 | |
| 1382 | fn write_golden_config(path: &Path) { |
| 1383 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 1384 | fs::write(path, GOLDEN_CONFIG).unwrap(); |
| 1385 | } |
| 1386 | |
| 1387 | #[test] |
| 1388 | fn golden_replacing_existing_root_value_only_touches_that_value() { |
| 1389 | let temp_root = temp_root("codewhale-golden-root-value"); |
| 1390 | fs::create_dir_all(&temp_root).unwrap(); |
| 1391 | let _guard = EnvGuard::new(&temp_root); |
| 1392 | let path = temp_root.join(".deepseek").join("config.toml"); |
| 1393 | write_golden_config(&path); |
| 1394 | |
| 1395 | persist_root_string_key(Some(&path), "model", "deepseek-v4-flash") |
| 1396 | .expect("persist should succeed"); |
| 1397 | |
| 1398 | let body = fs::read_to_string(&path).unwrap(); |
| 1399 | // The fixture is a pre-migration home config, so this first write also |
| 1400 | // commits the one-way route-preference migration receipt in the same |
| 1401 | // atomic replacement. That stamp and the model value are the only two |
| 1402 | // permitted edits: comments, ordering and quoted tables stay byte-exact. |
| 1403 | let expected = GOLDEN_CONFIG.replace( |
| 1404 | "model = \"deepseek-v4-pro\" # pinned for release QA", |
| 1405 | "model = \"deepseek-v4-flash\" # pinned for release QA\nroute_preferences_version = 1", |
| 1406 | ); |
| 1407 | assert_eq!( |
| 1408 | body, expected, |
| 1409 | "only the model value and the migration stamp may change" |
| 1410 | ); |
| 1411 | } |
| 1412 | |
| 1413 | #[test] |
| 1414 | fn golden_mutations_preserve_unrelated_comments_order_and_quoted_tables() { |
| 1415 | let temp_root = temp_root("codewhale-golden-mutations"); |
| 1416 | fs::create_dir_all(&temp_root).unwrap(); |
| 1417 | let _guard = EnvGuard::new(&temp_root); |
| 1418 | let path = temp_root.join(".deepseek").join("config.toml"); |
| 1419 | write_golden_config(&path); |
| 1420 | |
| 1421 | persist_root_bool_key(Some(&path), "allow_shell", true).unwrap(); |
| 1422 | persist_table_value_key(Some(&path), "tui", "scrollback_lines", 4000_i64.into()).unwrap(); |
| 1423 | persist_table_string_key(Some(&path), "memory", "backend", "native").unwrap(); |
| 1424 | persist_subagents_bool_key(Some(&path), "enabled", true).unwrap(); |
| 1425 | persist_route_base_url( |
| 1426 | Some(&path), |
| 1427 | &selection_identity(&path, "openrouter"), |
| 1428 | "https://openrouter.example/v2", |
| 1429 | ) |
| 1430 | .unwrap(); |
| 1431 | persist_status_items(&[crate::config::StatusItem::Mode]).unwrap(); |
| 1432 | persist_hotbar_bindings( |
| 1433 | Some(&path), |
| 1434 | &[codewhale_config::HotbarBindingToml { |
| 1435 | slot: 2, |
| 1436 | action: "session.compact".to_string(), |
| 1437 | label: None, |
| 1438 | }], |
| 1439 | ) |
| 1440 | .unwrap(); |
| 1441 | |
| 1442 | let body = fs::read_to_string(&path).unwrap(); |
| 1443 | for comment in [ |
| 1444 | "# CodeWhale golden config fixture, top note.", |
| 1445 | "# api_key = \"sk-placeholder\" (uncomment to set the key by hand)", |
| 1446 | "# pinned for release QA", |
| 1447 | "# workspace trust note", |
| 1448 | "# granted manually", |
| 1449 | "# providers note", |
| 1450 | "# keep in sync with docs", |
| 1451 | ] { |
| 1452 | assert!(body.contains(comment), "comment lost: {comment}\n{body}"); |
| 1453 | } |
| 1454 | // Updated in place, keeping the trailing comment on the same line. |
| 1455 | assert!( |
| 1456 | body.contains("base_url = \"https://openrouter.example/v2\" # keep in sync with docs"), |
| 1457 | "{body}" |
| 1458 | ); |
| 1459 | assert!(body.contains("[providers.\"quoted.provider\"]"), "{body}"); |
| 1460 | assert!( |
| 1461 | !body.contains("mode.plan"), |
| 1462 | "old hotbar entry must be replaced: {body}" |
| 1463 | ); |
| 1464 | |
| 1465 | // Original section order is intact. |
| 1466 | let model_at = body.find("model = ").unwrap(); |
| 1467 | let projects_at = body.find("[projects.").unwrap(); |
| 1468 | let providers_at = body.find("[providers.openrouter]").unwrap(); |
| 1469 | assert!( |
| 1470 | model_at < projects_at && projects_at < providers_at, |
| 1471 | "{body}" |
| 1472 | ); |
| 1473 | |
| 1474 | let parsed: toml::Value = toml::from_str(&body).unwrap(); |
| 1475 | assert_eq!( |
| 1476 | parsed.get("allow_shell").and_then(toml::Value::as_bool), |
| 1477 | Some(true) |
| 1478 | ); |
| 1479 | assert_eq!( |
| 1480 | parsed |
| 1481 | .get("tui") |
| 1482 | .and_then(|t| t.get("scrollback_lines")) |
| 1483 | .and_then(toml::Value::as_integer), |
| 1484 | Some(4000) |
| 1485 | ); |
| 1486 | assert_eq!( |
| 1487 | parsed |
| 1488 | .get("memory") |
| 1489 | .and_then(|t| t.get("backend")) |
| 1490 | .and_then(toml::Value::as_str), |
| 1491 | Some("native") |
| 1492 | ); |
| 1493 | assert_eq!( |
| 1494 | parsed |
| 1495 | .get("subagents") |
| 1496 | .and_then(|t| t.get("enabled")) |
| 1497 | .and_then(toml::Value::as_bool), |
| 1498 | Some(true) |
| 1499 | ); |
| 1500 | } |
| 1501 | |
| 1502 | #[test] |
| 1503 | fn set_document_value_inserts_api_key_even_when_a_comment_mentions_it() { |
| 1504 | // Finding #20 at the primitive level: the old string scan treated a |
| 1505 | // comment mentioning api_key as an existing assignment and skipped |
| 1506 | // the insert entirely. |
| 1507 | let temp_root = temp_root("codewhale-golden-api-key-comment"); |
| 1508 | fs::create_dir_all(&temp_root).unwrap(); |
| 1509 | let _guard = EnvGuard::new(&temp_root); |
| 1510 | let path = temp_root.join(".deepseek").join("config.toml"); |
| 1511 | write_golden_config(&path); |
| 1512 | |
| 1513 | mutate_config_document(&path, |doc| { |
| 1514 | set_document_value(doc, &["api_key"], "sk-fresh") |
| 1515 | }) |
| 1516 | .expect("mutation should succeed"); |
| 1517 | |
| 1518 | let body = fs::read_to_string(&path).unwrap(); |
| 1519 | assert!( |
| 1520 | body.contains("# api_key = \"sk-placeholder\""), |
| 1521 | "comment lost: {body}" |
| 1522 | ); |
| 1523 | let parsed: toml::Value = toml::from_str(&body).unwrap(); |
| 1524 | assert_eq!( |
| 1525 | parsed.get("api_key").and_then(toml::Value::as_str), |
| 1526 | Some("sk-fresh"), |
| 1527 | "real key must be inserted despite the comment: {body}" |
| 1528 | ); |
| 1529 | } |
| 1530 | |
| 1531 | #[test] |
| 1532 | fn unset_document_value_reports_removal_and_tolerates_missing_parents() { |
| 1533 | let mut doc = "model = \"deepseek-v4-pro\"\n" |
| 1534 | .parse::<toml_edit::DocumentMut>() |
| 1535 | .unwrap(); |
| 1536 | assert!(!unset_document_value(&mut doc, &["providers", "openrouter", "api_key"]).unwrap()); |
| 1537 | assert!(!unset_document_value(&mut doc, &["model", "nested"]).unwrap()); |
| 1538 | assert!(unset_document_value(&mut doc, &["model"]).unwrap()); |
| 1539 | assert!(!unset_document_value(&mut doc, &["model"]).unwrap()); |
| 1540 | } |
| 1541 | |
| 1542 | #[test] |
| 1543 | fn unset_last_root_value_preserves_its_leading_comment() { |
| 1544 | let mut doc = "# keep this explanation\napproval_policy = \"on-request\"\n" |
| 1545 | .parse::<toml_edit::DocumentMut>() |
| 1546 | .unwrap(); |
| 1547 | |
| 1548 | assert!(unset_document_value(&mut doc, &["approval_policy"]).unwrap()); |
| 1549 | |
| 1550 | let saved = doc.to_string(); |
| 1551 | assert!(saved.contains("# keep this explanation"), "{saved:?}"); |
| 1552 | assert!(!saved.contains("approval_policy"), "{saved:?}"); |
| 1553 | } |
| 1554 | |
| 1555 | #[test] |
| 1556 | fn set_document_value_rejects_non_table_parents() { |
| 1557 | let mut doc = "model = \"deepseek-v4-pro\"\n" |
| 1558 | .parse::<toml_edit::DocumentMut>() |
| 1559 | .unwrap(); |
| 1560 | let err = set_document_value(&mut doc, &["model", "nested"], "x") |
| 1561 | .expect_err("scalar parent must be rejected"); |
| 1562 | assert!(err.to_string().contains("must be a table"), "{err}"); |
| 1563 | } |
| 1564 | |
| 1565 | #[test] |
| 1566 | fn remove_document_key_recursive_strips_nested_and_quoted_tables() { |
| 1567 | let mut doc = r#"# root note |
| 1568 | api_key = "root" |
| 1569 | api_key_env = "KEEP_ENV" |
| 1570 | |
| 1571 | [providers.openrouter] |
| 1572 | api_key = "or" |
| 1573 | base_url = "https://openrouter.ai/api/v1" |
| 1574 | |
| 1575 | [providers."quoted.provider"] |
| 1576 | api_key = "quoted" |
| 1577 | |
| 1578 | [[hotbar]] |
| 1579 | slot = 1 |
| 1580 | "# |
| 1581 | .parse::<toml_edit::DocumentMut>() |
| 1582 | .unwrap(); |
| 1583 | |
| 1584 | remove_document_key_recursive(doc.as_table_mut(), "api_key"); |
| 1585 | |
| 1586 | let body = doc.to_string(); |
| 1587 | assert!(!body.contains("api_key = "), "{body}"); |
| 1588 | assert!(body.contains("# root note"), "{body}"); |
| 1589 | assert!(body.contains("api_key_env = \"KEEP_ENV\""), "{body}"); |
| 1590 | assert!(body.contains("base_url"), "{body}"); |
| 1591 | assert!(body.contains("[[hotbar]]"), "{body}"); |
| 1592 | } |
| 1593 | |
| 1594 | #[test] |
| 1595 | fn persist_custom_provider_unsets_removed_optional_fields() { |
| 1596 | let temp_root = temp_root("codewhale-custom-provider-unset"); |
| 1597 | fs::create_dir_all(&temp_root).unwrap(); |
| 1598 | let _guard = EnvGuard::new(&temp_root); |
| 1599 | let path = temp_root.join(".codewhale").join("config.toml"); |
| 1600 | |
| 1601 | persist_custom_provider( |
| 1602 | Some(&path), |
| 1603 | "acme_ai", |
| 1604 | "https://api.acme.example/v1", |
| 1605 | Some("acme/code-1"), |
| 1606 | Some("ACME_API_KEY"), |
| 1607 | ) |
| 1608 | .expect("first persist should succeed"); |
| 1609 | persist_custom_provider( |
| 1610 | Some(&path), |
| 1611 | "acme_ai", |
| 1612 | "https://api.acme.example/v2", |
| 1613 | None, |
| 1614 | None, |
| 1615 | ) |
| 1616 | .expect("second persist should succeed"); |
| 1617 | |
| 1618 | let body = fs::read_to_string(&path).unwrap(); |
| 1619 | let parsed: toml::Value = toml::from_str(&body).unwrap(); |
| 1620 | let entry = parsed |
| 1621 | .get("providers") |
| 1622 | .and_then(|providers| providers.get("acme_ai")) |
| 1623 | .expect("provider entry"); |
| 1624 | assert_eq!( |
| 1625 | entry.get("base_url").and_then(toml::Value::as_str), |
| 1626 | Some("https://api.acme.example/v2") |
| 1627 | ); |
| 1628 | assert!(entry.get("model").is_none(), "model must be unset: {body}"); |
| 1629 | assert!( |
| 1630 | entry.get("api_key_env").is_none(), |
| 1631 | "api_key_env must be unset: {body}" |
| 1632 | ); |
| 1633 | } |
| 1634 | |
| 1635 | #[cfg(unix)] |
| 1636 | #[test] |
| 1637 | fn config_writes_land_with_owner_only_permissions() { |
| 1638 | use std::os::unix::fs::PermissionsExt; |
| 1639 | |
| 1640 | let temp_root = temp_root("codewhale-persist-perms"); |
| 1641 | fs::create_dir_all(&temp_root).unwrap(); |
| 1642 | let _guard = EnvGuard::new(&temp_root); |
| 1643 | let path = temp_root.join(".deepseek").join("config.toml"); |
| 1644 | write_golden_config(&path); |
| 1645 | fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); |
| 1646 | |
| 1647 | persist_root_bool_key(Some(&path), "allow_shell", true).expect("persist should succeed"); |
| 1648 | |
| 1649 | let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777; |
| 1650 | assert_eq!(mode, 0o600, "config.toml can hold api keys"); |
| 1651 | } |
| 1652 | |
| 1653 | /// The active model must be one answer, not two. |
| 1654 | #[test] |
| 1655 | fn the_dispatcher_and_the_tui_resolve_the_same_active_model() { |
| 1656 | // (case, config body, what both chains must answer) |
| 1657 | let cases: &[(&str, &str, &str)] = &[ |
| 1658 | ( |
| 1659 | "a non-DeepSeek provider honours the user's chosen model", |
| 1660 | "provider = \"zai\"\ndefault_text_model = \"GLM-4.6\"\n\n[providers.zai]\napi_key = \"k\"\n", |
| 1661 | "GLM-4.6", |
| 1662 | ), |
| 1663 | ( |
| 1664 | "a stale DeepSeek id must not be forwarded to a native non-DeepSeek endpoint", |
| 1665 | "provider = \"zai\"\ndefault_text_model = \"deepseek-chat\"\n\n[providers.zai]\napi_key = \"k\"\n", |
| 1666 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL, |
| 1667 | ), |
| 1668 | ( |
| 1669 | "no root default falls through to the provider default", |
| 1670 | "provider = \"zai\"\n\n[providers.zai]\napi_key = \"k\"\n", |
| 1671 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL, |
| 1672 | ), |
| 1673 | ( |
| 1674 | "a provider-scoped model outranks the root default", |
| 1675 | "provider = \"zai\"\ndefault_text_model = \"GLM-4.6\"\n\n[providers.zai]\napi_key = \"k\"\nmodel = \"GLM-4.5-Air\"\n", |
| 1676 | "GLM-4.5-Air", |
| 1677 | ), |
| 1678 | ( |
| 1679 | "DeepSeek itself keeps honouring the root default", |
| 1680 | "provider = \"deepseek\"\ndefault_text_model = \"deepseek-v4-pro\"\n\n[providers.deepseek]\napi_key = \"k\"\n", |
| 1681 | "deepseek-v4-pro", |
| 1682 | ), |
| 1683 | ( |
| 1684 | "a vendor-locked endpoint refuses a DeepSeek id (#3227)", |
| 1685 | "provider = \"xai\"\ndefault_text_model = \"deepseek-v4-pro\"\n\n[providers.xai]\napi_key = \"k\"\n", |
| 1686 | codewhale_config::descriptors::defaults::DEFAULT_XAI_MODEL, |
| 1687 | ), |
| 1688 | ( |
| 1689 | "an aggregator legitimately serves DeepSeek ids", |
| 1690 | "provider = \"openrouter\"\ndefault_text_model = \"deepseek/deepseek-v4-pro\"\n\n[providers.openrouter]\napi_key = \"k\"\n", |
| 1691 | "deepseek/deepseek-v4-pro", |
| 1692 | ), |
| 1693 | ( |
| 1694 | "a local runtime passes its own tag through", |
| 1695 | "provider = \"ollama\"\ndefault_text_model = \"qwen3-coder:30b\"\n", |
| 1696 | "qwen3-coder:30b", |
| 1697 | ), |
| 1698 | ( |
| 1699 | "a custom base URL keeps full pass-through (#1519)", |
| 1700 | "provider = \"zai\"\ndefault_text_model = \"deepseek-chat\"\n\n[providers.zai]\napi_key = \"k\"\nbase_url = \"https://proxy.example.invalid/v1\"\n", |
| 1701 | "deepseek-chat", |
| 1702 | ), |
| 1703 | ]; |
| 1704 | |
| 1705 | for (case, body, expected) in cases { |
| 1706 | let temp_root = temp_root("codewhale-model-chain-agreement"); |
| 1707 | fs::create_dir_all(&temp_root).unwrap(); |
| 1708 | let _guard = EnvGuard::new(&temp_root); |
| 1709 | let _model_guard = ModelEnvGuard::new(); |
| 1710 | let path = temp_root.join(".deepseek").join("config.toml"); |
| 1711 | fs::create_dir_all(path.parent().unwrap()).unwrap(); |
| 1712 | fs::write(&path, body).unwrap(); |
| 1713 | |
| 1714 | let tui = crate::config::Config::load(Some(path.clone()), None) |
| 1715 | .expect("the TUI must parse this config"); |
| 1716 | let tui_model = tui.default_model(); |
| 1717 | |
| 1718 | let dispatcher = codewhale_config::ConfigStore::load(Some(path.clone())) |
| 1719 | .expect("the dispatcher must parse the same config"); |
| 1720 | let runtime = dispatcher |
| 1721 | .config |
| 1722 | .resolve_runtime_options(&codewhale_config::CliRuntimeOverrides::default()); |
| 1723 | |
| 1724 | assert_eq!( |
| 1725 | tui_model, *expected, |
| 1726 | "{case}: the TUI chain (what actually reaches the provider) is wrong" |
| 1727 | ); |
| 1728 | assert_eq!( |
| 1729 | runtime.model, *expected, |
| 1730 | "{case}: the dispatcher chain (what `model resolve` reports) is wrong" |
| 1731 | ); |
| 1732 | |
| 1733 | let _ = fs::remove_dir_all(&temp_root); |
| 1734 | } |
| 1735 | } |
| 1736 | } |
| 1737 | |
| 1738 | #[cfg(any(test, feature = "test-support"))] |
| 1739 | pub mod test_support; |
| 1740 |