| 1 | //! Provider and route plumbing reached from the UI: switching providers, |
| 2 | //! MCP import/reload, balance and catalog fetches, and onboarding's |
| 3 | //! provider/trust steps. |
| 4 | //! |
| 5 | //! Moved verbatim out of `ui.rs`. |
| 6 | |
| 7 | use super::*; |
| 8 | |
| 9 | pub(crate) fn complete_trust_directory_onboarding( |
| 10 | app: &mut App, |
| 11 | config: &Config, |
| 12 | ) -> Result<(), String> { |
| 13 | onboarding::mark_trusted(&app.workspace).map_err(|err| err.to_string())?; |
| 14 | app.trust_mode = true; |
| 15 | // `rebind`, not `new`: trusting the directory can add project hooks, but |
| 16 | // it does not start a new session. Hooks that already fired this session |
| 17 | // reported a `DEEPSEEK_SESSION_ID`, and it has to keep meaning the same |
| 18 | // session afterwards. |
| 19 | app.hooks = app.hooks.rebind( |
| 20 | codewhale_engine::hooks::config::load_with_project_and_plugins( |
| 21 | config.hooks_config(), |
| 22 | &app.workspace, |
| 23 | Some(app.plugin_registry.as_ref()), |
| 24 | ), |
| 25 | app.workspace.clone(), |
| 26 | ); |
| 27 | app.runtime_services.hook_executor = Some(std::sync::Arc::new(app.hooks.clone())); |
| 28 | app.clear_setup_notice(); |
| 29 | advance_after_trust_directory_choice(app); |
| 30 | Ok(()) |
| 31 | } |
| 32 | |
| 33 | /// Continue past the trust step without recording workspace trust. |
| 34 | /// |
| 35 | /// Tools and hooks stay restricted for this session; the next launch will |
| 36 | /// re-prompt until the user trusts (or uses an explicit trust command). |
| 37 | pub(crate) fn continue_without_trusting_directory(app: &mut App) { |
| 38 | app.trust_mode = false; |
| 39 | app.show_onboarding_notice( |
| 40 | app.tr(MessageId::OnboardTrustUntrustedNotice).into_owned(), |
| 41 | StatusToastLevel::Warning, |
| 42 | ); |
| 43 | advance_after_trust_directory_choice(app); |
| 44 | } |
| 45 | |
| 46 | pub(crate) fn advance_after_trust_directory_choice(app: &mut App) { |
| 47 | if app.onboarding_workspace_trust_gate { |
| 48 | app.finish_onboarding_without_feature_intro(); |
| 49 | if app.onboarding == OnboardingState::None { |
| 50 | app.onboarding_workspace_trust_gate = false; |
| 51 | } |
| 52 | } else if !app.composer.input.trim().is_empty() && !app.onboarding_explore_offline { |
| 53 | app.finish_onboarding_without_feature_intro(); |
| 54 | } else { |
| 55 | app.onboarding = OnboardingState::Ready; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | /// Decide the onboarding route for one key press. |
| 60 | /// |
| 61 | /// Two invariants this encodes, both regressions reported in #4763: |
| 62 | /// Ctrl+C quits from *any* onboarding state — a modal on the stack must not |
| 63 | /// swallow it — and Escape is never intercepted on the picker's behalf, so |
| 64 | /// the picker can back out one stage at a time instead of the shell popping |
| 65 | /// the whole modal from a key/OAuth sub-stage. |
| 66 | pub(crate) fn onboarding_key_route( |
| 67 | onboarding: OnboardingState, |
| 68 | top_kind: Option<ModalKind>, |
| 69 | key: &KeyEvent, |
| 70 | ) -> OnboardingKeyRoute { |
| 71 | if onboarding == OnboardingState::None { |
| 72 | return OnboardingKeyRoute::Legacy; |
| 73 | } |
| 74 | if top_kind == Some(ModalKind::AccountLogin) { |
| 75 | return OnboardingKeyRoute::AccountLogin; |
| 76 | } |
| 77 | if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) { |
| 78 | return OnboardingKeyRoute::Quit; |
| 79 | } |
| 80 | // Checked before the picker claim: the offline exit must stay reachable |
| 81 | // from behind a modal the user cannot satisfy. |
| 82 | if onboarding == OnboardingState::Provider && is_explore_offline_shortcut(key) { |
| 83 | return OnboardingKeyRoute::ExploreOffline; |
| 84 | } |
| 85 | if onboarding == OnboardingState::Provider && top_kind == Some(ModalKind::ProviderPicker) { |
| 86 | return OnboardingKeyRoute::ProviderPicker; |
| 87 | } |
| 88 | OnboardingKeyRoute::Legacy |
| 89 | } |
| 90 | |
| 91 | pub(crate) fn back_from_provider_onboarding(app: &mut App) { |
| 92 | app.onboarding_key_rejected = None; |
| 93 | if app.onboarding_missing_key_recovery { |
| 94 | // A returning user declined missing-key recovery: leave onboarding |
| 95 | // for the offline composer without mutating the saved route. |
| 96 | app.onboarding = OnboardingState::None; |
| 97 | app.clear_setup_notice(); |
| 98 | app.needs_redraw = true; |
| 99 | return; |
| 100 | } |
| 101 | // Esc walks back to the previous decision this run actually asked: the |
| 102 | // language screen when it appeared, otherwise the welcome screen. |
| 103 | app.onboarding = if app.onboarding_had_language_step { |
| 104 | OnboardingState::Language |
| 105 | } else { |
| 106 | OnboardingState::Welcome |
| 107 | }; |
| 108 | app.clear_setup_notice(); |
| 109 | } |
| 110 | |
| 111 | pub(crate) fn begin_first_connection_setup(app: &mut App) { |
| 112 | if app.onboarding == OnboardingState::None |
| 113 | && app.onboarding_needs_api_key |
| 114 | && !app.startup_route_configured |
| 115 | { |
| 116 | app.onboarding = OnboardingState::Provider; |
| 117 | app.onboarding_missing_key_recovery = true; |
| 118 | app.onboarding_provider = app.api_provider; |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | pub(crate) fn complete_provider_picker_onboarding(app: &mut App, provider: ProviderKind) { |
| 123 | // Ordinary `/provider` changes stay session-local until the operator |
| 124 | // answers the route-save prompt. Onboarding is different: choosing a |
| 125 | // provider is the explicit decision that establishes the startup route. |
| 126 | // Persist the exact live identity/model before advancing, otherwise a |
| 127 | // clean first run can finish on Ollama (or another non-DeepSeek route) |
| 128 | // while the next launch silently reconstructs the old DeepSeek default. |
| 129 | // The user-global `config.toml` owns this startup choice. |
| 130 | let provider_action_receipt = app |
| 131 | .route_receipt() |
| 132 | .map(|notice| (notice.text.clone(), notice.level)); |
| 133 | let startup_default_receipt = match app.try_save_live_route_as_startup_default() { |
| 134 | Ok(receipt) => receipt, |
| 135 | Err(err) => { |
| 136 | // Persistence is part of completing first-run provider setup. Keep |
| 137 | // the provider step active on failure so the current session may |
| 138 | // use the selected route, but onboarding cannot claim that the |
| 139 | // next launch will restore it. The exact selected provider remains |
| 140 | // focused for an immediate retry. |
| 141 | app.onboarding_provider = provider; |
| 142 | app.onboarding_needs_api_key = true; |
| 143 | app.show_route_receipt( |
| 144 | match provider_action_receipt { |
| 145 | Some((receipt, _)) if !receipt.trim().is_empty() => { |
| 146 | format!("{receipt} · Save failed: {err}") |
| 147 | } |
| 148 | _ => format!("Save failed: {err}"), |
| 149 | }, |
| 150 | StatusToastLevel::Error, |
| 151 | ); |
| 152 | app.needs_redraw = true; |
| 153 | return; |
| 154 | } |
| 155 | }; |
| 156 | app.onboarding_provider = provider; |
| 157 | app.onboarding_needs_api_key = false; |
| 158 | app.onboarding_key_rejected = None; |
| 159 | // The route now has its key, so a later local-Ollama probe must not treat |
| 160 | // this session as still recovering from a missing one. |
| 161 | app.onboarding_missing_key_recovery = false; |
| 162 | app.api_key_env_only = false; |
| 163 | app.offline_mode = false; |
| 164 | onboarding::advance_onboarding_after_provider(app); |
| 165 | // `advance_onboarding_after_provider` clears the previous switch status. |
| 166 | // Restore the persistence receipt last so an I/O failure remains visible |
| 167 | // instead of allowing onboarding to imply that the restart route landed. |
| 168 | let level = provider_action_receipt |
| 169 | .as_ref() |
| 170 | .map(|(_, level)| *level) |
| 171 | .filter(|level| matches!(level, StatusToastLevel::Error | StatusToastLevel::Warning)) |
| 172 | .unwrap_or(StatusToastLevel::Success); |
| 173 | app.show_route_receipt( |
| 174 | match provider_action_receipt { |
| 175 | Some((receipt, _)) if !receipt.trim().is_empty() => { |
| 176 | format!("{receipt} · {startup_default_receipt}") |
| 177 | } |
| 178 | _ => startup_default_receipt, |
| 179 | }, |
| 180 | level, |
| 181 | ); |
| 182 | } |
| 183 | |
| 184 | pub(crate) fn complete_provider_picker_onboarding_if_switched( |
| 185 | app: &mut App, |
| 186 | provider: ProviderKind, |
| 187 | switched: bool, |
| 188 | ) { |
| 189 | if switched && app.onboarding == OnboardingState::Provider { |
| 190 | complete_provider_picker_onboarding(app, provider); |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | /// How one prepaid provider publishes remaining credit. Each variant is a |
| 195 | /// distinct wire contract — do not send DeepSeek `/user/balance` to a |
| 196 | /// provider that does not speak it. |
| 197 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 198 | enum BalanceApi { |
| 199 | DeepSeekUserBalance, |
| 200 | OpenRouterCredits, |
| 201 | SiliconFlowUserInfo, |
| 202 | } |
| 203 | |
| 204 | fn balance_api_for(provider: ProviderKind) -> Option<BalanceApi> { |
| 205 | match provider { |
| 206 | ProviderKind::Deepseek => Some(BalanceApi::DeepSeekUserBalance), |
| 207 | ProviderKind::Openrouter => Some(BalanceApi::OpenRouterCredits), |
| 208 | ProviderKind::Siliconflow | ProviderKind::SiliconflowCN => { |
| 209 | Some(BalanceApi::SiliconFlowUserInfo) |
| 210 | } |
| 211 | _ => None, |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | /// Fetch remaining credit for the active prepaid provider. |
| 216 | /// |
| 217 | /// Returns the reason on any error (network, auth, parse) — callers treat that |
| 218 | /// as "balance unknown" and keep the previous value. |
| 219 | pub(crate) async fn fetch_provider_balance( |
| 220 | provider: ProviderKind, |
| 221 | api_key: &str, |
| 222 | base_url: &str, |
| 223 | ) -> Result<codewhale_engine::pricing::BalanceInfo, String> { |
| 224 | let api_key = api_key.trim(); |
| 225 | if api_key.is_empty() { |
| 226 | return Err("no API key".to_string()); |
| 227 | } |
| 228 | match balance_api_for(provider).ok_or_else(|| "balance is not supported".to_string())? { |
| 229 | BalanceApi::DeepSeekUserBalance => fetch_deepseek_user_balance(api_key, base_url).await, |
| 230 | BalanceApi::OpenRouterCredits => fetch_openrouter_credits(api_key, base_url).await, |
| 231 | BalanceApi::SiliconFlowUserInfo => { |
| 232 | fetch_siliconflow_user_info(api_key, base_url, provider).await |
| 233 | } |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | async fn fetch_deepseek_user_balance( |
| 238 | api_key: &str, |
| 239 | base_url: &str, |
| 240 | ) -> Result<codewhale_engine::pricing::BalanceInfo, String> { |
| 241 | let origin = base_url.trim_end_matches('/'); |
| 242 | let origin = origin |
| 243 | .strip_suffix("/beta") |
| 244 | .or_else(|| origin.strip_suffix("/v1")) |
| 245 | .unwrap_or(origin); |
| 246 | let url = format!("{origin}/user/balance"); |
| 247 | let body: codewhale_engine::pricing::BalanceResponse = balance_get_json(api_key, &url).await?; |
| 248 | body.balance_infos |
| 249 | .into_iter() |
| 250 | .next() |
| 251 | .ok_or_else(|| "the response listed no balance".to_string()) |
| 252 | } |
| 253 | |
| 254 | #[derive(serde::Deserialize)] |
| 255 | struct OpenRouterCreditsResponse { |
| 256 | data: OpenRouterCreditsData, |
| 257 | } |
| 258 | |
| 259 | #[derive(serde::Deserialize)] |
| 260 | struct OpenRouterCreditsData { |
| 261 | total_credits: f64, |
| 262 | total_usage: f64, |
| 263 | } |
| 264 | |
| 265 | fn openrouter_remaining_credits(total_credits: f64, total_usage: f64) -> f64 { |
| 266 | (total_credits - total_usage).max(0.0) |
| 267 | } |
| 268 | |
| 269 | async fn fetch_openrouter_credits( |
| 270 | api_key: &str, |
| 271 | base_url: &str, |
| 272 | ) -> Result<codewhale_engine::pricing::BalanceInfo, String> { |
| 273 | let url = format!("{}/credits", base_url.trim_end_matches('/')); |
| 274 | let body: OpenRouterCreditsResponse = balance_get_json(api_key, &url).await?; |
| 275 | let remaining = openrouter_remaining_credits(body.data.total_credits, body.data.total_usage); |
| 276 | Ok(codewhale_engine::pricing::BalanceInfo { |
| 277 | currency: "USD".to_string(), |
| 278 | total_balance: format!("{remaining:.2}"), |
| 279 | topped_up_balance: format!("{:.2}", body.data.total_credits), |
| 280 | granted_balance: String::new(), |
| 281 | }) |
| 282 | } |
| 283 | |
| 284 | #[derive(serde::Deserialize)] |
| 285 | struct SiliconFlowUserInfo { |
| 286 | data: Option<SiliconFlowUserData>, |
| 287 | } |
| 288 | |
| 289 | #[derive(serde::Deserialize)] |
| 290 | struct SiliconFlowUserData { |
| 291 | #[serde(default, alias = "totalBalance")] |
| 292 | total_balance: Option<String>, |
| 293 | #[serde(default, alias = "chargeBalance")] |
| 294 | charge_balance: Option<String>, |
| 295 | #[serde(default)] |
| 296 | balance: Option<String>, |
| 297 | } |
| 298 | |
| 299 | async fn fetch_siliconflow_user_info( |
| 300 | api_key: &str, |
| 301 | base_url: &str, |
| 302 | provider: ProviderKind, |
| 303 | ) -> Result<codewhale_engine::pricing::BalanceInfo, String> { |
| 304 | let url = format!("{}/user/info", base_url.trim_end_matches('/')); |
| 305 | let body: SiliconFlowUserInfo = balance_get_json(api_key, &url).await?; |
| 306 | let data = body |
| 307 | .data |
| 308 | .ok_or_else(|| "the response carried no account data".to_string())?; |
| 309 | let total = data |
| 310 | .total_balance |
| 311 | .as_deref() |
| 312 | .or(data.balance.as_deref()) |
| 313 | .map(str::trim) |
| 314 | .filter(|value| !value.is_empty()) |
| 315 | .ok_or_else(|| "the response carried no balance".to_string())?; |
| 316 | let currency = if provider == ProviderKind::SiliconflowCN { |
| 317 | "CNY" |
| 318 | } else { |
| 319 | "USD" |
| 320 | }; |
| 321 | Ok(codewhale_engine::pricing::BalanceInfo { |
| 322 | currency: currency.to_string(), |
| 323 | total_balance: total.to_string(), |
| 324 | topped_up_balance: data.charge_balance.unwrap_or_default(), |
| 325 | granted_balance: String::new(), |
| 326 | }) |
| 327 | } |
| 328 | |
| 329 | async fn balance_get_json<T: serde::de::DeserializeOwned>( |
| 330 | api_key: &str, |
| 331 | url: &str, |
| 332 | ) -> Result<T, String> { |
| 333 | let client = &*BALANCE_CLIENT; |
| 334 | let response = client |
| 335 | .get(url) |
| 336 | .header("Authorization", format!("Bearer {api_key}")) |
| 337 | .send() |
| 338 | .await |
| 339 | .map_err(|error| { |
| 340 | let error = error.without_url(); |
| 341 | tracing::warn!(%error, "provider balance request failed"); |
| 342 | if error.is_timeout() { |
| 343 | format!("request timed out: {error}") |
| 344 | } else if error.is_connect() { |
| 345 | format!("could not connect to the balance service: {error}") |
| 346 | } else { |
| 347 | format!("request failed: {error}") |
| 348 | } |
| 349 | })?; |
| 350 | let status = response.status(); |
| 351 | if !status.is_success() { |
| 352 | tracing::debug!( |
| 353 | "balance API returned {}: {}", |
| 354 | status.as_u16(), |
| 355 | response.text().await.unwrap_or_default() |
| 356 | ); |
| 357 | return Err(format!("HTTP {status}")); |
| 358 | } |
| 359 | response.json().await.map_err(|error| { |
| 360 | tracing::warn!(%error, "provider balance response was not readable"); |
| 361 | format!("the response was not readable: {error}") |
| 362 | }) |
| 363 | } |
| 364 | |
| 365 | pub(crate) fn should_fetch_provider_balance(app: &App) -> bool { |
| 366 | app.status_items.contains(&StatusItem::Balance) |
| 367 | && codewhale_runtime::config::provider_has_balance_api(app.api_provider) |
| 368 | } |
| 369 | |
| 370 | /// The balance cell for this route. A reading belongs to the route that |
| 371 | /// fetched it: when the provider, endpoint or key changes, a fresh cell |
| 372 | /// replaces the old one, so a response still in flight for the previous route |
| 373 | /// lands in a cell nothing reads (U03-08), and the new route is not held behind |
| 374 | /// the previous route's fetch cooldown. |
| 375 | pub(crate) fn balance_cell_for_route( |
| 376 | app: &mut App, |
| 377 | provider: ProviderKind, |
| 378 | api_key: &str, |
| 379 | base_url: &str, |
| 380 | ) -> std::sync::Arc<std::sync::Mutex<Option<codewhale_engine::pricing::BalanceInfo>>> { |
| 381 | use std::hash::{Hash, Hasher}; |
| 382 | let mut key_fingerprint = std::collections::hash_map::DefaultHasher::new(); |
| 383 | api_key.hash(&mut key_fingerprint); |
| 384 | let route = format!( |
| 385 | "{}\u{1f}{base_url}\u{1f}{:016x}", |
| 386 | provider.as_str(), |
| 387 | key_fingerprint.finish() |
| 388 | ); |
| 389 | if app.balance_route.as_deref() != Some(route.as_str()) { |
| 390 | app.balance_cell = std::sync::Arc::new(std::sync::Mutex::new(None)); |
| 391 | app.balance_route = Some(route); |
| 392 | app.last_balance_fetch = None; |
| 393 | } |
| 394 | app.balance_cell.clone() |
| 395 | } |
| 396 | |
| 397 | /// Kick a background remaining-credit fetch for the live route. |
| 398 | /// |
| 399 | /// `force` skips the status-item gate (used by `/balance`). Providers without |
| 400 | /// a known endpoint clear the parked chip so a previous route cannot linger. |
| 401 | pub(crate) fn schedule_balance_fetch(app: &mut App, api_key: &str, base_url: &str, force: bool) { |
| 402 | if !codewhale_runtime::config::provider_has_balance_api(app.api_provider) { |
| 403 | // A fresh cell, not a cleared one: a fetch still in flight for the |
| 404 | // previous route holds the old cell and cannot repaint the chip. |
| 405 | app.balance_cell = std::sync::Arc::new(std::sync::Mutex::new(None)); |
| 406 | app.balance_route = None; |
| 407 | return; |
| 408 | } |
| 409 | let provider = app.api_provider; |
| 410 | let cell = balance_cell_for_route(app, provider, api_key, base_url); |
| 411 | if !force && !should_fetch_provider_balance(app) { |
| 412 | return; |
| 413 | } |
| 414 | if api_key.trim().is_empty() { |
| 415 | return; |
| 416 | } |
| 417 | let cooldown_ok = force |
| 418 | || app |
| 419 | .last_balance_fetch |
| 420 | .is_none_or(|t| t.elapsed() >= BALANCE_FETCH_COOLDOWN); |
| 421 | if !cooldown_ok { |
| 422 | return; |
| 423 | } |
| 424 | app.last_balance_fetch = Some(Instant::now()); |
| 425 | let api_key = api_key.to_string(); |
| 426 | let base_url = base_url.to_string(); |
| 427 | tokio::spawn(async move { |
| 428 | if let Ok(info) = fetch_provider_balance(provider, &api_key, &base_url).await |
| 429 | && let Ok(mut guard) = cell.lock() |
| 430 | { |
| 431 | *guard = Some(info); |
| 432 | } |
| 433 | }); |
| 434 | } |
| 435 | |
| 436 | #[cfg(test)] |
| 437 | pub(crate) fn openrouter_credits_from_json( |
| 438 | json: &str, |
| 439 | ) -> Option<codewhale_engine::pricing::BalanceInfo> { |
| 440 | let body: OpenRouterCreditsResponse = serde_json::from_str(json).ok()?; |
| 441 | let remaining = openrouter_remaining_credits(body.data.total_credits, body.data.total_usage); |
| 442 | Some(codewhale_engine::pricing::BalanceInfo { |
| 443 | currency: "USD".to_string(), |
| 444 | total_balance: format!("{remaining:.2}"), |
| 445 | topped_up_balance: format!("{:.2}", body.data.total_credits), |
| 446 | granted_balance: String::new(), |
| 447 | }) |
| 448 | } |
| 449 | |
| 450 | pub(crate) async fn fetch_available_models(config: &Config) -> Result<Vec<String>> { |
| 451 | let client = crate::active_route_client(config).await?; |
| 452 | let models = tokio::time::timeout(Duration::from_secs(20), client.list_models()).await??; |
| 453 | let mut ids = models.into_iter().map(|model| model.id).collect::<Vec<_>>(); |
| 454 | ids.sort(); |
| 455 | ids.dedup(); |
| 456 | Ok(ids) |
| 457 | } |
| 458 | |
| 459 | pub(crate) fn resolve_cache_replay_route( |
| 460 | app: &App, |
| 461 | config: &Config, |
| 462 | ) -> Result<codewhale_engine::route_runtime::ResolvedRuntimeRoute> { |
| 463 | let target = app.cache_replay_target().ok_or_else(|| { |
| 464 | anyhow::anyhow!("Auto has no concrete route yet; send a turn before warming its cache") |
| 465 | })?; |
| 466 | let identity = config |
| 467 | .resolve_persisted_provider_identity( |
| 468 | Some(target.provider.as_str()), |
| 469 | target.provider_id.as_deref(), |
| 470 | ) |
| 471 | .map_err(anyhow::Error::msg)?; |
| 472 | if identity.provider != target.provider || identity.key.as_str() != target.provider_identity { |
| 473 | anyhow::bail!( |
| 474 | "saved cache route identity `{}` now resolves as {}/{} instead of {}/{}; send a new turn before warming", |
| 475 | target.provider_identity, |
| 476 | identity.provider.as_str(), |
| 477 | identity.key, |
| 478 | target.provider.as_str(), |
| 479 | target.provider_identity |
| 480 | ); |
| 481 | } |
| 482 | let route = resolve_runtime_route_for_identity(config, &identity, Some(&target.model)) |
| 483 | .map_err(anyhow::Error::msg)?; |
| 484 | if let Some(previous_base_url) = target.base_url.as_deref() { |
| 485 | let previous_endpoint = |
| 486 | codewhale_engine::route_receipt::endpoint_identity(previous_base_url); |
| 487 | let current_endpoint = codewhale_engine::route_receipt::endpoint_identity( |
| 488 | &route.candidate.endpoint().base_url, |
| 489 | ); |
| 490 | if previous_endpoint != current_endpoint { |
| 491 | anyhow::bail!( |
| 492 | "the cache route endpoint changed since the last turn; send a new turn before warming" |
| 493 | ); |
| 494 | } |
| 495 | } |
| 496 | Ok(route) |
| 497 | } |
| 498 | |
| 499 | pub(crate) fn error_health_route(app: &App) -> Option<(ProviderIdentity, String)> { |
| 500 | let route = app.active_turn.as_ref()?.route.as_ref()?; |
| 501 | let receipt = route.receipt.as_ref()?; |
| 502 | Some((receipt.admitted_identity().clone(), route.model.clone())) |
| 503 | } |
| 504 | |
| 505 | pub(crate) fn rollback_provider_after_auth_failure( |
| 506 | app: &mut App, |
| 507 | config: &mut Config, |
| 508 | ) -> Option<String> { |
| 509 | let pending = app.pending_provider_switch.take()?; |
| 510 | let PendingProviderSwitch { |
| 511 | previous_provider, |
| 512 | previous_model, |
| 513 | previous_model_ids_passthrough, |
| 514 | previous_route_limits, |
| 515 | previous_route_base_url, |
| 516 | previous_context_window_source, |
| 517 | previous_context_window, |
| 518 | previous_context_window_override, |
| 519 | previous_config, |
| 520 | previous_onboarding, |
| 521 | previous_onboarding_needs_api_key, |
| 522 | previous_api_key_env_only, |
| 523 | } = pending; |
| 524 | |
| 525 | *config = previous_config; |
| 526 | |
| 527 | app.refresh_notification_settings(config); |
| 528 | app.provider_identity = config |
| 529 | .active_provider_identity() |
| 530 | .ok() |
| 531 | .filter(|identity| identity.provider == previous_provider); |
| 532 | app.api_provider = previous_provider; |
| 533 | app.billing_presentation = app.provider_identity.as_ref().map_or( |
| 534 | codewhale_engine::route_billing::BillingPresentation::Unknown, |
| 535 | |identity| codewhale_engine::route_billing::for_route(config, identity), |
| 536 | ); |
| 537 | |
| 538 | app.set_model_selection(previous_model.clone()); |
| 539 | app.provider_models.insert( |
| 540 | app.provider_identity_for_persistence().to_string(), |
| 541 | previous_model, |
| 542 | ); |
| 543 | // The rolled-back switch leaves the session where it started: any pending |
| 544 | // route-save decision belongs to the failed provider and must not linger. |
| 545 | app.pending_route_save = None; |
| 546 | app.model_ids_passthrough = previous_model_ids_passthrough; |
| 547 | app.active_context_window_override = previous_context_window_override; |
| 548 | app.active_route_limits = previous_route_limits; |
| 549 | app.active_route_base_url = previous_route_base_url; |
| 550 | app.active_context_window_source = previous_context_window_source; |
| 551 | app.active_context_window = previous_context_window; |
| 552 | app.update_model_compaction_budget(); |
| 553 | app.clear_model_scoped_telemetry(); |
| 554 | maybe_warn_context_pressure(app); |
| 555 | app.offline_mode = false; |
| 556 | app.onboarding = previous_onboarding; |
| 557 | app.onboarding_needs_api_key = previous_onboarding_needs_api_key; |
| 558 | app.api_key_env_only = previous_api_key_env_only; |
| 559 | |
| 560 | // The failed switch never wrote config or settings, so the rollback has |
| 561 | // nothing to undo on disk — and it must not leave a pending save decision |
| 562 | // behind (cleared above). Only the on-screen setup-state receipt is |
| 563 | // corrected so the record matches reality. |
| 564 | let mut persistence_errors = Vec::new(); |
| 565 | if let Err(err) = crate::tui::setup::record_provider_model_setup_state_for_app(app, config) { |
| 566 | persistence_errors.push(format!("setup state was not saved: {err}")); |
| 567 | } |
| 568 | let persistence_error = if persistence_errors.is_empty() { |
| 569 | None |
| 570 | } else { |
| 571 | Some(format!( |
| 572 | "provider rollback not fully persisted: {}", |
| 573 | persistence_errors.join("; ") |
| 574 | )) |
| 575 | }; |
| 576 | |
| 577 | Some(match persistence_error { |
| 578 | Some(warning) => format!( |
| 579 | "Provider switch failed and has been rolled back to {}. {}", |
| 580 | previous_provider.as_str(), |
| 581 | warning |
| 582 | ), |
| 583 | None => format!( |
| 584 | "Provider switch failed and has been rolled back to {}.", |
| 585 | previous_provider.as_str() |
| 586 | ), |
| 587 | }) |
| 588 | } |
| 589 | |
| 590 | pub(crate) fn validated_app_runtime_route( |
| 591 | app: &App, |
| 592 | config: &Config, |
| 593 | ) -> Result<codewhale_engine::route_runtime::ValidatedRuntimeRoute, String> { |
| 594 | let (identity, scoped) = app_scoped_runtime_config(app, config)?; |
| 595 | resolve_runtime_route_for_identity(&scoped, &identity, Some(&app.model))?.validate() |
| 596 | } |
| 597 | |
| 598 | pub(crate) fn compaction_for_validated_route( |
| 599 | app: &App, |
| 600 | route: &codewhale_engine::route_runtime::ValidatedRuntimeRoute, |
| 601 | ) -> codewhale_engine::compaction::CompactionConfig { |
| 602 | let mut config = app.compaction_config_for_route( |
| 603 | route.identity.provider, |
| 604 | &route.model, |
| 605 | codewhale_engine::route_budget::known_route_limits(route.candidate.limits()), |
| 606 | Some(route.context_window), |
| 607 | ); |
| 608 | config.image_input = route.candidate.capabilities().image_input; |
| 609 | config |
| 610 | } |
| 611 | |
| 612 | pub(crate) fn validated_profile_default_route( |
| 613 | config: &Config, |
| 614 | ) -> Result<codewhale_engine::route_runtime::ValidatedRuntimeRoute> { |
| 615 | let identity = config |
| 616 | .active_provider_identity() |
| 617 | .map_err(anyhow::Error::msg)?; |
| 618 | let model = config.default_model(); |
| 619 | resolve_runtime_route_for_identity(config, &identity, Some(&model)) |
| 620 | .and_then(codewhale_engine::route_runtime::ResolvedRuntimeRoute::validate) |
| 621 | .map_err(anyhow::Error::msg) |
| 622 | } |
| 623 | |
| 624 | pub(crate) fn reasoning_effort_receipt_for_route( |
| 625 | tier: ReasoningEffort, |
| 626 | provider: ProviderKind, |
| 627 | endpoint_identity: &str, |
| 628 | model: &str, |
| 629 | ) -> EffectiveReasoningEffort { |
| 630 | codewhale_engine::work_graph::constrained_effective_reasoning_for_route( |
| 631 | tier.into(), |
| 632 | provider, |
| 633 | endpoint_identity, |
| 634 | model, |
| 635 | ) |
| 636 | .map(Into::into) |
| 637 | .unwrap_or(EffectiveReasoningEffort::Tier(tier)) |
| 638 | } |
| 639 | |
| 640 | pub(crate) async fn sync_mode_update(app: &mut App, engine_handle: &EngineHandle) { |
| 641 | if app.mode != AppMode::Agent || app.approval_mode != ApprovalMode::Auto { |
| 642 | app.revoke_approvable_auto_review_receipts(); |
| 643 | } |
| 644 | // #6150: non-blocking send on the input path. ChangeMode is safe to drop |
| 645 | // on a full channel — `try_send` still publishes the live authority |
| 646 | // snapshot, which the drain applies before the next queued op. |
| 647 | let _ = engine_handle.try_send(Op::ChangeMode { |
| 648 | mode: app.mode, |
| 649 | allow_shell: app.allow_shell, |
| 650 | trust_mode: app.trust_mode, |
| 651 | auto_approve: app_auto_approve_enabled(app), |
| 652 | approval_mode: app.approval_mode, |
| 653 | configured_sandbox_mode: app.configured_sandbox_mode.clone(), |
| 654 | }); |
| 655 | if app.is_loading { |
| 656 | app.push_status_toast( |
| 657 | format!( |
| 658 | "{} · {} — applies at the agent's next step in this turn", |
| 659 | crate::tui::app::AppModeUi::display_name_localized(app.mode, app.ui_locale), |
| 660 | app.effective_permission_label(), |
| 661 | ), |
| 662 | StatusToastLevel::Info, |
| 663 | Some(6_000), |
| 664 | ); |
| 665 | } |
| 666 | } |
| 667 | |
| 668 | /// Apply a `/provider` switch by resolving a complete route candidate before |
| 669 | /// mutating state, then respawning the engine so the API client picks up the |
| 670 | /// new base URL/key. When `model_override` is set, it replaces the active |
| 671 | /// model post-switch after provider-scoped normalization. |
| 672 | pub(crate) async fn switch_provider( |
| 673 | app: &mut App, |
| 674 | engine_handle: &mut EngineHandle, |
| 675 | config: &mut Config, |
| 676 | identity: codewhale_runtime::config::ProviderIdentity, |
| 677 | model_override: Option<String>, |
| 678 | ) -> bool { |
| 679 | switch_provider_inner(app, engine_handle, config, identity, model_override, None).await |
| 680 | } |
| 681 | |
| 682 | pub(super) async fn switch_provider_with_ollama_probe( |
| 683 | app: &mut App, |
| 684 | engine_handle: &mut EngineHandle, |
| 685 | config: &mut Config, |
| 686 | identity: codewhale_runtime::config::ProviderIdentity, |
| 687 | model: String, |
| 688 | endpoint: &str, |
| 689 | ticket: &codewhale_engine::provider_catalog_live::ProviderCatalogRefreshTicket, |
| 690 | ) -> bool { |
| 691 | switch_provider_inner( |
| 692 | app, |
| 693 | engine_handle, |
| 694 | config, |
| 695 | identity, |
| 696 | Some(model), |
| 697 | Some((endpoint, ticket)), |
| 698 | ) |
| 699 | .await |
| 700 | } |
| 701 | |
| 702 | async fn switch_provider_inner( |
| 703 | app: &mut App, |
| 704 | engine_handle: &mut EngineHandle, |
| 705 | config: &mut Config, |
| 706 | identity: codewhale_runtime::config::ProviderIdentity, |
| 707 | model_override: Option<String>, |
| 708 | probe: Option<( |
| 709 | &str, |
| 710 | &codewhale_engine::provider_catalog_live::ProviderCatalogRefreshTicket, |
| 711 | )>, |
| 712 | ) -> bool { |
| 713 | app.clear_setup_notice(); |
| 714 | if app.is_loading { |
| 715 | app.show_route_receipt( |
| 716 | app.setting_locked_message(MessageId::SettingSubjectProvider), |
| 717 | StatusToastLevel::Warning, |
| 718 | ); |
| 719 | return false; |
| 720 | } |
| 721 | if let Err(reason) = config.verify_provider_identity(&identity) { |
| 722 | app.show_route_receipt(reason, StatusToastLevel::Error); |
| 723 | return false; |
| 724 | } |
| 725 | let target = identity.provider; |
| 726 | let previous_provider = app.api_provider; |
| 727 | let previous_identity = app.provider_identity_for_persistence().to_string(); |
| 728 | let requested_identity = identity.key.to_string(); |
| 729 | let previous_model = app.model.clone(); |
| 730 | let previous_model_ids_passthrough = app.model_ids_passthrough; |
| 731 | let previous_config = config.clone(); |
| 732 | app.pending_provider_switch = Some(PendingProviderSwitch { |
| 733 | previous_provider, |
| 734 | previous_model: previous_model.clone(), |
| 735 | previous_model_ids_passthrough, |
| 736 | previous_route_limits: app.active_route_limits, |
| 737 | previous_route_base_url: app.active_route_base_url.clone(), |
| 738 | previous_context_window_source: app.active_context_window_source, |
| 739 | previous_context_window: app.active_context_window, |
| 740 | previous_context_window_override: app.active_context_window_override, |
| 741 | previous_config: previous_config.clone(), |
| 742 | previous_onboarding: app.onboarding, |
| 743 | previous_onboarding_needs_api_key: app.onboarding_needs_api_key, |
| 744 | previous_api_key_env_only: app.api_key_env_only, |
| 745 | }); |
| 746 | |
| 747 | // A session-local switch keeps the same ownership rule the persisted |
| 748 | // writers apply (`reconcile_root_model_aliases`): the root alias the |
| 749 | // outgoing route was using moves onto that route's own leaf, so coming |
| 750 | // back lands on it instead of the catalog default. Every failure path |
| 751 | // below restores `previous_config`. |
| 752 | if let Some((outgoing, value)) = config.root_model_alias_owned_by_outgoing(&identity) { |
| 753 | if let Err(reason) = config.set_provider_model_override(&outgoing, Some(value)) { |
| 754 | app.pending_provider_switch = None; |
| 755 | app.show_route_receipt(reason.to_string(), StatusToastLevel::Error); |
| 756 | return false; |
| 757 | } |
| 758 | config.default_text_model = None; |
| 759 | } |
| 760 | |
| 761 | let resolution = if let Some((endpoint, _)) = probe { |
| 762 | if identity.provider != ProviderKind::Ollama |
| 763 | || identity.key.as_str() != "ollama" |
| 764 | || config.base_url_for_route(&identity) != endpoint |
| 765 | { |
| 766 | Err("The local model endpoint changed during discovery.".to_string()) |
| 767 | } else { |
| 768 | resolve_runtime_route_for_identity(config, &identity, model_override.as_deref()) |
| 769 | } |
| 770 | } else { |
| 771 | codewhale_engine::provider_lake::refresh_local_ollama_catalog(config, &identity).await; |
| 772 | resolve_runtime_route_for_identity(config, &identity, model_override.as_deref()) |
| 773 | }; |
| 774 | let resolved_route = match resolution { |
| 775 | Ok(route) => route, |
| 776 | Err(reason) => { |
| 777 | app.pending_provider_switch = None; |
| 778 | // #3830: if the switch failed only because the target provider has |
| 779 | // no key or local runtime, hand off to /provider already focused |
| 780 | // on that provider's key prompt instead of dead-ending with an |
| 781 | // error the user has to translate into an action. |
| 782 | if !codewhale_engine::provider_readiness::has_api_key_for(config, &identity) |
| 783 | && app.view_stack.top_kind() != Some(ModalKind::ProviderPicker) |
| 784 | { |
| 785 | let runtime_status = query_provider_runtime_status(engine_handle).await; |
| 786 | if let Some(picker) = |
| 787 | crate::tui::provider_picker::ProviderPickerView::new_for_missing_auth( |
| 788 | previous_provider, |
| 789 | &identity, |
| 790 | config, |
| 791 | runtime_status, |
| 792 | ) |
| 793 | .map(|picker| { |
| 794 | picker |
| 795 | .with_locale(app.ui_locale) |
| 796 | .with_provider_health(&app.provider_health) |
| 797 | }) |
| 798 | { |
| 799 | *config = previous_config; |
| 800 | app.refresh_notification_settings(config); |
| 801 | app.view_stack.push(picker); |
| 802 | app.show_route_receipt( |
| 803 | format!( |
| 804 | "{} needs a key or local runtime — enter one to switch.", |
| 805 | identity |
| 806 | .compatibility() |
| 807 | .map(|row| row.label) |
| 808 | .unwrap_or(identity.key.as_str()) |
| 809 | ), |
| 810 | StatusToastLevel::Warning, |
| 811 | ); |
| 812 | app.needs_redraw = true; |
| 813 | return false; |
| 814 | } |
| 815 | } |
| 816 | *config = previous_config; |
| 817 | app.refresh_notification_settings(config); |
| 818 | app.add_message(HistoryCell::System { |
| 819 | content: format!( |
| 820 | "Cannot switch to {}: {reason}\nProvider unchanged ({}).", |
| 821 | requested_identity, previous_identity |
| 822 | ), |
| 823 | }); |
| 824 | app.show_route_receipt( |
| 825 | format!( |
| 826 | "Route rejected before provider switch: {}.", |
| 827 | target.as_str() |
| 828 | ), |
| 829 | StatusToastLevel::Error, |
| 830 | ); |
| 831 | return false; |
| 832 | } |
| 833 | }; |
| 834 | let validated_route = match resolved_route.validate_async().await { |
| 835 | Ok(route) => route, |
| 836 | Err(err) => { |
| 837 | app.pending_provider_switch = None; |
| 838 | *config = previous_config; |
| 839 | app.refresh_notification_settings(config); |
| 840 | app.add_message(HistoryCell::System { |
| 841 | content: format!( |
| 842 | "Failed to switch provider to {}: {err}\nProvider unchanged ({}).", |
| 843 | requested_identity, previous_identity |
| 844 | ), |
| 845 | }); |
| 846 | return false; |
| 847 | } |
| 848 | }; |
| 849 | let engine_route = validated_route.clone().into_resolved(); |
| 850 | let target_identity_record = validated_route.identity.clone(); |
| 851 | let target_identity = target_identity_record.key.to_string(); |
| 852 | let new_base_url = validated_route.candidate.endpoint().base_url.clone(); |
| 853 | let route_limits = validated_route.candidate.limits(); |
| 854 | let context_window = validated_route.context_window; |
| 855 | let new_model = validated_route.model.clone(); |
| 856 | let apply_route = || { |
| 857 | *config = *validated_route.config; |
| 858 | app.set_provider_identity_record(target_identity_record.clone()); |
| 859 | app.set_model_selection(new_model.clone()); |
| 860 | app.set_active_context_window_override(config, &target_identity_record); |
| 861 | app.set_active_route_resolution(new_base_url.clone(), route_limits, context_window); |
| 862 | }; |
| 863 | let applied = if let Some((endpoint, ticket)) = probe { |
| 864 | codewhale_engine::provider_catalog_live::with_current_route_ticket( |
| 865 | ticket, |
| 866 | ProviderKind::Ollama, |
| 867 | "ollama", |
| 868 | endpoint, |
| 869 | apply_route, |
| 870 | ) |
| 871 | } else { |
| 872 | apply_route(); |
| 873 | Some(()) |
| 874 | }; |
| 875 | if applied.is_none() { |
| 876 | app.pending_provider_switch = None; |
| 877 | *config = previous_config; |
| 878 | app.refresh_notification_settings(config); |
| 879 | return false; |
| 880 | } |
| 881 | app.refresh_notification_settings(config); |
| 882 | let new_endpoint = display_base_url_host(&new_base_url); |
| 883 | let cache_scope_changed = previous_provider != target |
| 884 | || previous_identity != target_identity |
| 885 | || previous_model != new_model; |
| 886 | // Launch computed "needs a key" for the launch provider. A switch to a |
| 887 | // route that has its credential answers that, even when the user left the |
| 888 | // picker with Esc first; otherwise the stale flag keeps the info line on |
| 889 | // "model not connected" and keeps local-Ollama adoption armed against the |
| 890 | // provider the user just chose. An auth-failure rollback restores it. |
| 891 | app.onboarding_needs_api_key = !codewhale_engine::provider_readiness::has_api_key(config); |
| 892 | if !app.onboarding_needs_api_key { |
| 893 | app.onboarding_missing_key_recovery = false; |
| 894 | } |
| 895 | app.billing_presentation = |
| 896 | codewhale_engine::route_billing::for_route(config, &target_identity_record); |
| 897 | app.max_subagents = config |
| 898 | .max_subagents_for_provider(&target_identity_record) |
| 899 | .clamp(1, codewhale_runtime::config::MAX_SUBAGENTS); |
| 900 | app.provider_chain = (target_identity_record.key.as_str() == target.as_str() |
| 901 | && target != ProviderKind::Antigravity) |
| 902 | .then(|| codewhale_config::ProviderChain::new(target, &config.fallback_providers)) |
| 903 | .filter(|chain| chain.providers().len() > 1); |
| 904 | app.last_fallback_reason = None; |
| 905 | app.model_ids_passthrough = config.model_ids_pass_through(); |
| 906 | app.apply_provider_switch_reasoning_effort(target, &new_base_url, model_override.as_deref()); |
| 907 | if model_override.is_some() { |
| 908 | app.provider_models |
| 909 | .insert(target_identity.clone(), new_model.clone()); |
| 910 | } |
| 911 | app.note_route_used(&target_identity, &new_model); |
| 912 | app.update_model_compaction_budget(); |
| 913 | if cache_scope_changed { |
| 914 | app.clear_model_scoped_telemetry(); |
| 915 | } else { |
| 916 | app.session.last_prompt_tokens = None; |
| 917 | app.session.last_completion_tokens = None; |
| 918 | } |
| 919 | maybe_warn_context_pressure(app); |
| 920 | |
| 921 | let _ = engine_handle |
| 922 | .send(Op::SetRoute { |
| 923 | route: Box::new(engine_route), |
| 924 | mode: app.mode, |
| 925 | }) |
| 926 | .await; |
| 927 | // A successful in-session switch must refresh the same key-scoped live |
| 928 | // catalog as startup. TelecomJS is currently the only provider using this |
| 929 | // seam; failures preserve the existing/static rows. |
| 930 | codewhale_engine::client::CodewhaleClient::spawn_active_provider_catalog_refresh(config); |
| 931 | |
| 932 | let _ = engine_handle |
| 933 | .send(Op::SetCompaction { |
| 934 | config: app.compaction_config(), |
| 935 | }) |
| 936 | .await; |
| 937 | |
| 938 | // Route changes are temporary by default: nothing is written here. The |
| 939 | // route-save prompt offers the explicit persistence choices, so a |
| 940 | // workspace's config file can never be silently rewritten by a switch |
| 941 | // made in another folder. |
| 942 | app.note_session_route_change(&target_identity, &new_model); |
| 943 | let persist_warning: Option<String> = None; |
| 944 | |
| 945 | // Re-selecting the same provider (the usual first-run key entry) is a |
| 946 | // connection, not a switch: "deepseek → deepseek" read as a glitch (#6566). |
| 947 | let mut switch_summary = if previous_identity == target_identity { |
| 948 | format!("Connected: {target_identity}") |
| 949 | } else { |
| 950 | format!("Provider switched: {previous_identity} → {target_identity}") |
| 951 | }; |
| 952 | switch_summary.push(char::from(10)); |
| 953 | if previous_model == new_model { |
| 954 | switch_summary.push_str(&format!("Model: {new_model}")); |
| 955 | } else { |
| 956 | switch_summary.push_str(&format!("Model: {previous_model} → {new_model}")); |
| 957 | } |
| 958 | switch_summary.push(char::from(10)); |
| 959 | switch_summary.push_str(&format!("Endpoint: {new_endpoint}")); |
| 960 | if let Some(ref warning) = persist_warning { |
| 961 | switch_summary.push(char::from(10)); |
| 962 | switch_summary.push_str(warning); |
| 963 | } |
| 964 | app.add_message(HistoryCell::System { |
| 965 | content: switch_summary, |
| 966 | }); |
| 967 | |
| 968 | let mut summary = format!("Provider: {target_identity} via {new_endpoint}"); |
| 969 | let persisted = persist_warning.is_none(); |
| 970 | if persist_warning.is_some() { |
| 971 | summary.push_str(" (not fully persisted)"); |
| 972 | } |
| 973 | app.show_route_receipt( |
| 974 | summary, |
| 975 | if persisted { |
| 976 | StatusToastLevel::Info |
| 977 | } else { |
| 978 | StatusToastLevel::Warning |
| 979 | }, |
| 980 | ); |
| 981 | // #3927: activating a route is the single event that retires the |
| 982 | // explore-offline label. Nothing time-based or screen-based clears it. |
| 983 | onboarding::clear_offline_explore_on_route_activation(app); |
| 984 | if persisted { |
| 985 | record_provider_model_setup_progress(app, config); |
| 986 | } |
| 987 | true |
| 988 | } |
| 989 | |
| 990 | pub(crate) fn display_base_url_host(base_url: &str) -> String { |
| 991 | let without_scheme = base_url |
| 992 | .split_once("://") |
| 993 | .map_or(base_url, |(_, rest)| rest); |
| 994 | without_scheme |
| 995 | .split('/') |
| 996 | .next() |
| 997 | .filter(|host| !host.is_empty()) |
| 998 | .unwrap_or(base_url) |
| 999 | .to_string() |
| 1000 | } |
| 1001 | |
| 1002 | pub(crate) fn sync_config_provider_from_app(config: &mut Config, app: &App) { |
| 1003 | config.provider = Some(app.provider_identity_for_persistence().to_string()); |
| 1004 | } |
| 1005 | |
| 1006 | pub(crate) fn provider_picker_model_override( |
| 1007 | app: &App, |
| 1008 | config: &Config, |
| 1009 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 1010 | ) -> Option<String> { |
| 1011 | config.verify_provider_identity(identity).ok()?; |
| 1012 | (app.admitted_provider_identity().ok() == Some(identity)).then(|| app.model.clone()) |
| 1013 | } |
| 1014 | |
| 1015 | pub(crate) async fn query_provider_runtime_status( |
| 1016 | engine_handle: &EngineHandle, |
| 1017 | ) -> Option<ProviderRuntimeStatus> { |
| 1018 | tokio::time::timeout( |
| 1019 | Duration::from_millis(100), |
| 1020 | engine_handle.get_provider_runtime_status(), |
| 1021 | ) |
| 1022 | .await |
| 1023 | .ok() |
| 1024 | .and_then(|result| result.ok()) |
| 1025 | } |
| 1026 | |
| 1027 | pub(crate) fn mcp_reload_summary(snapshot: &codewhale_engine::mcp::McpManagerSnapshot) -> String { |
| 1028 | let connected = snapshot |
| 1029 | .servers |
| 1030 | .iter() |
| 1031 | .filter(|server| server.connected) |
| 1032 | .count(); |
| 1033 | let failed = snapshot |
| 1034 | .servers |
| 1035 | .iter() |
| 1036 | .filter(|server| server.enabled && server.error.is_some()) |
| 1037 | .count(); |
| 1038 | let disabled = snapshot |
| 1039 | .servers |
| 1040 | .iter() |
| 1041 | .filter(|server| !server.enabled) |
| 1042 | .count(); |
| 1043 | let idle = snapshot |
| 1044 | .servers |
| 1045 | .iter() |
| 1046 | .filter(|server| server.enabled && !server.connected && server.error.is_none()) |
| 1047 | .count(); |
| 1048 | format!( |
| 1049 | "MCP tool pool reloaded in process: {connected} connected, {failed} failed, {idle} not connected, {disabled} disabled of {} configured. The next model turn uses this catalog.", |
| 1050 | snapshot.servers.len() |
| 1051 | ) |
| 1052 | } |
| 1053 | |
| 1054 | pub(crate) fn mcp_server_diagnosis(app: &App, name: &str) -> String { |
| 1055 | let Some(server) = app |
| 1056 | .mcp_snapshot |
| 1057 | .as_ref() |
| 1058 | .and_then(|snapshot| snapshot.servers.iter().find(|server| server.name == name)) |
| 1059 | else { |
| 1060 | return app |
| 1061 | .tr(MessageId::McpDiagnosisUnobserved) |
| 1062 | .replace("{server}", name) |
| 1063 | .replace("{command}", "/mcp"); |
| 1064 | }; |
| 1065 | let state = if !server.enabled { |
| 1066 | MessageId::McpStateDisabled |
| 1067 | } else if server.connected { |
| 1068 | MessageId::ExtensionsStateConnected |
| 1069 | } else if server.auth_required { |
| 1070 | MessageId::McpStateAuthorizationRequired |
| 1071 | } else if server.error.is_some() { |
| 1072 | MessageId::McpStateFailed |
| 1073 | } else { |
| 1074 | MessageId::McpStateDisconnected |
| 1075 | }; |
| 1076 | let mut receipt = app |
| 1077 | .tr(MessageId::McpDiagnosisSummary) |
| 1078 | .replace("{server}", name) |
| 1079 | .replace("{state}", &app.tr(state)) |
| 1080 | .replace("{transport}", &server.transport) |
| 1081 | .replace("{tools}", &server.tools.len().to_string()) |
| 1082 | .replace("{resources}", &server.resources.len().to_string()) |
| 1083 | .replace("{prompts}", &server.prompts.len().to_string()); |
| 1084 | if let Some(error) = &server.error { |
| 1085 | receipt.push(' '); |
| 1086 | receipt.push_str(&app.tr(MessageId::McpDiagnosisLastError).replace( |
| 1087 | "{error}", |
| 1088 | &codewhale_config::persistence::redact_secrets(error), |
| 1089 | )); |
| 1090 | } |
| 1091 | if codewhale_engine::mcp::mcp_name_is_command_safe(name) { |
| 1092 | let command = if !server.enabled { |
| 1093 | format!("/mcp enable {name}") |
| 1094 | } else if server.auth_required { |
| 1095 | format!("/mcp login {name}") |
| 1096 | } else { |
| 1097 | format!("/mcp retry {name}") |
| 1098 | }; |
| 1099 | receipt.push(' '); |
| 1100 | receipt.push_str( |
| 1101 | &app.tr(MessageId::McpDiagnosisNext) |
| 1102 | .replace("{command}", &command), |
| 1103 | ); |
| 1104 | } else { |
| 1105 | receipt.push(' '); |
| 1106 | receipt.push_str( |
| 1107 | &app.tr(MessageId::McpDiagnosisNext) |
| 1108 | .replace("{command}", "/mcp reload"), |
| 1109 | ); |
| 1110 | } |
| 1111 | receipt |
| 1112 | } |
| 1113 | |
| 1114 | pub(crate) fn mcp_ui_action_refreshes_discovery(action: &crate::tui::app::McpUiAction) -> bool { |
| 1115 | matches!( |
| 1116 | action, |
| 1117 | crate::tui::app::McpUiAction::Logout { .. } |
| 1118 | | crate::tui::app::McpUiAction::ImportList |
| 1119 | | crate::tui::app::McpUiAction::ImportApprove { .. } |
| 1120 | ) |
| 1121 | } |
| 1122 | |
| 1123 | pub(crate) fn mcp_external_import_status_text( |
| 1124 | workspace: &std::path::Path, |
| 1125 | mcp_path: &std::path::Path, |
| 1126 | plugins: &codewhale_plugins::PluginRegistry, |
| 1127 | ) -> String { |
| 1128 | use codewhale_engine::mcp::external_import::{ImportContext, preview_imports}; |
| 1129 | let result = ImportContext::new(workspace, mcp_path, plugins) |
| 1130 | .and_then(|context| preview_imports(&context)); |
| 1131 | match result { |
| 1132 | Err(error) => format!("Cannot review MCP imports: {error}"), |
| 1133 | Ok(preview) => { |
| 1134 | let mut lines = vec!["Review external connectors. Imports stay OFF; enable and test separately. Credential values and command arguments are hidden.".to_string()]; |
| 1135 | for candidate in preview.candidates { |
| 1136 | lines.push(format!( |
| 1137 | "\n{} — {} · {} arguments · {}\nSource: {}\nContent: {}", |
| 1138 | candidate.name, |
| 1139 | candidate.destination, |
| 1140 | candidate.argument_count, |
| 1141 | if candidate.hard_blocked { |
| 1142 | "BLOCKED" |
| 1143 | } else if candidate.conflict { |
| 1144 | "NAME IN USE" |
| 1145 | } else { |
| 1146 | "Ready for review" |
| 1147 | }, |
| 1148 | candidate.source_path.display(), |
| 1149 | candidate.content_hash |
| 1150 | )); |
| 1151 | if !candidate.hard_blocked && !candidate.conflict { |
| 1152 | lines.push(format!( |
| 1153 | "Approve: /mcp import approve {}", |
| 1154 | candidate.review_token |
| 1155 | )); |
| 1156 | } |
| 1157 | lines.push(format!( |
| 1158 | "Decline: /mcp import decline {}", |
| 1159 | candidate.review_token |
| 1160 | )); |
| 1161 | } |
| 1162 | for problem in preview.problems { |
| 1163 | lines.push(format!( |
| 1164 | "{}: {}", |
| 1165 | problem.source_kind.as_str(), |
| 1166 | problem.message |
| 1167 | )); |
| 1168 | } |
| 1169 | lines.join("\n") |
| 1170 | } |
| 1171 | } |
| 1172 | } |
| 1173 | |
| 1174 | pub(crate) fn mcp_import_apply( |
| 1175 | workspace: &std::path::Path, |
| 1176 | mcp_path: &std::path::Path, |
| 1177 | plugins: &codewhale_plugins::PluginRegistry, |
| 1178 | token: &str, |
| 1179 | approve: bool, |
| 1180 | ) -> anyhow::Result<String> { |
| 1181 | use codewhale_engine::mcp::external_import::{ |
| 1182 | ImportContext, ImportDecision, apply_reviewed_import, parse_review_token, |
| 1183 | }; |
| 1184 | let (id, hash, revision) = parse_review_token(token)?; |
| 1185 | let context = ImportContext::new(workspace, mcp_path, plugins)?; |
| 1186 | let receipt = apply_reviewed_import( |
| 1187 | &context, |
| 1188 | id, |
| 1189 | hash, |
| 1190 | revision, |
| 1191 | if approve { |
| 1192 | ImportDecision::Approve |
| 1193 | } else { |
| 1194 | ImportDecision::Decline |
| 1195 | }, |
| 1196 | )?; |
| 1197 | let mut message = if receipt.imported { |
| 1198 | format!( |
| 1199 | "Imported '{}' with the connector OFF. Enable it explicitly, then test its connection.", |
| 1200 | receipt.name |
| 1201 | ) |
| 1202 | } else { |
| 1203 | format!( |
| 1204 | "Declined '{}'; connector configuration was unchanged.", |
| 1205 | receipt.name |
| 1206 | ) |
| 1207 | }; |
| 1208 | if let Some(warning) = receipt.warning { |
| 1209 | message.push(' '); |
| 1210 | message.push_str(&warning); |
| 1211 | } |
| 1212 | Ok(message) |
| 1213 | } |
| 1214 | |
| 1215 | pub(crate) fn clear_active_provider_api_key_from_memory( |
| 1216 | app: &App, |
| 1217 | config: &mut Config, |
| 1218 | ) -> Result<(), String> { |
| 1219 | let identity = app.admitted_provider_identity()?; |
| 1220 | config.verify_provider_identity(identity)?; |
| 1221 | config |
| 1222 | .set_provider_api_key_override(identity, None) |
| 1223 | .map_err(|error| error.to_string())?; |
| 1224 | // Region presentation shares the intrinsic secret owner through D6. |
| 1225 | if identity.key.as_str() == codewhale_config::descriptors::LEGACY_DEEPSEEK_CN.id { |
| 1226 | let primary = config.builtin_provider_identity(ProviderKind::Deepseek)?; |
| 1227 | config |
| 1228 | .set_provider_api_key_override(&primary, None) |
| 1229 | .map_err(|error| error.to_string())?; |
| 1230 | } |
| 1231 | if identity.provider == ProviderKind::Xai { |
| 1232 | let entry = config |
| 1233 | .provider_config_for_mut(identity) |
| 1234 | .map_err(|error| error.to_string())?; |
| 1235 | entry.auth_mode = None; |
| 1236 | entry.oauth_credential_generation = None; |
| 1237 | entry.external_credentials = None; |
| 1238 | } |
| 1239 | Ok(()) |
| 1240 | } |
| 1241 | |
| 1242 | pub(crate) fn record_provider_model_setup_progress(app: &mut App, config: &Config) { |
| 1243 | if let Err(err) = crate::tui::setup::record_provider_model_setup_state_for_app(app, config) { |
| 1244 | let note = format!("Setup provider/model state was not saved: {err:#}"); |
| 1245 | let text = match app.route_receipt() { |
| 1246 | Some(receipt) => format!("{} · {note}", receipt.text), |
| 1247 | None => note.clone(), |
| 1248 | }; |
| 1249 | app.show_route_receipt(text, StatusToastLevel::Warning); |
| 1250 | app.add_message(HistoryCell::System { content: note }); |
| 1251 | } |
| 1252 | } |
| 1253 | |
| 1254 | #[cfg(test)] |
| 1255 | pub(crate) fn picker_provider_identity( |
| 1256 | config: &Config, |
| 1257 | provider: ProviderKind, |
| 1258 | provider_id: Option<&str>, |
| 1259 | ) -> Result<codewhale_runtime::config::ProviderIdentity, String> { |
| 1260 | let identity = match provider_id { |
| 1261 | Some(provider_id) => config |
| 1262 | .resolve_persisted_provider_identity(Some(provider.as_str()), Some(provider_id))?, |
| 1263 | None if provider == ProviderKind::Custom => config.active_provider_identity()?, |
| 1264 | None => config.resolve_persisted_provider_identity( |
| 1265 | Some(provider.as_str()), |
| 1266 | Some(provider.as_str()), |
| 1267 | )?, |
| 1268 | }; |
| 1269 | if identity.provider != provider { |
| 1270 | return Err(format!( |
| 1271 | "provider picker identity '{}' resolved as {}, not {}", |
| 1272 | identity.key, |
| 1273 | identity.provider.as_str(), |
| 1274 | provider.as_str() |
| 1275 | )); |
| 1276 | } |
| 1277 | Ok(identity) |
| 1278 | } |
| 1279 | |
| 1280 | pub(crate) fn provider_verification_error_category( |
| 1281 | reason: &str, |
| 1282 | ) -> codewhale_error_taxonomy::ErrorCategory { |
| 1283 | let lower = reason.to_ascii_lowercase(); |
| 1284 | if lower.contains("http 401") || lower.contains("status 401") { |
| 1285 | codewhale_error_taxonomy::ErrorCategory::Authentication |
| 1286 | } else if lower.contains("http 403") || lower.contains("status 403") { |
| 1287 | codewhale_error_taxonomy::ErrorCategory::Authorization |
| 1288 | } else if ["500", "502", "503", "504"] |
| 1289 | .iter() |
| 1290 | .any(|status| lower.contains(&format!("http {status}"))) |
| 1291 | { |
| 1292 | codewhale_error_taxonomy::ErrorCategory::Network |
| 1293 | } else { |
| 1294 | codewhale_error_taxonomy::classify_error_message(reason) |
| 1295 | } |
| 1296 | } |
| 1297 |