| 1 | //! Application initialization: `App` construction lives here so the central |
| 2 | //! `app.rs` module holds state and behavior rather than a ~830-line |
| 3 | //! constructor. `App::new` remains a thin test-only shim over |
| 4 | //! [`App::new_with_plugin_registry`]; all callers construct `App` exactly as |
| 5 | //! before. |
| 6 | |
| 7 | use super::*; |
| 8 | |
| 9 | impl App { |
| 10 | /// Install the Config owner's current policy and refresh its read-only UI projection. |
| 11 | pub(crate) fn refresh_notification_settings(&mut self, config: &Config) { |
| 12 | self.notification_settings = config.notifications_config(); |
| 13 | let _ = crate::tui::notifications::settings(config); |
| 14 | } |
| 15 | |
| 16 | #[cfg(test)] |
| 17 | pub fn new(options: TuiOptions, config: &Config) -> Self { |
| 18 | let workspace = options.workspace.clone(); |
| 19 | Self::new_with_plugin_registry( |
| 20 | options, |
| 21 | config, |
| 22 | std::sync::Arc::new(codewhale_plugins::PluginRegistry::empty(&workspace)), |
| 23 | ) |
| 24 | } |
| 25 | |
| 26 | #[allow(clippy::too_many_lines)] |
| 27 | pub fn new_with_plugin_registry( |
| 28 | options: TuiOptions, |
| 29 | config: &Config, |
| 30 | plugin_registry: std::sync::Arc<codewhale_plugins::PluginRegistry>, |
| 31 | ) -> Self { |
| 32 | let TuiOptions { |
| 33 | model, |
| 34 | workspace, |
| 35 | config_path, |
| 36 | config_profile, |
| 37 | allow_shell, |
| 38 | use_mouse_capture, |
| 39 | use_bracketed_paste, |
| 40 | max_subagents, |
| 41 | skills_dir: global_skills_dir, |
| 42 | memory_path, |
| 43 | mcp_config_path, |
| 44 | use_memory, |
| 45 | start_in_agent_mode, |
| 46 | skip_onboarding, |
| 47 | yolo, |
| 48 | resume_session_id, |
| 49 | initial_input, |
| 50 | // Consumed by `run_app` after the App exists, so it can be shown |
| 51 | // alongside (or instead of) the resume receipt. |
| 52 | startup_notice: _, |
| 53 | } = options; |
| 54 | |
| 55 | // Start from disk-only preferences so one-time migrations can never |
| 56 | // persist terminal/environment overlays such as NO_ANIMATIONS. Apply |
| 57 | // those overlays only after any normalized settings write succeeds. |
| 58 | let mut settings = Settings::load_persisted().unwrap_or_else(|_| Settings::default()); |
| 59 | let legacy_yolo_default = settings.legacy_yolo_default_detected(); |
| 60 | let legacy_yolo_full_access = if legacy_yolo_default { |
| 61 | let control = config.approval_policy_control( |
| 62 | config_path.as_deref(), |
| 63 | config_profile.as_deref(), |
| 64 | &workspace, |
| 65 | ); |
| 66 | match control { |
| 67 | codewhale_runtime::config::ApprovalPolicyControl::Unset => { |
| 68 | if let Err(error) = normalize_legacy_yolo_settings() { |
| 69 | tracing::warn!( |
| 70 | "failed to normalize legacy YOLO settings; retrying next launch: {error:#}" |
| 71 | ); |
| 72 | } |
| 73 | true |
| 74 | } |
| 75 | codewhale_runtime::config::ApprovalPolicyControl::RootConfig => { |
| 76 | let active_config_path = |
| 77 | match codewhale_runtime::config::resolve_load_config_path( |
| 78 | config_path.clone(), |
| 79 | ) { |
| 80 | Ok(path) => path, |
| 81 | Err(error) => { |
| 82 | tracing::error!( |
| 83 | error = %error, |
| 84 | "could not resolve the active config path for legacy policy migration" |
| 85 | ); |
| 86 | None |
| 87 | } |
| 88 | }; |
| 89 | match codewhale_runtime::config_persistence::persist_unset_root_key( |
| 90 | active_config_path.as_deref(), |
| 91 | "approval_policy", |
| 92 | ) { |
| 93 | Ok(_) => { |
| 94 | if let Err(error) = normalize_legacy_yolo_settings() { |
| 95 | tracing::warn!( |
| 96 | "removed legacy approval_policy but could not normalize settings; retrying next launch: {error:#}" |
| 97 | ); |
| 98 | } |
| 99 | true |
| 100 | } |
| 101 | Err(error) => { |
| 102 | tracing::warn!( |
| 103 | "could not migrate legacy YOLO approval policy; keeping the controlling policy: {error:#}" |
| 104 | ); |
| 105 | false |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | source => { |
| 110 | tracing::warn!( |
| 111 | "legacy YOLO setting was not allowed to override {}", |
| 112 | source.label() |
| 113 | ); |
| 114 | false |
| 115 | } |
| 116 | } |
| 117 | } else { |
| 118 | false |
| 119 | }; |
| 120 | settings.apply_env_overrides(); |
| 121 | // Config::load resolves this once for every runtime. Direct in-memory |
| 122 | // callers use the same policy here, before any startup route is used. |
| 123 | let mut startup_config = config.clone(); |
| 124 | if config_profile.is_some() |
| 125 | || (startup_config.remembered_selection_scope.is_none() |
| 126 | && (codewhale_runtime::config::explicit_launch_provider_override().is_some() |
| 127 | || codewhale_runtime::config::explicit_launch_model_override().is_some())) |
| 128 | { |
| 129 | startup_config.remembered_selection_scope = Some(false); |
| 130 | } |
| 131 | let selected = startup_config.apply_saved_selection(&settings); |
| 132 | let config = &startup_config; |
| 133 | let startup_route_configured = |
| 134 | codewhale_engine::local_ollama::startup_route_configured(config); |
| 135 | // Provider and model come from the same resolved config, even on the |
| 136 | // first run. An options default must not replace a configured model. |
| 137 | let model = if selected || startup_route_configured { |
| 138 | config.default_model() |
| 139 | } else { |
| 140 | model |
| 141 | }; |
| 142 | // Tideline Startup is the fresh interactive landing surface. It must |
| 143 | // not be bypassed by a stale historical `launch_screen = false`, a |
| 144 | // provider/config notice, or a previous session record: only an |
| 145 | // intentional resume or explicit initial input enters the live session |
| 146 | // path directly. |
| 147 | let launch_visible = resume_session_id.is_none() && initial_input.is_none(); |
| 148 | let launch = LaunchState::new(launch_visible, &workspace); |
| 149 | |
| 150 | // If settings.toml exists on disk but couldn't be parsed (we fell back |
| 151 | // to defaults), surface a warning in the TUI so the user knows their |
| 152 | // file is broken instead of silently losing all settings. |
| 153 | let settings_parse_warning = |
| 154 | codewhale_runtime::settings::Settings::path() |
| 155 | .ok() |
| 156 | .and_then(|p| { |
| 157 | if p.exists() { |
| 158 | std::fs::read_to_string(&p).ok().and_then(|raw| { |
| 159 | ::toml::from_str::<::toml::Value>(&raw).err().map(|e| { |
| 160 | format!("⚠ settings.toml is malformed — using defaults ({e})") |
| 161 | }) |
| 162 | }) |
| 163 | } else { |
| 164 | None |
| 165 | } |
| 166 | }); |
| 167 | let admission = config.active_provider_identity(); |
| 168 | let admission_error = admission.as_ref().err().cloned(); |
| 169 | let provider_identity = admission.ok(); |
| 170 | // An unadmitted selection remains visible as a refusal; this inert |
| 171 | // display kind cannot be used as request/config authority. |
| 172 | let provider = provider_identity |
| 173 | .as_ref() |
| 174 | .map_or(ProviderKind::Custom, |identity| identity.provider); |
| 175 | let mut effective_auth_config = config.clone(); |
| 176 | |
| 177 | // #5032: a stale `[providers.xai] oauth_credential_generation` pointer |
| 178 | // whose owned credential file is gone makes `credentials_valid` return |
| 179 | // false with no recovery, so the generic provider picker reopened on |
| 180 | // EVERY launch (the dogfood bricked state). Detect that specific |
| 181 | // corrupted state, best-effort clear the stale pointer from the |
| 182 | // persisted config, and surface a truthful xAI-specific message. The |
| 183 | // repair never blocks or aborts launch; after it the state is the |
| 184 | // normal "needs auth", not a bricked loop. |
| 185 | // #5032: an onboarded user whose active xAI OAuth credential is missing |
| 186 | // must be guided to re-authenticate THAT provider — not be re-run through |
| 187 | // the generic provider picker on every launch. Detect the missing-cred |
| 188 | // state (broader than a dangling pointer: it also covers a repaired |
| 189 | // pointer, an expired/revoked token, or a never-completed login), repair |
| 190 | // a stale pointer once, surface a truthful xAI message, and suppress the |
| 191 | // picker-recovery path below. |
| 192 | let xai_oauth_needs_reauth = provider == ProviderKind::Xai |
| 193 | && provider_identity |
| 194 | .as_ref() |
| 195 | .and_then(|identity| effective_auth_config.provider_config_for(identity)) |
| 196 | .and_then(|entry| entry.auth_mode.as_deref()) |
| 197 | .is_some_and(codewhale_runtime::oauth::auth_mode_uses_xai_oauth) |
| 198 | && !codewhale_runtime::oauth::credentials_present( |
| 199 | codewhale_runtime::oauth::OAuthProvider::Xai, |
| 200 | &effective_auth_config, |
| 201 | ); |
| 202 | let xai_dangling_repair_message = if xai_oauth_needs_reauth { |
| 203 | if codewhale_runtime::oauth::owned_generation_is_dangling( |
| 204 | codewhale_runtime::oauth::OAuthProvider::Xai, |
| 205 | &effective_auth_config, |
| 206 | ) { |
| 207 | match codewhale_runtime::oauth::clear_dangling_generation( |
| 208 | codewhale_runtime::oauth::OAuthProvider::Xai, |
| 209 | config_path.as_deref(), |
| 210 | ) { |
| 211 | Ok(()) => { |
| 212 | // Keep the in-memory route consistent with the repaired |
| 213 | // persisted file so the running app never reaches for |
| 214 | // the missing generation. |
| 215 | if let Some(identity) = provider_identity.as_ref() |
| 216 | && let Ok(entry) = |
| 217 | effective_auth_config.provider_config_for_mut(identity) |
| 218 | { |
| 219 | entry.oauth_credential_generation = None; |
| 220 | } |
| 221 | } |
| 222 | Err(error) => { |
| 223 | tracing::warn!( |
| 224 | target: "codewhale::xai_oauth", |
| 225 | error = %error, |
| 226 | "could not clear the dangling xAI OAuth generation pointer; continuing launch" |
| 227 | ); |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | Some( |
| 232 | "⚠ xAI OAuth credentials are missing. Re-authenticate with \ |
| 233 | `codewhale auth xai-device` or the in-app login, or switch providers." |
| 234 | .to_string(), |
| 235 | ) |
| 236 | } else { |
| 237 | None |
| 238 | }; |
| 239 | let model_ids_passthrough = effective_auth_config.model_ids_pass_through(); |
| 240 | let provider_chain = provider_identity |
| 241 | .as_ref() |
| 242 | .filter(|identity| { |
| 243 | identity.key.as_str() == identity.provider.as_str() |
| 244 | && identity.provider != ProviderKind::Antigravity |
| 245 | }) |
| 246 | .map(|identity| ProviderChain::new(identity.provider, &config.fallback_providers)) |
| 247 | .filter(|chain| chain.providers().len() > 1); |
| 248 | let provider_readiness = provider_chain |
| 249 | .as_ref() |
| 250 | .map(|chain| { |
| 251 | chain |
| 252 | .providers() |
| 253 | .iter() |
| 254 | .filter_map(|kind| config.builtin_provider_identity(*kind).ok()) |
| 255 | .map(|identity| { |
| 256 | let ready = has_api_key_for(config, &identity); |
| 257 | (identity, ready) |
| 258 | }) |
| 259 | .collect() |
| 260 | }) |
| 261 | .unwrap_or_default(); |
| 262 | |
| 263 | // Check if the effective provider has an API key. This must happen |
| 264 | // after settings.default_provider is applied; otherwise a saved |
| 265 | // third-party provider can be pushed back into DeepSeek onboarding. |
| 266 | let needs_api_key = !has_api_key(&effective_auth_config); |
| 267 | let api_key_env_only = codewhale_runtime::config::active_provider_uses_env_only_api_key( |
| 268 | &effective_auth_config, |
| 269 | ); |
| 270 | let was_onboarded = crate::tui::onboarding::is_onboarded(); |
| 271 | let settings_auto_compact = settings.auto_compact; |
| 272 | let auto_compact_user_configured = Settings::auto_compact_explicitly_configured(); |
| 273 | let auto_compact_threshold_percent = settings.auto_compact_threshold_percent; |
| 274 | let compaction_summary_instructions = config.compaction_summary_instructions(); |
| 275 | let compaction_retained_user_message_tokens = |
| 276 | config.compaction_retained_user_message_tokens(); |
| 277 | let calm_mode = settings.calm_mode; |
| 278 | let low_motion = settings.low_motion; |
| 279 | let constrained_frame_rate = settings.constrained_frame_rate; |
| 280 | let fancy_animations = settings.fancy_animations; |
| 281 | let focus_texture = |
| 282 | crate::tui::focus_texture::FocusTextureMode::parse(&settings.focus_texture) |
| 283 | .unwrap_or_default(); |
| 284 | let work_surface_placement = |
| 285 | crate::tui::work_surface::WorkSurfacePlacement::parse(&settings.work_surface_placement); |
| 286 | let work_surface_top_height = settings.work_surface_top_height; |
| 287 | let work_surface_side_width = settings.work_surface_side_width; |
| 288 | let synchronized_output_enabled = settings.synchronized_output_enabled(); |
| 289 | let status_indicator = settings.status_indicator.clone(); |
| 290 | let show_thinking = settings.show_thinking; |
| 291 | let thinking_highlight = settings.thinking_highlight; |
| 292 | let thinking_default_expanded = settings.thinking_default_expanded; |
| 293 | let thinking_preview_lines = settings.thinking_preview_lines; |
| 294 | let help_expand_groups = settings.help_expand_groups; |
| 295 | let pin_last_prompt = settings.pin_last_prompt; |
| 296 | let show_tool_details = settings.show_tool_details; |
| 297 | let inline_diff_mode = InlineDiffMode::parse(&settings.inline_diffs); |
| 298 | let ui_locale = resolve_locale(&settings.locale); |
| 299 | // The dead `tui.toml` store was folded into settings.toml on load. |
| 300 | // Say so once, in the user's language, rather than letting a theme |
| 301 | // move under them unexplained. |
| 302 | let tui_prefs_migration_notice = settings |
| 303 | .tui_prefs_migration() |
| 304 | .map(|receipt| receipt.lines(ui_locale).join(" ")) |
| 305 | .filter(|line| !line.is_empty()); |
| 306 | let cost_currency = match (settings.cost_currency.as_str(), ui_locale.tag()) { |
| 307 | ("usd", "zh-Hans") => CostCurrency::Cny, |
| 308 | _ => CostCurrency::from_setting(&settings.cost_currency).unwrap_or(CostCurrency::Usd), |
| 309 | }; |
| 310 | let composer_density = ComposerDensity::from_setting(&settings.composer_density); |
| 311 | let composer_border = settings.composer_border; |
| 312 | let composer_multiline_mode = settings.composer_multiline_mode; |
| 313 | let composer_vim_enabled = settings |
| 314 | .composer_vim_mode |
| 315 | .trim() |
| 316 | .eq_ignore_ascii_case("vim"); |
| 317 | let transcript_spacing = TranscriptSpacing::from_setting(&settings.transcript_spacing); |
| 318 | let max_input_history = settings.max_input_history; |
| 319 | // Requesting bracketed paste does not prove the terminal delivers it. |
| 320 | // Keep the fallback until handle_paste_burst_key observes a real paste |
| 321 | // via bracketed_paste_seen; otherwise raw pasted newlines can submit. |
| 322 | let use_paste_burst_detection = settings.paste_burst_detection; |
| 323 | // Resolve the named theme from settings; unknown values were already |
| 324 | // normalised to the underwater default in Settings::load. The |
| 325 | // background_color setting still overlays on top. |
| 326 | let background_color_override = settings |
| 327 | .background_color |
| 328 | .as_deref() |
| 329 | .and_then(palette::parse_hex_rgb_color); |
| 330 | let background_setting = background_color_override.and_then(palette::hex_rgb_string); |
| 331 | let resolved_theme = |
| 332 | palette::resolve_theme_setting(&settings.theme, background_setting.as_deref()); |
| 333 | let theme_warning = resolved_theme.as_ref().err().map(|error| { |
| 334 | format!( |
| 335 | "⚠ configured theme '{}' could not be loaded — using System ({error})", |
| 336 | settings.theme |
| 337 | ) |
| 338 | }); |
| 339 | let (theme_name, theme_id, ui_theme) = resolved_theme.unwrap_or_else(|_| { |
| 340 | let id = palette::ThemeId::System; |
| 341 | let mut theme = id.ui_theme(); |
| 342 | if let Some(background) = background_color_override { |
| 343 | theme = theme.with_background_color(background); |
| 344 | } |
| 345 | (id.name().to_string(), id, theme) |
| 346 | }); |
| 347 | // Remembered route choices were resolved once into Config. The |
| 348 | // chooser and hotbar must not revive archived Settings values. |
| 349 | let mut provider_models = HashMap::new(); |
| 350 | for identity in config.provider_identities() { |
| 351 | if let Some(model) = config |
| 352 | .provider_config_for(&identity) |
| 353 | .and_then(|entry| entry.model.as_ref()) |
| 354 | { |
| 355 | provider_models.insert(identity.key.to_string(), model.clone()); |
| 356 | } |
| 357 | } |
| 358 | if let Some(identity) = &provider_identity { |
| 359 | provider_models.insert(identity.key.to_string(), model.clone()); |
| 360 | } |
| 361 | let auto_model = model.trim().eq_ignore_ascii_case("auto"); |
| 362 | // `settings.toml [enabled_models]` is no longer read (#6533): the |
| 363 | // picker ranks by use, which this index derives from saved sessions. |
| 364 | let route_usage = codewhale_engine::model_relevance::SharedRouteUsage::default(); |
| 365 | codewhale_engine::model_relevance::spawn_build(route_usage.clone()); |
| 366 | let active_context_window_override = provider_identity |
| 367 | .as_ref() |
| 368 | .and_then(|identity| config.context_window_for_provider_config(identity)); |
| 369 | let active_model_context_windows = provider_identity |
| 370 | .as_ref() |
| 371 | .and_then(|identity| config.model_context_windows_for(identity).cloned()); |
| 372 | let configured_route_base_url = effective_auth_config.active_route_base_url(); |
| 373 | let ( |
| 374 | active_route_limits, |
| 375 | active_route_base_url, |
| 376 | active_context_window_source, |
| 377 | active_context_window, |
| 378 | ) = if auto_model { |
| 379 | ( |
| 380 | active_context_window_override.map(|window| RouteLimits { |
| 381 | context_tokens: Some(u64::from(window)), |
| 382 | ..RouteLimits::default() |
| 383 | }), |
| 384 | configured_route_base_url, |
| 385 | if active_context_window_override.is_some() { |
| 386 | codewhale_engine::route_runtime::ContextWindowSource::Configured |
| 387 | } else { |
| 388 | codewhale_engine::route_runtime::ContextWindowSource::Fallback |
| 389 | }, |
| 390 | None, |
| 391 | ) |
| 392 | } else { |
| 393 | provider_identity |
| 394 | .as_ref() |
| 395 | .ok_or_else(|| "provider identity unavailable".to_string()) |
| 396 | .and_then(|identity| { |
| 397 | codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 398 | &effective_auth_config, |
| 399 | identity, |
| 400 | Some(&model), |
| 401 | ) |
| 402 | }) |
| 403 | .map(|resolution| { |
| 404 | ( |
| 405 | codewhale_engine::route_budget::known_route_limits( |
| 406 | resolution.candidate.limits(), |
| 407 | ), |
| 408 | resolution.candidate.endpoint().base_url.clone(), |
| 409 | resolution.context_window.source, |
| 410 | Some(resolution.context_window), |
| 411 | ) |
| 412 | }) |
| 413 | .unwrap_or(( |
| 414 | None, |
| 415 | configured_route_base_url, |
| 416 | codewhale_engine::route_runtime::ContextWindowSource::Fallback, |
| 417 | None, |
| 418 | )) |
| 419 | }; |
| 420 | let reasoning_effort_explicit = config.fleet_operator_reasoning_applied |
| 421 | || settings.reasoning_effort.is_some() |
| 422 | || config.reasoning_effort_is_explicit(); |
| 423 | let configured_reasoning_effort = if config.fleet_operator_reasoning_applied { |
| 424 | config.reasoning_effort() |
| 425 | } else { |
| 426 | settings |
| 427 | .reasoning_effort |
| 428 | .as_deref() |
| 429 | .or_else(|| config.reasoning_effort()) |
| 430 | }; |
| 431 | let reasoning_effort_preference = configured_reasoning_effort |
| 432 | .filter(|_| reasoning_effort_explicit) |
| 433 | .map(ReasoningEffort::from_setting); |
| 434 | let threshold_model = if auto_model { |
| 435 | DEFAULT_TEXT_MODEL |
| 436 | } else { |
| 437 | model.as_str() |
| 438 | }; |
| 439 | let compact_threshold = |
| 440 | codewhale_engine::route_budget::compaction_threshold_for_route_at_percent_with_window( |
| 441 | provider, |
| 442 | threshold_model, |
| 443 | active_route_limits, |
| 444 | active_context_window.map(|window| window.tokens), |
| 445 | auto_compact_threshold_percent, |
| 446 | ); |
| 447 | let auto_compact = if auto_compact_user_configured { |
| 448 | settings_auto_compact |
| 449 | } else { |
| 450 | codewhale_engine::route_budget::auto_compact_default_for_route( |
| 451 | provider, |
| 452 | threshold_model, |
| 453 | active_route_limits, |
| 454 | ) |
| 455 | }; |
| 456 | let mut reasoning_effort = if auto_model && !reasoning_effort_explicit { |
| 457 | // A retired fixed-model alias can infer a compatibility effort in |
| 458 | // Config. That is route metadata, not an explicit user preference, |
| 459 | // so it must not silently constrain unresolved auto routing. |
| 460 | ReasoningEffort::Auto |
| 461 | } else { |
| 462 | configured_reasoning_effort.map_or_else( |
| 463 | || { |
| 464 | if auto_model { |
| 465 | ReasoningEffort::Auto |
| 466 | } else { |
| 467 | ReasoningEffort::default() |
| 468 | } |
| 469 | }, |
| 470 | |setting| { |
| 471 | if auto_model { |
| 472 | ReasoningEffort::from_setting(setting) |
| 473 | } else { |
| 474 | ReasoningEffort::from_setting_for_provider(setting, provider) |
| 475 | } |
| 476 | }, |
| 477 | ) |
| 478 | }; |
| 479 | if !auto_model |
| 480 | && !reasoning_effort_explicit |
| 481 | && let Some(effort) = codewhale_runtime::config::legacy_deepseek_alias_effort_for_route( |
| 482 | provider, |
| 483 | &effective_auth_config.active_route_base_url(), |
| 484 | &model, |
| 485 | ) |
| 486 | { |
| 487 | reasoning_effort = ReasoningEffort::from_setting_for_provider(effort, provider); |
| 488 | } |
| 489 | if !auto_model |
| 490 | && codewhale_runtime::config::is_exact_direct_moonshot_k3_route( |
| 491 | provider, |
| 492 | &active_route_base_url, |
| 493 | &model, |
| 494 | ) |
| 495 | { |
| 496 | // Keep the visible/effective tier truthful on first launch too; |
| 497 | // direct K3 cannot honor a persisted `off` setting. |
| 498 | reasoning_effort = |
| 499 | reasoning_effort.normalize_for_route(provider, &active_route_base_url, &model); |
| 500 | } else if !auto_model && !reasoning_effort_explicit { |
| 501 | if let Some(default) = |
| 502 | ReasoningEffort::catalog_default(provider, &active_route_base_url, &model) |
| 503 | { |
| 504 | reasoning_effort = default; |
| 505 | } |
| 506 | } else if !auto_model |
| 507 | && ReasoningEffort::catalog_effort_values(provider, &active_route_base_url, &model) |
| 508 | .is_some() |
| 509 | { |
| 510 | reasoning_effort = |
| 511 | reasoning_effort.normalize_for_route(provider, &active_route_base_url, &model); |
| 512 | } |
| 513 | |
| 514 | // Resolve the saved mode separately from the permission posture. |
| 515 | let preferred_mode = AppMode::from_setting(&settings.default_mode); |
| 516 | // Legacy `default_mode = "yolo"` was split into Act plus the |
| 517 | // full-access posture at the settings edge, so only the CLI flag |
| 518 | // requests the compat elevation here. |
| 519 | let yolo_requested = yolo; |
| 520 | let initial_mode = if yolo_requested || start_in_agent_mode { |
| 521 | AppMode::Agent |
| 522 | } else { |
| 523 | preferred_mode |
| 524 | }; |
| 525 | |
| 526 | // Durable Agent-era permission baseline (#3386). Plan/YOLO derive from |
| 527 | // and restore to this. When the user starts in YOLO the live shell |
| 528 | // flag is force-enabled below, so |
| 529 | // the baseline shell value is taken from the interactive default (the |
| 530 | // pre-mode Agent surface) rather than the YOLO-forced live mirror; |
| 531 | // otherwise it mirrors the resolved `allow_shell` option, which already |
| 532 | // carries that same interactive default. Using `interactive_allow_shell()` |
| 533 | // here keeps the Agent baseline identical regardless of launch mode, so |
| 534 | // a YOLO -> Agent downshift exposes shell (approval-gated) exactly as |
| 535 | // documented, while an explicit `allow_shell = false` still hides it. |
| 536 | // Trust is never part of the Agent baseline (it is YOLO-only authority). |
| 537 | // Approval mirrors the configured policy. |
| 538 | let explicit_approval_mode = (!legacy_yolo_full_access) |
| 539 | .then_some(config.approval_policy.as_deref()) |
| 540 | .flatten() |
| 541 | .and_then(ApprovalMode::from_config_value); |
| 542 | let approval_policy_control = if legacy_yolo_full_access { |
| 543 | ApprovalPolicyControl::Unset |
| 544 | } else { |
| 545 | config.approval_policy_control( |
| 546 | config_path.as_deref(), |
| 547 | config_profile.as_deref(), |
| 548 | &workspace, |
| 549 | ) |
| 550 | }; |
| 551 | let approval_policy_locked = approval_policy_control != ApprovalPolicyControl::Unset; |
| 552 | let approval_policy_root_editable = |
| 553 | approval_policy_control == ApprovalPolicyControl::RootConfig; |
| 554 | let approval_policy_requirements_managed = |
| 555 | approval_policy_control == ApprovalPolicyControl::Requirements; |
| 556 | let shell_access_editable = config |
| 557 | .allow_shell_control( |
| 558 | config_path.as_deref(), |
| 559 | config_profile.as_deref(), |
| 560 | &workspace, |
| 561 | ) |
| 562 | .editable_root(); |
| 563 | // YOLO is a permission change. A locked policy must not be sidestepped |
| 564 | // by --yolo, default_mode=yolo, /zidong, or Alt+Y. |
| 565 | let yolo_compat = yolo_requested && !approval_policy_locked; |
| 566 | let needs_workspace_trust = |
| 567 | !yolo_compat && codewhale_runtime::config::needs_trust(&workspace); |
| 568 | // The language screen is required only when the locale cannot be |
| 569 | // confidently inferred from settings or the environment; returning |
| 570 | // users never see it. |
| 571 | let onboarding_needs_language = !was_onboarded |
| 572 | && !crate::tui::onboarding::locale_confidently_inferred(&settings.locale); |
| 573 | // Suppress the missing-key provider picker for the xAI-OAuth-missing- |
| 574 | // credential case: the user already chose xAI and just needs to |
| 575 | // re-authenticate it, not re-pick a provider every launch. |
| 576 | let (onboarding, onboarding_missing_key_recovery) = launch_onboarding_decision( |
| 577 | skip_onboarding, |
| 578 | was_onboarded, |
| 579 | onboarding_needs_language, |
| 580 | needs_api_key, |
| 581 | needs_workspace_trust, |
| 582 | xai_oauth_needs_reauth, |
| 583 | ); |
| 584 | let onboarding_workspace_trust_gate = onboarding_is_workspace_trust_gate( |
| 585 | skip_onboarding, |
| 586 | was_onboarded, |
| 587 | needs_api_key, |
| 588 | needs_workspace_trust, |
| 589 | ); |
| 590 | let auto_review_disabled = config.auto_review_disabled(); |
| 591 | let saved_permission_posture = if approval_policy_locked { |
| 592 | None |
| 593 | } else { |
| 594 | settings |
| 595 | .permission_posture |
| 596 | .as_deref() |
| 597 | .and_then(ApprovalMode::from_config_value) |
| 598 | .filter(|mode| !(auto_review_disabled && *mode == ApprovalMode::Auto)) |
| 599 | }; |
| 600 | let configured_approval_mode = explicit_approval_mode |
| 601 | .or(saved_permission_posture) |
| 602 | .unwrap_or(if approval_policy_locked { |
| 603 | ApprovalMode::Suggest |
| 604 | } else { |
| 605 | ApprovalMode::AcceptEdits |
| 606 | }); |
| 607 | let configured_trust_mode = configured_approval_mode == ApprovalMode::Bypass; |
| 608 | let mode_prefs = ModeSessionPrefs { |
| 609 | agent_allow_shell: if yolo_compat { |
| 610 | config.interactive_allow_shell() |
| 611 | } else { |
| 612 | allow_shell |
| 613 | }, |
| 614 | agent_trust_mode: configured_trust_mode, |
| 615 | // The YOLO-compat launch elevates the *live* approval mirror to |
| 616 | // Bypass below; the durable Agent baseline keeps the configured |
| 617 | // policy so a YOLO -> Agent downshift restores it. |
| 618 | agent_approval_mode: configured_approval_mode, |
| 619 | }; |
| 620 | let allow_shell = if yolo_compat { |
| 621 | allow_shell || shell_access_editable |
| 622 | } else { |
| 623 | allow_shell |
| 624 | }; |
| 625 | let shell_manager = new_shared_shell_manager(workspace.clone()); |
| 626 | |
| 627 | for error in crate::commands::user_registry::install_plugin_registry( |
| 628 | &workspace, |
| 629 | plugin_registry.as_ref(), |
| 630 | ) { |
| 631 | tracing::warn!(target: "plugins", "{error}"); |
| 632 | } |
| 633 | |
| 634 | // Initialize hooks executor from config, reviewed plugin snapshots, |
| 635 | // then project-local `.codewhale/hooks.toml` (#3026). |
| 636 | let hooks_config = codewhale_engine::hooks::config::load_with_project_and_plugins( |
| 637 | config.hooks_config(), |
| 638 | &workspace, |
| 639 | Some(plugin_registry.as_ref()), |
| 640 | ); |
| 641 | let hooks = HookExecutor::new(hooks_config, workspace.clone()); |
| 642 | |
| 643 | // Initialize the lifecycle event outbox (`[lifecycle_outbox]`). |
| 644 | // Disabled (all emits no-op) when the config has no path. |
| 645 | let lifecycle_outbox = config |
| 646 | .lifecycle_outbox |
| 647 | .as_ref() |
| 648 | .map(|outbox| { |
| 649 | codewhale_hooks::LifecycleOutbox::new( |
| 650 | outbox.path.clone(), |
| 651 | outbox.webhook_url.clone(), |
| 652 | outbox.webhook_token.clone(), |
| 653 | ) |
| 654 | }) |
| 655 | .unwrap_or_else(codewhale_hooks::LifecycleOutbox::disabled); |
| 656 | |
| 657 | // Initialize plan state |
| 658 | let plan_state = new_shared_plan_state(); |
| 659 | let todos = new_shared_todo_list(); |
| 660 | let work_runtime = codewhale_engine::work_graph::new_shared_work_runtime( |
| 661 | todos.clone(), |
| 662 | plan_state.clone(), |
| 663 | ); |
| 664 | |
| 665 | let skills_config = std::sync::Arc::new(config.skills_config()); |
| 666 | let skills_dir = resolve_skills_dir(&workspace, &global_skills_dir, config); |
| 667 | let cached_skills = Self::discover_cached_skills( |
| 668 | &workspace, |
| 669 | &skills_dir, |
| 670 | &skills_config, |
| 671 | plugin_registry.as_ref(), |
| 672 | ); |
| 673 | |
| 674 | // The recall cap applies from the first keystroke, not only after the |
| 675 | // first submit: the persisted file keeps its own larger cap (U01-m2). |
| 676 | let mut input_history = crate::composer_history::load_history(); |
| 677 | input_history.drain(..input_history.len().saturating_sub(max_input_history)); |
| 678 | let mention_cwd = std::env::current_dir().ok(); |
| 679 | let start_remote_control = matches!(initial_input, Some(InitialInput::RemoteControl)); |
| 680 | let (initial_input_text, initial_input_cursor, auto_submit_initial_input) = |
| 681 | match initial_input { |
| 682 | Some(InitialInput::Submit(text)) if !text.is_empty() => { |
| 683 | let cursor = text.chars().count(); |
| 684 | (text, cursor, true) |
| 685 | } |
| 686 | Some(InitialInput::RemoteControl) => (String::new(), 0, false), |
| 687 | _ => (String::new(), 0, false), |
| 688 | }; |
| 689 | let (mcp_configured_count, mcp_connecting) = |
| 690 | codewhale_engine::mcp::load_config_with_workspace_and_plugins( |
| 691 | &mcp_config_path, |
| 692 | &workspace, |
| 693 | plugin_registry.as_ref(), |
| 694 | ) |
| 695 | .map(|cfg| { |
| 696 | // The pre-event "connecting" prediction names only servers a |
| 697 | // session must start — `required` ones plus those the user's |
| 698 | // `tools.always_load` selection covers — not every server the |
| 699 | // boot pass starts. The engine's first boot event replaces |
| 700 | // this with the real in-flight set. |
| 701 | let requested = config |
| 702 | .tools |
| 703 | .as_ref() |
| 704 | .map(|tools| { |
| 705 | tools |
| 706 | .always_load |
| 707 | .iter() |
| 708 | .map(|name| name.trim().to_ascii_lowercase()) |
| 709 | .filter(|name| name.starts_with("mcp_")) |
| 710 | .collect::<Vec<_>>() |
| 711 | }) |
| 712 | .unwrap_or_default(); |
| 713 | let mut connecting = cfg |
| 714 | .servers |
| 715 | .iter() |
| 716 | .filter(|(_, server)| server.is_enabled()) |
| 717 | .filter(|(name, server)| { |
| 718 | server.required |
| 719 | || codewhale_engine::mcp::tool_selection_covers_server(&requested, name) |
| 720 | }) |
| 721 | .map(|(name, _)| name.clone()) |
| 722 | .collect::<Vec<_>>(); |
| 723 | connecting.sort(); |
| 724 | (cfg.servers.len(), connecting) |
| 725 | }) |
| 726 | .unwrap_or((0, Vec::new())); |
| 727 | let mut hotbar_actions = HotbarActionRegistry::with_configured_routes( |
| 728 | config, |
| 729 | provider_identity.as_ref(), |
| 730 | &model, |
| 731 | &provider_models, |
| 732 | ); |
| 733 | // #2069: expose the already-discovered skills as bindable hotbar |
| 734 | // actions. Reuses the startup skill cache, so no extra filesystem I/O. |
| 735 | hotbar_actions.register_skills(&cached_skills); |
| 736 | // The initial `connecting` list is a prediction about the pass the |
| 737 | // engine is about to run, so it carries the boot stamp (#7035). |
| 738 | let mcp_boot_initializing = !mcp_connecting.is_empty() |
| 739 | && config |
| 740 | .features() |
| 741 | .enabled(codewhale_runtime::features::Feature::Mcp); |
| 742 | let startup_notice = admission_error |
| 743 | .map(|message| (message, StatusToastLevel::Error)) |
| 744 | .or_else(|| { |
| 745 | xai_dangling_repair_message.map(|message| (message, StatusToastLevel::Warning)) |
| 746 | }) |
| 747 | .or_else(|| settings_parse_warning.map(|message| (message, StatusToastLevel::Warning))) |
| 748 | .or_else(|| tui_prefs_migration_notice.map(|message| (message, StatusToastLevel::Info))) |
| 749 | .or_else(|| theme_warning.map(|message| (message, StatusToastLevel::Warning))); |
| 750 | let mut app = Self { |
| 751 | mode: initial_mode, |
| 752 | hotbar_actions, |
| 753 | composer: ComposerState { |
| 754 | input: initial_input_text, |
| 755 | cursor_position: initial_input_cursor, |
| 756 | kill_buffer: String::new(), |
| 757 | paste_burst: PasteBurst::default(), |
| 758 | pending_paste_reference: None, |
| 759 | oversized_paste_full_text: None, |
| 760 | input_history, |
| 761 | draft_history: VecDeque::new(), |
| 762 | clear_undo_buffer: None, |
| 763 | history_index: None, |
| 764 | history_navigation_draft: None, |
| 765 | composer_history_search: None, |
| 766 | selected_attachment_index: None, |
| 767 | slash_menu_selected: 0, |
| 768 | slash_menu_hidden: false, |
| 769 | mention_menu_selected: 0, |
| 770 | mention_menu_hidden: false, |
| 771 | mention_completion_cache: None, |
| 772 | mention_discovery: crate::tui::mention_completion::MentionDiscovery::default(), |
| 773 | mention_cwd, |
| 774 | vim_enabled: composer_vim_enabled, |
| 775 | vim_mode: VimMode::Normal, |
| 776 | vim_pending_d: false, |
| 777 | selection_anchor: None, |
| 778 | // Seeded text was not typed, so it makes no command claim; |
| 779 | // startup integrity is decided by the replay receipt (#5925). |
| 780 | line_began_with_slash: false, |
| 781 | startup_input_unproven: false, |
| 782 | }, |
| 783 | viewport: ViewportState { |
| 784 | selection_copy_markdown: config |
| 785 | .tui |
| 786 | .as_ref() |
| 787 | .and_then(|tui| tui.selection_copy_markdown) |
| 788 | .unwrap_or(true), |
| 789 | ..ViewportState::default() |
| 790 | }, |
| 791 | pet_watch: crate::tui::pet_watch::PetWatch::default(), |
| 792 | attachment_preview: Box::new(crate::tui::image_preview::ThumbnailCache::new()), |
| 793 | work_surface: { |
| 794 | let mut state = crate::tui::work_surface::WorkSurfaceState::with_layout( |
| 795 | work_surface_placement, |
| 796 | work_surface_top_height, |
| 797 | work_surface_side_width, |
| 798 | ); |
| 799 | state.panel = crate::tui::work_surface::RailPanel::parse(&settings.rail_panel); |
| 800 | state |
| 801 | }, |
| 802 | goal: HostGoalState::default(), |
| 803 | session: SessionState::default(), |
| 804 | last_billed_input_tokens: None, |
| 805 | last_compaction: None, |
| 806 | active_allowed_tools: None, |
| 807 | pausable: false, |
| 808 | pending_route_save: None, |
| 809 | paused: false, |
| 810 | paused_goal_objective: None, |
| 811 | history: Vec::new(), |
| 812 | history_version: 0, |
| 813 | transcript_identity_epoch: 0, |
| 814 | history_revisions: Vec::new(), |
| 815 | tool_run_cache: ToolRunCache::default(), |
| 816 | next_history_revision: 1, |
| 817 | api_messages: Arc::new(Vec::new()), |
| 818 | api_message_stamps: Vec::new(), |
| 819 | window_reroot_cause: None, |
| 820 | session_journal: codewhale_runtime::session_tree::SessionJournal::new(), |
| 821 | completed_assistant_outputs: Vec::new(), |
| 822 | pending_plan_handoff: None, |
| 823 | context_token_cache: std::cell::RefCell::new(Default::default()), |
| 824 | remote_control: codewhale_app_server::remote_control::RemoteControlController::default( |
| 825 | ), |
| 826 | start_remote_control_on_launch: start_remote_control, |
| 827 | is_loading: false, |
| 828 | feedback_dispatch: None, |
| 829 | dispatch_completion_tx: None, |
| 830 | dispatch_in_flight: false, |
| 831 | preparing_steers: Default::default(), |
| 832 | steer_cancel: Default::default(), |
| 833 | preview_cancel: Default::default(), |
| 834 | dispatch_cancel: None, |
| 835 | pending_paste: None, |
| 836 | paste_shortcut_press_seen: false, |
| 837 | provider_wait_incident_logged: false, |
| 838 | prompt_suggestion: None, |
| 839 | notification_settings: config.notifications_config(), |
| 840 | prompt_suggestion_gen: std::sync::atomic::AtomicU64::new(0), |
| 841 | offline_mode: false, |
| 842 | turn_error_posted: false, |
| 843 | turn_error_notice: None, |
| 844 | turn_error_cause: None, |
| 845 | status_toasts: VecDeque::new(), |
| 846 | update_available: None, |
| 847 | sticky_status: None, |
| 848 | context_pressure_warning_dismissed: None, |
| 849 | plugin_reload_nudge_stamp: None, |
| 850 | last_plugin_catalog_poll: None, |
| 851 | mcp_config_watch: None, |
| 852 | plugin_cta: crate::tui::plugin_suggestions::PluginCtaState::from_settings(&settings), |
| 853 | model, |
| 854 | provider_models, |
| 855 | route_usage, |
| 856 | configured_models: config.custom_models.clone().unwrap_or_default(), |
| 857 | pinned_models: settings.pinned_models.clone(), |
| 858 | auto_model, |
| 859 | last_effective_model: None, |
| 860 | last_effective_budget: None, |
| 861 | last_effective_provider: None, |
| 862 | last_effective_provider_identity: None, |
| 863 | last_auto_route_receipt: None, |
| 864 | pending_turn_route: None, |
| 865 | pending_auto_route_receipt: None, |
| 866 | active_turn: None, |
| 867 | api_provider: provider, |
| 868 | provider_identity: provider_identity.clone(), |
| 869 | provider_chain, |
| 870 | provider_readiness, |
| 871 | provider_health: |
| 872 | codewhale_engine::provider_readiness::ProviderReadinessSnapshot::default(), |
| 873 | last_fallback_reason: None, |
| 874 | model_ids_passthrough, |
| 875 | active_route_limits, |
| 876 | active_route_base_url, |
| 877 | active_context_window_source, |
| 878 | active_context_window, |
| 879 | active_context_window_override, |
| 880 | active_model_context_windows, |
| 881 | pending_provider_switch: None, |
| 882 | reasoning_effort, |
| 883 | reasoning_effort_preference, |
| 884 | last_effective_reasoning_effort: None, |
| 885 | workspace, |
| 886 | workflow_config: config.workflow_config(), |
| 887 | goal_max_continuations: config.goal_max_continuations(), |
| 888 | goal_enforce_token_budget: config.goal_enforce_token_budget(), |
| 889 | goal_continuation_waiting: false, |
| 890 | configured_sandbox_mode: config.sandbox_mode.clone(), |
| 891 | configured_sandbox_network: config.sandbox_network_access, |
| 892 | sandbox_backend: codewhale_sandbox::get_platform_sandbox_with_bwrap_preference( |
| 893 | config.prefers_bwrap(), |
| 894 | ), |
| 895 | // #4022: the worker thread is spawned lazily on first submit, so |
| 896 | // constructing an App never costs a thread. |
| 897 | lane_control: codewhale_runtime::lane_control::LaneControlQueue::new(), |
| 898 | plugin_registry, |
| 899 | config_path, |
| 900 | config_profile, |
| 901 | legacy_plugin_tools_dir: config |
| 902 | .tools |
| 903 | .as_ref() |
| 904 | .and_then(|tools| tools.plugin_dir.as_deref()) |
| 905 | .map(PathBuf::from), |
| 906 | mcp_config_path: mcp_config_path.clone(), |
| 907 | skills_dir, |
| 908 | skills_config, |
| 909 | project_context_pack_enabled: config.project_context_pack_enabled(), |
| 910 | memory_path, |
| 911 | use_memory, |
| 912 | use_mouse_capture, |
| 913 | use_bracketed_paste, |
| 914 | use_paste_burst_detection, |
| 915 | bracketed_paste_seen: false, |
| 916 | bracketed_paste_trusted: crate::tui::paste::terminal_delivers_bracketed_paste(), |
| 917 | system_prompt: None, |
| 918 | instruction_assembly: None, |
| 919 | auto_compact, |
| 920 | auto_compact_user_configured, |
| 921 | auto_compact_threshold_percent, |
| 922 | compaction_summary_instructions, |
| 923 | compaction_retained_user_message_tokens, |
| 924 | stopped_turn: false, |
| 925 | calm_mode, |
| 926 | low_motion, |
| 927 | constrained_frame_rate, |
| 928 | ambient_clock_ms: 0, |
| 929 | ambient_clock_sampled_at: None, |
| 930 | ambient_idle_since: None, |
| 931 | ambient_life_held_ms: None, |
| 932 | ocean_completion_started_at: None, |
| 933 | ocean_turn_history_start: 0, |
| 934 | ocean_receipt_settle_start: None, |
| 935 | fancy_animations, |
| 936 | focus_texture, |
| 937 | launch, |
| 938 | pending_launch_action: None, |
| 939 | pending_composer_submit: None, |
| 940 | pending_hotbar_slot: None, |
| 941 | synchronized_output_enabled, |
| 942 | status_indicator, |
| 943 | show_thinking, |
| 944 | thinking_highlight, |
| 945 | thinking_default_expanded, |
| 946 | thinking_preview_lines, |
| 947 | help_expand_groups, |
| 948 | pin_last_prompt, |
| 949 | verbose_transcript: false, |
| 950 | show_tool_details, |
| 951 | inline_diff_mode, |
| 952 | ui_locale, |
| 953 | constitution_reviewed_digest: None, |
| 954 | cost_currency, |
| 955 | billing_presentation: provider_identity.as_ref().map_or( |
| 956 | codewhale_engine::route_billing::BillingPresentation::Unknown, |
| 957 | |identity| codewhale_engine::route_billing::for_route(config, identity), |
| 958 | ), |
| 959 | composer_density, |
| 960 | composer_border, |
| 961 | composer_multiline_mode, |
| 962 | voice_enabled: false, |
| 963 | voice_send_enabled: false, |
| 964 | voice_control_enabled: false, |
| 965 | transcript_spacing, |
| 966 | sidebar_hover: SidebarHoverState::default(), |
| 967 | sidebar_hover_tooltip: None, |
| 968 | model_picker_memory: None, |
| 969 | external_agents: Vec::new(), |
| 970 | external_agents_rx: None, |
| 971 | external_agent: None, |
| 972 | provider_picker_memory: None, |
| 973 | last_mouse_pos: None, |
| 974 | context_panel: settings.context_panel, |
| 975 | sessions_rail: settings.sessions_rail, |
| 976 | tool_collapse_threshold: 3, |
| 977 | expanded_tool_runs: HashSet::new(), |
| 978 | turn_work_durations: HashMap::new(), |
| 979 | turn_durations_revision: 0, |
| 980 | active_turn_user_index: None, |
| 981 | tool_collapse_mode: ToolCollapseMode::from_setting(&settings.tool_collapse_mode), |
| 982 | file_tree: None, |
| 983 | file_tree_visible: false, |
| 984 | compact_threshold, |
| 985 | max_input_history, |
| 986 | allow_shell, |
| 987 | verbosity: config.verbosity.clone(), |
| 988 | max_subagents, |
| 989 | stream_chunk_timeout_secs: config.stream_chunk_timeout_secs(), |
| 990 | subagent_cache: Vec::new(), |
| 991 | subagent_terminal_seen_at: HashMap::new(), |
| 992 | agent_progress: HashMap::new(), |
| 993 | agent_progress_meta: HashMap::new(), |
| 994 | delegated_writes: Default::default(), |
| 995 | subagent_card_index: HashMap::new(), |
| 996 | last_fanout_card_index: None, |
| 997 | pending_subagent_dispatch: None, |
| 998 | agent_activity_started_at: None, |
| 999 | agent_counter: 0, |
| 1000 | agent_label_map: HashMap::new(), |
| 1001 | background_finished: Vec::new(), |
| 1002 | finished_shell_ids: HashMap::new(), |
| 1003 | notified_shell_ids: HashSet::new(), |
| 1004 | notified_task_ids: HashSet::new(), |
| 1005 | subagent_cache_received_at: None, |
| 1006 | agent_focus: None, |
| 1007 | agent_queued_follow_ups: HashMap::new(), |
| 1008 | last_agent_progress_redraw: None, |
| 1009 | ui_theme, |
| 1010 | background_color_override, |
| 1011 | theme_id, |
| 1012 | theme_name, |
| 1013 | onboarding, |
| 1014 | redaction_gate: false, |
| 1015 | redaction_gate_confirming: false, |
| 1016 | redaction_gate_scroll: std::cell::Cell::new(0), |
| 1017 | onboarding_needs_api_key: needs_api_key, |
| 1018 | startup_route_configured, |
| 1019 | onboarding_provider: provider, |
| 1020 | onboarding_workspace_trust_gate, |
| 1021 | onboarding_missing_key_recovery, |
| 1022 | onboarding_key_rejected: None, |
| 1023 | onboarding_explore_offline: false, |
| 1024 | // Language is asked in /setup, never at launch: counting it here |
| 1025 | // made the one launch screen read "Getting started · 2/3" with no |
| 1026 | // step 1 in sight (#6566). |
| 1027 | onboarding_had_language_step: onboarding_needs_language |
| 1028 | && onboarding == OnboardingState::Language, |
| 1029 | onboarding_had_provider_step: !was_onboarded && needs_api_key, |
| 1030 | onboarding_had_trust_step: !was_onboarded && needs_workspace_trust, |
| 1031 | local_runtime_detected: false, |
| 1032 | local_ollama_probe: None, |
| 1033 | api_key_env_only, |
| 1034 | hooks, |
| 1035 | lifecycle_outbox, |
| 1036 | yolo: yolo_compat, |
| 1037 | yolo_compat_notified: false, |
| 1038 | permission_receipt_deferred: false, |
| 1039 | operate_retired_notified: false, |
| 1040 | startup_defaults: Default::default(), |
| 1041 | keybinding_migration_notified: false, |
| 1042 | mode_prefs, |
| 1043 | approval_policy_locked, |
| 1044 | approval_policy_root_editable, |
| 1045 | approval_policy_requirements_managed, |
| 1046 | auto_review_disabled, |
| 1047 | auto_review_reviewer_model: config.auto_review_reviewer_model().map(str::to_string), |
| 1048 | exec_policy_engine: config.exec_policy_engine.clone(), |
| 1049 | auto_review_broad_allow_warnings: |
| 1050 | codewhale_engine::core::authority::auto_review::AutoReviewPolicy::from_config( |
| 1051 | config, |
| 1052 | ) |
| 1053 | .suspended_allow_warnings, |
| 1054 | clipboard: ClipboardHandler::new(), |
| 1055 | approval_session_approved: HashSet::new(), |
| 1056 | approval_session_denied: HashSet::new(), |
| 1057 | approval_mode: if yolo_compat { |
| 1058 | ApprovalMode::Bypass |
| 1059 | } else { |
| 1060 | configured_approval_mode |
| 1061 | }, |
| 1062 | view_stack: ViewStack::new(), |
| 1063 | pending_user_input_prompt: None, |
| 1064 | pending_child_requests: std::collections::BTreeMap::new(), |
| 1065 | child_agent_sessions: std::collections::HashMap::new(), |
| 1066 | backtrack: crate::tui::backtrack::BacktrackState::new(), |
| 1067 | undo_selection: false, |
| 1068 | current_session_id: None, |
| 1069 | conversation_mode: None, |
| 1070 | conversation_mode_unavailable: None, |
| 1071 | session_write_receipt: None, |
| 1072 | session_write_owner: None, |
| 1073 | offline_queue_lease: None, |
| 1074 | last_known_work_state: None, |
| 1075 | last_known_goal_state: None, |
| 1076 | pending_goal_controls: VecDeque::new(), |
| 1077 | pending_fresh_session: None, |
| 1078 | current_session_metadata: None, |
| 1079 | session_artifacts: Vec::new(), |
| 1080 | session_turn_outcomes: Vec::new(), |
| 1081 | trust_mode: yolo_compat || configured_trust_mode, |
| 1082 | translation_enabled: false, |
| 1083 | mini_window: config.mini_window.clone().unwrap_or_default(), |
| 1084 | status_items: config |
| 1085 | .tui |
| 1086 | .as_ref() |
| 1087 | .and_then(|tui| tui.status_items.clone()) |
| 1088 | .unwrap_or_else(codewhale_runtime::config::StatusItem::default_footer), |
| 1089 | posture_bar: config |
| 1090 | .tui |
| 1091 | .as_ref() |
| 1092 | .and_then(|tui| tui.posture_bar) |
| 1093 | .unwrap_or_default(), |
| 1094 | metrics_line: config |
| 1095 | .tui |
| 1096 | .as_ref() |
| 1097 | .and_then(|tui| tui.metrics_line) |
| 1098 | .unwrap_or(codewhale_runtime::config::ChromeRowPreset::Compact), |
| 1099 | // Prose wrap cap (`[transcript] prose_measure`, #5436). Resolved |
| 1100 | // once here so every render pass — main cache and full-screen |
| 1101 | // overlay — shares one effective width; `None` = full width. |
| 1102 | prose_measure: config.prose_measure(), |
| 1103 | plan_state, |
| 1104 | todos, |
| 1105 | runtime_services: RuntimeToolServices { |
| 1106 | shell_manager: Some(shell_manager), |
| 1107 | work: Some(work_runtime), |
| 1108 | media_originals_dir: codewhale_runtime::media_originals::default_store_dir(), |
| 1109 | ..RuntimeToolServices::default() |
| 1110 | }, |
| 1111 | coordination_detail: None, |
| 1112 | mcp_snapshot: None, |
| 1113 | mcp_initializing: mcp_boot_initializing, |
| 1114 | mcp_boot_predicted_at: mcp_boot_initializing.then(std::time::Instant::now), |
| 1115 | mcp_snapshot_generation: 0, |
| 1116 | mcp_snapshot_generation_invalidated: false, |
| 1117 | mcp_connecting, |
| 1118 | mcp_announced_problems: std::collections::BTreeMap::new(), |
| 1119 | // Read the MCP config once at boot to know how many servers |
| 1120 | // the user has declared. The footer chip uses this even when |
| 1121 | // no live snapshot is available (#502). Cheap (just reads |
| 1122 | // the JSON files); errors fall through to zero so a missing |
| 1123 | // or malformed config simply hides the chip. |
| 1124 | mcp_configured_count, |
| 1125 | mcp_reload_required: false, |
| 1126 | mcp_reload_in_flight: false, |
| 1127 | tool_log: Vec::new(), |
| 1128 | active_skill: None, |
| 1129 | active_skill_provenance: None, |
| 1130 | cached_skills, |
| 1131 | tool_cells: HashMap::new(), |
| 1132 | tool_details_by_cell: HashMap::new(), |
| 1133 | context_references_by_cell: HashMap::new(), |
| 1134 | session_context_references: Vec::new(), |
| 1135 | active_cell: None, |
| 1136 | active_cell_revision: 0, |
| 1137 | active_tool_details: HashMap::new(), |
| 1138 | agent_roster: Vec::new(), |
| 1139 | agent_roster_session_id: None, |
| 1140 | agent_roster_print_requested: false, |
| 1141 | active_tool_entry_completed_at: HashMap::new(), |
| 1142 | exploring_entries: HashMap::new(), |
| 1143 | ignored_tool_calls: HashMap::new(), |
| 1144 | last_exec_wait_command: None, |
| 1145 | streaming_message_index: None, |
| 1146 | streaming_source_receipt: None, |
| 1147 | suppress_stream_events_until_turn_complete: false, |
| 1148 | streaming_thinking_active_entry: None, |
| 1149 | pending_thinking_translation_cells: HashMap::new(), |
| 1150 | thinking_revision_last_bump_at: None, |
| 1151 | thinking_read_window: Default::default(), |
| 1152 | thinking_revision_owed: false, |
| 1153 | streaming_state: StreamingState::new(), |
| 1154 | streaming_output_token_estimate: 0, |
| 1155 | reasoning_buffer: String::new(), |
| 1156 | reasoning_header: None, |
| 1157 | last_reasoning: None, |
| 1158 | pending_tool_uses: Vec::new(), |
| 1159 | pending_gate_receipts: Vec::new(), |
| 1160 | child_gate_receipts: std::collections::HashMap::new(), |
| 1161 | auto_review_blocked_receipts: Vec::new(), |
| 1162 | queued_messages: VecDeque::new(), |
| 1163 | held_restored_queue: 0, |
| 1164 | queued_draft: None, |
| 1165 | queued_draft_was_held: false, |
| 1166 | inflight_steers: VecDeque::new(), |
| 1167 | turn_started_at: None, |
| 1168 | turn_last_activity_at: None, |
| 1169 | cumulative_turn_duration: std::time::Duration::ZERO, |
| 1170 | session_metrics: crate::tui::session_metrics::SessionMetrics::default(), |
| 1171 | balance_cell: std::sync::Arc::new(std::sync::Mutex::new(None)), |
| 1172 | balance_route: None, |
| 1173 | draft_gen: std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)), |
| 1174 | fleet_draft_cell: std::sync::Arc::new(std::sync::Mutex::new(None)), |
| 1175 | constitution_draft_cell: std::sync::Arc::new(std::sync::Mutex::new(None)), |
| 1176 | mcp_login: None, |
| 1177 | mcp_retries: Vec::new(), |
| 1178 | mcp_login_reconnect: None, |
| 1179 | prompt_suggestion_cell: std::sync::Arc::new(std::sync::Mutex::new(None)), |
| 1180 | balance_initiated: false, |
| 1181 | last_balance_fetch: None, |
| 1182 | runtime_turn_id: None, |
| 1183 | runtime_turn_status: None, |
| 1184 | turn_counter: 0, |
| 1185 | dispatch_started_at: None, |
| 1186 | workspace_context: None, |
| 1187 | workspace_is_linked_worktree: false, |
| 1188 | workspace_context_cell: std::sync::Arc::new(std::sync::Mutex::new(None)), |
| 1189 | workspace_context_refreshed_at: None, |
| 1190 | memory_size_hint: None, |
| 1191 | workspace_notes: Vec::new(), |
| 1192 | task_panel: Vec::new(), |
| 1193 | task_panel_session_id: None, |
| 1194 | task_panel_unavailable: false, |
| 1195 | automation_panel: crate::tui::automation_panel::AutomationPanelState::default(), |
| 1196 | automation_scan: None, |
| 1197 | behavioral_tips: crate::tui::behavioral_tips::BehavioralTipState::new( |
| 1198 | settings.contextual_tips, |
| 1199 | ), |
| 1200 | footer_hint_uses: settings.footer_hint_uses.clone(), |
| 1201 | workflow_runs: Vec::new(), |
| 1202 | session_started_at: chrono::Utc::now(), |
| 1203 | needs_redraw: true, |
| 1204 | fleet_roster_stale: false, |
| 1205 | force_next_full_repaint: false, |
| 1206 | thinking_started_at: None, |
| 1207 | is_compacting: false, |
| 1208 | active_compaction: None, |
| 1209 | manual_compaction_queued: false, |
| 1210 | manual_compaction_id: None, |
| 1211 | deferred_manual_compaction: None, |
| 1212 | is_purging: false, |
| 1213 | user_scrolled_during_stream: false, |
| 1214 | last_send_at: None, |
| 1215 | last_submitted_prompt: None, |
| 1216 | unanswered_submission: None, |
| 1217 | auto_submit_initial_input, |
| 1218 | quit_armed_until: None, |
| 1219 | prefix_change_count: 0, |
| 1220 | prefix_checks_total: 0, |
| 1221 | prefix_stability_pct: None, |
| 1222 | last_prefix_change_desc: None, |
| 1223 | last_pinned_prefix_hash: None, |
| 1224 | prefix_pin_reason: None, |
| 1225 | prefix_last_miss_reason: None, |
| 1226 | prefix_drift_count: 0, |
| 1227 | prefix_context_updates: 0, |
| 1228 | collapsed_cells: HashSet::new(), |
| 1229 | cell_folds: HashMap::new(), |
| 1230 | collapsed_cell_map: Vec::new(), |
| 1231 | edit_in_progress: false, |
| 1232 | lsp_enabled: config |
| 1233 | .lsp |
| 1234 | .as_ref() |
| 1235 | .is_some_and(|l| l.enabled.unwrap_or(true)), |
| 1236 | lsp_config: config.lsp.clone().map(codewhale_lsp::LspConfig::from), |
| 1237 | lsp_repair: LspRepairState::default(), |
| 1238 | composer_arrows_scroll: config |
| 1239 | .tui |
| 1240 | .as_ref() |
| 1241 | .and_then(|tui| tui.composer_arrows_scroll) |
| 1242 | .unwrap_or_else(|| default_composer_arrows_scroll(use_mouse_capture)), |
| 1243 | mention_menu_limit: settings.mention_menu_limit, |
| 1244 | mention_walk_depth: settings.mention_walk_depth, |
| 1245 | mention_menu_behavior: settings.mention_menu_behavior.clone(), |
| 1246 | workspace_follow_symlinks: settings.workspace_follow_symlinks, |
| 1247 | session_title: None, |
| 1248 | window_title: None, |
| 1249 | composer_color: None, |
| 1250 | title_default: config |
| 1251 | .title |
| 1252 | .as_deref() |
| 1253 | .map(codewhale_engine::session_manager::sanitize_session_title) |
| 1254 | .map(|title| title.trim().to_string()) |
| 1255 | .filter(|title| !title.is_empty()), |
| 1256 | receipt_text: None, |
| 1257 | receipt_started_at: None, |
| 1258 | tool_evidence: Vec::new(), |
| 1259 | }; |
| 1260 | // Restore presentation only; the visible-frame tick owns companion startup. |
| 1261 | app.pet_watch.enabled = settings.pet_mode; |
| 1262 | if let Some((message, level)) = startup_notice { |
| 1263 | if level == StatusToastLevel::Error { |
| 1264 | app.set_sticky_status(message, level, None); |
| 1265 | } else { |
| 1266 | app.show_event_notice(message, level); |
| 1267 | } |
| 1268 | } |
| 1269 | app.pet_watch.apply_identity( |
| 1270 | settings.whale_name.as_deref(), |
| 1271 | settings.whale_color.as_deref(), |
| 1272 | ); |
| 1273 | if settings.pet_mode { |
| 1274 | app.launch.visible = false; |
| 1275 | } |
| 1276 | if yolo_compat { |
| 1277 | app.notify_yolo_compat_once(); |
| 1278 | } |
| 1279 | if settings.legacy_operate_default_detected() { |
| 1280 | app.notify_operate_retired_once(); |
| 1281 | } |
| 1282 | if app.approval_mode == ApprovalMode::Auto && app.has_suspended_broad_allows() { |
| 1283 | app.emit_auto_review_broad_allows_paused_note(); |
| 1284 | } |
| 1285 | app.refresh_agent_approved_plugins_notice(); |
| 1286 | app |
| 1287 | } |
| 1288 | } |
| 1289 | |
| 1290 | /// Rewrite `settings.toml` with the legacy `default_mode = "yolo"` value |
| 1291 | /// normalized away. |
| 1292 | /// |
| 1293 | /// The normalization happens during parsing, so an empty transaction *is* the |
| 1294 | /// migration: load (which normalizes), then save. Doing it as its own |
| 1295 | /// [`codewhale_runtime::settings::Settings::transact`] rather than saving the snapshot |
| 1296 | /// `App::new` already loaded matters twice over. It cannot write back a stale |
| 1297 | /// pre-image, and — because `App::new` runs on the same hot path as several |
| 1298 | /// hundred tests — it keeps the transaction lock out of the common construction |
| 1299 | /// path entirely, taking it only when a legacy file actually needs migrating. |
| 1300 | fn normalize_legacy_yolo_settings() -> anyhow::Result<()> { |
| 1301 | codewhale_runtime::settings::Settings::transact(|_normalized_on_load| Ok(())) |
| 1302 | } |
| 1303 |