返回 CodeWhale
route_preferences.rs
根目录 / crates / engine / src / route_preferences.rs
1 //! Durable CLI route edits use the same Config owner as Runtime and the TUI.
2 //! `model` and the legacy `default_text_model` address the saved active route;
3 //! `default_model` addresses DeepSeek (CN while that route is active). Project root keys retain their scope.
4
5 use std::path::Path;
6
7 use anyhow::{Context, Result, ensure};
8
9 use codewhale_config::ProviderKind;
10 use codewhale_runtime::config::{BaseUrlEnvReceipt, Config, ProviderIdentity};
11 use codewhale_runtime::config_persistence as persistence;
12
13 /// Whether a config key names a provider or model selection.
14 pub fn is_route_key(key: &str) -> bool {
15 matches!(
16 key,
17 "provider" | "model" | "default_model" | "default_text_model"
18 ) || provider_model_id(key).is_some()
19 }
20
21 fn provider_model_id(key: &str) -> Option<&str> {
22 key.strip_prefix("providers.")?
23 .strip_suffix(".model")
24 .filter(|id| !id.is_empty())
25 }
26
27 fn parse_config(body: &str) -> Result<Config> {
28 codewhale_runtime::config::parse_config_base_diagnosed(
29 "Could not parse route configuration",
30 body,
31 )
32 }
33
34 fn model_identity(config: &Config, key: &str) -> Result<ProviderIdentity> {
35 let identity = if key == "default_model" {
36 let china = codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id;
37 let selector = if config
38 .active_provider_identity()
39 .is_ok_and(|identity| identity.key.as_str() == china)
40 {
41 china
42 } else {
43 ProviderKind::Deepseek.as_str()
44 };
45 config.resolve_provider_pin_identity(selector)
46 } else if let Some(id) = provider_model_id(key) {
47 let custom = config
48 .providers
49 .as_ref()
50 .and_then(|providers| providers.custom_provider_config(id))
51 .is_some();
52 let selector = if custom {
53 id
54 } else {
55 codewhale_config::descriptors::provider_compatibility()
56 .iter()
57 .find(|row| row.config_key == id)
58 .map_or(id, |row| row.id)
59 };
60 config.resolve_provider_selection_identity(selector)
61 } else {
62 config.active_provider_identity()
63 };
64 identity.map_err(anyhow::Error::msg)
65 }
66
67 fn model_slot(identity: &ProviderIdentity) -> Result<Vec<&str>> {
68 Ok(vec!["providers", identity.config_table_key()?, "model"])
69 }
70
71 /// Locate the canonical model leaf in a saved document without applying
72 /// device preferences or launch overrides. Export uses this same identity
73 /// resolution to omit only root aliases shadowed by that leaf.
74 pub fn model_slot_for_document(body: &str, key: &str) -> Result<Vec<String>> {
75 ensure!(
76 is_route_key(key) && key != "provider",
77 "Not a model preference key: {key}"
78 );
79 let config = parse_config(body)?;
80 let identity = model_identity(&config, key)?;
81 Ok(model_slot(&identity)?
82 .into_iter()
83 .map(str::to_string)
84 .collect())
85 }
86
87 fn document_slot_value(document: &toml::value::Table, slot: &[String]) -> Option<String> {
88 let [root, provider, field] = slot else {
89 return None;
90 };
91 document
92 .get(root)?
93 .as_table()?
94 .get(provider)?
95 .as_table()?
96 .get(field)?
97 .as_str()
98 .map(str::trim)
99 .filter(|model| !model.is_empty())
100 .map(str::to_string)
101 }
102
103 fn insert_document_slot_value(
104 document: &mut toml::value::Table,
105 slot: &[String],
106 value: &str,
107 ) -> bool {
108 let [root, provider, field] = slot else {
109 return false;
110 };
111 let Some(providers) = document
112 .entry(root.clone())
113 .or_insert_with(|| toml::Value::Table(toml::value::Table::new()))
114 .as_table_mut()
115 else {
116 return false;
117 };
118 let Some(entry) = providers
119 .entry(provider.clone())
120 .or_insert_with(|| toml::Value::Table(toml::value::Table::new()))
121 .as_table_mut()
122 else {
123 return false;
124 };
125 entry.insert(field.clone(), toml::Value::String(value.to_string()));
126 true
127 }
128
129 /// Scrub root model aliases from a serialized config document for export.
130 ///
131 /// Root `model`/`default_text_model` address the *active* route on import and
132 /// `default_model` addresses DeepSeek (CN when that route is active), so a raw root alias exported next to
133 /// the canonical `[providers.<id>].model` leaf fails the importer's replay
134 /// check. This rewrites `document` in place:
135 ///
136 /// - A root alias the active route still consumes is shadowed state once the
137 /// route's canonical leaf is exported; it is dropped.
138 /// - A root alias the active route ignores but DeepSeek recognizes is
139 /// DeepSeek's saved fallback; it moves to `providers.deepseek.model` unless
140 /// that slot already carries a value. Any other unrecognized value is dead
141 /// state that would only conflict on import and is dropped.
142 /// - `default_model` folds into the selected DeepSeek region's model slot when
143 /// nothing live occupies that slot, and is dropped otherwise.
144 ///
145 /// Only route-selection keys are parsed as `Config` here. Export documents
146 /// intentionally preserve unknown or differently typed local-authority
147 /// extras, and reparsing them merely to locate the model slot would fail the
148 /// whole export.
149 pub fn scrub_root_model_aliases_for_export(document: &mut toml::value::Table) -> Result<()> {
150 let mut scratch = toml::value::Table::new();
151 for key in [
152 "provider",
153 "model",
154 "default_text_model",
155 "defaultTextModel",
156 "base_url",
157 "baseUrl",
158 "providers",
159 ] {
160 if let Some(value) = document.get(key) {
161 scratch.insert(key.to_string(), value.clone());
162 }
163 }
164 let body = toml::to_string(&toml::Value::Table(scratch))
165 .context("serializing route selection for export")?;
166 // Slot resolution reuses the exact document identity rules; the extra
167 // parse below only exists so the ownership test can scope a Config clone.
168 let active_slot = model_slot_for_document(&body, "model")?;
169 let deepseek_slot = model_slot_for_document(&body, "default_model")?;
170 let config = parse_config(&body)?;
171 let identity = model_identity(&config, "model")?;
172
173 if document_slot_value(document, &active_slot).is_some() {
174 for root_key in ["model", "default_text_model"] {
175 let Some(value) = document
176 .get(root_key)
177 .and_then(toml::Value::as_str)
178 .map(str::to_owned)
179 else {
180 continue;
181 };
182 // Same ownership test as `unset`: scope to the active route with
183 // its canonical leaf cleared and ask whether this root value is
184 // what the route would then resolve. A foreign DeepSeek root
185 // ignored by the active vendor remains DeepSeek's fallback.
186 let mut scoped = config.clone();
187 scoped
188 .scope_to_provider_identity(&identity)
189 .map_err(anyhow::Error::msg)?;
190 scoped.set_provider_model_override(&identity, None)?;
191 scoped.legacy_model = None;
192 scoped.default_text_model = Some(value.to_string());
193 let wire_model = codewhale_config::route::resolve_model(
194 identity.provider,
195 &value,
196 Some(&scoped.active_route_base_url()),
197 )
198 .map_or_else(|_| value.trim().to_string(), |resolved| resolved.wire_id);
199 if scoped.default_model() == wire_model {
200 document.remove(root_key);
201 continue;
202 }
203 if !codewhale_config::route::resolve_model(ProviderKind::Deepseek, &value, None)
204 .is_ok_and(|resolved| !resolved.is_auto)
205 {
206 document.remove(root_key);
207 continue;
208 }
209 if document_slot_value(document, &deepseek_slot).is_some() {
210 document.remove(root_key);
211 continue;
212 }
213 ensure!(
214 insert_document_slot_value(document, &deepseek_slot, &value),
215 "Cannot export a root model alias into a non-table provider slot"
216 );
217 document.remove(root_key);
218 }
219 }
220
221 match document.get("default_model").and_then(toml::Value::as_str) {
222 Some(value) => {
223 let value = value.trim().to_string();
224 // A root alias the DeepSeek route still consumes lands in this
225 // same slot on import; the live choice wins over the dead alias.
226 let root_covers_slot = active_slot == deepseek_slot
227 && ["model", "default_text_model"]
228 .iter()
229 .any(|key| document.get(*key).and_then(toml::Value::as_str).is_some());
230 let folded = !value.is_empty()
231 && !root_covers_slot
232 && document_slot_value(document, &deepseek_slot).is_none();
233 if folded {
234 ensure!(
235 insert_document_slot_value(document, &deepseek_slot, &value),
236 "Cannot export default_model into a non-table provider slot"
237 );
238 }
239 document.remove("default_model");
240 }
241 None => {
242 ensure!(
243 !document.contains_key("default_model"),
244 "Cannot export a non-string default_model without losing its value"
245 );
246 }
247 }
248 Ok(())
249 }
250
251 fn project_root_key<'a>(path: &Path, key: &'a str) -> Option<&'a str> {
252 (codewhale_config::config_path_is_workspace_scoped(path)
253 && matches!(key, "model" | "default_text_model"))
254 .then_some(key)
255 }
256
257 fn saved_config(store: &codewhale_config::ConfigStore) -> Result<Config> {
258 let rendered;
259 let body = if let Some(original) = store.original_body() {
260 original
261 } else {
262 rendered = store.rendered_body()?;
263 &rendered
264 };
265 let mut config = parse_config(body)?;
266 if config.route_preferences_version.is_none()
267 && codewhale_runtime::config::is_home_config_path(store.path())
268 {
269 config.apply_saved_selection(
270 &codewhale_runtime::settings::Settings::load_legacy_route_preferences_read_only()?,
271 );
272 }
273 Ok(config)
274 }
275
276 /// Read the saved route without applying launch overrides or credentials.
277 pub fn get(path: &Path, key: &str) -> Result<Option<String>> {
278 ensure!(is_route_key(key), "Not a route preference key: {key}");
279 let store = codewhale_config::ConfigStore::load(Some(path.to_path_buf()))?;
280 if let Some(key) = project_root_key(store.path(), key) {
281 return Ok(store.config.get_value(key));
282 }
283 let mut config = saved_config(&store)?;
284 if key == "provider" {
285 return Ok(Some(
286 config.provider.unwrap_or_else(|| "deepseek".to_string()),
287 ));
288 }
289 let identity = model_identity(&config, key)?;
290 let active_key = config
291 .active_provider_identity()
292 .ok()
293 .map(|active| active.key.to_string());
294 config
295 .scope_to_provider_identity(&identity)
296 .map_err(anyhow::Error::msg)?;
297 let has_root_model = config.default_text_model.is_some() || config.legacy_model.is_some();
298 if has_root_model
299 && active_key.as_deref() != Some(identity.key.as_str())
300 && config.configured_model_error().is_some()
301 {
302 config.default_text_model = None;
303 config.legacy_model = None;
304 }
305 Ok(config
306 .provider_config_for(&identity)
307 .and_then(|entry| entry.model.clone())
308 .or_else(|| {
309 (provider_model_id(key).is_none() && has_root_model).then(|| config.default_model())
310 }))
311 }
312
313 /// One saved snapshot for CLI route reports, including exact legacy identities.
314 /// The source distinguishes an explicit model from the provider default.
315 pub fn selected_route(path: &Path) -> Result<(String, String, codewhale_config::ModelSource)> {
316 let store = codewhale_config::ConfigStore::load(Some(path.to_path_buf()))?;
317 let config = saved_config(&store)?;
318 let identity = config
319 .active_provider_identity()
320 .map_err(anyhow::Error::msg)?;
321 let provider = identity.key.to_string();
322 let source = if config
323 .provider_config_for(&identity)
324 .and_then(|entry| entry.model.as_ref())
325 .is_some()
326 {
327 codewhale_config::ModelSource::ProviderConfig
328 } else if config.default_text_model.is_some() || config.legacy_model.is_some() {
329 if store.config.default_text_model.is_none() && store.config.model.is_some() {
330 codewhale_config::ModelSource::RootModel
331 } else {
332 codewhale_config::ModelSource::RootDefaultTextModel
333 }
334 } else {
335 codewhale_config::ModelSource::ProviderDefault
336 };
337 Ok((provider, config.default_model(), source))
338 }
339
340 pub fn list_models(
341 store: &codewhale_config::ConfigStore,
342 filter: Option<ProviderKind>,
343 ) -> Result<Vec<(String, Vec<String>)>> {
344 crate::models_dev_live::maybe_load_persisted_cache();
345 let mut config = saved_config(store)?;
346 config.base_url_env_receipt = config
347 .active_provider_identity()
348 .map_or(BaseUrlEnvReceipt::NoOwner, |identity| {
349 BaseUrlEnvReceipt::Route(identity.provider, identity.key.to_string())
350 });
351 let mut custom_routes: Vec<String> = config
352 .providers
353 .as_ref()
354 .map(|providers| providers.custom.keys().cloned().collect())
355 .unwrap_or_default();
356 custom_routes.sort();
357 let providers = filter
358 .as_ref()
359 .map_or(ProviderKind::all(), std::slice::from_ref);
360 let mut catalogs = Vec::with_capacity(providers.len());
361 for provider in providers {
362 let routes = if *provider == ProviderKind::Custom {
363 custom_routes.clone()
364 } else {
365 vec![provider.as_str().to_string()]
366 };
367 for route in routes {
368 let identity = config
369 .legacy_selection_identity(&route)
370 .map_err(anyhow::Error::msg)?;
371 let mut route_config = config.clone();
372 route_config
373 .scope_to_provider_identity(&identity)
374 .map_err(anyhow::Error::msg)?;
375 let models = crate::provider_lake::listed_models_for_route(&route_config, &identity);
376 catalogs.push((route, models));
377 }
378 }
379 Ok(catalogs)
380 }
381
382 pub fn resolve_model(
383 path: &Path,
384 provider_identity: &str,
385 base_url: &str,
386 model: Option<&str>,
387 ) -> Result<codewhale_config::route::ReadyRouteCandidate> {
388 crate::models_dev_live::maybe_load_persisted_cache();
389 let store = codewhale_config::ConfigStore::load(Some(path.to_path_buf()))?;
390 let mut config = saved_config(&store)?;
391 let identity = config
392 .resolve_provider_selection_identity(provider_identity)
393 .map_err(anyhow::Error::msg)?;
394 config.set_provider_base_url_override(&identity, Some(base_url.into()))?;
395 crate::provider_catalog_live::maybe_load_persisted_cache_for_config(&config);
396 let route = crate::route_runtime::resolve_runtime_route_for_identity(&config, &identity, model)
397 .map_err(anyhow::Error::msg);
398 if !route.as_ref().is_ok_and(|route| {
399 (route.identity.provider == ProviderKind::OpenaiCodex
400 && crate::codex_model_cache::model_roster_for(&route.config)
401 .metadata_for(route.candidate.wire_model_id().as_str())
402 .is_some())
403 || crate::provider_lake::configured_catalog_offering_for_route(
404 &route.config,
405 route.identity.provider,
406 route.identity.key.as_str(),
407 &route.candidate.endpoint().base_url,
408 route.candidate.wire_model_id().as_str(),
409 )
410 .is_some()
411 }) && crate::provider_catalog_live::cached_entry_for_route(
412 identity.provider,
413 identity.key.as_str(),
414 base_url,
415 )?
416 .is_some_and(|entry| entry.fetched_at > 0)
417 {
418 return Err(model_not_available(
419 identity.provider,
420 model.unwrap_or("auto"),
421 ));
422 }
423 Ok(route?.candidate)
424 }
425
426 fn model_not_available(provider: ProviderKind, requested: &str) -> anyhow::Error {
427 anyhow::anyhow!(
428 "model '{requested}' is not available from provider '{}'",
429 provider.as_str()
430 )
431 }
432
433 /// Save one explicit route preference after atomically adopting legacy choices.
434 pub fn set(path: &Path, key: &str, value: &str) -> Result<()> {
435 persistence::mutate_config_document(path, |doc| set_document(path, doc, key, value))
436 }
437
438 /// Prepare a validated snapshot for a caller's preview and atomic save.
439 /// Migration changes only this document; this function never writes a file.
440 pub fn prepare_document(path: &Path, raw: &str) -> Result<toml_edit::DocumentMut> {
441 parse_config(raw)?;
442 let mut doc = raw.parse::<toml_edit::DocumentMut>().map_err(|_| {
443 anyhow::anyhow!("Could not parse route configuration; file contents were omitted")
444 })?;
445 persistence::migrate_legacy_route_preferences(path, &mut doc)?;
446 Ok(doc)
447 }
448
449 /// Edit one route selection in an already-prepared candidate without saving.
450 /// Callers must prepare migration first and atomically save the final snapshot.
451 pub fn set_document(
452 path: &Path,
453 doc: &mut toml_edit::DocumentMut,
454 key: &str,
455 value: &str,
456 ) -> Result<()> {
457 ensure!(is_route_key(key), "Not a route preference key: {key}");
458 let value = value.trim();
459 ensure!(
460 !value.is_empty() && !value.chars().any(char::is_control),
461 "Route preference must be nonempty and contain no control characters"
462 );
463 if let Some(key) = project_root_key(path, key) {
464 return persistence::set_document_value(doc, &[key], value);
465 }
466 let config = parse_config(&doc.to_string())?;
467 if key == "provider" {
468 let identity = config
469 .resolve_provider_selection_identity(value)
470 .map_err(anyhow::Error::msg)?;
471 persistence::set_document_value(
472 doc,
473 &["provider"],
474 identity.persisted_id().unwrap_or(identity.key.as_str()),
475 )?;
476 // Same root-alias authority as the Runtime/TUI provider writer: a CLI
477 // switch must not leave the incoming route holding the outgoing one's
478 // fallback, and must not delete a choice to get there.
479 return reconcile_root_model_aliases(doc, &config, &identity);
480 }
481 let identity = model_identity(&config, key)?;
482 set_provider_model_document(doc, &identity, value)
483 }
484
485 /// Clear a canonical selection without allowing archived Settings to restore it.
486 pub fn unset(path: &Path, key: &str) -> Result<()> {
487 ensure!(is_route_key(key), "Not a route preference key: {key}");
488 persistence::mutate_config_document(path, |doc| {
489 if key == "provider" || project_root_key(path, key).is_some() {
490 persistence::unset_document_value(doc, &[key])?;
491 return Ok(());
492 }
493 let config = parse_config(&doc.to_string())?;
494 let identity = model_identity(&config, key)?;
495 persistence::unset_document_value(doc, &model_slot(&identity)?)?;
496 // Clear relevant legacy fallbacks as well, or deleting the canonical
497 // leaf would restore an older choice on reload. Root fields belong to
498 // the active route, with DeepSeek's historical default as an exception.
499 if matches!(identity.provider, ProviderKind::Deepseek)
500 || config
501 .active_provider_identity()
502 .is_ok_and(|active| active == identity)
503 {
504 let mut scoped = config.clone();
505 scoped
506 .scope_to_provider_identity(&identity)
507 .map_err(anyhow::Error::msg)?;
508 scoped.set_provider_model_override(&identity, None)?;
509 scoped.legacy_model = None;
510 for root_key in ["default_text_model", "model"] {
511 let Some(model) = doc.get(root_key).and_then(toml_edit::Item::as_str) else {
512 continue;
513 };
514 scoped.default_text_model = Some(model.to_string());
515 let wire_model = codewhale_config::route::resolve_model(
516 identity.provider,
517 model,
518 Some(&scoped.active_route_base_url()),
519 )
520 .map_or_else(|_| model.trim().to_string(), |resolved| resolved.wire_id);
521 // Reuse Config's root-model guards: a foreign DeepSeek root
522 // ignored by the active vendor remains that provider's fallback.
523 if scoped.default_model() == wire_model {
524 persistence::unset_document_value(doc, &[root_key])?;
525 }
526 }
527 }
528 Ok(())
529 })
530 }
531
532 pub fn set_provider_model_document(
533 doc: &mut toml_edit::DocumentMut,
534 identity: &ProviderIdentity,
535 model: &str,
536 ) -> anyhow::Result<()> {
537 let mut config = codewhale_runtime::config::parse_config_base_diagnosed(
538 "Could not parse destination route identity",
539 &doc.to_string(),
540 )?;
541 codewhale_plugins::providers::apply_startup_providers(&mut config)?;
542 persistence::set_verified_provider_model_document(doc, &config, identity, model)
543 }
544
545 /// One persistent owner and atomic write for an explicitly saved route.
546 ///
547 /// Also returns the undo for exactly this write, taken under the config lock,
548 /// so a caller whose follow-up apply step is rejected can take back only the
549 /// switch.
550 pub fn persist_provider_selection(
551 config_path: Option<&Path>,
552 identity: &ProviderIdentity,
553 model: Option<&str>,
554 ) -> anyhow::Result<(std::path::PathBuf, codewhale_config::ConfigDocumentUndo)> {
555 let path = persistence::config_toml_path(config_path)?;
556 let ((), undo) =
557 codewhale_config::mutate_config_document_undoable_with_migration(&path, |doc, moved| {
558 persistence::migrate_legacy_route_preferences(&path, doc)?;
559 let mut config =
560 codewhale_runtime::config::parse_config_after_locked_migration_diagnosed(
561 "Could not parse destination route",
562 &doc.to_string(),
563 moved,
564 )?;
565 codewhale_plugins::providers::apply_startup_providers(&mut config)?;
566 config
567 .verify_provider_identity(identity)
568 .map_err(anyhow::Error::msg)?;
569 if let Some(model) = model {
570 persistence::set_verified_provider_model_document(doc, &config, identity, model)?;
571 }
572 persistence::set_document_value(
573 doc,
574 &["provider"],
575 identity.persisted_id().unwrap_or(identity.key.as_str()),
576 )?;
577 reconcile_root_model_aliases(doc, &config, identity)
578 })?;
579 Ok((path, undo))
580 }
581
582 /// Keep a root `default_text_model` alias from stranding a route switch,
583 /// without discarding the choice it holds.
584 ///
585 /// The root alias is the *active* route's fallback: `Config` resolves it only
586 /// when the selected route has no model of its own. A switch that leaves the
587 /// incoming route without a leaf therefore hands it an alias naming the route
588 /// on its way out, and `Config::load` rejects the file the caller just wrote —
589 /// a committed switch that produces an unloadable config — or, on a
590 /// pass-through incoming route that loads it, a model the incoming route never
591 /// chose while the outgoing route comes back on its catalog default.
592 ///
593 /// When the outgoing route has no leaf and was resolving the alias, relocate
594 /// that value onto the outgoing route's own canonical leaf, because it is real
595 /// saved state, and only then clear the alias. Any other alias the incoming
596 /// route already shadows with its own leaf is inert and stays: deleting a
597 /// saved choice to satisfy validation of a value nothing resolves is data
598 /// loss, not a repair. Likewise an unnamed custom route stores its
599 /// model in the alias itself and has no leaf to receive it. If the incoming
600 /// route cannot shadow that value, refuse the switch atomically and ask for an
601 /// explicit destination model instead of saving an unloadable configuration.
602 ///
603 /// `previous` is the document's configuration before the switch; `incoming` is
604 /// the identity now selected. Every route writer calls this, so no writer can
605 /// keep a private rule about which route owns the root alias.
606 pub fn reconcile_root_model_aliases(
607 doc: &mut toml_edit::DocumentMut,
608 previous: &codewhale_runtime::config::Config,
609 incoming: &codewhale_runtime::config::ProviderIdentity,
610 ) -> anyhow::Result<()> {
611 // A freshly admitted id-less root keeps its legacy alias as a receipt.
612 // Its effective model is written to the canonical leaf created by this
613 // same-lock migration; the alias is never another route's saved choice.
614 if incoming.provider == ProviderKind::Custom && incoming.persisted_id().is_none() {
615 return Ok(());
616 }
617 // The outgoing route was resolving the alias as its own model. Move it
618 // onto that route's leaf even when the incoming route could load it: a
619 // pass-through incoming route would otherwise inherit a model it never
620 // chose, and the outgoing route would come back on its catalog default.
621 if let Some((outgoing, value)) = previous.root_model_alias_owned_by_outgoing(incoming) {
622 persistence::set_verified_provider_model_document(doc, previous, &outgoing, &value)?;
623 unset_root_model_aliases(doc)?;
624 return Ok(());
625 }
626 // Below, only `default_text_model` is read. The legacy root `model` key is
627 // never what blocks a load: `Config::default_model` already refuses to
628 // route a foreign legacy value to a provider that cannot serve it, and
629 // `Config::validate` does not consult it, so relocating it would move a
630 // value nothing is asking about. It is still cleared together with the
631 // alias that shadows it (`unset_root_model_aliases`).
632 const ROOT_KEY: &str = "default_text_model";
633 let Some(value) = doc
634 .get(ROOT_KEY)
635 .and_then(toml_edit::Item::as_str)
636 .map(str::to_owned)
637 else {
638 return Ok(());
639 };
640 let mut switched = codewhale_runtime::config::parse_config_base_diagnosed(
641 "Could not parse switched route",
642 &doc.to_string(),
643 )?;
644 codewhale_plugins::providers::apply_startup_providers(&mut switched)?;
645 // `Config::validate` is the single authority on what the incoming route can
646 // serve, so a writer cannot disagree with the loader. Act only when this
647 // alias is what the loader rejects: a document already broken for an
648 // unrelated reason is not this writer's to rewrite.
649 let mut without_alias = switched.clone();
650 without_alias.default_text_model = None;
651 if switched
652 .provider_config_for(incoming)
653 .and_then(|entry| entry.model.as_deref())
654 .is_some()
655 || switched.validate().is_ok()
656 || without_alias.validate().is_err()
657 {
658 return Ok(());
659 }
660 // An empty or control-bearing alias names no saved model. Nothing to
661 // relocate, and clearing it loses nothing.
662 if value.trim().is_empty() || value.chars().any(char::is_control) {
663 unset_root_model_aliases(doc)?;
664 return Ok(());
665 }
666 // No leaf can hold this value. Keep the only copy of the user's choice
667 // rather than discard it for a document the incoming route loads as soon as
668 // it saves a model of its own.
669 let outgoing = previous.active_provider_identity().ok();
670 if outgoing.as_ref().is_some_and(|outgoing| {
671 outgoing != incoming
672 && outgoing.provider == ProviderKind::Custom
673 && outgoing.persisted_id().is_none()
674 }) {
675 // This same-lock canonicalizer copied the root model before moving
676 // its endpoint. Clear an alias only when that exact outgoing leaf
677 // proves the choice survives; otherwise retain the refusal.
678 if outgoing.as_ref().is_some_and(|outgoing| {
679 previous
680 .provider_config_for(outgoing)
681 .and_then(|entry| entry.model.as_deref())
682 == Some(value.as_str())
683 }) {
684 return unset_root_model_aliases(doc);
685 }
686 anyhow::bail!(
687 "Choose a model for the destination provider before switching from a legacy custom connection; the saved configuration was not changed"
688 );
689 }
690 let Some(outgoing) = outgoing.as_ref().filter(|outgoing| *outgoing != incoming) else {
691 return Ok(());
692 };
693 let mut scoped = switched;
694 scoped
695 .scope_to_provider_identity(outgoing)
696 .map_err(anyhow::Error::msg)?;
697 if scoped
698 .provider_config_for(outgoing)
699 .and_then(|entry| entry.model.as_deref())
700 .is_none()
701 {
702 persistence::set_verified_provider_model_document(doc, previous, outgoing, &value)?;
703 }
704 // The outgoing route either already saved its own choice or has just
705 // received this one, so the alias is now a shadowed duplicate that only
706 // blocks the incoming route.
707 unset_root_model_aliases(doc)?;
708 Ok(())
709 }
710
711 /// Clear the root model alias: `default_text_model` and the legacy root
712 /// `model` that `Config::default_model` falls back to when the former is
713 /// unset. While `default_text_model` is present the legacy key resolves on no
714 /// route, so removing only the alias would resurrect a stale legacy model on
715 /// the incoming route (a pass-through route would then use a model nobody
716 /// chose for it). When the legacy key *is* the alias, the caller has already
717 /// moved its value onto the outgoing route's leaf.
718 fn unset_root_model_aliases(doc: &mut toml_edit::DocumentMut) -> anyhow::Result<()> {
719 persistence::unset_document_value(doc, &["default_text_model"])?;
720 persistence::unset_document_value(doc, &["model"])?;
721 Ok(())
722 }
723
724 #[cfg(test)]
725 mod tests {
726 use super::*;
727 use crate::test_support::{EnvVarGuard, lock_test_env};
728
729 fn document(path: &Path) -> toml::Value {
730 toml::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
731 }
732
733 #[test]
734 fn route_edits_adopt_legacy_selection_once_and_preserve_settings() -> Result<()> {
735 let _env = lock_test_env();
736 let home = tempfile::tempdir()?;
737 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
738 let _path = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
739 let _legacy_path = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
740 let path = home.path().join("config.toml");
741 std::fs::write(
742 &path,
743 "provider = \"deepseek\"\ndefault_text_model = \"deepseek-v4-pro\"\n[providers.zai]\nmodel = \"GLM-5.2\"\n",
744 )?;
745 let settings_path = home.path().join("settings.toml");
746 let settings = "default_provider = \"zai\"\n[provider_models]\nzai = \"GLM-5.3\"\n";
747 std::fs::write(&settings_path, settings)?;
748 let before = std::fs::read(&path)?;
749 assert_eq!(get(&path, "provider")?.as_deref(), Some("zai"));
750 assert_eq!(get(&path, "model")?.as_deref(), Some("GLM-5.3"));
751 assert_eq!(std::fs::read(&path)?, before);
752
753 let mut candidate = prepare_document(&path, &std::fs::read_to_string(&path)?)?;
754 set_document(&path, &mut candidate, "model", "GLM-5.2")?;
755 assert_eq!(std::fs::read(&path)?, before);
756 set(&path, "model", "GLM-5.2")?;
757 assert_eq!(
758 document(&path),
759 toml::from_str::<toml::Value>(&candidate.to_string())?
760 );
761 assert_eq!(
762 document(&path)["route_preferences_version"].as_integer(),
763 Some(1)
764 );
765 assert_eq!(
766 get(&path, "default_text_model")?.as_deref(),
767 Some("GLM-5.2")
768 );
769 assert_eq!(
770 get(&path, "providers.zai.model")?.as_deref(),
771 Some("GLM-5.2")
772 );
773 set(&path, "default_model", "deepseek-v4-flash")?;
774 assert_eq!(
775 get(&path, "default_model")?.as_deref(),
776 Some("deepseek-v4-flash")
777 );
778 set(&path, "provider", "deepseek")?;
779 assert_eq!(get(&path, "model")?.as_deref(), Some("deepseek-v4-flash"));
780 unset(&path, "providers.deepseek.model")?;
781 assert!(get(&path, "default_model")?.is_none());
782 unset(&path, "providers.zai.model")?;
783 assert!(get(&path, "providers.zai.model")?.is_none());
784 unset(&path, "provider")?;
785 assert_eq!(get(&path, "provider")?.as_deref(), Some("deepseek"));
786 assert_eq!(std::fs::read_to_string(settings_path)?, settings);
787 // An unrelated typed store write must preserve the migration receipt.
788 let mut store = codewhale_config::ConfigStore::load(Some(path.clone()))?;
789 store.config.set_value("verbosity", "concise")?;
790 store.save()?;
791 assert_eq!(
792 document(&path)["route_preferences_version"].as_integer(),
793 Some(1)
794 );
795 Ok(())
796 }
797
798 #[test]
799 fn route_edits_keep_exact_named_provider_keys_and_reject_unknown_routes() -> Result<()> {
800 let _env = lock_test_env();
801 let home = tempfile::tempdir()?;
802 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
803 let _path = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
804 let _legacy_path = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
805 let path = home.path().join("config.toml");
806 std::fs::write(
807 &path,
808 r#"provider = "Team.A"
809 [providers."Team.A"]
810 kind = "openai-compatible"
811 base_url = "http://127.0.0.1:9/v1"
812 model = "Model-X"
813 [providers."team.a"]
814 kind = "openai-compatible"
815 base_url = "http://127.0.0.1:10/v1"
816 model = "Other-X"
817 "#,
818 )?;
819 set(&path, "providers.Team.A.model", "Model-Y")?;
820 assert_eq!(get(&path, "model")?.as_deref(), Some("Model-Y"));
821 assert_eq!(
822 get(&path, "providers.team.a.model")?.as_deref(),
823 Some("Other-X")
824 );
825 let before = std::fs::read(&path)?;
826 assert!(set(&path, "providers.TEAM.A.model", "Model-Z").is_err());
827 assert!(set(&path, "provider", "unconfigured-route").is_err());
828 assert_eq!(std::fs::read(&path)?, before);
829 unset(&path, "providers.Team.A.model")?;
830 assert!(get(&path, "providers.Team.A.model")?.is_none());
831 assert_eq!(
832 document(&path)["providers"]["team.a"]["model"].as_str(),
833 Some("Other-X")
834 );
835 Ok(())
836 }
837
838 #[test]
839 fn cli_provider_edits_share_the_runtime_writer_root_alias_authority() -> Result<()> {
840 let _env = lock_test_env();
841 let home = tempfile::tempdir()?;
842 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
843 let _path = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
844 let _legacy_path = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
845 let _cloud = EnvVarGuard::set("CODEWHALE_DISABLE_CLOUD_FACTS", "1");
846 let _overrides: Vec<_> = [
847 "CODEWHALE_MODEL",
848 "DEEPSEEK_MODEL",
849 "DEEPSEEK_DEFAULT_TEXT_MODEL",
850 "CODEWHALE_PROVIDER",
851 "DEEPSEEK_PROVIDER",
852 "CODEWHALE_BASE_URL",
853 "DEEPSEEK_BASE_URL",
854 "CODEWHALE_PROFILE",
855 "DEEPSEEK_PROFILE",
856 "ZAI_MODEL",
857 "ZAI_BASE_URL",
858 ]
859 .into_iter()
860 .map(EnvVarGuard::remove)
861 .collect();
862 let path = home.path().join("config.toml");
863
864 // The outgoing route was resolving the root fallback as its own
865 // model, so a CLI switch moves it onto that route's leaf (never
866 // deletes it), and switching back must still find it.
867 std::fs::write(
868 &path,
869 "route_preferences_version = 1\nprovider = \"zai\"\ndefault_text_model = \"GLM-4.6\"\n[providers.deepseek]\nmodel = \"deepseek-v4-pro\"\n",
870 )?;
871 set(&path, "provider", "deepseek")?;
872 let doc = document(&path);
873 assert!(doc.get("default_text_model").is_none());
874 assert_eq!(doc["providers"]["zai"]["model"].as_str(), Some("GLM-4.6"));
875 let switched = codewhale_plugins::providers::load_config(Some(path.clone()), None)
876 .expect("a CLI provider switch must remain loadable");
877 assert_eq!(
878 switched.active_provider_identity().unwrap().provider,
879 ProviderKind::Deepseek
880 );
881 assert_eq!(switched.default_model(), "deepseek-v4-pro");
882 set(&path, "provider", "zai")?;
883 assert_eq!(
884 codewhale_plugins::providers::load_config(Some(path.clone()), None)
885 .expect("switching back must remain loadable")
886 .default_model(),
887 "GLM-4.6"
888 );
889
890 // With no leaf on the incoming route the alias is what `Config::load`
891 // rejects. Move it to the route that owns it rather than drop it.
892 std::fs::write(
893 &path,
894 "route_preferences_version = 1\nprovider = \"volcengine\"\ndefault_text_model = \"ark-private-id\"\n",
895 )?;
896 set(&path, "provider", "deepseek")?;
897 let doc = document(&path);
898 assert!(doc.get("default_text_model").is_none());
899 assert_eq!(
900 doc["providers"]["volcengine"]["model"].as_str(),
901 Some("ark-private-id")
902 );
903 codewhale_plugins::providers::load_config(Some(path.clone()), None)
904 .expect("a CLI switch must not commit an unloadable config");
905 set(&path, "provider", "volcengine")?;
906 assert_eq!(
907 codewhale_plugins::providers::load_config(Some(path), None)
908 .expect("switching back must remain loadable")
909 .default_model(),
910 "ark-private-id"
911 );
912 Ok(())
913 }
914
915 #[test]
916 fn project_model_edits_keep_root_fields_and_skip_device_migration() -> Result<()> {
917 let _env = lock_test_env();
918 let root = tempfile::tempdir()?;
919 let home = root.path().join("home");
920 std::fs::create_dir_all(&home)?;
921 let _home = EnvVarGuard::set("CODEWHALE_HOME", &home);
922 let _path = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
923 let _legacy_path = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
924 std::fs::write(home.join("settings.toml"), "default_provider = \"zai\"\n")?;
925 let project = root.path().join("project/.codewhale");
926 std::fs::create_dir_all(&project)?;
927 // An absolute config outside the process workspace is project-scoped
928 // only when its parent is a checkout, not merely named `.codewhale`.
929 std::fs::create_dir(root.path().join("project/.git"))?;
930 let path = project.join("config.toml");
931 std::fs::write(&path, "model = \"project-old\"\n")?;
932 set(&path, "model", "project-new")?;
933 assert_eq!(get(&path, "model")?.as_deref(), Some("project-new"));
934 assert!(document(&path).get("providers").is_none());
935 assert!(document(&path).get("route_preferences_version").is_none());
936 unset(&path, "model")?;
937 assert!(document(&path).get("model").is_none());
938 Ok(())
939 }
940
941 #[test]
942 fn saved_routes_preserve_regional_and_legacy_table_identity() -> Result<()> {
943 let _env = lock_test_env();
944 let home = tempfile::tempdir()?;
945 let _home = EnvVarGuard::set("CODEWHALE_HOME", home.path());
946 let _path = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
947 let _legacy_path = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
948 let _cloud = EnvVarGuard::set("CODEWHALE_DISABLE_CLOUD_FACTS", "1");
949 let _overrides: Vec<_> = [
950 "CODEWHALE_MODEL",
951 "DEEPSEEK_MODEL",
952 "DEEPSEEK_DEFAULT_TEXT_MODEL",
953 "CODEWHALE_PROVIDER",
954 "DEEPSEEK_PROVIDER",
955 "CODEWHALE_BASE_URL",
956 "DEEPSEEK_BASE_URL",
957 "CODEWHALE_PROFILE",
958 "DEEPSEEK_PROFILE",
959 "ZAI_MODEL",
960 "ZAI_BASE_URL",
961 "OLLAMA_MODEL",
962 "OLLAMA_CLOUD_MODEL",
963 "OLLAMA_BASE_URL",
964 "OLLAMA_CLOUD_BASE_URL",
965 ]
966 .into_iter()
967 .map(EnvVarGuard::remove)
968 .collect();
969 let path = home.path().join("config.toml");
970 for (provider, table, endpoint, model) in [
971 (
972 "deepseek-cn",
973 "deepseek_cn",
974 "https://api.deepseek.cn",
975 "deepseek-v4-flash",
976 ),
977 (
978 "ollama",
979 "ollama",
980 "https://ollama.com/v1",
981 "saved-cloud-model",
982 ),
983 ] {
984 std::fs::write(
985 &path,
986 format!(
987 "route_preferences_version = 1\nprovider = '{provider}'\n[providers.{table}]\nbase_url = '{endpoint}'\n"
988 ),
989 )?;
990 set(&path, "model", model)?;
991 assert_eq!(document(&path)["provider"].as_str(), Some(provider));
992 assert_eq!(
993 document(&path)["providers"][table]["model"].as_str(),
994 Some(model)
995 );
996 assert_eq!(get(&path, "model")?.as_deref(), Some(model));
997 assert_eq!(
998 selected_route(&path)?,
999 (
1000 if provider == "ollama" {
1001 "ollama-cloud"
1002 } else {
1003 provider
1004 }
1005 .to_string(),
1006 model.to_string(),
1007 codewhale_config::ModelSource::ProviderConfig
1008 )
1009 );
1010 unset(&path, "model")?;
1011 assert!(document(&path)["providers"][table].get("model").is_none());
1012 let leaf = format!("providers.{table}.model");
1013 set(&path, &leaf, model)?;
1014 assert_eq!(get(&path, &leaf)?.as_deref(), Some(model));
1015 assert_eq!(
1016 codewhale_plugins::providers::load_config(Some(path.clone()), None)?
1017 .default_model(),
1018 model
1019 );
1020 assert_eq!(document(&path)["provider"].as_str(), Some(provider));
1021 unset(&path, &leaf)?;
1022 assert!(get(&path, &leaf)?.is_none());
1023 assert!(document(&path)["providers"][table].get("model").is_none());
1024 }
1025
1026 std::fs::write(
1027 &path,
1028 "route_preferences_version = 1\nprovider = 'zai'\nmodel = 'GLM-5.3'\n",
1029 )?;
1030 assert_eq!(get(&path, "model")?.as_deref(), Some("GLM-5.3"));
1031 assert_eq!(
1032 codewhale_plugins::providers::load_config(Some(path.clone()), None)?.default_model(),
1033 "GLM-5.3"
1034 );
1035 assert_eq!(
1036 selected_route(&path)?.2,
1037 codewhale_config::ModelSource::RootModel
1038 );
1039 // A foreign active-route root must never become the DeepSeek default.
1040 assert_eq!(
1041 get(&path, "default_model")?.as_deref(),
1042 Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL)
1043 );
1044 unset(&path, "providers.zai.model")?;
1045 assert!(document(&path).get("model").is_none());
1046 assert_eq!(
1047 codewhale_plugins::providers::load_config(Some(path.clone()), None)?.default_model(),
1048 selected_route(&path)?.1
1049 );
1050
1051 for (provider, root, leaf) in [
1052 (
1053 "deepseek",
1054 "default_text_model = 'deepseek-v4-flash'\nmodel = 'deepseek-v4-flash-vision-exp'",
1055 "deepseek-v4-pro",
1056 ),
1057 (
1058 "zai",
1059 "default_text_model = 'GLM-5.1'\nmodel = 'GLM-5.2'",
1060 "GLM-5.3",
1061 ),
1062 ] {
1063 std::fs::write(
1064 &path,
1065 format!(
1066 "route_preferences_version = 1\nprovider = '{provider}'\n{root}\n[providers.{provider}]\nmodel = '{leaf}'\n"
1067 ),
1068 )?;
1069 assert_eq!(
1070 codewhale_plugins::providers::load_config(Some(path.clone()), None)?
1071 .default_model(),
1072 leaf
1073 );
1074 unset(&path, &format!("providers.{provider}.model"))?;
1075 let doc = document(&path);
1076 assert!(doc.get("model").is_none());
1077 assert!(doc.get("default_text_model").is_none());
1078 assert!(doc["providers"][provider].get("model").is_none());
1079 let loaded = codewhale_plugins::providers::load_config(Some(path.clone()), None)?;
1080 assert_eq!(loaded.default_model(), selected_route(&path)?.1);
1081 assert!(loaded.legacy_model.is_none());
1082 }
1083
1084 // Clearing Z.ai cannot erase the independent DeepSeek root fallback.
1085 std::fs::write(
1086 &path,
1087 "route_preferences_version = 1\nprovider = 'zai'\ndefault_text_model = 'deepseek-v4-flash'\nmodel = 'GLM-5.1'\n[providers.zai]\nmodel = 'GLM-5.2'\n",
1088 )?;
1089 unset(&path, "providers.zai.model")?;
1090 assert_eq!(
1091 document(&path)["default_text_model"].as_str(),
1092 Some("deepseek-v4-flash")
1093 );
1094 assert!(document(&path).get("model").is_none());
1095 let loaded = codewhale_plugins::providers::load_config(Some(path.clone()), None)?;
1096 assert_ne!(loaded.default_model(), "GLM-5.1");
1097 assert_eq!(loaded.default_model(), selected_route(&path)?.1);
1098 Ok(())
1099 }
1100
1101 #[test]
1102 fn route_preferences_surfaces_safe_config_parse_diagnostics() -> Result<()> {
1103 let dir = tempfile::tempdir()?;
1104 let path = dir.path().join("config.toml");
1105 let secret = "sk-route-secret-must-not-leak-9182";
1106
1107 std::fs::write(
1108 &path,
1109 format!("[providers.deepseek]\napi_key = \"{secret}\"\n\n[skills]\nbogus = 1\n"),
1110 )?;
1111 let store = codewhale_config::ConfigStore::load(Some(path.clone()))?;
1112 let err = list_models(&store, None).expect_err("unknown [skills] key must fail");
1113 let message = format!("{err:#}");
1114 assert!(
1115 message.contains("unknown setting \"bogus\" in [skills]"),
1116 "{message}"
1117 );
1118 assert!(message.contains("file contents were omitted"), "{message}");
1119 assert!(!message.contains(secret), "{message}");
1120
1121 let wrong_type = format!("[skills]\nlisting_budget_fraction = \"{secret}\"\n");
1122 let doc_err = prepare_document(&path, &wrong_type).expect_err("wrong type must fail");
1123 let doc_message = format!("{doc_err:#}");
1124 assert!(
1125 doc_message.contains("invalid value for skills.listing_budget_fraction"),
1126 "{doc_message}"
1127 );
1128 assert!(
1129 doc_message.contains("file contents were omitted"),
1130 "{doc_message}"
1131 );
1132 assert!(!doc_message.contains(secret), "{doc_message}");
1133
1134 let syntax_err = prepare_document(&path, &format!("api_key = \"{secret}\"\n[broken\n"))
1135 .expect_err("syntax error must fail");
1136 let syntax_message = format!("{syntax_err:#}");
1137 assert!(syntax_message.contains("line 2"), "{syntax_message}");
1138 assert!(
1139 syntax_message.contains("file contents were omitted"),
1140 "{syntax_message}"
1141 );
1142 assert!(!syntax_message.contains(secret), "{syntax_message}");
1143 Ok(())
1144 }
1145 }
1146
1146 lines RUST